Skip to content

Commit

Permalink
修复无限递归和id错误bug,加入注释功能
Browse files Browse the repository at this point in the history
  • Loading branch information
limuy2022 committed Feb 6, 2024
1 parent 3a6ece3 commit e98c232
Show file tree
Hide file tree
Showing 15 changed files with 154 additions and 79 deletions.
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ num-bigint = "0.4.4"
reqwest = { version = "0.11.24", features = ["json", "multipart"] }
tokio = { version = "1.36.0", features = ["full"] }
llvm-sys = "170.0.1"
once_cell = "1.19.0"
derive = { path = "./derive" }

[profile.release]
Expand Down
3 changes: 2 additions & 1 deletion rust/derive/src/def_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ pub fn def_impl(content: TokenStream) -> TokenStream {
check_next_iter(&mut iter, "=");
if let TokenTree::Group(x, ..) = iter.next().unwrap() {
// println!("{}", x);
let mut iter = x.stream().into_iter();
let iter = x.stream().into_iter();
for i in iter {
if let TokenTree::Ident(x) = i {
submodules
Expand Down Expand Up @@ -151,6 +151,7 @@ pub fn def_impl(content: TokenStream) -> TokenStream {
)*
#(
classes.insert(stringify!(#right_class).to_string(), #left_class::export_info());
#left_class::gen_funcs_info();
)*
#(
submodules.insert(stringify!(#submodules).to_string(), #submodules::init());
Expand Down
71 changes: 45 additions & 26 deletions rust/derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use syn::ImplItem;
use syn::{
parse_macro_input, parse_str, Expr, Ident, ItemFn, ItemImpl, ItemStruct, Stmt, Type, Visibility,
};

mod def_module;
mod function;

Expand Down Expand Up @@ -32,7 +33,6 @@ pub fn trc_function(attr: TokenStream, input: TokenStream) -> TokenStream {
new_stmts.push(i);
continue;
}

new_stmts.push(
parse_str::<Stmt>(&format!(
"dydata.obj_stack.push(Box::new({}));",
Expand Down Expand Up @@ -69,7 +69,7 @@ pub fn trc_function(attr: TokenStream, input: TokenStream) -> TokenStream {
return RustFunction::new(stringify!(#name), #function_path, IOType::new(ret_classes, #output));
}
);
println!("{}", rettmp.to_token_stream());
// println!("{}", rettmp.to_token_stream());
rettmp.into()
}

Expand Down Expand Up @@ -108,25 +108,49 @@ pub fn trc_class(_: TokenStream, input: TokenStream) -> TokenStream {
}
}
// export_info函数会调用method宏生成function_export函数
// 目前的实现策略是先提供一个由once_cell储存的usize数,表示在类型表中的索引,里面储存该类型的Rc指针
// 因为很可能某个函数的参数就是标准库中的某个类型,所以我们需要先将类型导入到class_table中
let ret = quote!(#input
use crate::base::stdlib::RustClass;
impl #name {
pub fn export_info() -> RustClass {
use std::collections::hash_map::HashMap;
use crate::compiler::scope::Var;
let mut members = HashMap::new();
#(
members.insert(Var::new(stringify!(#members_ty), #members_ident));
)*
let mut ret = RustClass::new(
use crate::base::stdlib::{RustClass, new_class_id, STD_CLASS_TABLE};
use once_cell::sync::OnceCell;
impl #name {
pub fn init_info() -> usize {
use std::collections::hash_map::HashMap;
use crate::compiler::scope::Var;
let mut members = HashMap::new();
#(
members.insert(Var::new(stringify!(#members_ty), #members_ident));
)*
let classid = new_class_id();
let mut ret = RustClass::new(
stringify!(#name),
members,
Self::function_export(),
Self::override_export()
None,
Self::override_export(),
classid
);
ret
STD_CLASS_TABLE.with(|std| {
std.borrow_mut().push(ret);
});
// let funcs_info = Self::function_export()
// ret.functions = funcs_info;
classid
}

pub fn gen_funcs_info() {
STD_CLASS_TABLE.with(|std| {
std.borrow_mut()[Self::export_info()].functions = Self::function_export();
});
}

pub fn export_info() -> usize {
static ID: OnceCell<usize> = OnceCell::new();
*ID.get_or_init(|| {
let id = Self::init_info();
id
})
}
}
}
);
// println!("{}", ret.to_string());
ret.into()
Expand All @@ -144,18 +168,13 @@ pub fn trc_method(_: TokenStream, input: TokenStream) -> TokenStream {
// println!("!!!!!!!!!!!!!!!!!!!!!!!!!!:{:#?}", name);
let mut funcs = vec![];
for i in &input.items {
match i {
ImplItem::Fn(func) => {
if let Visibility::Public(_) = func.vis {
funcs.push(
parse_str::<Ident>(&function::convent_to_info_func(
func.sig.ident.to_string(),
))
if let ImplItem::Fn(func) = i {
if let Visibility::Public(_) = func.vis {
funcs.push(
parse_str::<Ident>(&function::convent_to_info_func(func.sig.ident.to_string()))
.unwrap(),
);
}
);
}
_ => {}
}
}
let ret = quote!(
Expand Down
5 changes: 4 additions & 1 deletion rust/examples/expr.trc
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/*
test expr
*/
print(1+1)
print("hello")
print("ppp"+1)
#print("ppp"+1)
Binary file modified rust/locales/zh_CN/LC_MESSAGES/trans.mo
Binary file not shown.
5 changes: 4 additions & 1 deletion rust/locales/zh_CN/LC_MESSAGES/trans.po
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ msgid "Float {} is too large to store"
msgstr "浮点数{}超过了储存范围"

msgid "token {} is not expected"
msgstr "token{}不是被期望的"
msgstr "token {}不是被期望的"

msgid "In module {}"
msgstr "在模块{}中"
Expand Down Expand Up @@ -80,3 +80,6 @@ msgstr "期望{}.但是输入{}"
msgid "Expect type {}.But given type {}"
msgstr "期望类型{}.但是传入类型是{}"

msgid "unclosed comment"
msgstr "未闭合的注释"

1 change: 1 addition & 0 deletions rust/src/base/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub const SYMBOL_REDEFINED: &str = "Symbol {} redefined";
pub const TYPE_NOT_THE_SAME: &str = "Type {} and {} are not the same";
pub const ARGU_NUMBER: &str = "expect {}.But given {}";
pub const EXPECT_TYPE: &str = "Expect type {}.But given type {}";
pub const UNCLODED_COMMENT: &str = "unclosed comment";

#[derive(Debug)]
pub struct ErrorInfo {
Expand Down
32 changes: 19 additions & 13 deletions rust/src/base/stdlib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type StdlibFunc = fn(&mut DynaData) -> RuntimeResult<()>;

#[derive(Clone, Debug)]
pub struct IOType {
pub argvs_type: Vec<RustClass>,
pub argvs_type: Vec<usize>,
pub return_type: TypeAllowNull,
}

Expand All @@ -32,25 +32,25 @@ pub struct RustFunction {
}

impl IOType {
pub fn new(argvs_type: Vec<RustClass>, return_type: TypeAllowNull) -> IOType {
pub fn new(argvs_type: Vec<usize>, return_type: TypeAllowNull) -> IOType {
IOType {
argvs_type,
return_type,
}
}

pub fn check_argvs(&self, argvs: Vec<Type>) -> Result<(), ErrorInfo> {
pub fn check_argvs(&self, argvs: Vec<usize>) -> Result<(), ErrorInfo> {
if argvs.len() != self.argvs_type.len() {
return Err(ErrorInfo::new(
gettextrs::gettext!(ARGU_NUMBER, self.argvs_type.len(), argvs.len()),
gettextrs::gettext(ARGUMENT_ERROR),
));
}
for i in 0..self.argvs_type.len() {
if self.argvs_type[i].is_any() {
if self.argvs_type[i] == 0 {
continue;
}
if self.argvs_type[i].get_id() != argvs[i].get_id() {
if self.argvs_type[i] != argvs[i] {
return Err(ErrorInfo::new(
gettextrs::gettext!(EXPECT_TYPE, self.argvs_type[i], argvs[i]),
gettextrs::gettext(ARGUMENT_ERROR),
Expand Down Expand Up @@ -146,15 +146,16 @@ impl RustClass {
pub fn new(
name: impl Into<String>,
members: HashMap<String, Var>,
functions: HashMap<String, RustFunction>,
functions: Option<HashMap<String, RustFunction>>,
overrides: HashMap<TokenType, IOType>,
id: usize,
) -> RustClass {
RustClass {
name: name.into(),
members,
functions,
functions: functions.unwrap_or_else(|| HashMap::new()),
overrides,
id: 0,
id,
}
}

Expand All @@ -166,8 +167,8 @@ impl RustClass {
self.members.insert(name.into(), attr);
}

pub fn export_info() -> Self {
ANY_TYPE.clone()
pub fn export_info() -> usize {
0
}
}

Expand Down Expand Up @@ -206,6 +207,11 @@ impl Display for RustClass {

thread_local! {
pub static STD_FUNC_TABLE: RefCell<Vec<StdlibFunc>> = RefCell::new(vec![]);
pub static STD_CLASS_TABLE: RefCell<Vec<RustClass>> = RefCell::new(vec![]);
}

pub fn new_class_id() -> usize {
STD_CLASS_TABLE.with(|std| std.borrow().len())
}

impl RustFunction {
Expand All @@ -227,15 +233,15 @@ pub struct Stdlib {
pub name: String,
pub sub_modules: HashMap<String, Stdlib>,
pub functions: HashMap<String, RustFunction>,
pub classes: HashMap<String, RustClass>,
pub classes: HashMap<String, usize>,
}

impl Stdlib {
pub fn new(
name: impl Into<String>,
sub_modules: HashMap<String, Stdlib>,
functions: HashMap<String, RustFunction>,
classes: HashMap<String, RustClass>,
classes: HashMap<String, usize>,
) -> Stdlib {
Stdlib {
name: name.into(),
Expand Down Expand Up @@ -267,6 +273,6 @@ impl Stdlib {

lazy_static! {
pub static ref ANY_TYPE: RustClass =
RustClass::new("any", HashMap::new(), HashMap::new(), HashMap::new());
RustClass::new("any", HashMap::new(), None, HashMap::new(), new_class_id());
pub static ref STDLIB_ROOT: Stdlib = crate::tvm::stdlib::init();
}
9 changes: 3 additions & 6 deletions rust/src/compiler/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ macro_rules! tmp_expe_function_gen {
if let TypeAllowNull::No = ty_now {
return Ok(ty_now)
}
if(ty_now.unwrap().get_id() == ty_after.unwrap().get_id()) {
if(ty_now.unwrap() == ty_after.unwrap()) {
return Ok(ty_now);
}
return try_err!(istry,
Expand Down Expand Up @@ -72,7 +72,7 @@ macro_rules! expr_gen {
if let TypeAllowNull::No = t1 {
return Ok(t1);
}
if t1.unwrap().get_id() != t2.unwrap().get_id() {
if t1.unwrap() != t2.unwrap() {
return try_err!(istry,
Box::new(self.token_lexer.compiler_data.content.clone()),
ErrorInfo::new(gettext!(TYPE_NOT_THE_SAME, t1,
Expand Down Expand Up @@ -160,7 +160,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn opt_args(&mut self) -> AstError<Vec<Type>> {
fn opt_args(&mut self) -> AstError<Vec<usize>> {
let mut ret = vec![];
loop {
let t = self.expr(true);
Expand Down Expand Up @@ -469,9 +469,6 @@ impl<'a> AstBuilder<'a> {
pub fn generate_code(&mut self) -> RunResult<()> {
loop {
let token = self.token_lexer.next_token()?;
if token.tp == TokenType::EndOfLine {
continue;
}
if token.tp == TokenType::EndOfFile {
break;
}
Expand Down
Loading

0 comments on commit e98c232

Please sign in to comment.