Skip to content

Commit

Permalink
refactor(trc):split stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
limuy2022 committed Apr 9, 2024
1 parent 7a24089 commit f7ebdfa
Show file tree
Hide file tree
Showing 18 changed files with 423 additions and 314 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ num-bigint = "0.4"
# llvm-sys = "170.0.1"
derive = { path = "./derive" }
libloading = "0.8"
stdlib = { path = "./stdlib" }
# stdlib = { path = "./stdlib" }
rust-i18n = "3.0"
sys-locale = "0.3"
rustyline = { version = "14.0", features = ["with-file-history"] }
Expand Down
31 changes: 29 additions & 2 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,10 @@ pub fn trc_class(_: TokenStream, input: TokenStream) -> TokenStream {
// 目前的实现策略是先提供一个由once_cell储存的usize数,表示在类型表中的索引,里面储存该类型的Rc指针
// 因为很可能某个函数的参数就是标准库中的某个类型,所以我们需要先将类型导入到class_table中
let ret = quote!(#input
use std::sync::OnceLock;
impl #name {
pub fn init_info(storage: Option<&mut ModuleStorage>) -> usize {
use std::collections::hash_map::HashMap;
static CLASS_ID: OnceLock<usize> = OnceLock::new();
static CLASS_ID: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
*CLASS_ID.get_or_init(|| {
let mut members = HashMap::new();
#(
Expand Down Expand Up @@ -247,3 +246,31 @@ pub fn trc_const(_: TokenStream, input: TokenStream) -> TokenStream {
input.expr = parse_str(&format!("stringify!({})", input.expr.to_token_stream(),)).unwrap();
quote!(#input).into()
}

#[proc_macro]
pub fn def_module_export(_t: TokenStream) -> TokenStream {
quote!(
fn import_lib() -> (&'static libcore::Module, &'static libcore::ModuleStorage) {
// this is for any type
static STDLIB_STORAGE: std::sync::OnceLock<ModuleStorage> = std::sync::OnceLock::new();
static RETURN_VAL: std::sync::OnceLock<Module> = std::sync::OnceLock::new();
let stro = STDLIB_STORAGE.get_or_init(|| {
let mut storage = libcore::ModuleStorage::new();
RETURN_VAL.get_or_init(|| module_init(&mut storage));
storage
});
(RETURN_VAL.get().unwrap(), stro)
}

#[no_mangle]
pub fn get_lib() -> &'static libcore::Module {
import_lib().0
}

#[no_mangle]
pub fn get_storage() -> &'static libcore::ModuleStorage {
import_lib().1
}
)
.into()
}
7 changes: 7 additions & 0 deletions libcore/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ pub fn symbol_redefined(name: &str) -> ErrorInfo {
ErrorInfo::new(t!(SYMBOL_REDEFINED, "0" = name), t!(SYMBOL_ERROR))
}

pub fn module_not_found(module_name: &str) -> ErrorInfo {
ErrorInfo::new(
t!(MODULE_NOT_FOUND, "0" = module_name),
t!(MODULE_NOT_FOUND_ERROR),
)
}

#[derive(Debug)]
pub struct ErrorInfo {
pub message: String,
Expand Down
7 changes: 5 additions & 2 deletions libcore/src/gc.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
//! provide gc for trc
#[derive(Default, Debug)]
pub struct GcMgr {}
pub struct GcMgr {
objs: Vec<*mut ()>,
}

impl GcMgr {
pub fn new() -> Self {
Self {}
Self { objs: Vec::new() }
}

pub fn alloc<T>(&mut self, obj: T) -> *mut T {
// unsafe { alloc(Layout::new::<T>()) as *mut T }
// TODO: change it into alloc and change = into write
Box::into_raw(Box::new(obj))
}
}
3 changes: 3 additions & 0 deletions libcore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ pub use error::*;
pub use libbasic::*;
pub use types::*;

pub const GET_LIB_FUNC_NAME: &str = "get_lib";
pub const GET_STORAGE_FUNC_NAME: &str = "get_storage";

rust_i18n::i18n!("locales");
67 changes: 57 additions & 10 deletions 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::*};

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

pub type ScopeAllocIdTy = usize;
pub type TypeAllowNull = Option<TyIdxTy>;
Expand Down Expand Up @@ -55,7 +55,7 @@ pub type ArgsNameTy = Vec<ConstPoolIndexTy>;
pub struct RustFunction {
pub name: String,
pub buildin_id: usize,
pub ptr: StdlibFunc,
pub ptr: RustlibFunc,
pub io: IOType,
}

Expand Down Expand Up @@ -110,6 +110,7 @@ pub trait FunctionInterface: Downcast + Debug {
fn get_io(&self) -> &IOType;
fn get_name(&self) -> &str;
fn get_io_mut(&mut self) -> &mut IOType;
fn get_func_id(&self) -> usize;
}

impl_downcast!(FunctionInterface);
Expand Down Expand Up @@ -144,6 +145,10 @@ impl FunctionInterface for RustFunction {
fn get_name(&self) -> &str {
&self.name
}

fn get_func_id(&self) -> usize {
self.buildin_id
}
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -235,8 +240,9 @@ impl Display for RustClass {

/// 最基础的储存一个动态链接库中的函数和类的地方
#[derive(Default)]
#[repr(C)]
pub struct ModuleStorage {
pub func_table: Vec<StdlibFunc>,
pub func_table: Vec<RustlibFunc>,
pub class_table: Vec<RustClass>,
}

Expand All @@ -248,7 +254,7 @@ impl ModuleStorage {
}
}

pub fn add_func(&mut self, f: StdlibFunc) -> usize {
pub fn add_func(&mut self, f: RustlibFunc) -> usize {
self.func_table.push(f);
self.func_table.len() - 1
}
Expand All @@ -267,7 +273,7 @@ impl ModuleStorage {
impl RustFunction {
pub fn new(
name: impl Into<String>,
ptr: StdlibFunc,
ptr: RustlibFunc,
io: IOType,
storage: &mut ModuleStorage,
) -> RustFunction {
Expand All @@ -282,13 +288,14 @@ impl RustFunction {
}

#[derive(Debug, Clone)]
#[repr(C)]
pub struct Module {
pub name: String,
pub sub_modules: HashMap<String, Module>,
pub functions: HashMap<String, RustFunction>,
name: String,
sub_modules: HashMap<String, Module>,
functions: HashMap<String, RustFunction>,
// class name 和class id
pub classes: HashMap<String, usize>,
pub consts: HashMap<String, String>,
classes: HashMap<String, usize>,
consts: HashMap<String, String>,
}

impl Module {
Expand Down Expand Up @@ -327,6 +334,46 @@ impl Module {
let lock = self.sub_modules.get(&item.into()).unwrap();
lock.get_module(path)
}

pub fn name(&self) -> &str {
&self.name
}

pub fn set_name(&mut self, name: String) {
self.name = name;
}

pub fn sub_modules(&self) -> &HashMap<String, Module> {
&self.sub_modules
}

pub fn set_sub_modules(&mut self, sub_modules: HashMap<String, Module>) {
self.sub_modules = sub_modules;
}

pub fn functions(&self) -> &HashMap<String, RustFunction> {
&self.functions
}

pub fn set_functions(&mut self, functions: HashMap<String, RustFunction>) {
self.functions = functions;
}

pub fn classes(&self) -> &HashMap<String, usize> {
&self.classes
}

pub fn consts(&self) -> &HashMap<String, String> {
&self.consts
}

pub fn set_consts(&mut self, consts: HashMap<String, String>) {
self.consts = consts;
}

pub fn set_classes(&mut self, classes: HashMap<String, usize>) {
self.classes = classes;
}
}

pub const INT: &str = "int";
Expand Down
1 change: 1 addition & 0 deletions src/base.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod ctrc;
pub mod dll;
pub mod utils;
12 changes: 12 additions & 0 deletions src/base/dll.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use libcore::{Module, ModuleStorage};

pub type GetLibFuncTy = unsafe fn() -> &'static Module;
pub type GetStorageFuncTy = unsafe fn() -> &'static ModuleStorage;

pub fn load_module_storage(lib: &libloading::Library) -> (&'static Module, &'static ModuleStorage) {
let get_lib_func: libloading::Symbol<GetLibFuncTy> =
unsafe { lib.get(libcore::GET_LIB_FUNC_NAME.as_bytes()).unwrap() };
let get_storage_func: libloading::Symbol<GetStorageFuncTy> =
unsafe { lib.get(libcore::GET_STORAGE_FUNC_NAME.as_bytes()).unwrap() };
unsafe { (get_lib_func(), get_storage_func()) }
}
27 changes: 16 additions & 11 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,26 +140,31 @@ pub struct ValuePool {
const_floats: Pool<Float>,
name_pool: Pool<String>,
_const_big_int: Pool<String>,
id_int: Vec<i64>,
id_float: Vec<Float>,
id_str: Vec<String>,
id_name: Vec<String>,
pub id_int: Vec<i64>,
pub id_float: Vec<Float>,
pub id_str: Vec<String>,
pub id_name: Vec<String>,
}

pub const INT_VAL_POOL_ZERO: usize = 0;
pub const INT_VAL_POOL_ONE: usize = 1;

macro_rules! gen_add_funcs {
macro_rules! gen_getter_setter {
($($func_name:ident => ($const_pool:ident, $id_pool:ident, $type:ty)),*) => {
$(
fn $func_name(&mut self, val: $type) -> usize {
paste::paste!{
pub fn [<add_ $func_name>](&mut self, val: $type) -> usize {
let len_tmp = self.$const_pool.len();
let ret = *self.$const_pool.entry(val.clone()).or_insert(len_tmp);
if len_tmp != self.$const_pool.len() {
self.$id_pool.push(val);
}
ret
}
pub fn [<get_ $func_name>](&self, val: &$type) -> Option<usize> {
self.$const_pool.get(val).copied()
}
}
)*
};
}
Expand All @@ -174,11 +179,11 @@ impl ValuePool {
ret
}

gen_add_funcs!(
add_int => (const_ints, id_int, i64),
add_float => (const_floats, id_float, Float),
add_string => (const_strings, id_str, String),
add_id => (name_pool, id_name, String)
gen_getter_setter!(
int => (const_ints, id_int, i64),
float => (const_floats, id_float, Float),
string => (const_strings, id_str, String),
id => (name_pool, id_name, String)
);

fn store_val_to_vm(&mut self) -> ConstPool {
Expand Down
Loading

0 comments on commit f7ebdfa

Please sign in to comment.