From 8debe05479422b61759dc333e49fdcf15ee1b302 Mon Sep 17 00:00:00 2001 From: limuy Date: Wed, 31 Jan 2024 19:29:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E7=B1=BB=E5=9E=8B=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/Cargo.lock | 33 ++++ rust/Cargo.toml | 1 + rust/docs/usage.md | 14 ++ rust/locales/zh_CN/LC_MESSAGES/trans.mo | Bin 1714 -> 1853 bytes rust/locales/zh_CN/LC_MESSAGES/trans.po | 6 + rust/src/base.rs | 1 + rust/src/base/codegen.rs | 2 + rust/src/base/error.rs | 45 +++++ rust/src/base/stdlib.rs | 1 + rust/src/compiler.rs | 10 +- rust/src/compiler/ast.rs | 235 +++++++++++++++--------- rust/src/compiler/scope.rs | 102 +++++++++- rust/src/compiler/token.rs | 49 +++-- rust/src/tvm.rs | 2 + rust/src/tvm/rustlib.rs | 1 + 15 files changed, 392 insertions(+), 110 deletions(-) create mode 100644 rust/src/base/stdlib.rs create mode 100644 rust/src/tvm/rustlib.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 83a1658e..15f5fdca 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -74,6 +74,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "anyhow" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca" + [[package]] name = "autocfg" version = "1.1.0" @@ -528,6 +534,20 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" +[[package]] +name = "llvm-sys" +version = "170.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed90f72df5504c0af2e3a08ee7762a4a3e42ec2605811fc19f64879de40c50a" +dependencies = [ + "anyhow", + "cc", + "lazy_static", + "libc", + "regex-lite", + "semver", +] + [[package]] name = "locale_config" version = "0.3.0" @@ -887,6 +907,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e" + [[package]] name = "regex-syntax" version = "0.8.2" @@ -995,6 +1021,12 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" + [[package]] name = "serde" version = "1.0.196" @@ -1232,6 +1264,7 @@ dependencies = [ "downcast-rs", "gettext-rs", "lazy_static", + "llvm-sys", "num-bigint", "rand", "reqwest", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index a79ad497..84376d41 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -19,6 +19,7 @@ lazy_static = "1.4.0" num-bigint = "0.4.4" reqwest = { version = "0.11.23", features = ["json", "multipart"] } tokio = { version = "1.35.1", features = ["full"] } +llvm-sys = "170.0.1" [profile.release] panic = "abort" diff --git a/rust/docs/usage.md b/rust/docs/usage.md index 026f43be..bfba68dd 100644 --- a/rust/docs/usage.md +++ b/rust/docs/usage.md @@ -206,3 +206,17 @@ func add(T a, T b) -> T { return a + b; } ``` + +## module + +You can import by the following ways: + +```go +import "a.b.c" +``` + +Or: + +```go +import "a/b/c" +``` diff --git a/rust/locales/zh_CN/LC_MESSAGES/trans.mo b/rust/locales/zh_CN/LC_MESSAGES/trans.mo index e619d2ddfae6e3052682dbab90a00f9410970b64..f77a039d89b5101445d329a291e882433bb30789 100644 GIT binary patch delta 651 zcmY+>OG`pQ6u|K@wU=pSZ-|--p@JgIP0>myXsusB>Oz||Oo$K>+C>J^gAl4!)KW@_ zC|b9%FA!lHrOZ{Eh*tfN-WDA=_czYman783?R;=03vSzyB6`Vw@`dz}Cl(&WRGm_7 z=*0o_V+)3`1H-t4+vvnR4&t-9{$uL0D&=5)*mM&8N+s1C1KE(kCOpLkyhI;nu^o#z zgI_p`<2I#6Fo070CU#*OTk!(ry&IJMuc+}8UFf!xoUeu$1ex%mY}`SO8I+B8rg@Z` z7fdTS%kOWLPE6O=))!I!CxBA$vN?Z@QqVa{r=L)BzWQL$hYqeSE%KOpQN98N{|mXT z94K9qki+B?Nl1ax1&JP#?yF{!8mrOBvy+rg%jcSq8_J;))KQIY(?8q{q-EAz*%Gvj z1-I4>9Z%>`c%@3z(BVi-$5su!5n3~ptS>~Pk!Wt-nyS-pSNEl}-FTw3pNc1nw|k{@ RO4a7dhne?m_TbT8`2|%YP*(r| delta 530 zcmY+>Jxjw-6o>JXwAQz#)%t=3wGly_>Y$5I2Ll}h2SInitsn|P7ZIwHgT+N$`T?r5 z9Rxve6cJ}92R9u=S0|r;dL2A)`b&C~+;h&o%UuWc*FyTjh*5H!d?F{vLysTg3kUEU zC(-xKvN(l9SjH8MFu(?uu<6!sozK|M|8LGujLhox!$mg>ODVGjtl}UZ;5;^P7VmKy z-*F6swAl#GU>+-|=T=eg?_-E3n8Pb9;0KBekK%{TG@H12Xn78c#atK@~s) tNx}N4jzZB(>KGJ!--byY?Z2qT@opT}cEasiyW%f) -> std::fmt::Result { + write!(f, "") + } +} + +impl LightFakeError { + pub fn new() -> LightFakeError { + LightFakeError {} + } +} + +pub struct LightFakeContent {} + +impl ErrorContent for LightFakeError { + fn get_module_name(&self) -> &str { + "" + } + fn get_line(&self) -> usize { + 0 + } +} + +impl LightFakeContent { + pub fn new() -> LightFakeContent { + LightFakeContent {} + } +} + +impl From for RuntimeError { + fn from(_: LightFakeError) -> RuntimeError { + RuntimeError::new( + Box::new(LightFakeError::new()), + ErrorInfo::new("".to_string(), "".to_string()), + ) + } +} + pub type RunResult = Result; diff --git a/rust/src/base/stdlib.rs b/rust/src/base/stdlib.rs new file mode 100644 index 00000000..8474a5bd --- /dev/null +++ b/rust/src/base/stdlib.rs @@ -0,0 +1 @@ +pub const STDLIB_LIST: Vec = vec![]; diff --git a/rust/src/compiler.rs b/rust/src/compiler.rs index cd808f5e..f729a2b0 100644 --- a/rust/src/compiler.rs +++ b/rust/src/compiler.rs @@ -14,7 +14,7 @@ use std::fmt::Display; use std::io::BufRead; use std::{fs, io, vec}; -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum InputSource { File(String), StringInternal, @@ -133,6 +133,10 @@ pub struct ValuePool { const INT_VAL_POOL_ZERO: usize = 0; const INT_VAL_POOL_ONE: usize = 1; +const INT_ID_POS: usize = 0; +const FLOAT_ID_POS: usize = 1; +const BOOL_ID_POS: usize = 2; +const STR_ID_POS: usize = 3; macro_rules! gen_add_funcs { ($($func_name:ident => ($const_pool:ident, $id_pool:ident, $type:ty)),*) => { @@ -164,6 +168,10 @@ impl ValuePool { }; ret.add_int(0); ret.add_int(1); + ret.add_id("int".to_string()); + ret.add_id("float".to_string()); + ret.add_id("bool".to_string()); + ret.add_id("str".to_string()); ret } diff --git a/rust/src/compiler/ast.rs b/rust/src/compiler/ast.rs index 60acbf4c..f521296f 100644 --- a/rust/src/compiler/ast.rs +++ b/rust/src/compiler/ast.rs @@ -1,6 +1,6 @@ -use super::scope::SymScope; use super::token::TokenType; -use super::{token::Token, TokenLex}; +use super::TokenLex; +use super::{scope::*, InputSource}; use crate::base::codegen::{Inst, Opcode, NO_ARG}; use crate::base::{codegen::StaticData, error::*}; use gettextrs::gettext; @@ -13,49 +13,65 @@ pub struct AstBuilder<'a> { self_scope: Rc>, } -#[derive(PartialEq, Debug)] -enum LexState { - Success, - Failure, -} - -type AstError = RunResult; +type AstError = RunResult; -macro_rules! Trythrow { - ($istry:expr, $($error_info:expr),*) => { - { - if $istry { - Ok(LexState::Failure) +macro_rules! TryErr { + ($istry: expr, $($argvs:expr),*) => { + {if $istry { + Err(LightFakeError::new().into()) } else { - Err(RuntimeError::new( - $($error_info),* - )) - } + Err(RuntimeError::new($($argvs),*)) } + } }; } -/// there are a log of similar operators to be generated -macro_rules! ExprGen { - ($funcname:ident, $tmpfuncname:ident, $next_item_func:ident, $($accepted_token:path => $add_opcode:path),*) => { - fn $tmpfuncname(&mut self, istry: bool) -> AstError { +macro_rules! TmpExpeFunctionGen { + ($tmpfuncname:ident, $next_item_func:ident, $($accepted_token:path => $add_opcode:path),*) => { + fn $tmpfuncname(&mut self, istry: bool) -> AstError { let next_sym = self.token_lexer.next_token()?; match next_sym.tp { $($accepted_token => { - self.$next_item_func(istry)?; + let ty_now = self.$next_item_func(istry)?; self.staticdata.inst.push(Inst::new($add_opcode, NO_ARG)); - self.$tmpfuncname(istry)?; + let ty_after = self.$tmpfuncname(istry)?; + if let TypeAllowNull::No = ty_after { + return Ok(ty_now); + } + if(ty_now == ty_after) { + return Ok(ty_now); + } + return TryErr!(istry, + Box::new(self.token_lexer.compiler_data.content.clone()), + ErrorInfo::new(gettext!(TYPE_NOT_THE_SAME, self.get_type_name(ty_now), + self.get_type_name(ty_after)), gettextrs::gettext(TYPE_ERROR))) })* _ => { self.token_lexer.next_back(next_sym); + return Ok(TypeAllowNull::No); } } - Ok(LexState::Success) } - fn $funcname(&mut self, istry: bool) -> AstError { - self.$next_item_func(istry)?; - self.$tmpfuncname(istry)?; - Ok(LexState::Success) + }; +} + +/// there are a log of similar operators to be generated +macro_rules! ExprGen { + ($funcname:ident, $tmpfuncname:ident, $next_item_func:ident, $($accepted_token:path => $add_opcode:path),*) => { + TmpExpeFunctionGen!($tmpfuncname, $next_item_func, $($accepted_token => $add_opcode),*); + fn $funcname(&mut self, istry: bool) -> AstError { + let t1 = self.$next_item_func(istry)?; + let t2 = self.$tmpfuncname(istry)?; + if let TypeAllowNull::No = t2 { + return Ok(t1); + } + if t1 != t2 { + return TryErr!(istry, + Box::new(self.token_lexer.compiler_data.content.clone()), + ErrorInfo::new(gettext!(TYPE_NOT_THE_SAME, self.get_type_name(t1), + self.get_type_name(t2)), gettextrs::gettext(TYPE_ERROR))) + } + Ok(t1) } }; } @@ -70,6 +86,15 @@ impl<'a> AstBuilder<'a> { } } + fn get_type_name(&self, ty: TypeAllowNull) -> String { + match ty { + TypeAllowNull::Yes(ty) => { + self.token_lexer.compiler_data.const_pool.id_name[ty.name].clone() + } + TypeAllowNull::No => "null".to_string(), + } + } + ExprGen!(expr9, expr9_, factor, TokenType::Power => Opcode::Power); ExprGen!(expr8, expr8_, expr9, TokenType::Mul => Opcode::Mul, TokenType::Div => Opcode::Div, @@ -92,19 +117,19 @@ impl<'a> AstBuilder<'a> { ExprGen!(expr1, expr1_, expr2, TokenType::And => Opcode::And); ExprGen!(expr, expr_, expr1, TokenType::Or => Opcode::Or); - fn while_lex(&mut self, istry: bool) -> AstError { - Ok(LexState::Success) + fn while_lex(&mut self, istry: bool) -> AstError { + todo!() } - fn for_lex(&mut self, istry: bool) -> AstError { - Ok(LexState::Success) + fn for_lex(&mut self, istry: bool) -> AstError { + todo!() } - fn generate_block(&mut self, istry: bool) -> AstError { - Ok(LexState::Success) + fn generate_block(&mut self, istry: bool) -> AstError { + todo!() } - fn check_next_token(&mut self, tp: TokenType) -> AstError { + fn check_next_token(&mut self, tp: TokenType) -> AstError<()> { let next_sym = self.token_lexer.next_token()?; if next_sym.tp != tp { return Err(RuntimeError::new( @@ -115,15 +140,15 @@ impl<'a> AstBuilder<'a> { ), )); } - Ok(LexState::Success) + Ok(()) } - fn val(&mut self, istry: bool) -> AstError { + fn val(&mut self, istry: bool) -> AstError { let t = self.token_lexer.next_token()?; if t.tp == TokenType::ID { let idx = t.data.unwrap(); if self.self_scope.as_ref().borrow().get_sym_idx(idx).is_none() { - return Trythrow!( + return TryErr!( istry, Box::new(self.token_lexer.compiler_data.content.clone()), ErrorInfo::new( @@ -135,13 +160,15 @@ impl<'a> AstBuilder<'a> { ) ); } - self.staticdata.inst.push(Inst::new( - Opcode::LoadLocal, - self.self_scope.as_ref().borrow_mut().insert_sym(idx), - )); + let varidx = self.self_scope.as_ref().borrow_mut().insert_sym(idx); + self.staticdata + .inst + .push(Inst::new(Opcode::LoadLocal, varidx)); + let tt = self.self_scope.as_ref().borrow().get_type(varidx); + return Ok(TypeAllowNull::Yes(tt)); } else { self.token_lexer.next_back(t.clone()); - return Trythrow!( + return TryErr!( istry, Box::new(self.token_lexer.compiler_data.content.clone()), ErrorInfo::new( @@ -150,19 +177,11 @@ impl<'a> AstBuilder<'a> { ) ); } - Ok(LexState::Success) } - fn item(&mut self, istry: bool) -> AstError { - match self.val(true) { - Err(e) => { - return Err(e); - } - Ok(v) => { - if v == LexState::Success { - return Ok(LexState::Success); - } - } + fn item(&mut self, istry: bool) -> AstError { + if let Ok(v) = self.val(true) { + return Ok(v); } let t = self.token_lexer.next_token()?; match t.tp { @@ -170,19 +189,22 @@ impl<'a> AstBuilder<'a> { self.staticdata .inst .push(Inst::new(Opcode::LoadInt, t.data.unwrap())); + return Ok(TypeAllowNull::Yes(INT_TYPE.clone())); } TokenType::FloatValue => { self.staticdata .inst .push(Inst::new(Opcode::LoadFloat, t.data.unwrap())); + return Ok(TypeAllowNull::Yes(FLOAT_TYPE.clone())); } TokenType::StringValue => { self.staticdata .inst .push(Inst::new(Opcode::LoadString, t.data.unwrap())); + return Ok(TypeAllowNull::Yes(STR_TYPE.clone())); } _ => { - return Trythrow!( + return TryErr!( istry, Box::new(self.token_lexer.compiler_data.content.clone()), ErrorInfo::new( @@ -192,54 +214,87 @@ impl<'a> AstBuilder<'a> { ); } } - Ok(LexState::Success) } - fn factor(&mut self, istry: bool) -> AstError { + fn factor(&mut self, istry: bool) -> AstError { let next_token = self.token_lexer.next_token()?; match next_token.tp { TokenType::Sub => { - self.factor(istry)?; + let ret = self.factor(istry)?; self.staticdata .inst - .push(Inst::new(Opcode::SelfNegative, NO_ARG)) + .push(Inst::new(Opcode::SelfNegative, NO_ARG)); + return Ok(ret); } TokenType::BitNot => { - self.factor(istry)?; + let ret = self.factor(istry)?; self.staticdata.inst.push(Inst::new(Opcode::BitNot, NO_ARG)); + return Ok(ret); } TokenType::Not => { - self.factor(istry)?; + let ret = self.factor(istry)?; self.staticdata.inst.push(Inst::new(Opcode::Not, NO_ARG)); + return Ok(ret); } TokenType::Add => { - self.factor(istry)?; + return Ok(self.factor(istry)?); } TokenType::LeftSmallBrace => { - self.expr(istry)?; + let ret = self.expr(istry)?; self.check_next_token(TokenType::RightSmallBrace)?; + return Ok(ret); } _ => { self.token_lexer.next_back(next_token); - self.item(istry)?; + return Ok(self.item(istry)?); } } - Ok(LexState::Success) } - fn def_func(&mut self, istry: bool) -> RunResult { - Ok(LexState::Success) + fn def_func(&mut self, istry: bool) -> AstError<()> { + Ok(()) } - fn def_class(&mut self, istry: bool) -> RunResult { - Ok(LexState::Success) + fn def_class(&mut self, istry: bool) -> AstError<()> { + Ok(()) } - fn func_call(&mut self, istry: bool) -> RunResult { - Ok(LexState::Success) + fn func_call(&mut self, istry: bool) -> AstError<()> { + Ok(()) + } + + fn import_module(&mut self, istry: bool) -> AstError<()> { + let mut path = self.token_lexer.next_token()?; + if path.tp != TokenType::StringValue { + return TryErr!( + istry, + Box::new(self.token_lexer.compiler_data.content.clone()), + ErrorInfo::new( + gettext!(UNEXPECTED_TOKEN, path.tp.to_string()), + gettextrs::gettext(SYNTAX_ERROR), + ) + ); + } + let path = std::path::PathBuf::from( + self.token_lexer.compiler_data.const_pool.id_str[path.data.unwrap()] + .clone() + .replace('.', "/"), + ); + // the standard library first + + if let InputSource::File(now_module_path) = + self.token_lexer.compiler_data.option.inputsource.clone() + { + let mut now_module_path = std::path::PathBuf::from(now_module_path); + now_module_path.pop(); + now_module_path = now_module_path.join(path); + if now_module_path.exists() {} + } + Ok(()) } - fn statement(&mut self, t: Token) -> RunResult<()> { + fn statement(&mut self) -> RunResult<()> { + let t = self.token_lexer.next_token()?; match t.tp { super::token::TokenType::Func => { self.def_func(false)?; @@ -299,36 +354,37 @@ impl<'a> AstBuilder<'a> { .inst .push(Inst::new(Opcode::StoreLocal, var_idx)) } - super::token::TokenType::LeftSmallBrace => { - self.func_call(false)?; - } _ => { + self.token_lexer.next_back(tt.clone()); return Err(RuntimeError::new( Box::new(self.token_lexer.compiler_data.content.clone()), ErrorInfo::new( gettext!(UNEXPECTED_TOKEN, tt.tp.to_string()), gettextrs::gettext(SYNTAX_ERROR), ), - )) + )); } } } _ => {} } self.token_lexer.next_back(t.clone()); - match self.expr(true) { - Ok(_) => {} - Err(_) => { - return Err(RuntimeError::new( - Box::new(self.token_lexer.compiler_data.content.clone()), - ErrorInfo::new( - gettext!(UNEXPECTED_TOKEN, t.tp.to_string()), - gettextrs::gettext(SYNTAX_ERROR), - ), - )) + if let Ok(_) = self.expr(true) { + return Ok(()); + } + if let Ok(_) = self.val(false) { + let t = self.token_lexer.next_token()?; + if t.tp == TokenType::LeftSmallBrace { + // func call } } - Ok(()) + return Err(RuntimeError::new( + Box::new(self.token_lexer.compiler_data.content.clone()), + ErrorInfo::new( + gettext!(UNEXPECTED_TOKEN, t.tp.to_string()), + gettextrs::gettext(SYNTAX_ERROR), + ), + )); } pub fn generate_code(&mut self) -> RunResult<()> { @@ -340,7 +396,8 @@ impl<'a> AstBuilder<'a> { if token.tp == super::token::TokenType::EndOfFile { break; } - self.statement(token)?; + self.token_lexer.next_back(token); + self.statement()?; } return Ok(()); } diff --git a/rust/src/compiler/scope.rs b/rust/src/compiler/scope.rs index 147cac21..8273720f 100644 --- a/rust/src/compiler/scope.rs +++ b/rust/src/compiler/scope.rs @@ -1,5 +1,7 @@ use lazy_static::lazy_static; -use std::{cell::RefCell, collections::HashMap, rc::Rc}; +use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc}; + +use super::{BOOL_ID_POS, FLOAT_ID_POS, INT_ID_POS, STR_ID_POS}; lazy_static! { static ref VAR_TYPE: Vec = vec![ @@ -11,10 +13,81 @@ lazy_static! { ]; } +#[derive(Clone, Debug, PartialEq)] +pub enum TypeAllowNull { + Yes(Type), + No, +} + +/// Manager of function +#[derive(Clone, Debug, PartialEq)] +pub struct Function { + args_type: Vec, + return_type: TypeAllowNull, +} + +impl Function { + pub fn new(return_type: TypeAllowNull) -> Self { + Self { + args_type: vec![], + return_type, + } + } + + pub fn add_argv() {} +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Var { + ty: Function, +} + +impl Var { + pub fn new(ty: Function) -> Self { + Self { ty } + } +} + +/// Manager of type +#[derive(Clone, Debug, PartialEq)] +pub struct Type { + attr: Vec, + funcs: Vec, + pub name: usize, +} + +impl Type { + pub fn new(name: usize) -> Self { + Self { + attr: vec![], + funcs: vec![], + name, + } + } + + pub fn add_attr(&mut self, attr: Var) { + self.attr.push(attr); + } + + pub fn add_func(&mut self, f: Function) { + self.funcs.push(f); + } +} +lazy_static! { + pub static ref INT_TYPE: Type = Type::new(INT_ID_POS); + pub static ref FLOAT_TYPE: Type = Type::new(INT_ID_POS); + pub static ref STR_TYPE: Type = Type::new(INT_ID_POS); + pub static ref BOOL_TYPE: Type = Type::new(INT_ID_POS); +} + pub struct SymScope { prev_scope: Option>>, sym_map: HashMap, scope_sym_id: usize, + types: HashMap, + funcs: HashMap, + vars: HashMap, + native_funcs: HashMap, } impl SymScope { @@ -23,12 +96,21 @@ impl SymScope { prev_scope: prev_scope.clone(), sym_map: HashMap::new(), scope_sym_id: 0, + types: HashMap::new(), + funcs: HashMap::new(), + vars: HashMap::new(), + native_funcs: HashMap::new(), }; match prev_scope { Some(prev_scope) => { ret.scope_sym_id = prev_scope.as_ref().borrow().scope_sym_id; } - None => {} + None => { + ret.add_type(INT_TYPE.clone()); + ret.add_type(FLOAT_TYPE.clone()); + ret.add_type(BOOL_TYPE.clone()); + ret.add_type(STR_TYPE.clone()); + } } ret } @@ -66,6 +148,22 @@ impl SymScope { } } + pub fn add_func(&mut self, id: usize, f: Function) { + self.funcs.insert(id, f); + } + + pub fn add_var(&mut self, id: usize, v: Var) { + self.vars.insert(id, v); + } + + pub fn add_type(&mut self, t: Type) { + self.types.insert(t.name, t); + } + + pub fn get_type(&self, id: usize) -> Type { + return self.types.get(&id).unwrap().clone(); + } + pub fn get_scope_last_idx(&self) -> usize { self.scope_sym_id } diff --git a/rust/src/compiler/token.rs b/rust/src/compiler/token.rs index 98ab7262..a0f74610 100644 --- a/rust/src/compiler/token.rs +++ b/rust/src/compiler/token.rs @@ -812,7 +812,10 @@ mod tests { use std::{collections::HashSet, fmt::Debug, hash::Hash}; use super::*; - use crate::compiler::{Float, InputSource, Option, Pool, INT_VAL_POOL_ONE, INT_VAL_POOL_ZERO}; + use crate::compiler::{ + Float, InputSource, Option, Pool, INT_ID_POS, INT_VAL_POOL_ONE, INT_VAL_POOL_ZERO, + STR_ID_POS, + }; macro_rules! gen_test_token_env { ($test_string:expr, $env_name:ident) => { @@ -995,16 +998,16 @@ func main() { Token::new(TokenType::Import, None), Token::new(TokenType::StringValue, Some(0)), Token::new(TokenType::Func, None), - Token::new(TokenType::ID, Some(0)), + Token::new(TokenType::ID, Some(4)), Token::new(TokenType::LeftSmallBrace, None), - Token::new(TokenType::ID, Some(1)), - Token::new(TokenType::ID, Some(2)), + Token::new(TokenType::ID, Some(INT_ID_POS)), + Token::new(TokenType::ID, Some(5)), Token::new(TokenType::RightSmallBrace, None), Token::new(TokenType::Arrow, None), Token::new(TokenType::ID, Some(3)), Token::new(TokenType::LeftBigBrace, None), Token::new(TokenType::If, None), - Token::new(TokenType::ID, Some(2)), + Token::new(TokenType::ID, Some(5)), Token::new(TokenType::Mod, None), Token::new(TokenType::IntValue, Some(2)), Token::new(TokenType::Equal, None), @@ -1020,25 +1023,25 @@ func main() { Token::new(TokenType::RightBigBrace, None), Token::new(TokenType::RightBigBrace, None), Token::new(TokenType::Func, None), - Token::new(TokenType::ID, Some(4)), + Token::new(TokenType::ID, Some(6)), Token::new(TokenType::LeftSmallBrace, None), Token::new(TokenType::RightSmallBrace, None), Token::new(TokenType::LeftBigBrace, None), - Token::new(TokenType::ID, Some(5)), + Token::new(TokenType::ID, Some(7)), Token::new(TokenType::LeftSmallBrace, None), Token::new(TokenType::StringValue, Some(3)), Token::new(TokenType::RightSmallBrace, None), - Token::new(TokenType::ID, Some(6)), + Token::new(TokenType::ID, Some(8)), Token::new(TokenType::Store, None), - Token::new(TokenType::ID, Some(0)), + Token::new(TokenType::ID, Some(4)), Token::new(TokenType::LeftSmallBrace, None), - Token::new(TokenType::ID, Some(7)), + Token::new(TokenType::ID, Some(9)), Token::new(TokenType::LeftSmallBrace, None), Token::new(TokenType::RightSmallBrace, None), Token::new(TokenType::RightSmallBrace, None), - Token::new(TokenType::ID, Some(5)), + Token::new(TokenType::ID, Some(7)), Token::new(TokenType::LeftSmallBrace, None), - Token::new(TokenType::ID, Some(6)), + Token::new(TokenType::ID, Some(8)), Token::new(TokenType::RightSmallBrace, None), Token::new(TokenType::RightBigBrace, None), ], @@ -1051,11 +1054,11 @@ func main() { check( &mut t, vec![ - Token::new(TokenType::ID, Some(0)), - Token::new(TokenType::ID, Some(1)), - Token::new(TokenType::ID, Some(2)), - Token::new(TokenType::ID, Some(3)), Token::new(TokenType::ID, Some(4)), + Token::new(TokenType::ID, Some(5)), + Token::new(TokenType::ID, Some(6)), + Token::new(TokenType::ID, Some(7)), + Token::new(TokenType::ID, Some(8)), ], ); check_pool( @@ -1065,6 +1068,10 @@ func main() { String::from("_fuck"), String::from("天帝abc"), String::from("abc天帝"), + "int".to_string(), + "float".to_string(), + "bool".to_string(), + "str".to_string(), ], &t.compiler_data.const_pool.name_pool, ); @@ -1090,12 +1097,18 @@ func main() { &mut t, vec![ Token::new(TokenType::IntValue, Some(2)), - Token::new(TokenType::ID, Some(0)), + Token::new(TokenType::ID, Some(4)), ], ); check_pool(vec![0xabc, 0, 1], &t.compiler_data.const_pool.const_ints); check_pool( - vec![String::from("hds")], + vec![ + "hds".to_string(), + "int".to_string(), + "float".to_string(), + "bool".to_string(), + "str".to_string(), + ], &t.compiler_data.const_pool.name_pool, ); } diff --git a/rust/src/tvm.rs b/rust/src/tvm.rs index cf77fb65..4271443c 100644 --- a/rust/src/tvm.rs +++ b/rust/src/tvm.rs @@ -2,6 +2,7 @@ mod algo; mod def; mod function; mod gc; +mod rustlib; mod types; use self::types::trcfloat::TrcFloat; @@ -194,6 +195,7 @@ impl<'a> Vm<'a> { codegen::Opcode::SelfNegative => { unary_opcode!(self_negative, self); } + codegen::Opcode::CallNative => {} } self.pc += 1; } diff --git a/rust/src/tvm/rustlib.rs b/rust/src/tvm/rustlib.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/rust/src/tvm/rustlib.rs @@ -0,0 +1 @@ +