Skip to content

Commit

Permalink
fix(compiler):make compiler extern function id become global
Browse files Browse the repository at this point in the history
  • Loading branch information
limuy2022 committed Apr 10, 2024
1 parent b1ac492 commit e2e32ec
Show file tree
Hide file tree
Showing 17 changed files with 253 additions and 93 deletions.
3 changes: 2 additions & 1 deletion derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ pub fn trc_function(attr: TokenStream, input: TokenStream) -> TokenStream {
}
}
}
input.sig.output = parse_str::<syn::ReturnType>("-> RuntimeResult<()>").expect("err1");
input.sig.output =
parse_str::<syn::ReturnType>("-> libcore::ErrorInfoResult<()>").expect("err1");
let return_stmt = parse_str::<Stmt>("return Ok(());").expect("err2");
for i in input.block.stmts {
if let Stmt::Expr(Expr::Return(reexpr), ..) = i.clone() {
Expand Down
6 changes: 6 additions & 0 deletions libcore/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ pub struct StaticData {
pub line_table: Vec<usize>,
pub type_list: Vec<Vec<VmStackType>>,
pub function_split: Option<usize>,
pub dll_module_should_loaded: Vec<String>,
}

impl StaticData {
Expand All @@ -242,4 +243,9 @@ impl StaticData {
pub fn get_next_opcode_id(&self) -> usize {
self.inst.len()
}

#[inline]
pub fn add_dll_module(&mut self, module_name: String) {
self.dll_module_should_loaded.push(module_name);
}
}
4 changes: 2 additions & 2 deletions libcore/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,5 +153,5 @@ impl From<LightFakeError> for RuntimeError {
}
}

pub type RunResult<T> = Result<T, RuntimeError>;
pub type RuntimeResult<T> = Result<T, ErrorInfo>;
pub type RuntimeResult<T> = Result<T, RuntimeError>;
pub type ErrorInfoResult<T> = Result<T, ErrorInfo>;
2 changes: 1 addition & 1 deletion libcore/src/libbasic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{

use super::{codegen::Opcode, error::*};

pub type RustlibFunc = fn(&mut DynaData) -> RuntimeResult<()>;
pub type RustlibFunc = fn(&mut DynaData) -> ErrorInfoResult<()>;

pub type ScopeAllocIdTy = usize;
pub type TypeAllowNull = Option<TyIdxTy>;
Expand Down
22 changes: 11 additions & 11 deletions libcore/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub use trcstr::*;
macro_rules! batch_unsupported_operators {
($($traie_name:ident => $oper_name:expr),*) => {
$(
fn $traie_name(&self, _:*mut dyn TrcObj, _: &mut $crate::gc::GcMgr) -> RuntimeResult<*mut dyn TrcObj> {
fn $traie_name(&self, _:*mut dyn TrcObj, _: &mut $crate::gc::GcMgr) -> ErrorInfoResult<*mut dyn TrcObj> {
return Err(ErrorInfo::new(
t!(
OPERATOR_IS_NOT_SUPPORT,
Expand All @@ -39,7 +39,7 @@ macro_rules! impl_oper {
// for unsupported operator in rust
($trait_oper_fn_name:ident, $oper:ident, $error_oper_name:expr, $self_type:ident, $newtype:ident, $whether_throw_error:tt) => {
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn $trait_oper_fn_name(&self, other:*mut dyn TrcObj, gc: &mut $crate::gc::GcMgr) -> $crate::error::RuntimeResult<*mut dyn TrcObj> {
fn $trait_oper_fn_name(&self, other:*mut dyn TrcObj, gc: &mut $crate::gc::GcMgr) -> $crate::error::ErrorInfoResult<*mut dyn TrcObj> {
unsafe {
match (*other).downcast_ref::<$self_type>() {
Some(v) => {
Expand All @@ -55,7 +55,7 @@ macro_rules! impl_oper {
// for supported operator in rust
($trait_oper_fn_name:ident, $oper:tt, $error_oper_name:expr, $self_type:ident, $newtype:ident) => {
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn $trait_oper_fn_name(&self, other:*mut dyn TrcObj, gc: &mut $crate::gc::GcMgr) -> $crate::error::RuntimeResult<*mut dyn TrcObj> {
fn $trait_oper_fn_name(&self, other:*mut dyn TrcObj, gc: &mut $crate::gc::GcMgr) -> $crate::error::ErrorInfoResult<*mut dyn TrcObj> {
unsafe {
match (*other).downcast_ref::<$self_type>() {
Some(v) => {
Expand All @@ -82,23 +82,23 @@ macro_rules! batch_impl_opers {
#[macro_export]
macro_rules! impl_single_oper {
($trait_oper_fn_name:ident, $oper:tt, $error_oper_name:expr, $self_type:ident, $newtype:ident) => {
fn $trait_oper_fn_name(&self, gc: &mut $crate::gc::GcMgr) -> $crate::error::RuntimeResult<*mut dyn TrcObj> {
fn $trait_oper_fn_name(&self, gc: &mut $crate::gc::GcMgr) -> $crate::error::ErrorInfoResult<*mut dyn TrcObj> {
return Ok(gc.alloc($newtype::new($oper self._value)));
}
};
}

macro_rules! gen_interface {
($funcname:ident, 2) => {
pub fn $funcname(dydata: &mut DynaData) -> RuntimeResult<()> {
pub fn $funcname(dydata: &mut DynaData) -> ErrorInfoResult<()> {
let t2 = dydata.pop_data::<*mut dyn TrcObj>();
let t1 = dydata.pop_data::<*mut dyn TrcObj>();
let tmp = unsafe { (*t1).$funcname(t2, dydata.get_gc())? };
dydata.push_data(tmp);
Ok(())
}
paste::paste!(
pub fn [<$funcname _without_pop>](dydata: &mut DynaData) -> RuntimeResult<()> {
pub fn [<$funcname _without_pop>](dydata: &mut DynaData) -> ErrorInfoResult<()> {
let t2 = dydata.pop_data::<*mut dyn TrcObj>();
let t1 = dydata.read_top_data::<*mut dyn TrcObj>();
let tmp = unsafe { (*t1).$funcname(t2, dydata.get_gc())? };
Expand All @@ -108,14 +108,14 @@ macro_rules! gen_interface {
);
};
($funcname:ident, 1) => {
pub fn $funcname(dydata: &mut DynaData) -> RuntimeResult<()> {
pub fn $funcname(dydata: &mut DynaData) -> ErrorInfoResult<()> {
let t1 = dydata.pop_data::<*mut dyn TrcObj>();
let tmp = unsafe { (*t1).$funcname(dydata.get_gc())? };
dydata.push_data(tmp);
Ok(())
}
paste::paste!(
pub fn [<$funcname _without_pop>](dydata: &mut DynaData) -> RuntimeResult<()> {
pub fn [<$funcname _without_pop>](dydata: &mut DynaData) -> ErrorInfoResult<()> {
let t1 = dydata.read_top_data::<*mut dyn TrcObj>();
let tmp = unsafe { (*t1).$funcname(dydata.get_gc())? };
dydata.push_data(tmp);
Expand Down Expand Up @@ -168,7 +168,7 @@ pub trait TrcObj: Downcast + std::fmt::Display + Debug + TrcObjClone {
bit_right_shift => ">>"
);

fn not(&self, _: &mut GcMgr) -> RuntimeResult<*mut dyn TrcObj> {
fn not(&self, _: &mut GcMgr) -> ErrorInfoResult<*mut dyn TrcObj> {
Err(ErrorInfo::new(
t!(
OPERATOR_IS_NOT_SUPPORT,
Expand All @@ -179,7 +179,7 @@ pub trait TrcObj: Downcast + std::fmt::Display + Debug + TrcObjClone {
))
}

fn bit_not(&self, _: &mut GcMgr) -> RuntimeResult<*mut dyn TrcObj> {
fn bit_not(&self, _: &mut GcMgr) -> ErrorInfoResult<*mut dyn TrcObj> {
Err(ErrorInfo::new(
t!(
OPERATOR_IS_NOT_SUPPORT,
Expand All @@ -190,7 +190,7 @@ pub trait TrcObj: Downcast + std::fmt::Display + Debug + TrcObjClone {
))
}

fn self_negative(&self, _: &mut GcMgr) -> RuntimeResult<*mut dyn TrcObj> {
fn self_negative(&self, _: &mut GcMgr) -> ErrorInfoResult<*mut dyn TrcObj> {
Err(ErrorInfo::new(
t!(
OPERATOR_IS_NOT_SUPPORT,
Expand Down
4 changes: 2 additions & 2 deletions libcore/src/types/trcstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl TrcObj for TrcStr {
}

#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn add(&self, other: *mut dyn TrcObj, gc: &mut GcMgr) -> RuntimeResult<*mut dyn TrcObj> {
fn add(&self, other: *mut dyn TrcObj, gc: &mut GcMgr) -> ErrorInfoResult<*mut dyn TrcObj> {
unsafe { self.add_impl(other, gc) }
}
}
Expand All @@ -53,7 +53,7 @@ impl TrcStr {
&self,
other: *mut dyn TrcObj,
gc: &mut GcMgr,
) -> RuntimeResult<*mut dyn TrcObj> {
) -> ErrorInfoResult<*mut dyn TrcObj> {
unsafe {
match (*other).downcast_ref::<TrcStr>() {
Some(v) => {
Expand Down
4 changes: 2 additions & 2 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ impl Compiler {
self.input = input;
}

pub fn lex(&mut self) -> RunResult<AstBuilder> {
pub fn lex(&mut self) -> RuntimeResult<AstBuilder> {
let token_lexer = TokenLex::new(self);
let mut ast_builder = AstBuilder::new(token_lexer);
ast_builder.generate_code()?;
Expand All @@ -395,7 +395,7 @@ impl Compiler {
}

#[inline]
pub fn report_compiler_error<T>(&self, info: ErrorInfo) -> RunResult<T> {
pub fn report_compiler_error<T>(&self, info: ErrorInfo) -> RuntimeResult<T> {
Err(RuntimeError::new(Box::new(self.context.clone()), info))
}
}
Expand Down
58 changes: 40 additions & 18 deletions src/compiler/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use super::{
InputSource, TokenLex,
};
use crate::{base::dll::load_module_storage, compiler::token::TokenType::RightBigBrace};
use collection_literals::collection;
use libcore::*;
use rust_i18n::t;
use std::{cell::RefCell, mem::swap, path::PathBuf, rc::Rc};
use std::{cell::RefCell, collections::HashSet, mem::swap, path::PathBuf, rc::Rc};

#[derive(Default)]
struct Cache {
Expand All @@ -36,9 +37,11 @@ pub struct AstBuilder<'a> {
cache: Cache,
// record if the fisrt func is defined
first_func: bool,
modules_dll_dup: HashSet<String>,
modules_dll: Vec<String>,
}

type AstError<T> = RunResult<T>;
type AstError<T> = RuntimeResult<T>;

macro_rules! tmp_expe_function_gen {
($tmpfuncname:ident, $next_item_func:ident, $($accepted_token:path),*) => {
Expand Down Expand Up @@ -111,11 +114,10 @@ macro_rules! expr_gen {

impl<'a> AstBuilder<'a> {
pub fn new(mut token_lexer: TokenLex<'a>) -> Self {
let root_scope = Rc::new(RefCell::new(SymScope::new(None)));
let stdlib_dll = unsafe {
libloading::Library::new(libloading::library_filename("stdlib"))
.expect("without stdlib")
};
let root_scope = Rc::new(RefCell::new(SymScope::new(SymScopePrev::Root)));
let stdlib_dll_name = libloading::library_filename("stdlib");
let stdlib_dll =
unsafe { libloading::Library::new(stdlib_dll_name.clone()).expect("without stdlib") };
let (stdlib, stdstorage) = load_module_storage(&stdlib_dll);
let prelude = stdlib.sub_modules().get("prelude").unwrap();
for i in prelude.functions() {
Expand Down Expand Up @@ -159,13 +161,16 @@ impl<'a> AstBuilder<'a> {
// "{} {} {} {} {}",
// cache.intty_id, cache.floatty_id, cache.charty_id, cache.strty_id, cache.boolty_id
// );
let name_str = stdlib_dll_name.to_str().unwrap().to_owned();
AstBuilder {
token_lexer,
staticdata: StaticData::new(),
self_scope: root_scope,
process_info: lexprocess::LexProcess::new(),
cache,
first_func: false,
modules_dll_dup: collection! {name_str.clone()},
modules_dll: vec![name_str.clone()],
}
}

Expand Down Expand Up @@ -206,6 +211,11 @@ impl<'a> AstBuilder<'a> {

pub fn prepare_get_static(&mut self) -> &StaticData {
self.staticdata.constpool = self.token_lexer.const_pool.store_val_to_vm();
self.staticdata.dll_module_should_loaded.clear();
std::mem::swap(
&mut self.staticdata.dll_module_should_loaded,
&mut self.modules_dll,
);
&self.staticdata
}

Expand Down Expand Up @@ -823,7 +833,9 @@ impl<'a> AstBuilder<'a> {

fn def_class(&mut self) -> AstError<()> {
// new scope
self.self_scope = Rc::new(RefCell::new(SymScope::new(Some(self.self_scope.clone()))));
self.self_scope = Rc::new(RefCell::new(SymScope::new(SymScopePrev::Prev(
self.self_scope.clone(),
))));
self.self_scope.borrow_mut().in_class = true;
let name = self.get_token_checked(TokenType::ID)?.data.unwrap();
let name_id = self.insert_sym_with_error(name)?;
Expand All @@ -846,7 +858,9 @@ impl<'a> AstBuilder<'a> {
.get_token_checked(TokenType::StringValue)?
.data
.unwrap();
// import的路径
let mut path_with_dot = self.token_lexer.const_pool.id_str[tok].clone();
// 具体文件的路径
let mut import_file_path = String::new();
let mut is_dll = false;
if path_with_dot.starts_with("std") {
Expand All @@ -872,12 +886,15 @@ impl<'a> AstBuilder<'a> {
// 优先判断dll
now_module_path.set_file_name(file_name_dll);
if now_module_path.exists() {
// 是dll
is_dll = true;
now_module_path
.to_str()
.unwrap()
.clone_into(&mut import_file_path);
self.add_module(import_file_path.clone())
} else {
// 不是dll,尝试判断trc文件
let file_name_trc = format!("{}{}", file_name.to_str().unwrap(), ".trc");
now_module_path.set_file_name(file_name_trc);
// now_module_path.ex
Expand Down Expand Up @@ -953,8 +970,9 @@ impl<'a> AstBuilder<'a> {
let tmp = self.token_lexer.add_id_token(&import_item_name);
let module_sym_idx: ScopeAllocIdTy = self.insert_sym_with_error(tmp)?;
self.import_module_sym(module);
let sub_module =
Rc::new(RefCell::new(SymScope::new(Some(self.self_scope.clone()))));
let sub_module = Rc::new(RefCell::new(SymScope::new(SymScopePrev::Prev(
self.self_scope.clone(),
))));
self.self_scope
.borrow_mut()
.add_imported_module(module_sym_idx, sub_module.clone());
Expand Down Expand Up @@ -1012,7 +1030,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn store_var(&mut self, name: usize) -> RunResult<()> {
fn store_var(&mut self, name: usize) -> RuntimeResult<()> {
self.expr(false)?;
let var_type = match self.process_info.pop_last_ty() {
Some(v) => v,
Expand All @@ -1024,7 +1042,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn assign_var(&mut self, name: usize) -> RunResult<()> {
fn assign_var(&mut self, name: usize) -> RuntimeResult<()> {
self.expr(false)?;
let var_type = match self.process_info.pop_last_ty() {
Some(v) => v,
Expand Down Expand Up @@ -1063,7 +1081,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn lex_condit(&mut self) -> RunResult<()> {
fn lex_condit(&mut self) -> RuntimeResult<()> {
self.expr(false)?;
match self.process_info.pop_last_ty() {
None => {
Expand All @@ -1078,7 +1096,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn if_lex(&mut self) -> RunResult<()> {
fn if_lex(&mut self) -> RuntimeResult<()> {
self.lex_condit()?;
self.get_token_checked(TokenType::LeftBigBrace)?;
// 最后需要跳转地址
Expand Down Expand Up @@ -1115,7 +1133,7 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

fn statement(&mut self) -> RunResult<()> {
fn statement(&mut self) -> RuntimeResult<()> {
let t = self.token_lexer.next_token()?;
match t.tp {
TokenType::Continue => {
Expand Down Expand Up @@ -1245,7 +1263,7 @@ impl<'a> AstBuilder<'a> {

/// # Return
/// 返回函数的首地址
fn lex_function(&mut self, funcid: usize, body: &FuncBodyTy) -> RunResult<(usize, usize)> {
fn lex_function(&mut self, funcid: usize, body: &FuncBodyTy) -> RuntimeResult<(usize, usize)> {
if !self.first_func {
// 如果不是第一个函数,在末尾加上结束主程序的指令
self.first_func = true;
Expand All @@ -1263,7 +1281,7 @@ impl<'a> AstBuilder<'a> {
let io = func_obj.get_io();
let tmp = self.self_scope.clone();
// 解析参数
self.self_scope = Rc::new(RefCell::new(SymScope::new(Some(tmp.clone()))));
self.self_scope = Rc::new(RefCell::new(SymScope::new(SymScopePrev::Prev(tmp.clone()))));
self.self_scope.borrow_mut().func_io = Some(io.return_type);
debug_assert_eq!(io.argvs_type.len(), func_obj.args_names.len());
for (argty, argname) in io
Expand Down Expand Up @@ -1309,14 +1327,18 @@ impl<'a> AstBuilder<'a> {
Ok(())
}

pub fn generate_code(&mut self) -> RunResult<()> {
pub fn generate_code(&mut self) -> RuntimeResult<()> {
self.process_info.is_global = true;
self.lex_until(TokenType::EndOfFile)?;
// 结束一个作用域的代码解析后再解析这里面的函数
self.process_info.is_global = false;
self.generate_func_in_scope()?;
Ok(())
}

pub fn modules_dll(&self) -> &[String] {
&self.modules_dll
}
}

#[cfg(test)]
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/ast/ast_base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,10 @@ impl<'a> AstBuilder<'a> {
pub fn get_scope(&self) -> Rc<RefCell<SymScope>> {
self.self_scope.clone()
}

pub fn add_module(&mut self, module_name: String) {
if self.modules_dll_dup.insert(module_name.clone()) {
self.modules_dll.push(module_name);
}
}
}
Loading

0 comments on commit e2e32ec

Please sign in to comment.