diff --git a/compiler/erg_common/lib.rs b/compiler/erg_common/lib.rs index 9e6520c1..eed6d0f1 100644 --- a/compiler/erg_common/lib.rs +++ b/compiler/erg_common/lib.rs @@ -13,9 +13,9 @@ pub mod levenshtein; pub mod macros; pub mod opcode; pub mod python_util; -pub mod rccell; pub mod serialize; pub mod set; +pub mod shared; pub mod stdin; pub mod str; pub mod traits; diff --git a/compiler/erg_common/rccell.rs b/compiler/erg_common/shared.rs similarity index 80% rename from compiler/erg_common/rccell.rs rename to compiler/erg_common/shared.rs index 47ef43ef..986ab7f8 100644 --- a/compiler/erg_common/rccell.rs +++ b/compiler/erg_common/shared.rs @@ -4,42 +4,42 @@ use std::hash::{Hash, Hasher}; use std::rc::Rc; #[derive(Debug)] -pub struct RcCell(Rc>); +pub struct Shared(Rc>); -impl PartialEq for RcCell { +impl PartialEq for Shared { #[inline] fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } -impl Clone for RcCell { - fn clone(&self) -> RcCell { +impl Clone for Shared { + fn clone(&self) -> Shared { Self(Rc::clone(&self.0)) } } -impl Eq for RcCell {} +impl Eq for Shared {} -impl Hash for RcCell { +impl Hash for Shared { fn hash(&self, state: &mut H) { self.borrow().hash(state); } } -impl Default for RcCell { +impl Default for Shared { fn default() -> Self { Self::new(Default::default()) } } -impl fmt::Display for RcCell { +impl fmt::Display for Shared { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.borrow()) } } -impl RcCell { +impl Shared { pub fn new(t: T) -> Self { Self(Rc::new(RefCell::new(t))) } @@ -54,7 +54,7 @@ impl RcCell { } } -impl RcCell { +impl Shared { #[inline] pub fn copy(&self) -> Self { Self(self.0.clone()) @@ -89,7 +89,7 @@ impl RcCell { } } -impl RcCell { +impl Shared { #[inline] pub fn clone_inner(&self) -> T { self.borrow().clone() diff --git a/compiler/erg_compiler/context/eval.rs b/compiler/erg_compiler/context/eval.rs index 4bf9a0cf..9e10a86d 100644 --- a/compiler/erg_compiler/context/eval.rs +++ b/compiler/erg_compiler/context/eval.rs @@ -2,8 +2,8 @@ use std::mem; use erg_common::dict::Dict; use erg_common::error::Location; -use erg_common::rccell::RcCell; use erg_common::set::Set; +use erg_common::shared::Shared; use erg_common::traits::{Locational, Stream}; use erg_common::vis::Field; use erg_common::{dict, fn_name, option_enum_unwrap, set}; @@ -326,7 +326,12 @@ impl Context { fn eval_const_normal_record(&self, record: &NormalRecord) -> EvalResult { let mut attrs = vec![]; // HACK: should avoid cloning - let mut record_ctx = Context::instant(Str::ever(""), 2, self.clone()); + let mut record_ctx = Context::instant( + Str::ever(""), + 2, + self.mod_cache.clone(), + self.clone(), + ); for attr in record.attrs.iter() { let name = attr.sig.ident().map(|i| i.inspect()); let elem = record_ctx.eval_const_block(&attr.body.block, name)?; @@ -431,7 +436,7 @@ impl Context { match (lhs, rhs) { (TyParam::Value(ValueObj::Mut(lhs)), TyParam::Value(rhs)) => self .eval_bin(op, lhs.borrow().clone(), rhs.clone()) - .map(|v| TyParam::Value(ValueObj::Mut(RcCell::new(v)))), + .map(|v| TyParam::Value(ValueObj::Mut(Shared::new(v)))), (TyParam::Value(lhs), TyParam::Value(rhs)) => self .eval_bin(op, lhs.clone(), rhs.clone()) .map(TyParam::value), @@ -459,7 +464,7 @@ impl Context { Pos => todo!(), Neg => todo!(), Invert => todo!(), - Mutate => Ok(ValueObj::Mut(RcCell::new(val))), + Mutate => Ok(ValueObj::Mut(Shared::new(val))), other => todo!("{other}"), } } diff --git a/compiler/erg_compiler/context/initialize/mod.rs b/compiler/erg_compiler/context/initialize/mod.rs index 5efe5b19..44786884 100644 --- a/compiler/erg_compiler/context/initialize/mod.rs +++ b/compiler/erg_compiler/context/initialize/mod.rs @@ -20,6 +20,7 @@ use erg_parser::ast::VarName; use crate::context::initialize::const_func::{class_func, inherit_func, inheritable_func}; use crate::context::instantiate::{ConstTemplate, TyVarContext}; use crate::context::{ClassDefType, Context, ContextKind, DefaultInfo, ParamSpec, TraitInstance}; +use crate::mod_cache::SharedModuleCache; use crate::varinfo::{Mutability, VarInfo, VarKind}; use DefaultInfo::*; use Mutability::*; @@ -172,26 +173,26 @@ impl Context { // 型境界はすべて各サブルーチンで定義する // push_subtype_boundなどはユーザー定義APIの型境界決定のために使用する fn init_builtin_traits(&mut self) { - let unpack = Self::mono_trait("Unpack", Self::TOP_LEVEL); - let inheritable_type = Self::mono_trait("InheritableType", Self::TOP_LEVEL); - let named = Self::mono_trait("Named", Self::TOP_LEVEL); - let mut mutable = Self::mono_trait("Mutable", Self::TOP_LEVEL); + let unpack = Self::mono_trait("Unpack", None, Self::TOP_LEVEL); + let inheritable_type = Self::mono_trait("InheritableType", None, Self::TOP_LEVEL); + let named = Self::mono_trait("Named", None, Self::TOP_LEVEL); + let mut mutable = Self::mono_trait("Mutable", None, Self::TOP_LEVEL); let proj = mono_proj(mono_q("Self"), "ImmutType"); let f_t = func(vec![param_t("old", proj.clone())], None, vec![], proj); let t = pr1_met(ref_mut(mono_q("Self"), None), f_t, NoneType); let t = quant(t, set! { subtypeof(mono_q("Self"), mono("Immutizable")) }); mutable.register_builtin_decl("update!", t, Public); // REVIEW: Immutatable? - let mut immutizable = Self::mono_trait("Immutizable", Self::TOP_LEVEL); + let mut immutizable = Self::mono_trait("Immutizable", None, Self::TOP_LEVEL); immutizable.register_superclass(mono("Mutable"), &mutable); immutizable.register_builtin_decl("ImmutType", Type, Public); // REVIEW: Mutatable? - let mut mutizable = Self::mono_trait("Mutizable", Self::TOP_LEVEL); + let mut mutizable = Self::mono_trait("Mutizable", None, Self::TOP_LEVEL); mutizable.register_builtin_decl("MutType!", Type, Public); - let mut in_ = Self::poly_trait("In", vec![PS::t("T", NonDefault)], Self::TOP_LEVEL); + let mut in_ = Self::poly_trait("In", vec![PS::t("T", NonDefault)], None, Self::TOP_LEVEL); let params = vec![PS::t("T", NonDefault)]; - let input = Self::poly_trait("Input", params.clone(), Self::TOP_LEVEL); - let output = Self::poly_trait("Output", params, Self::TOP_LEVEL); + let input = Self::poly_trait("Input", params.clone(), None, Self::TOP_LEVEL); + let output = Self::poly_trait("Output", params, None, Self::TOP_LEVEL); in_.register_superclass(poly("Input", vec![ty_tp(mono_q("T"))]), &input); let op_t = fn1_met(mono_q("T"), mono_q("I"), Bool); let op_t = quant( @@ -202,7 +203,7 @@ impl Context { // Erg does not have a trait equivalent to `PartialEq` in Rust // This means, Erg's `Float` cannot be compared with other `Float` // use `l - r < EPSILON` to check if two floats are almost equal - let mut eq = Self::poly_trait("Eq", vec![PS::t("R", WithDefault)], Self::TOP_LEVEL); + let mut eq = Self::poly_trait("Eq", vec![PS::t("R", WithDefault)], None, Self::TOP_LEVEL); eq.register_superclass(poly("Output", vec![ty_tp(mono_q("R"))]), &output); // __eq__: |Self <: Eq()| Self.(Self) -> Bool let op_t = fn1_met(mono_q("Self"), mono_q("R"), Bool); @@ -214,8 +215,12 @@ impl Context { }, ); eq.register_builtin_decl("__eq__", op_t, Public); - let mut partial_ord = - Self::poly_trait("PartialOrd", vec![PS::t("R", WithDefault)], Self::TOP_LEVEL); + let mut partial_ord = Self::poly_trait( + "PartialOrd", + vec![PS::t("R", WithDefault)], + None, + Self::TOP_LEVEL, + ); partial_ord.register_superclass(poly("Eq", vec![ty_tp(mono_q("R"))]), &eq); let op_t = fn1_met(mono_q("Self"), mono_q("R"), option(mono("Ordering"))); let op_t = quant( @@ -226,17 +231,17 @@ impl Context { }, ); partial_ord.register_builtin_decl("__partial_cmp__", op_t, Public); - let mut ord = Self::mono_trait("Ord", Self::TOP_LEVEL); + let mut ord = Self::mono_trait("Ord", None, Self::TOP_LEVEL); ord.register_superclass(poly("Eq", vec![ty_tp(mono("Self"))]), &eq); ord.register_superclass(poly("PartialOrd", vec![ty_tp(mono("Self"))]), &partial_ord); // FIXME: poly trait - let num = Self::mono_trait("Num", Self::TOP_LEVEL); + let num = Self::mono_trait("Num", None, Self::TOP_LEVEL); /* vec![ poly("Add", vec![]), poly("Sub", vec![]), poly("Mul", vec![]), ], */ - let mut seq = Self::poly_trait("Seq", vec![PS::t("T", NonDefault)], Self::TOP_LEVEL); + let mut seq = Self::poly_trait("Seq", vec![PS::t("T", NonDefault)], None, Self::TOP_LEVEL); seq.register_superclass(poly("Output", vec![ty_tp(mono_q("T"))]), &output); let self_t = mono_q("Self"); let t = fn0_met(self_t.clone(), Nat); @@ -256,7 +261,7 @@ impl Context { let r_bound = static_instance("R", Type); let params = vec![PS::t("R", WithDefault)]; let ty_params = vec![ty_tp(mono_q("R"))]; - let mut add = Self::poly_trait("Add", params.clone(), Self::TOP_LEVEL); + let mut add = Self::poly_trait("Add", params.clone(), None, Self::TOP_LEVEL); // Rについて共変(__add__の型とは関係ない) add.register_superclass(poly("Output", vec![ty_tp(mono_q("R"))]), &output); let self_bound = subtypeof(mono_q("Self"), poly("Add", ty_params.clone())); @@ -268,7 +273,7 @@ impl Context { let op_t = quant(op_t, set! {r_bound.clone(), self_bound}); add.register_builtin_decl("__add__", op_t, Public); add.register_builtin_decl("Output", Type, Public); - let mut sub = Self::poly_trait("Sub", params.clone(), Self::TOP_LEVEL); + let mut sub = Self::poly_trait("Sub", params.clone(), None, Self::TOP_LEVEL); sub.register_superclass(poly("Output", vec![ty_tp(mono_q("R"))]), &output); let op_t = fn1_met( mono_q("Self"), @@ -279,7 +284,7 @@ impl Context { let op_t = quant(op_t, set! {r_bound.clone(), self_bound}); sub.register_builtin_decl("__sub__", op_t, Public); sub.register_builtin_decl("Output", Type, Public); - let mut mul = Self::poly_trait("Mul", params.clone(), Self::TOP_LEVEL); + let mut mul = Self::poly_trait("Mul", params.clone(), None, Self::TOP_LEVEL); mul.register_superclass(poly("Output", vec![ty_tp(mono_q("R"))]), &output); let op_t = fn1_met( mono_q("Self"), @@ -290,7 +295,7 @@ impl Context { let op_t = quant(op_t, set! {r_bound.clone(), self_bound}); mul.register_builtin_decl("__mul__", op_t, Public); mul.register_builtin_decl("Output", Type, Public); - let mut div = Self::poly_trait("Div", params, Self::TOP_LEVEL); + let mut div = Self::poly_trait("Div", params, None, Self::TOP_LEVEL); div.register_superclass(poly("Output", vec![ty_tp(mono_q("R"))]), &output); let op_t = fn1_met(mono_q("Self"), r, mono_proj(mono_q("Self"), "Output")); let self_bound = subtypeof(mono_q("Self"), poly("Div", ty_params.clone())); @@ -346,7 +351,7 @@ impl Context { } fn init_builtin_classes(&mut self) { - let mut obj = Self::mono_class("Obj", Self::TOP_LEVEL); + let mut obj = Self::mono_class("Obj", None, Self::TOP_LEVEL); let t = fn0_met(mono_q("Self"), mono_q("Self")); let t = quant(t, set! {subtypeof(mono_q("Self"), mono("Obj"))}); obj.register_builtin_impl("clone", t, Const, Public); @@ -356,20 +361,20 @@ impl Context { obj.register_builtin_impl("__str__", fn0_met(Obj, Str), Immutable, Public); obj.register_builtin_impl("__dict__", fn0_met(Obj, dict(Str, Obj)), Immutable, Public); obj.register_builtin_impl("__bytes__", fn0_met(Obj, mono("Bytes")), Immutable, Public); - let mut obj_in = Self::methods("In", Self::TOP_LEVEL); + let mut obj_in = Self::methods("In", None, Self::TOP_LEVEL); obj_in.register_builtin_impl("__in__", fn1_met(Obj, Type, Bool), Const, Public); obj.register_trait(Obj, poly("Eq", vec![ty_tp(Type)]), obj_in); - let mut obj_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut obj_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); obj_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Obj!"))); obj.register_trait(Obj, mono("Mutizable"), obj_mutizable); - let mut float = Self::mono_class("Float", Self::TOP_LEVEL); + let mut float = Self::mono_class("Float", None, Self::TOP_LEVEL); float.register_superclass(Obj, &obj); // TODO: support multi platform float.register_builtin_const("EPSILON", ValueObj::Float(2.220446049250313e-16)); float.register_builtin_impl("Real", Float, Const, Public); float.register_builtin_impl("Imag", Float, Const, Public); float.register_marker_trait(mono("Num")); - let mut float_partial_ord = Self::methods("PartialOrd", Self::TOP_LEVEL); + let mut float_partial_ord = Self::methods("PartialOrd", None, Self::TOP_LEVEL); float_partial_ord.register_builtin_impl( "__cmp__", fn1_met(Float, Float, mono("Ordering")), @@ -383,33 +388,33 @@ impl Context { ); // Float doesn't have an `Eq` implementation let op_t = fn1_met(Float, Float, Float); - let mut float_add = Self::methods("Add", Self::TOP_LEVEL); + let mut float_add = Self::methods("Add", None, Self::TOP_LEVEL); float_add.register_builtin_impl("__add__", op_t.clone(), Const, Public); float_add.register_builtin_const("Output", ValueObj::builtin_t(Float)); float.register_trait(Float, poly("Add", vec![ty_tp(Float)]), float_add); - let mut float_sub = Self::methods("Sub", Self::TOP_LEVEL); + let mut float_sub = Self::methods("Sub", None, Self::TOP_LEVEL); float_sub.register_builtin_impl("__sub__", op_t.clone(), Const, Public); float_sub.register_builtin_const("Output", ValueObj::builtin_t(Float)); float.register_trait(Float, poly("Sub", vec![ty_tp(Float)]), float_sub); - let mut float_mul = Self::methods("Mul", Self::TOP_LEVEL); + let mut float_mul = Self::methods("Mul", None, Self::TOP_LEVEL); float_mul.register_builtin_impl("__mul__", op_t.clone(), Const, Public); float_mul.register_builtin_const("Output", ValueObj::builtin_t(Float)); float.register_trait(Float, poly("Mul", vec![ty_tp(Float)]), float_mul); - let mut float_div = Self::methods("Div", Self::TOP_LEVEL); + let mut float_div = Self::methods("Div", None, Self::TOP_LEVEL); float_div.register_builtin_impl("__div__", op_t, Const, Public); float_div.register_builtin_const("Output", ValueObj::builtin_t(Float)); float.register_trait(Float, poly("Div", vec![ty_tp(Float)]), float_div); - let mut float_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut float_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); float_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Float!"))); float.register_trait(Float, mono("Mutizable"), float_mutizable); // TODO: Int, Nat, Boolの継承元をRatioにする(今はFloat) - let mut ratio = Self::mono_class("Ratio", Self::TOP_LEVEL); + let mut ratio = Self::mono_class("Ratio", None, Self::TOP_LEVEL); ratio.register_superclass(Obj, &obj); ratio.register_builtin_impl("Real", Ratio, Const, Public); ratio.register_builtin_impl("Imag", Ratio, Const, Public); ratio.register_marker_trait(mono("Num")); // ratio.register_marker_trait(mono("Ord")); - let mut ratio_partial_ord = Self::methods("PartialOrd", Self::TOP_LEVEL); + let mut ratio_partial_ord = Self::methods("PartialOrd", None, Self::TOP_LEVEL); ratio_partial_ord.register_builtin_impl( "__cmp__", fn1_met(Ratio, Ratio, mono("Ordering")), @@ -421,30 +426,30 @@ impl Context { poly("PartialOrd", vec![ty_tp(Ratio)]), ratio_partial_ord, ); - let mut ratio_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut ratio_eq = Self::methods("Eq", None, Self::TOP_LEVEL); ratio_eq.register_builtin_impl("__eq__", fn1_met(Ratio, Ratio, Bool), Const, Public); ratio.register_trait(Ratio, poly("Eq", vec![ty_tp(Ratio)]), ratio_eq); let op_t = fn1_met(Ratio, Ratio, Ratio); - let mut ratio_add = Self::methods("Add", Self::TOP_LEVEL); + let mut ratio_add = Self::methods("Add", None, Self::TOP_LEVEL); ratio_add.register_builtin_impl("__add__", op_t.clone(), Const, Public); ratio_add.register_builtin_const("Output", ValueObj::builtin_t(Ratio)); ratio.register_trait(Ratio, poly("Add", vec![ty_tp(Ratio)]), ratio_add); - let mut ratio_sub = Self::methods("Sub", Self::TOP_LEVEL); + let mut ratio_sub = Self::methods("Sub", None, Self::TOP_LEVEL); ratio_sub.register_builtin_impl("__sub__", op_t.clone(), Const, Public); ratio_sub.register_builtin_const("Output", ValueObj::builtin_t(Ratio)); ratio.register_trait(Ratio, poly("Sub", vec![ty_tp(Ratio)]), ratio_sub); - let mut ratio_mul = Self::methods("Mul", Self::TOP_LEVEL); + let mut ratio_mul = Self::methods("Mul", None, Self::TOP_LEVEL); ratio_mul.register_builtin_impl("__mul__", op_t.clone(), Const, Public); ratio_mul.register_builtin_const("Output", ValueObj::builtin_t(Ratio)); ratio.register_trait(Ratio, poly("Mul", vec![ty_tp(Ratio)]), ratio_mul); - let mut ratio_div = Self::methods("Div", Self::TOP_LEVEL); + let mut ratio_div = Self::methods("Div", None, Self::TOP_LEVEL); ratio_div.register_builtin_impl("__div__", op_t, Const, Public); ratio_div.register_builtin_const("Output", ValueObj::builtin_t(Ratio)); ratio.register_trait(Ratio, poly("Div", vec![ty_tp(Ratio)]), ratio_div); - let mut ratio_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut ratio_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); ratio_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Ratio!"))); ratio.register_trait(Ratio, mono("Mutizable"), ratio_mutizable); - let mut int = Self::mono_class("Int", Self::TOP_LEVEL); + let mut int = Self::mono_class("Int", None, Self::TOP_LEVEL); int.register_superclass(Float, &float); // TODO: Float -> Ratio int.register_superclass(Obj, &obj); int.register_marker_trait(mono("Num")); @@ -453,7 +458,7 @@ impl Context { // class("Rational"), // class("Integral"), int.register_builtin_impl("abs", fn0_met(Int, Nat), Immutable, Public); - let mut int_partial_ord = Self::methods("PartialOrd", Self::TOP_LEVEL); + let mut int_partial_ord = Self::methods("PartialOrd", None, Self::TOP_LEVEL); int_partial_ord.register_builtin_impl( "__partial_cmp__", fn1_met(Int, Int, option(mono("Ordering"))), @@ -461,29 +466,29 @@ impl Context { Public, ); int.register_trait(Int, poly("PartialOrd", vec![ty_tp(Int)]), int_partial_ord); - let mut int_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut int_eq = Self::methods("Eq", None, Self::TOP_LEVEL); int_eq.register_builtin_impl("__eq__", fn1_met(Int, Int, Bool), Const, Public); int.register_trait(Int, poly("Eq", vec![ty_tp(Int)]), int_eq); // __div__ is not included in Int (cast to Ratio) let op_t = fn1_met(Int, Int, Int); - let mut int_add = Self::methods("Add", Self::TOP_LEVEL); + let mut int_add = Self::methods("Add", None, Self::TOP_LEVEL); int_add.register_builtin_impl("__add__", op_t.clone(), Const, Public); int_add.register_builtin_const("Output", ValueObj::builtin_t(Int)); int.register_trait(Int, poly("Add", vec![ty_tp(Int)]), int_add); - let mut int_sub = Self::methods("Sub", Self::TOP_LEVEL); + let mut int_sub = Self::methods("Sub", None, Self::TOP_LEVEL); int_sub.register_builtin_impl("__sub__", op_t.clone(), Const, Public); int_sub.register_builtin_const("Output", ValueObj::builtin_t(Int)); int.register_trait(Int, poly("Sub", vec![ty_tp(Int)]), int_sub); - let mut int_mul = Self::methods("Mul", Self::TOP_LEVEL); + let mut int_mul = Self::methods("Mul", None, Self::TOP_LEVEL); int_mul.register_builtin_impl("__mul__", op_t, Const, Public); int_mul.register_builtin_const("Output", ValueObj::builtin_t(Int)); int.register_trait(Int, poly("Mul", vec![ty_tp(Int)]), int_mul); - let mut int_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut int_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); int_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Int!"))); int.register_trait(Int, mono("Mutizable"), int_mutizable); int.register_builtin_impl("Real", Int, Const, Public); int.register_builtin_impl("Imag", Int, Const, Public); - let mut nat = Self::mono_class("Nat", Self::TOP_LEVEL); + let mut nat = Self::mono_class("Nat", None, Self::TOP_LEVEL); nat.register_superclass(Int, &int); nat.register_superclass(Float, &float); // TODO: Float -> Ratio nat.register_superclass(Obj, &obj); @@ -503,10 +508,10 @@ impl Context { ); nat.register_marker_trait(mono("Num")); // nat.register_marker_trait(mono("Ord")); - let mut nat_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut nat_eq = Self::methods("Eq", None, Self::TOP_LEVEL); nat_eq.register_builtin_impl("__eq__", fn1_met(Nat, Nat, Bool), Const, Public); nat.register_trait(Nat, poly("Eq", vec![ty_tp(Nat)]), nat_eq); - let mut nat_partial_ord = Self::methods("PartialOrd", Self::TOP_LEVEL); + let mut nat_partial_ord = Self::methods("PartialOrd", None, Self::TOP_LEVEL); nat_partial_ord.register_builtin_impl( "__cmp__", fn1_met(Nat, Nat, mono("Ordering")), @@ -516,20 +521,20 @@ impl Context { nat.register_trait(Nat, poly("PartialOrd", vec![ty_tp(Nat)]), nat_partial_ord); // __sub__, __div__ is not included in Nat (cast to Int/ Ratio) let op_t = fn1_met(Nat, Nat, Nat); - let mut nat_add = Self::methods("Add", Self::TOP_LEVEL); + let mut nat_add = Self::methods("Add", None, Self::TOP_LEVEL); nat_add.register_builtin_impl("__add__", op_t.clone(), Const, Public); nat_add.register_builtin_const("Output", ValueObj::builtin_t(Nat)); nat.register_trait(Nat, poly("Add", vec![ty_tp(Nat)]), nat_add); - let mut nat_mul = Self::methods("Mul", Self::TOP_LEVEL); + let mut nat_mul = Self::methods("Mul", None, Self::TOP_LEVEL); nat_mul.register_builtin_impl("__mul__", op_t, Const, Public); nat_mul.register_builtin_const("Output", ValueObj::builtin_t(Nat)); nat.register_trait(Nat, poly("Mul", vec![ty_tp(Nat)]), nat_mul); - let mut nat_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut nat_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); nat_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Nat!"))); nat.register_trait(Nat, mono("Mutizable"), nat_mutizable); nat.register_builtin_impl("Real", Nat, Const, Public); nat.register_builtin_impl("Imag", Nat, Const, Public); - let mut bool_ = Self::mono_class("Bool", Self::TOP_LEVEL); + let mut bool_ = Self::mono_class("Bool", None, Self::TOP_LEVEL); bool_.register_superclass(Nat, &nat); bool_.register_superclass(Int, &int); bool_.register_superclass(Float, &float); // TODO: Float -> Ratio @@ -541,7 +546,7 @@ impl Context { bool_.register_builtin_impl("__or__", fn1_met(Bool, Bool, Bool), Const, Public); bool_.register_marker_trait(mono("Num")); // bool_.register_marker_trait(mono("Ord")); - let mut bool_partial_ord = Self::methods("PartialOrd", Self::TOP_LEVEL); + let mut bool_partial_ord = Self::methods("PartialOrd", None, Self::TOP_LEVEL); bool_partial_ord.register_builtin_impl( "__cmp__", fn1_met(Bool, Bool, mono("Ordering")), @@ -553,17 +558,17 @@ impl Context { poly("PartialOrd", vec![ty_tp(Bool)]), bool_partial_ord, ); - let mut bool_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut bool_eq = Self::methods("Eq", None, Self::TOP_LEVEL); bool_eq.register_builtin_impl("__eq__", fn1_met(Bool, Bool, Bool), Const, Public); bool_.register_trait(Bool, poly("Eq", vec![ty_tp(Bool)]), bool_eq); - let mut bool_add = Self::methods("Add", Self::TOP_LEVEL); + let mut bool_add = Self::methods("Add", None, Self::TOP_LEVEL); bool_add.register_builtin_impl("__add__", fn1_met(Bool, Bool, Int), Const, Public); bool_add.register_builtin_const("Output", ValueObj::builtin_t(Int)); bool_.register_trait(Bool, poly("Add", vec![ty_tp(Bool)]), bool_add); - let mut bool_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut bool_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); bool_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Bool!"))); bool_.register_trait(Bool, mono("Mutizable"), bool_mutizable); - let mut str_ = Self::mono_class("Str", Self::TOP_LEVEL); + let mut str_ = Self::mono_class("Str", None, Self::TOP_LEVEL); str_.register_superclass(Obj, &obj); str_.register_builtin_impl( "replace", @@ -589,47 +594,48 @@ impl Context { Immutable, Public, ); - let mut str_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut str_eq = Self::methods("Eq", None, Self::TOP_LEVEL); str_eq.register_builtin_impl("__eq__", fn1_met(Str, Str, Bool), Const, Public); str_.register_trait(Str, poly("Eq", vec![ty_tp(Str)]), str_eq); - let mut str_seq = Self::methods("Seq", Self::TOP_LEVEL); + let mut str_seq = Self::methods("Seq", None, Self::TOP_LEVEL); str_seq.register_builtin_impl("len", fn0_met(Str, Nat), Const, Public); str_seq.register_builtin_impl("get", fn1_met(Str, Nat, Str), Const, Public); str_.register_trait(Str, poly("Seq", vec![ty_tp(Str)]), str_seq); - let mut str_add = Self::methods("Add", Self::TOP_LEVEL); + let mut str_add = Self::methods("Add", None, Self::TOP_LEVEL); str_add.register_builtin_impl("__add__", fn1_met(Str, Str, Str), Const, Public); str_add.register_builtin_const("Output", ValueObj::builtin_t(Str)); str_.register_trait(Str, poly("Add", vec![ty_tp(Str)]), str_add); - let mut str_mul = Self::methods("Mul", Self::TOP_LEVEL); + let mut str_mul = Self::methods("Mul", None, Self::TOP_LEVEL); str_mul.register_builtin_impl("__mul__", fn1_met(Str, Nat, Str), Const, Public); str_mul.register_builtin_const("Output", ValueObj::builtin_t(Str)); str_.register_trait(Str, poly("Mul", vec![ty_tp(Nat)]), str_mul); - let mut str_mutizable = Self::methods("Mutizable", Self::TOP_LEVEL); + let mut str_mutizable = Self::methods("Mutizable", None, Self::TOP_LEVEL); str_mutizable.register_builtin_const("MutType!", ValueObj::builtin_t(mono("Str!"))); str_.register_trait(Str, mono("Mutizable"), str_mutizable); - let mut type_ = Self::mono_class("Type", Self::TOP_LEVEL); + let mut type_ = Self::mono_class("Type", None, Self::TOP_LEVEL); type_.register_superclass(Obj, &obj); type_.register_builtin_impl("mro", array(Type, TyParam::erased(Nat)), Immutable, Public); type_.register_marker_trait(mono("Named")); - let mut type_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut type_eq = Self::methods("Eq", None, Self::TOP_LEVEL); type_eq.register_builtin_impl("__eq__", fn1_met(Type, Type, Bool), Const, Public); type_.register_trait(Type, poly("Eq", vec![ty_tp(Type)]), type_eq); - let mut class_type = Self::mono_class("ClassType", Self::TOP_LEVEL); + let mut class_type = Self::mono_class("ClassType", None, Self::TOP_LEVEL); class_type.register_superclass(Type, &type_); class_type.register_superclass(Obj, &obj); class_type.register_marker_trait(mono("Named")); - let mut class_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut class_eq = Self::methods("Eq", None, Self::TOP_LEVEL); class_eq.register_builtin_impl("__eq__", fn1_met(Class, Class, Bool), Const, Public); class_type.register_trait(Class, poly("Eq", vec![ty_tp(Class)]), class_eq); - let mut module = Self::mono_class("Module", Self::TOP_LEVEL); + let mut module = Self::mono_class("Module", None, Self::TOP_LEVEL); module.register_superclass(Obj, &obj); module.register_marker_trait(mono("Named")); - let mut module_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut module_eq = Self::methods("Eq", None, Self::TOP_LEVEL); module_eq.register_builtin_impl("__eq__", fn1_met(Module, Module, Bool), Const, Public); module.register_trait(Module, poly("Eq", vec![ty_tp(Module)]), module_eq); let mut array_ = Self::poly_class( "Array", vec![PS::t_nd("T"), PS::named_nd("N", Nat)], + None, Self::TOP_LEVEL, ); array_.register_superclass(Obj, &obj); @@ -655,7 +661,7 @@ impl Context { )); // [T; N].MutType! = [T; !N] (neither [T!; N] nor [T; N]!) array_.register_builtin_const("MutType!", mut_type); - let mut array_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut array_eq = Self::methods("Eq", None, Self::TOP_LEVEL); array_eq.register_builtin_impl( "__eq__", fn1_met(array_t.clone(), array_t.clone(), Bool), @@ -666,9 +672,9 @@ impl Context { array_.register_marker_trait(mono("Mutizable")); array_.register_marker_trait(poly("Seq", vec![ty_tp(mono_q("T"))])); // TODO: make Tuple6, Tuple7, ... etc. - let mut tuple_ = Self::mono_class("Tuple", Self::TOP_LEVEL); + let mut tuple_ = Self::mono_class("Tuple", None, Self::TOP_LEVEL); tuple_.register_superclass(Obj, &obj); - let mut tuple_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple_eq.register_builtin_impl( "__eq__", fn1_met(mono("Tuple"), mono("Tuple"), Bool), @@ -680,10 +686,10 @@ impl Context { poly("Eq", vec![ty_tp(mono("Tuple"))]), tuple_eq, ); - let mut tuple1 = Self::poly_class("Tuple1", vec![PS::t_nd("A")], Self::TOP_LEVEL); + let mut tuple1 = Self::poly_class("Tuple1", vec![PS::t_nd("A")], None, Self::TOP_LEVEL); tuple1.register_superclass(mono("Tuple"), &tuple_); tuple1.register_superclass(Obj, &obj); - let mut tuple1_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple1_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple1_eq.register_builtin_impl( "__eq__", fn1_met( @@ -702,11 +708,12 @@ impl Context { let mut tuple2 = Self::poly_class( "Tuple2", vec![PS::t_nd("A"), PS::t_nd("B")], + None, Self::TOP_LEVEL, ); tuple2.register_superclass(mono("Tuple"), &tuple_); tuple2.register_superclass(Obj, &obj); - let mut tuple2_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple2_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple2_eq.register_builtin_impl( "__eq__", fn1_met( @@ -731,11 +738,12 @@ impl Context { let mut tuple3 = Self::poly_class( "Tuple3", vec![PS::t_nd("A"), PS::t_nd("B"), PS::t_nd("C")], + None, Self::TOP_LEVEL, ); tuple3.register_superclass(mono("Tuple"), &tuple_); tuple3.register_superclass(Obj, &obj); - let mut tuple3_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple3_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple3_eq.register_builtin_impl( "__eq__", fn1_met( @@ -769,11 +777,12 @@ impl Context { let mut tuple4 = Self::poly_class( "Tuple4", vec![PS::t_nd("A"), PS::t_nd("B"), PS::t_nd("C"), PS::t_nd("D")], + None, Self::TOP_LEVEL, ); tuple4.register_superclass(mono("Tuple"), &tuple_); tuple4.register_superclass(Obj, &obj); - let mut tuple4_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple4_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple4_eq.register_builtin_impl( "__eq__", fn1_met( @@ -833,11 +842,12 @@ impl Context { PS::t_nd("D"), PS::t_nd("E"), ], + None, Self::TOP_LEVEL, ); tuple5.register_superclass(mono("Tuple"), &tuple_); tuple5.register_superclass(Obj, &obj); - let mut tuple5_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple5_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple5_eq.register_builtin_impl( "__eq__", fn1_met( @@ -902,11 +912,12 @@ impl Context { PS::t_nd("E"), PS::t_nd("F"), ], + None, Self::TOP_LEVEL, ); tuple6.register_superclass(mono("Tuple"), &tuple_); tuple6.register_superclass(Obj, &obj); - let mut tuple6_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple6_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple6_eq.register_builtin_impl( "__eq__", fn1_met( @@ -976,11 +987,12 @@ impl Context { PS::t_nd("F"), PS::t_nd("G"), ], + None, Self::TOP_LEVEL, ); tuple7.register_superclass(mono("Tuple"), &tuple_); tuple7.register_superclass(Obj, &obj); - let mut tuple7_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple7_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple7_eq.register_builtin_impl( "__eq__", fn1_met( @@ -1055,11 +1067,12 @@ impl Context { PS::t_nd("G"), PS::t_nd("H"), ], + None, Self::TOP_LEVEL, ); tuple8.register_superclass(mono("Tuple"), &tuple_); tuple8.register_superclass(Obj, &obj); - let mut tuple8_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut tuple8_eq = Self::methods("Eq", None, Self::TOP_LEVEL); tuple8_eq.register_builtin_impl( "__eq__", fn1_met( @@ -1126,16 +1139,16 @@ impl Context { ), tuple8_eq, ); - let mut record = Self::mono_class("Record", Self::TOP_LEVEL); + let mut record = Self::mono_class("Record", None, Self::TOP_LEVEL); record.register_superclass(Obj, &obj); - let mut record_type = Self::mono_class("RecordType", Self::TOP_LEVEL); + let mut record_type = Self::mono_class("RecordType", None, Self::TOP_LEVEL); record_type.register_superclass(mono("Record"), &record); record_type.register_superclass(mono("Type"), &type_); record_type.register_superclass(Obj, &obj); - let mut float_mut = Self::mono_class("Float!", Self::TOP_LEVEL); + let mut float_mut = Self::mono_class("Float!", None, Self::TOP_LEVEL); float_mut.register_superclass(Float, &float); float_mut.register_superclass(Obj, &obj); - let mut float_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut float_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); float_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Float)); let f_t = param_t("f", func(vec![param_t("old", Float)], None, vec![], Float)); let t = pr_met( @@ -1147,10 +1160,10 @@ impl Context { ); float_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); float_mut.register_trait(mono("Float!"), mono("Mutable"), float_mut_mutable); - let mut ratio_mut = Self::mono_class("Ratio!", Self::TOP_LEVEL); + let mut ratio_mut = Self::mono_class("Ratio!", None, Self::TOP_LEVEL); ratio_mut.register_superclass(Ratio, &ratio); ratio_mut.register_superclass(Obj, &obj); - let mut ratio_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut ratio_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); ratio_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Ratio)); let f_t = param_t( "f", @@ -1170,11 +1183,11 @@ impl Context { ); ratio_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); ratio_mut.register_trait(mono("Ratio!"), mono("Mutable"), ratio_mut_mutable); - let mut int_mut = Self::mono_class("Int!", Self::TOP_LEVEL); + let mut int_mut = Self::mono_class("Int!", None, Self::TOP_LEVEL); int_mut.register_superclass(Int, &int); int_mut.register_superclass(mono("Float!"), &float_mut); int_mut.register_superclass(Obj, &obj); - let mut int_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut int_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); int_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Int)); let f_t = param_t("f", func(vec![param_t("old", Int)], None, vec![], Int)); let t = pr_met( @@ -1186,12 +1199,12 @@ impl Context { ); int_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); int_mut.register_trait(mono("Int!"), mono("Mutable"), int_mut_mutable); - let mut nat_mut = Self::mono_class("Nat!", Self::TOP_LEVEL); + let mut nat_mut = Self::mono_class("Nat!", None, Self::TOP_LEVEL); nat_mut.register_superclass(Nat, &nat); nat_mut.register_superclass(mono("Int!"), &int_mut); nat_mut.register_superclass(mono("Float!"), &float_mut); nat_mut.register_superclass(Obj, &obj); - let mut nat_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut nat_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); nat_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Nat)); let f_t = param_t("f", func(vec![param_t("old", Nat)], None, vec![], Nat)); let t = pr_met( @@ -1203,13 +1216,13 @@ impl Context { ); nat_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); nat_mut.register_trait(mono("Nat!"), mono("Mutable"), nat_mut_mutable); - let mut bool_mut = Self::mono_class("Bool!", Self::TOP_LEVEL); + let mut bool_mut = Self::mono_class("Bool!", None, Self::TOP_LEVEL); bool_mut.register_superclass(Bool, &bool_); bool_mut.register_superclass(mono("Nat!"), &nat_mut); bool_mut.register_superclass(mono("Int!"), &int_mut); bool_mut.register_superclass(mono("Float!"), &float_mut); bool_mut.register_superclass(Obj, &obj); - let mut bool_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut bool_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); bool_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Bool)); let f_t = param_t("f", func(vec![param_t("old", Bool)], None, vec![], Bool)); let t = pr_met( @@ -1221,10 +1234,10 @@ impl Context { ); bool_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); bool_mut.register_trait(mono("Bool!"), mono("Mutable"), bool_mut_mutable); - let mut str_mut = Self::mono_class("Str!", Self::TOP_LEVEL); + let mut str_mut = Self::mono_class("Str!", None, Self::TOP_LEVEL); str_mut.register_superclass(Str, &str_); str_mut.register_superclass(Obj, &obj); - let mut str_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut str_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); str_mut_mutable.register_builtin_const("ImmutType", ValueObj::builtin_t(Str)); let f_t = param_t("f", func(vec![param_t("old", Str)], None, vec![], Str)); let t = pr_met( @@ -1241,6 +1254,7 @@ impl Context { let mut array_mut_ = Self::poly_class( "Array!", vec![PS::t_nd("T"), PS::named_nd("N", mono("Nat!"))], + None, Self::TOP_LEVEL, ); array_mut_.register_superclass(array_t.clone(), &array_); @@ -1294,14 +1308,14 @@ impl Context { vec![], NoneType, ); - let mut array_mut_mutable = Self::methods("Mutable", Self::TOP_LEVEL); + let mut array_mut_mutable = Self::methods("Mutable", None, Self::TOP_LEVEL); array_mut_mutable.register_builtin_impl("update!", t, Immutable, Public); array_mut_.register_trait(array_mut_t.clone(), mono("Mutable"), array_mut_mutable); let range_t = poly("Range", vec![TyParam::t(mono_q("T"))]); - let mut range = Self::poly_class("Range", vec![PS::t_nd("T")], Self::TOP_LEVEL); + let mut range = Self::poly_class("Range", vec![PS::t_nd("T")], None, Self::TOP_LEVEL); range.register_superclass(Obj, &obj); range.register_marker_trait(poly("Output", vec![ty_tp(mono_q("T"))])); - let mut range_eq = Self::methods("Eq", Self::TOP_LEVEL); + let mut range_eq = Self::methods("Eq", None, Self::TOP_LEVEL); range_eq.register_builtin_impl( "__eq__", fn1_met(range_t.clone(), range_t.clone(), Bool), @@ -1313,16 +1327,16 @@ impl Context { poly("Eq", vec![ty_tp(range_t.clone())]), range_eq, ); - let mut proc = Self::mono_class("Procedure", Self::TOP_LEVEL); + let mut proc = Self::mono_class("Procedure", None, Self::TOP_LEVEL); proc.register_superclass(Obj, &obj); // TODO: lambda proc.register_marker_trait(mono("Named")); - let mut func = Self::mono_class("Func", Self::TOP_LEVEL); + let mut func = Self::mono_class("Func", None, Self::TOP_LEVEL); func.register_superclass(mono("Proc"), &proc); func.register_superclass(Obj, &obj); // TODO: lambda func.register_marker_trait(mono("Named")); - let mut qfunc = Self::mono_class("QuantifiedFunc", Self::TOP_LEVEL); + let mut qfunc = Self::mono_class("QuantifiedFunc", None, Self::TOP_LEVEL); qfunc.register_superclass(mono("Func"), &func); qfunc.register_superclass(Obj, &obj); self.register_builtin_type(Obj, obj, Const); @@ -1668,6 +1682,7 @@ impl Context { "Interval", params, // super: vec![Type::from(&m..=&n)], + None, Self::TOP_LEVEL, ); let op_t = fn1_met( @@ -1675,7 +1690,7 @@ impl Context { Type::from(&o..=&p), Type::from(m.clone() + o.clone()..=n.clone() + p.clone()), ); - let mut interval_add = Self::methods("Add", Self::TOP_LEVEL); + let mut interval_add = Self::methods("Add", None, Self::TOP_LEVEL); interval_add.register_builtin_impl("__add__", op_t, Const, Public); interval_add.register_builtin_const( "Output", @@ -1686,7 +1701,7 @@ impl Context { poly("Add", vec![TyParam::from(&o..=&p)]), interval_add, ); - let mut interval_sub = Self::methods("Sub", Self::TOP_LEVEL); + let mut interval_sub = Self::methods("Sub", None, Self::TOP_LEVEL); let op_t = fn1_met( Type::from(&m..=&n), Type::from(&o..=&p), @@ -1711,7 +1726,7 @@ impl Context { pub(crate) fn init_builtins() -> Self { // TODO: capacityを正確に把握する - let mut ctx = Context::module("".into(), 40); + let mut ctx = Context::module("".into(), None, 40); ctx.init_builtin_funcs(); ctx.init_builtin_const_funcs(); ctx.init_builtin_procs(); @@ -1728,6 +1743,7 @@ impl Context { ContextKind::Module, vec![], Some(Context::init_builtins()), + Some(SharedModuleCache::new()), Context::TOP_LEVEL, ) } diff --git a/compiler/erg_compiler/context/initialize/py_mods/importlib.rs b/compiler/erg_compiler/context/initialize/py_mods/importlib.rs index d23f8804..d4309d75 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/importlib.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/importlib.rs @@ -11,7 +11,7 @@ use Visibility::*; impl Context { pub(crate) fn init_py_importlib_mod() -> Self { - let mut importlib = Context::module("importlib".into(), 15); + let mut importlib = Context::module("importlib".into(), None, 15); importlib.register_builtin_impl("reload!", proc1(Module, NoneType), Immutable, Public); importlib } diff --git a/compiler/erg_compiler/context/initialize/py_mods/io.rs b/compiler/erg_compiler/context/initialize/py_mods/io.rs index 66ca5634..8769a3db 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/io.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/io.rs @@ -12,8 +12,8 @@ use Visibility::*; impl Context { pub(crate) fn init_py_io_mod() -> Self { - let mut io = Context::module("io".into(), 15); - let mut string_io = Context::mono_class(Str::ever("StringIO!"), 0); + let mut io = Context::module("io".into(), None, 15); + let mut string_io = Context::mono_class(Str::ever("StringIO!"), None, 0); // FIXME: include Obj (pass main_ctx as a param) // string_io.register_superclass(Obj, obj); string_io.register_builtin_impl( diff --git a/compiler/erg_compiler/context/initialize/py_mods/math.rs b/compiler/erg_compiler/context/initialize/py_mods/math.rs index 0bd63129..c909c79c 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/math.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/math.rs @@ -11,7 +11,7 @@ use Visibility::*; impl Context { pub(crate) fn init_py_math_mod() -> Self { - let mut math = Context::module("math".into(), 10); + let mut math = Context::module("math".into(), None, 10); math.register_builtin_impl("pi", Float, Immutable, Public); math.register_builtin_impl("tau", Float, Immutable, Public); math.register_builtin_impl("e", Float, Immutable, Public); diff --git a/compiler/erg_compiler/context/initialize/py_mods/random.rs b/compiler/erg_compiler/context/initialize/py_mods/random.rs index 09f02e1a..7f1b1a9d 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/random.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/random.rs @@ -14,7 +14,7 @@ use Visibility::*; impl Context { pub(crate) fn init_py_random_mod() -> Self { - let mut random = Context::module("random".into(), 10); + let mut random = Context::module("random".into(), None, 10); random.register_builtin_impl( "seed!", proc( diff --git a/compiler/erg_compiler/context/initialize/py_mods/socket.rs b/compiler/erg_compiler/context/initialize/py_mods/socket.rs index 84088f94..fedf52c3 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/socket.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/socket.rs @@ -12,8 +12,8 @@ use Visibility::*; impl Context { pub(crate) fn init_py_socket_mod() -> Self { - let mut socket = Context::module("socket".into(), 15); - let mut sock = Context::mono_class(Str::ever("Socket!"), 0); + let mut socket = Context::module("socket".into(), None, 15); + let mut sock = Context::mono_class(Str::ever("Socket!"), None, 0); // FIXME: include Obj (pass main_ctx as a param) // sock.register_superclass(Obj, obj); sock.register_builtin_impl( diff --git a/compiler/erg_compiler/context/initialize/py_mods/sys.rs b/compiler/erg_compiler/context/initialize/py_mods/sys.rs index ae36ea30..ab392fad 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/sys.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/sys.rs @@ -12,7 +12,7 @@ use Visibility::*; impl Context { pub(crate) fn init_py_sys_mod() -> Self { - let mut sys = Context::module("sys".into(), 15); + let mut sys = Context::module("sys".into(), None, 15); sys.register_builtin_impl("argv", array(Str, TyParam::erased(Nat)), Immutable, Public); sys.register_builtin_impl("byteorder", Str, Immutable, Public); sys.register_builtin_impl( diff --git a/compiler/erg_compiler/context/initialize/py_mods/time.rs b/compiler/erg_compiler/context/initialize/py_mods/time.rs index 7b91ef9b..c4c374ae 100644 --- a/compiler/erg_compiler/context/initialize/py_mods/time.rs +++ b/compiler/erg_compiler/context/initialize/py_mods/time.rs @@ -11,7 +11,7 @@ use Visibility::*; impl Context { pub(crate) fn init_py_time_mod() -> Self { - let mut time = Context::module("time".into(), 15); + let mut time = Context::module("time".into(), None, 15); time.register_builtin_impl("sleep!", proc1(Float, NoneType), Immutable, Public); time.register_builtin_impl("time!", proc0(Float), Immutable, Public); time diff --git a/compiler/erg_compiler/context/inquire.rs b/compiler/erg_compiler/context/inquire.rs index c43fc344..96d01ced 100644 --- a/compiler/erg_compiler/context/inquire.rs +++ b/compiler/erg_compiler/context/inquire.rs @@ -1223,7 +1223,11 @@ impl Context { } fn rec_get_mod(&self, name: &str) -> Option<&Context> { - if let Some(mod_) = self.mods.get(name) { + if let Some(mod_) = self + .mod_cache + .as_ref() + .and_then(|cache| cache.ref_ctx(name)) + { Some(mod_) } else if let Some(outer) = &self.outer { outer.rec_get_mod(name) diff --git a/compiler/erg_compiler/context/mod.rs b/compiler/erg_compiler/context/mod.rs index 155acdd9..a6c4323a 100644 --- a/compiler/erg_compiler/context/mod.rs +++ b/compiler/erg_compiler/context/mod.rs @@ -37,6 +37,7 @@ use erg_parser::token::Token; use crate::context::instantiate::ConstTemplate; use crate::error::{TyCheckError, TyCheckErrors, TyCheckResult}; +use crate::mod_cache::SharedModuleCache; use crate::varinfo::{Mutability, ParamIdx, VarInfo, VarKind}; use Mutability::*; use Visibility::*; @@ -310,7 +311,7 @@ pub struct Context { // patches can be accessed like normal records // but when used as a fallback to a type, values are traversed instead of accessing by keys pub(crate) patches: Dict, - pub(crate) mods: Dict, + pub(crate) mod_cache: Option, pub(crate) level: usize, } @@ -322,6 +323,7 @@ impl Default for Context { ContextKind::Dummy, vec![], None, + None, Self::TOP_LEVEL, ) } @@ -340,7 +342,7 @@ impl fmt::Display for Context { .field("mono_types", &self.mono_types) .field("poly_types", &self.poly_types) .field("patches", &self.patches) - .field("mods", &self.mods) + // .field("mod_cache", &self.mod_cache) .finish() } } @@ -352,9 +354,10 @@ impl Context { kind: ContextKind, params: Vec, outer: Option, + mod_cache: Option, level: usize, ) -> Self { - Self::with_capacity(name, kind, params, outer, 0, level) + Self::with_capacity(name, kind, params, outer, 0, mod_cache, level) } #[allow(clippy::too_many_arguments)] @@ -364,6 +367,7 @@ impl Context { params: Vec, outer: Option, capacity: usize, + mod_cache: Option, level: usize, ) -> Self { let mut params_ = Vec::new(); @@ -400,15 +404,21 @@ impl Context { consts: Dict::default(), mono_types: Dict::default(), poly_types: Dict::default(), - mods: Dict::default(), + mod_cache, patches: Dict::default(), level, } } #[inline] - pub fn mono(name: Str, kind: ContextKind, outer: Option, level: usize) -> Self { - Self::with_capacity(name, kind, vec![], outer, 0, level) + pub fn mono( + name: Str, + kind: ContextKind, + outer: Option, + mod_cache: Option, + level: usize, + ) -> Self { + Self::with_capacity(name, kind, vec![], outer, 0, mod_cache, level) } #[inline] @@ -417,61 +427,111 @@ impl Context { kind: ContextKind, params: Vec, outer: Option, + mod_cache: Option, level: usize, ) -> Self { - Self::with_capacity(name, kind, params, outer, 0, level) + Self::with_capacity(name, kind, params, outer, 0, mod_cache, level) } - pub fn poly_trait>(name: S, params: Vec, level: usize) -> Self { + pub fn poly_trait>( + name: S, + params: Vec, + mod_cache: Option, + level: usize, + ) -> Self { let name = name.into(); - Self::poly(name, ContextKind::Trait, params, None, level) + Self::poly(name, ContextKind::Trait, params, None, mod_cache, level) } - pub fn poly_class>(name: S, params: Vec, level: usize) -> Self { + pub fn poly_class>( + name: S, + params: Vec, + mod_cache: Option, + level: usize, + ) -> Self { let name = name.into(); - Self::poly(name, ContextKind::Class, params, None, level) + Self::poly(name, ContextKind::Class, params, None, mod_cache, level) } #[inline] - pub fn mono_trait>(name: S, level: usize) -> Self { - Self::poly_trait(name, vec![], level) + pub fn mono_trait>( + name: S, + mod_cache: Option, + level: usize, + ) -> Self { + Self::poly_trait(name, vec![], mod_cache, level) } #[inline] - pub fn mono_class>(name: S, level: usize) -> Self { - Self::poly_class(name, vec![], level) + pub fn mono_class>( + name: S, + mod_cache: Option, + level: usize, + ) -> Self { + Self::poly_class(name, vec![], mod_cache, level) } #[inline] - pub fn methods>(name: S, level: usize) -> Self { - Self::with_capacity(name.into(), ContextKind::MethodDefs, vec![], None, 2, level) + pub fn methods>( + name: S, + mod_cache: Option, + level: usize, + ) -> Self { + Self::with_capacity( + name.into(), + ContextKind::MethodDefs, + vec![], + None, + 2, + mod_cache, + level, + ) } #[inline] - pub fn poly_patch>(name: S, params: Vec, level: usize) -> Self { - Self::poly(name.into(), ContextKind::Trait, params, None, level) + pub fn poly_patch>( + name: S, + params: Vec, + mod_cache: Option, + level: usize, + ) -> Self { + Self::poly( + name.into(), + ContextKind::Trait, + params, + None, + mod_cache, + level, + ) } #[inline] - pub fn module(name: Str, capacity: usize) -> Self { + pub fn module(name: Str, mod_cache: Option, capacity: usize) -> Self { Self::with_capacity( name, ContextKind::Module, vec![], None, capacity, + mod_cache, Self::TOP_LEVEL, ) } #[inline] - pub fn instant(name: Str, capacity: usize, outer: Context) -> Self { + pub fn instant( + name: Str, + capacity: usize, + mod_cache: Option, + outer: Context, + ) -> Self { Self::with_capacity( name, ContextKind::Instant, vec![], Some(outer), capacity, + mod_cache, Self::TOP_LEVEL, ) } diff --git a/compiler/erg_compiler/context/register.rs b/compiler/erg_compiler/context/register.rs index 56d70658..49a026ec 100644 --- a/compiler/erg_compiler/context/register.rs +++ b/compiler/erg_compiler/context/register.rs @@ -18,6 +18,7 @@ use crate::context::{ClassDefType, Context, DefaultInfo, RegistrationMode, Trait use crate::error::readable_name; use crate::error::{TyCheckError, TyCheckResult}; use crate::hir; +use crate::mod_cache::ModuleEntry; use crate::varinfo::{Mutability, ParamIdx, VarInfo, VarKind}; use Mutability::*; use RegistrationMode::*; @@ -593,8 +594,10 @@ impl Context { TypeKind::Class => { if gen.t.is_monomorphic() { // let super_traits = gen.impls.iter().map(|to| to.typ().clone()).collect(); - let mut ctx = Self::mono_class(gen.t.name(), self.level); - let mut methods = Self::methods(gen.t.name(), self.level); + let mut ctx = + Self::mono_class(gen.t.name(), self.mod_cache.clone(), self.level); + let mut methods = + Self::methods(gen.t.name(), self.mod_cache.clone(), self.level); let require = gen.require_or_sup.typ().clone(); let new_t = func1(require, gen.t.clone()); methods.register_fixed_auto_impl("__new__", new_t.clone(), Immutable, Private); @@ -611,12 +614,14 @@ impl Context { if gen.t.is_monomorphic() { let super_classes = vec![gen.require_or_sup.typ().clone()]; // let super_traits = gen.impls.iter().map(|to| to.typ().clone()).collect(); - let mut ctx = Self::mono_class(gen.t.name(), self.level); + let mut ctx = + Self::mono_class(gen.t.name(), self.mod_cache.clone(), self.level); for sup in super_classes.into_iter() { let (_, sup_ctx) = self.get_nominal_type_ctx(&sup).unwrap(); ctx.register_superclass(sup, sup_ctx); } - let mut methods = Self::methods(gen.t.name(), self.level); + let mut methods = + Self::methods(gen.t.name(), self.mod_cache.clone(), self.level); if let Some(sup) = self.rec_get_const_obj(&gen.require_or_sup.typ().name()) { let sup = enum_unwrap!(sup, ValueObj::Type); let param_t = match sup { @@ -700,32 +705,55 @@ impl Context { hir::Expr::Lit(lit) => { if self.subtype_of(&lit.value.class(), &Str) { let name = enum_unwrap!(lit.value.clone(), ValueObj::Str); - match &name[..] { - "importlib" => { - self.mods - .insert(var_name.clone(), Self::init_py_importlib_mod()); + if let Some(mod_cache) = self.mod_cache.as_mut() { + match &name[..] { + "importlib" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_importlib_mod()), + ); + } + "io" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_io_mod()), + ); + } + "math" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_math_mod()), + ); + } + "random" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_random_mod()), + ); + } + "socket" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_socket_mod()), + ); + } + "sys" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_sys_mod()), + ); + } + "time" => { + mod_cache.register( + var_name.clone(), + ModuleEntry::builtin(Self::init_py_time_mod()), + ); + } + other => todo!("importing {other}"), } - "io" => { - self.mods.insert(var_name.clone(), Self::init_py_io_mod()); - } - "math" => { - self.mods.insert(var_name.clone(), Self::init_py_math_mod()); - } - "random" => { - self.mods - .insert(var_name.clone(), Self::init_py_random_mod()); - } - "socket" => { - self.mods - .insert(var_name.clone(), Self::init_py_socket_mod()); - } - "sys" => { - self.mods.insert(var_name.clone(), Self::init_py_sys_mod()); - } - "time" => { - self.mods.insert(var_name.clone(), Self::init_py_time_mod()); - } - other => todo!("importing {other}"), + } else { + // maybe unreachable + todo!("importing {name} in the builtin module") } } else { return Err(TyCheckError::type_mismatch_error( diff --git a/compiler/erg_compiler/lib.rs b/compiler/erg_compiler/lib.rs index 950c2dd4..392a1fbc 100644 --- a/compiler/erg_compiler/lib.rs +++ b/compiler/erg_compiler/lib.rs @@ -11,6 +11,7 @@ pub mod effectcheck; pub mod error; pub mod hir; pub mod lower; +pub mod mod_cache; pub mod optimize; pub mod ownercheck; pub mod reorder; diff --git a/compiler/erg_compiler/mod_cache.rs b/compiler/erg_compiler/mod_cache.rs new file mode 100644 index 00000000..be423fbe --- /dev/null +++ b/compiler/erg_compiler/mod_cache.rs @@ -0,0 +1,115 @@ +use std::borrow::Borrow; +use std::hash::Hash; +use std::rc::Rc; + +use erg_common::dict::Dict; +use erg_common::shared::Shared; + +use erg_parser::ast::VarName; + +use crate::context::Context; +use crate::hir::HIR; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ModId(usize); + +impl ModId { + pub const fn new(id: usize) -> Self { + Self(id) + } + pub const fn builtin() -> Self { + Self(0) + } + pub const fn main() -> Self { + Self(1) + } +} + +#[derive(Debug)] +pub struct ModuleEntry { + id: ModId, // builtin == 0, __main__ == 1 + hir: Option, + ctx: Rc, +} + +impl ModuleEntry { + pub fn new(id: ModId, hir: Option, ctx: Context) -> Self { + Self { + id, + hir, + ctx: Rc::new(ctx), + } + } + + pub fn builtin(ctx: Context) -> Self { + Self { + id: ModId::builtin(), + hir: None, + ctx: Rc::new(ctx), + } + } +} + +#[derive(Debug, Default)] +pub struct ModuleCache { + cache: Dict, +} + +impl ModuleCache { + pub fn new() -> Self { + Self { cache: Dict::new() } + } + + pub fn get(&self, name: &Q) -> Option<&ModuleEntry> + where + VarName: Borrow, + { + self.cache.get(name) + } + + pub fn register(&mut self, name: VarName, entry: ModuleEntry) { + self.cache.insert(name, entry); + } + + pub fn remove(&mut self, name: &Q) -> Option + where + VarName: Borrow, + { + self.cache.remove(name) + } +} + +#[derive(Debug, Clone, Default)] +pub struct SharedModuleCache(Shared); + +impl SharedModuleCache { + pub fn new() -> Self { + Self(Shared::new(ModuleCache::new())) + } + + pub fn get_ctx(&self, name: &Q) -> Option> + where + VarName: Borrow, + { + self.0.borrow().get(name).map(|entry| entry.ctx.clone()) + } + + pub fn ref_ctx(&self, name: &Q) -> Option<&Context> + where + VarName: Borrow, + { + let ref_ = unsafe { self.0.as_ptr().as_ref().unwrap() }; + ref_.get(name).map(|entry| entry.ctx.as_ref()) + } + + pub fn register(&self, name: VarName, entry: ModuleEntry) { + self.0.borrow_mut().register(name, entry); + } + + pub fn remove(&mut self, name: &Q) -> Option + where + VarName: Borrow, + { + self.0.borrow_mut().remove(name) + } +} diff --git a/compiler/erg_type/free.rs b/compiler/erg_type/free.rs index 6c42efc7..d5477352 100644 --- a/compiler/erg_type/free.rs +++ b/compiler/erg_type/free.rs @@ -3,7 +3,7 @@ use std::fmt; use std::mem; use erg_common::addr_eq; -use erg_common::rccell::RcCell; +use erg_common::shared::Shared; use erg_common::traits::LimitedDisplay; use crate::typaram::TyParam; @@ -14,8 +14,8 @@ pub type Level = usize; pub type Id = usize; thread_local! { - static UNBOUND_ID: RcCell = RcCell::new(0); - static REFINEMENT_VAR_ID: RcCell = RcCell::new(0); + static UNBOUND_ID: Shared = Shared::new(0); + static REFINEMENT_VAR_ID: Shared = Shared::new(0); } pub fn fresh_varname() -> String { @@ -340,7 +340,7 @@ impl FreeKind { } #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct Free(RcCell>); +pub struct Free(Shared>); impl fmt::Display for Free { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -390,13 +390,13 @@ impl Free { impl Free { pub fn new(f: FreeKind) -> Self { - Self(RcCell::new(f)) + Self(Shared::new(f)) } pub fn new_unbound(level: Level, constraint: Constraint) -> Self { UNBOUND_ID.with(|id| { *id.borrow_mut() += 1; - Self(RcCell::new(FreeKind::unbound( + Self(Shared::new(FreeKind::unbound( *id.borrow(), level, constraint, @@ -405,13 +405,13 @@ impl Free { } pub fn new_named_unbound(name: Str, level: Level, constraint: Constraint) -> Self { - Self(RcCell::new(FreeKind::named_unbound( + Self(Shared::new(FreeKind::named_unbound( name, level, constraint, ))) } pub fn new_linked(t: T) -> Self { - Self(RcCell::new(FreeKind::Linked(t))) + Self(Shared::new(FreeKind::Linked(t))) } pub fn link(&self, to: &T) { diff --git a/compiler/erg_type/value.rs b/compiler/erg_type/value.rs index 9bb7fe1c..b74e1cf4 100644 --- a/compiler/erg_type/value.rs +++ b/compiler/erg_type/value.rs @@ -9,9 +9,9 @@ use std::ops::Neg; use std::rc::Rc; use erg_common::dict::Dict; -use erg_common::rccell::RcCell; use erg_common::serialize::*; use erg_common::set; +use erg_common::shared::Shared; use erg_common::vis::Field; use erg_common::{fmt_iter, impl_display_from_debug, switch_lang}; use erg_common::{RcArray, Str}; @@ -124,7 +124,7 @@ pub enum ValueObj { NotImplemented, NegInf, Inf, - Mut(RcCell), + Mut(Shared), #[default] Illegal, // to avoid conversions with TryFrom }