Unify Type::Class/Trait

This commit is contained in:
Shunsuke Shibayama 2022-09-03 22:22:49 +09:00
parent 263c43d74b
commit 22cb113fcd
17 changed files with 365 additions and 570 deletions

View file

@ -184,44 +184,44 @@ impl Context {
&& self.supertype_of(&Type, &subr.return_t),
),
(
Type::MonoClass(n),
Type::Mono(n),
Subr(SubrType {
kind: SubrKind::Func,
..
}),
) if &n[..] == "GenericFunc" => (Absolutely, true),
(
Type::MonoClass(n),
Type::Mono(n),
Subr(SubrType {
kind: SubrKind::Proc,
..
}),
) if &n[..] == "GenericProc" => (Absolutely, true),
(
Type::MonoClass(n),
Type::Mono(n),
Subr(SubrType {
kind: SubrKind::FuncMethod(_),
..
}),
) if &n[..] == "GenericFuncMethod" => (Absolutely, true),
(
Type::MonoClass(n),
Type::Mono(n),
Subr(SubrType {
kind: SubrKind::ProcMethod { .. },
..
}),
) if &n[..] == "GenericProcMethod" => (Absolutely, true),
(Type::MonoClass(l), Type::PolyClass { name: r, .. })
(Type::Mono(l), Type::Poly { name: r, .. })
if &l[..] == "GenericArray" && &r[..] == "Array" =>
{
(Absolutely, true)
}
(Type::MonoClass(l), Type::PolyClass { name: r, .. })
(Type::Mono(l), Type::Poly { name: r, .. })
if &l[..] == "GenericDict" && &r[..] == "Dict" =>
{
(Absolutely, true)
}
(Type::MonoClass(l), Type::MonoClass(r))
(Type::Mono(l), Type::Mono(r))
if &l[..] == "GenericCallable"
&& (&r[..] == "GenericFunc"
|| &r[..] == "GenericProc"
@ -234,7 +234,7 @@ impl Context {
Some((Type::Never, Type::Obj)) => (Absolutely, true),
_ => (Maybe, false),
},
(Type::MonoClass(n), Subr(_)) if &n[..] == "GenericCallable" => (Absolutely, true),
(Type::Mono(n), Subr(_)) if &n[..] == "GenericCallable" => (Absolutely, true),
(lhs, rhs) if lhs.is_simple_class() && rhs.is_simple_class() => (Absolutely, false),
_ => (Maybe, false),
}
@ -258,7 +258,7 @@ impl Context {
}
_ => {}
}
match self.trait_supertype_of(lhs, rhs) {
match self.classsupertype_of(lhs, rhs) {
(Absolutely, judge) => {
self.register_cache(rhs, lhs, judge);
return judge;
@ -292,9 +292,6 @@ impl Context {
}
fn classes_supertype_of(&self, lhs: &Type, rhs: &Type) -> (Credibility, bool) {
if !lhs.is_class() || !rhs.is_class() {
return (Maybe, false);
}
for (rhs_sup, _) in self.rec_get_nominal_super_class_ctxs(rhs) {
match self.cheap_supertype_of(lhs, rhs_sup) {
(Absolutely, true) => {
@ -313,11 +310,8 @@ impl Context {
// e.g. Eq(Nat) :> Nat
// Nat.super_traits = [Add(Nat), Eq(Nat), ...]
fn trait_supertype_of(&self, lhs: &Type, rhs: &Type) -> (Credibility, bool) {
if !lhs.is_trait() {
return (Maybe, false);
}
for (rhs_sup, _) in self.rec_get_nominal_super_trait_ctxs(rhs) {
fn classsupertype_of(&self, lhs: &Type, rhs: &Type) -> (Credibility, bool) {
for (rhs_sup, _) in self.rec_get_nominal_super_classctxs(rhs) {
match self.cheap_supertype_of(lhs, rhs_sup) {
(Absolutely, true) => {
return (Absolutely, true);
@ -575,26 +569,11 @@ impl Context {
// REVIEW: RefMut is invariant, maybe
(Ref(lhs), rhs) | (RefMut(lhs), rhs) => self.supertype_of(lhs, rhs),
(
PolyClass {
Poly {
name: ln,
params: lparams,
},
PolyClass {
name: rn,
params: rparams,
},
) => {
if ln != rn || lparams.len() != rparams.len() {
return false;
}
self.poly_supertype_of(lhs, lparams, rparams)
}
(
PolyTrait {
name: ln,
params: lparams,
},
PolyTrait {
Poly {
name: rn,
params: rparams,
},
@ -619,7 +598,7 @@ impl Context {
pub(crate) fn cyclic_supertype_of(&self, lhs: &FreeTyVar, rhs: &Type) -> bool {
// if `rhs` is {S: Str | ... }, `defined_rhs` will be Str
let (defined_rhs, _) = self.rec_get_nominal_type_ctx(rhs).unwrap();
let super_traits = self.rec_get_nominal_super_trait_ctxs(rhs);
let super_traits = self.rec_get_nominal_super_classctxs(rhs);
for (sup_trait, _) in super_traits.into_iter() {
if self.sup_conforms(lhs, defined_rhs, sup_trait) {
return true;

View file

@ -1,18 +1,18 @@
use erg_common::Str;
use erg_type::constructors::class;
use erg_type::constructors::mono;
use erg_type::value::ValueObj;
use erg_type::ValueArgs;
/// Type -> Type
pub fn class_func(_args: ValueArgs, __name__: Option<Str>) -> ValueObj {
let t = class(__name__.unwrap_or(Str::ever("<Lambda>")));
let t = mono(__name__.unwrap_or(Str::ever("<Lambda>")));
ValueObj::t(t)
}
/// Type -> Type
pub fn inherit_func(_args: ValueArgs, __name__: Option<Str>) -> ValueObj {
let t = class(__name__.unwrap_or(Str::ever("<Lambda>")));
let t = mono(__name__.unwrap_or(Str::ever("<Lambda>")));
ValueObj::t(t)
}

View file

@ -152,23 +152,23 @@ impl Context {
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(mono_q("Self"), None, f_t, NoneType);
let t = quant(t, set! { subtypeof(mono_q("Self"), trait_("Immutizable")) });
let t = quant(t, set! { subtypeof(mono_q("Self"), mono("Immutizable")) });
mutable.register_decl("update!", t, Public);
let mut immutizable =
Self::mono_trait("Immutizable", vec![trait_("Mutable")], Self::TOP_LEVEL);
Self::mono_trait("Immutizable", vec![mono("Mutable")], Self::TOP_LEVEL);
immutizable.register_decl("ImmutType", Type, Public);
let mut mutizable = Self::mono_trait("Mutizable", vec![], Self::TOP_LEVEL);
mutizable.register_decl("MutType!", Type, Public);
let mut in_ = Self::poly_trait(
"In",
vec![PS::t("T", NonDefault)],
vec![poly_trait("Input", vec![ty_tp(mono_q("T"))])],
vec![poly("Input", vec![ty_tp(mono_q("T"))])],
Self::TOP_LEVEL,
);
let op_t = fn1_met(mono_q("T"), mono_q("I"), Bool);
let op_t = quant(
op_t,
set! { static_instance("T", Type), subtypeof(mono_q("I"), poly_trait("In", vec![ty_tp(mono_q("T"))])) },
set! { static_instance("T", Type), subtypeof(mono_q("I"), poly("In", vec![ty_tp(mono_q("T"))])) },
);
in_.register_decl("__in__", op_t, Public);
// Erg does not have a trait equivalent to `PartialEq` in Rust
@ -177,7 +177,7 @@ impl Context {
let mut eq = Self::poly_trait(
"Eq",
vec![PS::t("R", WithDefault)],
vec![poly_trait("Output", vec![ty_tp(mono_q("R"))])],
vec![poly("Output", vec![ty_tp(mono_q("R"))])],
Self::TOP_LEVEL,
);
// __eq__: |Self <: Eq()| Self.(Self) -> Bool
@ -185,7 +185,7 @@ impl Context {
let op_t = quant(
op_t,
set! {
subtypeof(mono_q("Self"), poly_trait("Eq", vec![ty_tp(mono_q("R"))])),
subtypeof(mono_q("Self"), poly("Eq", vec![ty_tp(mono_q("R"))])),
static_instance("R", Type)
},
);
@ -193,49 +193,49 @@ impl Context {
let mut partial_ord = Self::poly_trait(
"PartialOrd",
vec![PS::t("R", WithDefault)],
vec![poly_trait("PartialEq", vec![ty_tp(mono_q("R"))])],
vec![poly("PartialEq", vec![ty_tp(mono_q("R"))])],
Self::TOP_LEVEL,
);
let op_t = fn1_met(mono_q("Self"), mono_q("R"), Bool);
let op_t = quant(
op_t,
set! {
subtypeof(mono_q("Self"), poly_trait("PartialOrd", vec![ty_tp(mono_q("R"))])),
subtypeof(mono_q("Self"), poly("PartialOrd", vec![ty_tp(mono_q("R"))])),
static_instance("R", Type)
},
);
partial_ord.register_decl("__lt__", op_t.clone(), Public);
let ord = Self::mono_trait(
"Ord",
vec![poly_trait("Eq", vec![]), poly_trait("PartialOrd", vec![])],
vec![poly("Eq", vec![]), poly("PartialOrd", vec![])],
Self::TOP_LEVEL,
);
let num = Self::mono_trait(
"Num",
vec![
poly_trait("Add", vec![]),
poly_trait("Sub", vec![]),
poly_trait("Mul", vec![]),
poly("Add", vec![]),
poly("Sub", vec![]),
poly("Mul", vec![]),
],
Self::TOP_LEVEL,
);
let mut seq = Self::poly_trait(
"Seq",
vec![PS::t("T", NonDefault)],
vec![poly_trait("Output", vec![ty_tp(mono_q("T"))])],
vec![poly("Output", vec![ty_tp(mono_q("T"))])],
Self::TOP_LEVEL,
);
let self_t = mono_q("Self");
let t = fn0_met(self_t.clone(), Nat);
let t = quant(
t,
set! {subtypeof(self_t.clone(), poly_trait("Seq", vec![TyParam::erased(Type)]))},
set! {subtypeof(self_t.clone(), poly("Seq", vec![TyParam::erased(Type)]))},
);
seq.register_decl("__len__", t, Public);
let t = fn1_met(self_t.clone(), Nat, mono_q("T"));
let t = quant(
t,
set! {subtypeof(self_t, poly_trait("Seq", vec![ty_tp(mono_q("T"))])), static_instance("T", Type)},
set! {subtypeof(self_t, poly("Seq", vec![ty_tp(mono_q("T"))])), static_instance("T", Type)},
);
// Seq.get: |Self <: Seq(T)| Self.(Nat) -> T
seq.register_decl("get", t, Public);
@ -249,10 +249,10 @@ impl Context {
let mut add = Self::poly_trait(
"Add",
params.clone(),
vec![poly_trait("Output", vec![ty_tp(mono_q("R"))])], // Rについて共変(__add__の型とは関係ない)
vec![poly("Output", vec![ty_tp(mono_q("R"))])], // Rについて共変(__add__の型とは関係ない)
Self::TOP_LEVEL,
);
let self_bound = subtypeof(mono_q("Self"), poly_trait("Add", ty_params.clone()));
let self_bound = subtypeof(mono_q("Self"), poly("Add", ty_params.clone()));
let op_t = fn1_met(mono_q("Self"), r.clone(), mono_proj(mono_q("Self"), "AddO"));
let op_t = quant(op_t, set! {r_bound.clone(), self_bound});
add.register_decl("__add__", op_t, Public);
@ -260,61 +260,57 @@ impl Context {
let mut sub = Self::poly_trait(
"Sub",
params.clone(),
vec![poly_trait("Output", vec![ty_tp(mono_q("R"))])],
vec![poly("Output", vec![ty_tp(mono_q("R"))])],
Self::TOP_LEVEL,
);
let op_t = fn1_met(mono_q("Self"), r.clone(), mono_proj(mono_q("Self"), "SubO"));
let self_bound = subtypeof(mono_q("Self"), poly_trait("Sub", ty_params.clone()));
let self_bound = subtypeof(mono_q("Self"), poly("Sub", ty_params.clone()));
let op_t = quant(op_t, set! {r_bound.clone(), self_bound});
sub.register_decl("__sub__", op_t, Public);
sub.register_decl("SubO", Type, Public);
let mut mul = Self::poly_trait(
"Mul",
params.clone(),
vec![poly_trait("Output", vec![ty_tp(mono_q("R"))])],
vec![poly("Output", vec![ty_tp(mono_q("R"))])],
Self::TOP_LEVEL,
);
let op_t = fn1_met(mono_q("Self"), r.clone(), mono_proj(mono_q("Self"), "MulO"));
let self_bound = subtypeof(mono_q("Self"), poly_trait("Mul", ty_params.clone()));
let self_bound = subtypeof(mono_q("Self"), poly("Mul", ty_params.clone()));
let op_t = quant(op_t, set! {r_bound.clone(), self_bound});
mul.register_decl("__mul__", op_t, Public);
mul.register_decl("MulO", Type, Public);
let mut div = Self::poly_trait(
"Div",
params.clone(),
vec![poly_trait("Output", vec![ty_tp(mono_q("R"))])],
vec![poly("Output", vec![ty_tp(mono_q("R"))])],
Self::TOP_LEVEL,
);
let op_t = fn1_met(mono_q("Self"), r, mono_proj(mono_q("Self"), "DivO"));
let self_bound = subtypeof(mono_q("Self"), poly_trait("Div", ty_params.clone()));
let self_bound = subtypeof(mono_q("Self"), poly("Div", ty_params.clone()));
let op_t = quant(op_t, set! {r_bound.clone(), self_bound});
div.register_decl("__div__", op_t, Public);
div.register_decl("DivO", Type, Public);
self.register_type(trait_("Unpack"), unpack, Const);
self.register_type(trait_("Named"), named, Const);
self.register_type(trait_("Mutable"), mutable, Const);
self.register_type(trait_("Immutizable"), immutizable, Const);
self.register_type(trait_("Mutizable"), mutizable, Const);
self.register_type(poly_trait("In", vec![ty_tp(mono_q("T"))]), in_, Const);
self.register_type(poly_trait("Eq", vec![ty_tp(mono_q("R"))]), eq, Const);
self.register_type(mono("Unpack"), unpack, Const);
self.register_type(mono("Named"), named, Const);
self.register_type(mono("Mutable"), mutable, Const);
self.register_type(mono("Immutizable"), immutizable, Const);
self.register_type(mono("Mutizable"), mutizable, Const);
self.register_type(poly("In", vec![ty_tp(mono_q("T"))]), in_, Const);
self.register_type(poly("Eq", vec![ty_tp(mono_q("R"))]), eq, Const);
self.register_type(
poly_trait("PartialOrd", vec![ty_tp(mono_q("R"))]),
poly("PartialOrd", vec![ty_tp(mono_q("R"))]),
partial_ord,
Const,
);
self.register_type(trait_("Ord"), ord, Const);
self.register_type(trait_("Num"), num, Const);
self.register_type(poly_trait("Seq", vec![ty_tp(mono_q("T"))]), seq, Const);
self.register_type(poly_trait("Input", vec![ty_tp(mono_q("T"))]), input, Const);
self.register_type(
poly_trait("Output", vec![ty_tp(mono_q("T"))]),
output,
Const,
);
self.register_type(poly_trait("Add", ty_params.clone()), add, Const);
self.register_type(poly_trait("Sub", ty_params.clone()), sub, Const);
self.register_type(poly_trait("Mul", ty_params.clone()), mul, Const);
self.register_type(poly_trait("Div", ty_params), div, Const);
self.register_type(mono("Ord"), ord, Const);
self.register_type(mono("Num"), num, Const);
self.register_type(poly("Seq", vec![ty_tp(mono_q("T"))]), seq, Const);
self.register_type(poly("Input", vec![ty_tp(mono_q("T"))]), input, Const);
self.register_type(poly("Output", vec![ty_tp(mono_q("T"))]), output, Const);
self.register_type(poly("Add", ty_params.clone()), add, Const);
self.register_type(poly("Sub", ty_params.clone()), sub, Const);
self.register_type(poly("Mul", ty_params.clone()), mul, Const);
self.register_type(poly("Div", ty_params), div, Const);
self.register_const_param_defaults(
"Eq",
vec![ConstTemplate::Obj(ValueObj::t(mono_q("Self")))],
@ -344,31 +340,31 @@ impl Context {
fn init_builtin_classes(&mut self) {
let mut obj = Self::mono_class("Obj", vec![], vec![], Self::TOP_LEVEL);
let t = fn0_met(mono_q("Self"), mono_q("Self"));
let t = quant(t, set! {subtypeof(mono_q("Self"), class("Obj"))});
let t = quant(t, set! {subtypeof(mono_q("Self"), mono("Obj"))});
obj.register_impl("clone", t, Const, Public);
obj.register_impl("__module__", Str, Const, Public);
obj.register_impl("__sizeof__", fn0_met(Obj, Nat), Const, Public);
obj.register_impl("__repr__", fn0_met(Obj, Str), Immutable, Public);
obj.register_impl("__str__", fn0_met(Obj, Str), Immutable, Public);
obj.register_impl("__dict__", fn0_met(Obj, dict(Str, Obj)), Immutable, Public);
obj.register_impl("__bytes__", fn0_met(Obj, class("Bytes")), Immutable, Public);
obj.register_const("MutType!", ValueObj::t(class("Obj!")));
obj.register_impl("__bytes__", fn0_met(Obj, mono("Bytes")), Immutable, Public);
obj.register_const("MutType!", ValueObj::t(mono("Obj!")));
// let mut record = Self::mono_trait("Record", vec![Obj], Self::TOP_LEVEL);
// let mut class = Self::mono_class("Class", vec![Type, Obj], Self::TOP_LEVEL);
let mut int = Self::mono_class(
"Int",
vec![Ratio, Obj],
vec![
trait_("Ord"),
poly_trait("Eq", vec![ty_tp(Int)]),
poly_trait("Add", vec![ty_tp(Int)]),
poly_trait("Sub", vec![ty_tp(Int)]),
poly_trait("Mul", vec![ty_tp(Int)]),
poly_trait("Div", vec![ty_tp(Int)]),
trait_("Num"),
// trait_("Rational"),
// trait_("Integral"),
trait_("Mutizable"),
mono("Ord"),
poly("Eq", vec![ty_tp(Int)]),
poly("Add", vec![ty_tp(Int)]),
poly("Sub", vec![ty_tp(Int)]),
poly("Mul", vec![ty_tp(Int)]),
poly("Div", vec![ty_tp(Int)]),
mono("Num"),
// class("Rational"),
// class("Integral"),
mono("Mutizable"),
],
Self::TOP_LEVEL,
);
@ -382,23 +378,23 @@ impl Context {
int.register_const("SubO", ValueObj::t(Int));
int.register_const("MulO", ValueObj::t(Int));
int.register_const("DivO", ValueObj::t(Ratio));
int.register_const("MutType!", ValueObj::t(class("Int!")));
int.register_const("MutType!", ValueObj::t(mono("Int!")));
int.register_impl("Real", Int, Const, Public);
int.register_impl("Imag", Int, Const, Public);
let mut nat = Self::mono_class(
"Nat",
vec![Int, Ratio, Obj],
vec![
trait_("Ord"),
poly_trait("Eq", vec![ty_tp(Nat)]),
poly_trait("Add", vec![ty_tp(Nat)]),
poly_trait("Sub", vec![ty_tp(Nat)]),
poly_trait("Mul", vec![ty_tp(Nat)]),
poly_trait("Div", vec![ty_tp(Nat)]),
trait_("Num"),
// trait_("Rational"),
// trait_("Integral"),
trait_("Mutizable"),
mono("Ord"),
poly("Eq", vec![ty_tp(Nat)]),
poly("Add", vec![ty_tp(Nat)]),
poly("Sub", vec![ty_tp(Nat)]),
poly("Mul", vec![ty_tp(Nat)]),
poly("Div", vec![ty_tp(Nat)]),
mono("Num"),
// class("Rational"),
// class("Integral"),
mono("Mutizable"),
],
Self::TOP_LEVEL,
);
@ -423,21 +419,21 @@ impl Context {
nat.register_const("SubO", ValueObj::t(Int));
nat.register_const("MulO", ValueObj::t(Nat));
nat.register_const("DivO", ValueObj::t(Ratio));
nat.register_const("MutType!", ValueObj::t(class("Nat!")));
nat.register_const("MutType!", ValueObj::t(mono("Nat!")));
nat.register_impl("Real", Nat, Const, Public);
nat.register_impl("Imag", Nat, Const, Public);
let mut float = Self::mono_class(
"Float",
vec![Obj],
vec![
trait_("Num"),
// trait_("Eq"), // Float doesn't have an Eq implementation
trait_("Ord"),
poly_trait("Add", vec![ty_tp(Float)]),
poly_trait("Sub", vec![ty_tp(Float)]),
poly_trait("Mul", vec![ty_tp(Float)]),
poly_trait("Div", vec![ty_tp(Float)]),
trait_("Mutizable"),
mono("Num"),
// class("Eq"), // Float doesn't have an Eq implementation
mono("Ord"),
poly("Add", vec![ty_tp(Float)]),
poly("Sub", vec![ty_tp(Float)]),
poly("Mul", vec![ty_tp(Float)]),
poly("Div", vec![ty_tp(Float)]),
mono("Mutizable"),
],
Self::TOP_LEVEL,
);
@ -450,21 +446,21 @@ impl Context {
float.register_const("SubO", ValueObj::t(Float));
float.register_const("MulO", ValueObj::t(Float));
float.register_const("DivO", ValueObj::t(Float));
float.register_const("MutType!", ValueObj::t(class("Float!")));
float.register_const("MutType!", ValueObj::t(mono("Float!")));
float.register_impl("Real", Float, Const, Public);
float.register_impl("Imag", Float, Const, Public);
let mut ratio = Self::mono_class(
"Ratio",
vec![Obj],
vec![
trait_("Num"),
poly_trait("Eq", vec![ty_tp(Ratio)]),
trait_("Ord"),
poly_trait("Add", vec![ty_tp(Ratio)]),
poly_trait("Sub", vec![ty_tp(Ratio)]),
poly_trait("Mul", vec![ty_tp(Ratio)]),
poly_trait("Div", vec![ty_tp(Ratio)]),
trait_("Mutizable"),
mono("Num"),
poly("Eq", vec![ty_tp(Ratio)]),
mono("Ord"),
poly("Add", vec![ty_tp(Ratio)]),
poly("Sub", vec![ty_tp(Ratio)]),
poly("Mul", vec![ty_tp(Ratio)]),
poly("Div", vec![ty_tp(Ratio)]),
mono("Mutizable"),
],
Self::TOP_LEVEL,
);
@ -477,40 +473,40 @@ impl Context {
ratio.register_const("SubO", ValueObj::t(Ratio));
ratio.register_const("MulO", ValueObj::t(Ratio));
ratio.register_const("DivO", ValueObj::t(Ratio));
ratio.register_const("MutType!", ValueObj::t(class("Ratio!")));
ratio.register_const("MutType!", ValueObj::t(mono("Ratio!")));
ratio.register_impl("Real", Ratio, Const, Public);
ratio.register_impl("Imag", Ratio, Const, Public);
let mut bool_ = Self::mono_class(
"Bool",
vec![Nat, Int, Ratio, Obj],
vec![
trait_("Num"),
// trait_("Rational"),
// trait_("Integral"),
poly_trait("Eq", vec![ty_tp(Bool)]),
poly_trait("Add", vec![ty_tp(Bool)]),
trait_("Ord"),
mono("Num"),
// class("Rational"),
// class("Integral"),
poly("Eq", vec![ty_tp(Bool)]),
poly("Add", vec![ty_tp(Bool)]),
mono("Ord"),
// mono("SelfAdd"),
// mono("SelfSub"),
// mono("SelfMul"),
// mono("SelfDiv"),
trait_("Mutizable"),
mono("Mutizable"),
],
Self::TOP_LEVEL,
);
bool_.register_impl("__and__", fn1_met(Bool, Bool, Bool), Const, Public);
bool_.register_impl("__or__", fn1_met(Bool, Bool, Bool), Const, Public);
bool_.register_const("MutType!", ValueObj::t(class("Bool!")));
bool_.register_const("MutType!", ValueObj::t(mono("Bool!")));
let mut str_ = Self::mono_class(
"Str",
vec![Obj],
vec![
poly_trait("Eq", vec![ty_tp(Str)]),
trait_("Ord"),
trait_("Mutizable"),
poly_trait("Seq", vec![ty_tp(Str)]),
poly_trait("Add", vec![ty_tp(Str)]),
poly_trait("Mul", vec![ty_tp(Nat)]),
poly("Eq", vec![ty_tp(Str)]),
mono("Ord"),
mono("Mutizable"),
poly("Seq", vec![ty_tp(Str)]),
poly("Add", vec![ty_tp(Str)]),
poly("Mul", vec![ty_tp(Nat)]),
],
Self::TOP_LEVEL,
);
@ -534,21 +530,21 @@ impl Context {
vec![],
None,
vec![param_t("encoding", Str), param_t("errors", Str)],
class("Bytes"),
mono("Bytes"),
),
Immutable,
Public,
);
str_.register_const("AddO", ValueObj::t(Str));
str_.register_const("MulO", ValueObj::t(Str));
str_.register_const("MutType!", ValueObj::t(class("Str!")));
str_.register_const("MutType!", ValueObj::t(mono("Str!")));
let mut type_ = Self::mono_class(
"Type",
vec![Obj],
vec![
poly_trait("Eq", vec![ty_tp(Type)]),
poly_trait("In", vec![ty_tp(Obj)]), // x in Type
trait_("Named"),
poly("Eq", vec![ty_tp(Type)]),
poly("In", vec![ty_tp(Obj)]), // x in Type
mono("Named"),
],
Self::TOP_LEVEL,
);
@ -556,7 +552,7 @@ impl Context {
let module = Self::mono_class(
"Module",
vec![Obj],
vec![poly_trait("Eq", vec![ty_tp(Module)]), trait_("Named")],
vec![poly("Eq", vec![ty_tp(Module)]), mono("Named")],
Self::TOP_LEVEL,
);
let mut array_ = Self::poly_class(
@ -564,16 +560,16 @@ impl Context {
vec![PS::t_nd("T"), PS::named_nd("N", Nat)],
vec![Obj],
vec![
poly_trait(
poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Array",
vec![ty_tp(mono_q("T")), mono_q_tp("N")],
))],
),
trait_("Mutizable"),
poly_trait("Seq", vec![ty_tp(mono_q("T"))]),
poly_trait("Output", vec![ty_tp(mono_q("T"))]),
mono("Mutizable"),
poly("Seq", vec![ty_tp(mono_q("T"))]),
poly("Output", vec![ty_tp(mono_q("T"))]),
],
Self::TOP_LEVEL,
);
@ -608,10 +604,10 @@ impl Context {
);
let t = quant(
t,
set! {static_instance("N", Nat), static_instance("T", trait_("Mutable"))},
set! {static_instance("N", Nat), static_instance("T", mono("Mutable"))},
);
array_.register_impl("map!", t, Immutable, Public);
let mut_type = ValueObj::t(poly_class(
let mut_type = ValueObj::t(poly(
"Array!",
vec![TyParam::t(mono_q("T")), TyParam::mono_q("N").mutate()],
));
@ -619,34 +615,34 @@ impl Context {
array_.register_const("MutType!", mut_type);
let mut int_mut = Self::mono_class(
"Int!",
vec![Int, class("Ratio!"), Obj],
vec![trait_("Mutable")],
vec![Int, mono("Ratio!"), Obj],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
// TODO: make Tuple6, Tuple7, ... etc.
let tuple_ = Self::mono_class(
"Tuple",
vec![Obj],
vec![poly_trait("Eq", vec![ty_tp(class("Tuple"))])],
vec![poly("Eq", vec![ty_tp(mono("Tuple"))])],
Self::TOP_LEVEL,
);
let tuple1 = Self::poly_class(
"Tuple1",
vec![PS::t_nd("A")],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class("Tuple1", vec![ty_tp(mono_q("A"))]))],
vec![ty_tp(poly("Tuple1", vec![ty_tp(mono_q("A"))]))],
)],
Self::TOP_LEVEL,
);
let tuple2 = Self::poly_class(
"Tuple2",
vec![PS::t_nd("A"), PS::t_nd("B")],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple2",
vec![ty_tp(mono_q("A")), ty_tp(mono_q("B"))],
))],
@ -656,10 +652,10 @@ impl Context {
let tuple3 = Self::poly_class(
"Tuple3",
vec![PS::t_nd("A"), PS::t_nd("B"), PS::t_nd("C")],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple3",
vec![ty_tp(mono_q("A")), ty_tp(mono_q("B")), ty_tp(mono_q("C"))],
))],
@ -669,10 +665,10 @@ impl Context {
let tuple4 = Self::poly_class(
"Tuple4",
vec![PS::t_nd("A"), PS::t_nd("B"), PS::t_nd("C"), PS::t_nd("D")],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple4",
vec![
ty_tp(mono_q("A")),
@ -693,10 +689,10 @@ impl Context {
PS::t_nd("D"),
PS::t_nd("E"),
],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple5",
vec![
ty_tp(mono_q("A")),
@ -719,10 +715,10 @@ impl Context {
PS::t_nd("E"),
PS::t_nd("F"),
],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple6",
vec![
ty_tp(mono_q("A")),
@ -747,10 +743,10 @@ impl Context {
PS::t_nd("F"),
PS::t_nd("G"),
],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple7",
vec![
ty_tp(mono_q("A")),
@ -777,10 +773,10 @@ impl Context {
PS::t_nd("G"),
PS::t_nd("H"),
],
vec![class("Tuple"), Obj],
vec![poly_trait(
vec![mono("Tuple"), Obj],
vec![poly(
"Eq",
vec![ty_tp(poly_class(
vec![ty_tp(poly(
"Tuple8",
vec![
ty_tp(mono_q("A")),
@ -798,83 +794,77 @@ impl Context {
);
int_mut.register_const("ImmutType", ValueObj::t(Int));
let f_t = param_t("f", func(vec![param_t("old", Int)], None, vec![], Int));
let t = pr_met(class("Int!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Int!"), None, vec![f_t], None, vec![], NoneType);
int_mut.register_impl("update!", t, Immutable, Public);
let mut nat_mut = Self::mono_class(
"Nat!",
vec![Nat, class("Int!"), class("Ratio!"), Obj],
vec![trait_("Mutable")],
vec![Nat, mono("Int!"), mono("Ratio!"), Obj],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
nat_mut.register_const("ImmutType", ValueObj::t(Nat));
let f_t = param_t("f", func(vec![param_t("old", Nat)], None, vec![], Nat));
let t = pr_met(class("Nat!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Nat!"), None, vec![f_t], None, vec![], NoneType);
nat_mut.register_impl("update!", t, Immutable, Public);
let mut float_mut = Self::mono_class(
"Float!",
vec![Float, Obj],
vec![trait_("Mutable")],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
float_mut.register_const("ImmutType", ValueObj::t(Float));
let f_t = param_t("f", func(vec![param_t("old", Float)], None, vec![], Float));
let t = pr_met(class("Float!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Float!"), None, vec![f_t], None, vec![], NoneType);
float_mut.register_impl("update!", t, Immutable, Public);
let mut ratio_mut = Self::mono_class(
"Ratio!",
vec![Ratio, Obj],
vec![trait_("Mutable")],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
ratio_mut.register_const("ImmutType", ValueObj::t(Ratio));
let f_t = param_t(
"f",
func(
vec![param_t("old", class("Ratio"))],
vec![param_t("old", mono("Ratio"))],
None,
vec![],
class("Ratio"),
mono("Ratio"),
),
);
let t = pr_met(class("Ratio!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Ratio!"), None, vec![f_t], None, vec![], NoneType);
ratio_mut.register_impl("update!", t, Immutable, Public);
let mut bool_mut = Self::mono_class(
"Bool!",
vec![Bool, class("Nat!"), class("Int!"), class("Ratio!"), Obj],
vec![trait_("Mutable")],
vec![Bool, mono("Nat!"), mono("Int!"), mono("Ratio!"), Obj],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
bool_mut.register_const("ImmutType", ValueObj::t(Bool));
let f_t = param_t("f", func(vec![param_t("old", Bool)], None, vec![], Bool));
let t = pr_met(class("Bool!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Bool!"), None, vec![f_t], None, vec![], NoneType);
bool_mut.register_impl("update!", t, Immutable, Public);
let mut str_mut = Self::mono_class(
"Str!",
vec![Str, Obj],
vec![trait_("Mutable")],
vec![mono("Mutable")],
Self::TOP_LEVEL,
);
str_mut.register_const("ImmutType", ValueObj::t(Str));
let f_t = param_t("f", func(vec![param_t("old", Str)], None, vec![], Str));
let t = pr_met(class("Str!"), None, vec![f_t], None, vec![], NoneType);
let t = pr_met(mono("Str!"), None, vec![f_t], None, vec![], NoneType);
str_mut.register_impl("update!", t, Immutable, Public);
let array_mut_t = poly_class("Array!", vec![ty_tp(mono_q("T")), mono_q_tp("N")]);
let array_mut_t = poly("Array!", vec![ty_tp(mono_q("T")), mono_q_tp("N")]);
let mut array_mut = Self::poly_class(
"Array!",
vec![PS::t_nd("T"), PS::named_nd("N", class("Nat!"))],
vec![
poly_class("Range", vec![ty_tp(mono_q("T")), mono_q_tp("N")]),
Obj,
],
vec![
trait_("Mutizable"),
poly_trait("Seq", vec![ty_tp(mono_q("T"))]),
],
vec![PS::t_nd("T"), PS::named_nd("N", mono("Nat!"))],
vec![poly("Range", vec![ty_tp(mono_q("T")), mono_q_tp("N")]), Obj],
vec![mono("Mutizable"), poly("Seq", vec![ty_tp(mono_q("T"))])],
Self::TOP_LEVEL,
);
let t = pr_met(
ref_mut(array_mut_t.clone()),
Some(ref_mut(poly_class(
Some(ref_mut(poly(
"Array!",
vec![ty_tp(mono_q("T")), mono_q_tp("N") + value(1)],
))),
@ -885,7 +875,7 @@ impl Context {
);
let t = quant(
t,
set! {static_instance("T", Type), static_instance("N", class("Nat!"))},
set! {static_instance("T", Type), static_instance("N", mono("Nat!"))},
);
array_mut.register_impl("push!", t, Immutable, Public);
let f_t = param_t(
@ -899,31 +889,23 @@ impl Context {
);
let t = pr_met(array_mut_t.clone(), None, vec![f_t], None, vec![], NoneType);
array_mut.register_impl("update!", t, Immutable, Public);
let range_t = poly_class("Range", vec![TyParam::t(mono_q("T"))]);
let range_t = poly("Range", vec![TyParam::t(mono_q("T"))]);
let range = Self::poly_class(
"Range",
vec![PS::t_nd("T")],
vec![Obj],
vec![
poly_trait(
"Eq",
vec![ty_tp(poly_class("Range", vec![ty_tp(mono_q("T"))]))],
),
trait_("Mutizable"),
poly_trait("Seq", vec![ty_tp(mono_q("T"))]),
poly_trait("Output", vec![ty_tp(mono_q("T"))]),
poly("Eq", vec![ty_tp(poly("Range", vec![ty_tp(mono_q("T"))]))]),
mono("Mutizable"),
poly("Seq", vec![ty_tp(mono_q("T"))]),
poly("Output", vec![ty_tp(mono_q("T"))]),
],
Self::TOP_LEVEL,
);
let func = Self::mono_class(
"Function",
vec![Obj],
vec![trait_("Named")],
Self::TOP_LEVEL,
);
let func = Self::mono_class("Function", vec![Obj], vec![mono("Named")], Self::TOP_LEVEL);
let qfunc = Self::mono_class(
"QuantifiedFunction",
vec![class("Function"), Obj],
vec![mono("Function"), Obj],
vec![],
Self::TOP_LEVEL,
);
@ -1001,21 +983,21 @@ impl Context {
tuple8,
Const,
);
self.register_type(class("Int!"), int_mut, Const);
self.register_type(class("Nat!"), nat_mut, Const);
self.register_type(class("Float!"), float_mut, Const);
self.register_type(class("Ratio!"), ratio_mut, Const);
self.register_type(class("Bool!"), bool_mut, Const);
self.register_type(class("Str!"), str_mut, Const);
self.register_type(mono("Int!"), int_mut, Const);
self.register_type(mono("Nat!"), nat_mut, Const);
self.register_type(mono("Float!"), float_mut, Const);
self.register_type(mono("Ratio!"), ratio_mut, Const);
self.register_type(mono("Bool!"), bool_mut, Const);
self.register_type(mono("Str!"), str_mut, Const);
self.register_type(array_mut_t, array_mut, Const);
self.register_type(range_t, range, Const);
self.register_type(class("Tuple"), tuple_, Const);
self.register_type(class("Function"), func, Const);
self.register_type(class("QuantifiedFunction"), qfunc, Const);
self.register_type(mono("Tuple"), tuple_, Const);
self.register_type(mono("Function"), func, Const);
self.register_type(mono("QuantifiedFunction"), qfunc, Const);
}
fn init_builtin_funcs(&mut self) {
let t_abs = nd_func(vec![param_t("n", trait_("Num"))], None, Nat);
let t_abs = nd_func(vec![param_t("n", mono("Num"))], None, Nat);
let t_assert = func(
vec![param_t("condition", Bool)],
None,
@ -1054,7 +1036,7 @@ impl Context {
vec![
param_t("sep", Str),
param_t("end", Str),
param_t("file", class("Write")),
param_t("file", mono("Write")),
param_t("flush", Bool),
],
NoneType,
@ -1096,7 +1078,7 @@ impl Context {
vec![
param_t("sep", Str),
param_t("end", Str),
param_t("file", class("Write")),
param_t("file", mono("Write")),
param_t("flush", Bool),
],
NoneType,
@ -1123,7 +1105,7 @@ impl Context {
let t_for = quant(t_for, set! {static_instance("T", Type)});
let t_while = nd_proc(
vec![
param_t("cond", class("Bool!")),
param_t("cond", mono("Bool!")),
param_t("p", nd_proc(vec![], None, NoneType)),
],
None,
@ -1150,7 +1132,7 @@ impl Context {
op_t,
set! {
static_instance("R", Type),
subtypeof(l.clone(), poly_trait("Add", params.clone()))
subtypeof(l.clone(), poly("Add", params.clone()))
},
);
self.register_impl("__add__", op_t, Const, Private);
@ -1159,7 +1141,7 @@ impl Context {
op_t,
set! {
static_instance("R", Type),
subtypeof(l.clone(), poly_trait("Sub", params.clone()))
subtypeof(l.clone(), poly("Sub", params.clone()))
},
);
self.register_impl("__sub__", op_t, Const, Private);
@ -1168,7 +1150,7 @@ impl Context {
op_t,
set! {
static_instance("R", Type),
subtypeof(l.clone(), poly_trait("Mul", params.clone()))
subtypeof(l.clone(), poly("Mul", params.clone()))
},
);
self.register_impl("__mul__", op_t, Const, Private);
@ -1177,27 +1159,27 @@ impl Context {
op_t,
set! {
static_instance("R", Type),
subtypeof(l, poly_trait("Mul", params.clone()))
subtypeof(l, poly("Mul", params.clone()))
},
);
self.register_impl("__div__", op_t, Const, Private);
let m = mono_q("M");
let op_t = bin_op(m.clone(), m.clone(), m.clone());
let op_t = quant(op_t, set! {subtypeof(m, poly_trait("Mul", vec![]))});
let op_t = quant(op_t, set! {subtypeof(m, poly("Mul", vec![]))});
// TODO: add bound: M == MulO
self.register_impl("__pow__", op_t, Const, Private);
let d = mono_q("D");
let op_t = bin_op(d.clone(), d.clone(), d.clone());
let op_t = quant(op_t, set! {subtypeof(d, poly_trait("Div", vec![]))});
let op_t = quant(op_t, set! {subtypeof(d, poly("Div", vec![]))});
self.register_impl("__mod__", op_t, Const, Private);
let e = mono_q("E");
let op_t = bin_op(e.clone(), e.clone(), Bool);
let op_t = quant(op_t, set! {subtypeof(e, poly_trait("Eq", vec![]))});
let op_t = quant(op_t, set! {subtypeof(e, poly("Eq", vec![]))});
self.register_impl("__eq__", op_t.clone(), Const, Private);
self.register_impl("__ne__", op_t, Const, Private);
let o = mono_q("O");
let op_t = bin_op(o.clone(), o.clone(), Bool);
let op_t = quant(op_t, set! {subtypeof(o, trait_("Ord"))});
let op_t = quant(op_t, set! {subtypeof(o, mono("Ord"))});
self.register_impl("__lt__", op_t.clone(), Const, Private);
self.register_impl("__le__", op_t.clone(), Const, Private);
self.register_impl("__gt__", op_t.clone(), Const, Private);
@ -1206,7 +1188,7 @@ impl Context {
self.register_impl("__or__", bin_op(Bool, Bool, Bool), Const, Private);
let t = mono_q("T");
let op_t = bin_op(t.clone(), t.clone(), range(t.clone()));
let op_t = quant(op_t, set! {subtypeof(t.clone(), trait_("Ord"))});
let op_t = quant(op_t, set! {subtypeof(t.clone(), mono("Ord"))});
self.register_decl("__rng__", op_t.clone(), Private);
self.register_decl("__lorng__", op_t.clone(), Private);
self.register_decl("__rorng__", op_t.clone(), Private);
@ -1215,17 +1197,17 @@ impl Context {
let op_t = bin_op(mono_q("T"), mono_q("I"), Bool);
let op_t = quant(
op_t,
set! { static_instance("T", Type), subtypeof(mono_q("I"), poly_trait("In", vec![ty_tp(mono_q("T"))])) },
set! { static_instance("T", Type), subtypeof(mono_q("I"), poly("In", vec![ty_tp(mono_q("T"))])) },
);
self.register_impl("__in__", op_t, Const, Private);
/* unary */
// TODO: Boolの+/-は警告を出したい
let op_t = func1(mono_q("T"), mono_proj(mono_q("T"), "MutType!"));
let op_t = quant(op_t, set! {subtypeof(mono_q("T"), trait_("Mutizable"))});
let op_t = quant(op_t, set! {subtypeof(mono_q("T"), mono("Mutizable"))});
self.register_impl("__mutate__", op_t, Const, Private);
let n = mono_q("N");
let op_t = func1(n.clone(), n.clone());
let op_t = quant(op_t, set! {subtypeof(n, trait_("Num"))});
let op_t = quant(op_t, set! {subtypeof(n, mono("Num"))});
self.register_decl("__pos__", op_t.clone(), Private);
self.register_decl("__neg__", op_t, Private);
}
@ -1247,8 +1229,8 @@ impl Context {
params,
vec![Type::from(&m..=&n)],
vec![
poly_trait("Add", vec![TyParam::from(&o..=&p)]),
poly_trait("Sub", vec![TyParam::from(&o..=&p)]),
poly("Add", vec![TyParam::from(&o..=&p)]),
poly("Sub", vec![TyParam::from(&o..=&p)]),
],
Self::TOP_LEVEL,
);

View file

@ -1,7 +1,7 @@
use erg_common::vis::Visibility;
use erg_common::Str;
use erg_type::constructors::{class, pr0_met};
use erg_type::constructors::{mono, pr0_met};
use erg_type::Type;
use Type::*;
@ -16,11 +16,11 @@ impl Context {
let mut string_io = Context::mono_class(Str::ever("StringIO!"), vec![Obj], vec![], 0);
string_io.register_impl(
"getvalue!",
pr0_met(class("StringIO!"), None, Str),
pr0_met(mono("StringIO!"), None, Str),
Immutable,
Public,
);
io.register_type(class("StringIO!"), string_io, Const);
io.register_type(mono("StringIO!"), string_io, Const);
io
}
}

View file

@ -2,7 +2,7 @@ use erg_common::set;
use erg_common::vis::Visibility;
use erg_type::constructors::{
mono_q, nd_proc, param_t, poly_trait, proc, quant, static_instance, trait_, ty_tp,
mono, mono_q, nd_proc, param_t, poly, proc, quant, static_instance, ty_tp,
};
use erg_type::Type;
use Type::*;
@ -21,7 +21,7 @@ impl Context {
vec![],
None,
vec![
param_t("a", trait_("Num")), // TODO: NoneType, int, float, str, bytes, bytearray
param_t("a", mono("Num")), // TODO: NoneType, int, float, str, bytes, bytearray
param_t("version", Int),
],
NoneType,
@ -36,7 +36,7 @@ impl Context {
Public,
);
let t = nd_proc(
vec![param_t("seq", poly_trait("Seq", vec![ty_tp(mono_q("T"))]))],
vec![param_t("seq", poly("Seq", vec![ty_tp(mono_q("T"))]))],
None,
mono_q("T"),
);

View file

@ -1,7 +1,7 @@
use erg_common::vis::Visibility;
use erg_common::Str;
use erg_type::constructors::{class, func, option, param_t};
use erg_type::constructors::{func, mono, option, param_t};
use erg_type::Type;
use Type::*;
@ -25,12 +25,12 @@ impl Context {
param_t("proto", Int),
param_t("fileno", option(Int)),
],
class("Socket!"),
mono("Socket!"),
),
Immutable,
Public,
);
socket.register_type(class("Socket!"), sock, Const);
socket.register_type(mono("Socket!"), sock, Const);
socket
}
}

View file

@ -1,6 +1,6 @@
use erg_common::vis::Visibility;
use erg_type::constructors::{array, array_mut, class, func0, func1, proc1};
use erg_type::constructors::{array, array_mut, func0, func1, mono, proc1};
use erg_type::typaram::TyParam;
use erg_type::Type;
use Type::*;
@ -33,17 +33,17 @@ impl Context {
);
sys.register_impl("platform", Str, Immutable, Public);
sys.register_impl("prefix", Str, Immutable, Public);
sys.register_impl("ps1", class("Str!"), Immutable, Public);
sys.register_impl("ps2", class("Str!"), Immutable, Public);
sys.register_impl("ps1", mono("Str!"), Immutable, Public);
sys.register_impl("ps2", mono("Str!"), Immutable, Public);
sys.register_impl(
"setrecursionlimit!",
proc1(Int, NoneType),
Immutable,
Public,
);
sys.register_impl("stderr", class("TextIOWrapper!"), Immutable, Public);
sys.register_impl("stdin", class("TextIOWrapper!"), Immutable, Public);
sys.register_impl("stdout", class("TextIOWrapper!"), Immutable, Public);
sys.register_impl("stderr", mono("TextIOWrapper!"), Immutable, Public);
sys.register_impl("stdin", mono("TextIOWrapper!"), Immutable, Public);
sys.register_impl("stdout", mono("TextIOWrapper!"), Immutable, Public);
sys.register_impl("version", Str, Immutable, Public);
sys
}

View file

@ -14,9 +14,7 @@ use ast::VarName;
use erg_parser::ast;
use erg_parser::token::Token;
use erg_type::constructors::{
class, func, mono_proj, poly_class, ref_, ref_mut, refinement, subr_t,
};
use erg_type::constructors::{func, mono, mono_proj, poly, ref_, ref_mut, refinement, subr_t};
use erg_type::free::Constraint;
use erg_type::typaram::TyParam;
use erg_type::value::ValueObj;
@ -119,9 +117,9 @@ impl Context {
pos_arg.loc(),
self.caused_by(),
"match",
&class("LambdaFunc"),
&mono("LambdaFunc"),
t,
self.get_type_mismatch_hint(&class("LambdaFunc"), t),
self.get_type_mismatch_hint(&mono("LambdaFunc"), t),
));
}
}
@ -441,10 +439,10 @@ impl Context {
fv.update_constraint(new_constraint);
Ok(Type::FreeVar(fv))
}
Type::PolyTrait { name, params } if params.iter().all(|tp| tp.has_no_unbound_var()) => {
Type::Poly { name, params } if params.iter().all(|tp| tp.has_no_unbound_var()) => {
let t_name = name.clone();
let t_params = params.clone();
let maybe_trait = Type::PolyTrait { name, params };
let maybe_trait = Type::Poly { name, params };
let mut min = Type::Obj;
for pair in self.rec_get_trait_impls(&t_name) {
if self.rec_supertype_of(&pair.sup_trait, &maybe_trait) {
@ -466,7 +464,7 @@ impl Context {
}
}
}
Ok(poly_class(t_name, new_params))
Ok(poly(t_name, new_params))
} else {
Ok(min)
}
@ -969,7 +967,7 @@ impl Context {
concatenated
}
pub(crate) fn rec_get_nominal_super_trait_ctxs<'a>(
pub(crate) fn rec_get_nominal_super_classctxs<'a>(
&'a self,
t: &Type,
) -> impl Iterator<Item = (&'a Type, &'a Context)> {
@ -1026,9 +1024,9 @@ impl Context {
return self.rec_get_nominal_type_ctx(&refine.t);
}
Type::Quantified(_) => {
return self.rec_get_nominal_type_ctx(&class("QuantifiedFunction"));
return self.rec_get_nominal_type_ctx(&mono("QuantifiedFunction"));
}
Type::PolyClass { name, params: _ } | Type::PolyTrait { name, params: _ } => {
Type::Poly { name, params: _ } => {
if let Some((t, ctx)) = self.poly_types.get(name) {
return Some((t, ctx));
}

View file

@ -105,7 +105,7 @@ impl TyVarContext {
) -> Type {
if let Some(temp_defaults) = ctx.rec_get_const_param_defaults(&name) {
let (_, ctx) = ctx
.rec_get_nominal_type_ctx(&poly_trait(name.clone(), params.clone()))
.rec_get_nominal_type_ctx(&poly(name.clone(), params.clone()))
.unwrap_or_else(|| panic!("{} not found", name));
let defined_params_len = ctx.params.len();
let given_params_len = params.len();
@ -130,9 +130,9 @@ impl TyVarContext {
self.push_or_init_typaram(&tp.tvar_name().unwrap(), &tp);
inst_defaults.push(tp);
}
poly_trait(name, [inst_non_defaults, inst_defaults].concat())
poly(name, [inst_non_defaults, inst_defaults].concat())
} else {
poly_trait(
poly(
name,
params
.into_iter()
@ -154,18 +154,16 @@ impl TyVarContext {
match bound {
TyBound::Sandwiched { sub, mid, sup } => {
let sub_instance = match sub {
Type::PolyTrait { name, params } => {
Type::Poly { name, params } => {
self.instantiate_poly(mid.name(), &name, params, ctx)
}
Type::PolyClass { .. } => todo!(),
Type::MonoProj { lhs, rhs } => mono_proj(self.instantiate_qvar(*lhs), rhs),
sub => sub,
};
let sup_instance = match sup {
Type::PolyTrait { name, params } => {
Type::Poly { name, params } => {
self.instantiate_poly(mid.name(), &name, params, ctx)
}
Type::PolyClass { .. } => todo!(),
Type::MonoProj { lhs, rhs } => mono_proj(self.instantiate_qvar(*lhs), rhs),
sup => sup,
};
@ -178,8 +176,7 @@ impl TyVarContext {
}
TyBound::Instance { name, t } => {
let t = match t {
Type::PolyClass { .. } => todo!(),
Type::PolyTrait { name, params } => {
Type::Poly { name, params } => {
self.instantiate_poly(name.clone(), &name, params, ctx)
}
t => t,
@ -510,10 +507,10 @@ impl Context {
let len = self.instantiate_const_expr(&len.expr);
Ok(array(t, len))
} else {
Ok(class("GenericArray"))
Ok(mono("GenericArray"))
}
}
other if simple.args.is_empty() => Ok(class(Str::rc(other))),
other if simple.args.is_empty() => Ok(mono(Str::rc(other))),
other => {
// FIXME: kw args
let params = simple.args.pos_args().map(|arg| match &arg.expr {
@ -523,7 +520,7 @@ impl Context {
}
});
// FIXME: if type is a trait
Ok(poly_class(Str::rc(other), params.collect()))
Ok(poly(Str::rc(other), params.collect()))
}
}
}
@ -543,7 +540,7 @@ impl Context {
expr: &ast::ConstExpr,
) -> TyCheckResult<Type> {
match expr {
ast::ConstExpr::Accessor(ast::ConstAccessor::Local(name)) => Ok(class(name.inspect())),
ast::ConstExpr::Accessor(ast::ConstAccessor::Local(name)) => Ok(mono(name.inspect())),
_ => todo!(),
}
}
@ -813,17 +810,11 @@ impl Context {
let lhs = Self::instantiate_t(*lhs, tv_ctx);
mono_proj(lhs, rhs)
}
PolyClass { name, mut params } => {
Poly { name, mut params } => {
for param in params.iter_mut() {
*param = Self::instantiate_tp(mem::take(param), tv_ctx);
}
poly_class(name, params)
}
PolyTrait { name, mut params } => {
for param in params.iter_mut() {
*param = Self::instantiate_tp(mem::take(param), tv_ctx);
}
poly_trait(name, params)
poly(name, params)
}
Quantified(_) => {
panic!("a quantified type should not be instantiated, instantiate the inner type")

View file

@ -84,7 +84,7 @@ pub enum TyParamIdx {
impl TyParamIdx {
pub fn search(search_from: &Type, target: &Type) -> Option<Self> {
match search_from {
Type::PolyClass { params, .. } => {
Type::Poly { params, .. } => {
for (i, tp) in params.iter().enumerate() {
match tp {
TyParam::Type(t) if t.as_ref() == target => return Some(Self::Nth(i)),

View file

@ -2,7 +2,7 @@
use erg_common::Str;
use erg_common::{enum_unwrap, set};
use erg_type::constructors::{func1, mono_q, poly_trait, quant, refinement};
use erg_type::constructors::{func1, mono_q, poly, quant, refinement};
use erg_type::typaram::TyParam;
use erg_type::{Predicate, TyBound, Type};
use Type::*;
@ -28,7 +28,7 @@ impl Context {
}
pub fn test_resolve_trait(&self) -> Result<(), ()> {
let t = poly_trait("Add", vec![TyParam::t(Nat)]);
let t = poly("Add", vec![TyParam::t(Nat)]);
match self.resolve_trait(t) {
Ok(Nat) => Ok(()),
Ok(other) => {
@ -46,7 +46,7 @@ impl Context {
pub fn test_resolve_trait_inner1(&self) -> Result<(), ()> {
let name = Str::ever("Add");
let params = vec![TyParam::t(Nat)];
let maybe_trait = poly_trait(name.clone(), params);
let maybe_trait = poly(name.clone(), params);
let mut min = Type::Obj;
for pair in self.rec_get_trait_impls(&name) {
if self.rec_supertype_of(&pair.sup_trait, &maybe_trait) {
@ -62,7 +62,7 @@ impl Context {
pub fn test_instantiation_and_generalization(&self) -> Result<(), ()> {
let t = mono_q("T");
let eq = poly_trait("Eq", vec![TyParam::t(t.clone())]);
let eq = poly("Eq", vec![TyParam::t(t.clone())]);
let bound = TyBound::subtype_of(t.clone(), eq.clone());
let bounds = set! {bound};
let unbound_t = func1(t.clone(), t.clone());

View file

@ -158,19 +158,12 @@ impl Context {
Callable { .. } => todo!(),
Ref(t) => ref_(self.generalize_t_inner(*t, bounds, lazy_inits)),
RefMut(t) => ref_mut(self.generalize_t_inner(*t, bounds, lazy_inits)),
PolyClass { name, mut params } => {
Poly { name, mut params } => {
let params = params
.iter_mut()
.map(|p| self.generalize_tp(mem::take(p), bounds, lazy_inits))
.collect::<Vec<_>>();
poly_class(name, params)
}
PolyTrait { name, mut params } => {
let params = params
.iter_mut()
.map(|p| self.generalize_tp(mem::take(p), bounds, lazy_inits))
.collect::<Vec<_>>();
poly_trait(name, params)
poly(name, params)
}
// REVIEW: その他何でもそのまま通していいのか?
other => other,
@ -313,17 +306,11 @@ impl Context {
let t = fv.unwrap_linked();
self.deref_tyvar(t)
}
Type::PolyClass { name, mut params } => {
Type::Poly { name, mut params } => {
for param in params.iter_mut() {
*param = self.deref_tp(mem::take(param))?;
}
Ok(Type::PolyClass { name, params })
}
Type::PolyTrait { name, mut params } => {
for param in params.iter_mut() {
*param = self.deref_tp(mem::take(param))?;
}
let t = Type::PolyTrait { name, params };
let t = Type::Poly { name, params };
self.resolve_trait(t)
}
Type::Subr(mut subr) => {
@ -569,7 +556,7 @@ impl Context {
} else if allow_divergence
&& (self.eq_tp(tp, &TyParam::value(Inf))
|| self.eq_tp(tp, &TyParam::value(NegInf)))
&& self.rec_subtype_of(&fv_t, &trait_("Num"))
&& self.rec_subtype_of(&fv_t, &mono("Num"))
{
fv.link(tp);
Ok(())
@ -844,11 +831,11 @@ impl Context {
(Type::Ref(l), r) | (Type::RefMut(l), r) => self.unify(l, r, lhs_loc, rhs_loc),
(l, Type::Ref(r)) | (l, Type::RefMut(r)) => self.unify(l, r, lhs_loc, rhs_loc),
(
Type::PolyClass {
Type::Poly {
name: ln,
params: lps,
},
Type::PolyClass {
Type::Poly {
name: rn,
params: rps,
},
@ -868,32 +855,7 @@ impl Context {
}
Ok(())
}
(
Type::PolyTrait {
name: ln,
params: lps,
},
Type::PolyTrait {
name: rn,
params: rps,
},
) => {
if ln != rn {
return Err(TyCheckError::unification_error(
line!() as usize,
lhs_t,
rhs_t,
lhs_loc,
rhs_loc,
self.caused_by(),
));
}
for (l, r) in lps.iter().zip(rps.iter()) {
self.unify_tp(l, r, None, false)?;
}
Ok(())
}
(Type::PolyClass { name: _, params: _ }, _r) => {
(Type::Poly { name: _, params: _ }, _r) => {
todo!()
}
(l, r) => Err(TyCheckError::unification_error(
@ -931,43 +893,17 @@ impl Context {
(Type::Ref(l), r) | (Type::RefMut(l), r) => self.reunify(l, r, bef_loc, aft_loc),
(l, Type::Ref(r)) | (l, Type::RefMut(r)) => self.reunify(l, r, bef_loc, aft_loc),
(
Type::PolyClass {
Type::Poly {
name: ln,
params: lps,
},
Type::PolyClass {
Type::Poly {
name: rn,
params: rps,
},
) => {
if ln != rn {
let before_t = poly_class(ln.clone(), lps.clone());
return Err(TyCheckError::re_unification_error(
line!() as usize,
&before_t,
after_t,
bef_loc,
aft_loc,
self.caused_by(),
));
}
for (l, r) in lps.iter().zip(rps.iter()) {
self.reunify_tp(l, r)?;
}
Ok(())
}
(
Type::PolyTrait {
name: ln,
params: lps,
},
Type::PolyTrait {
name: rn,
params: rps,
},
) => {
if ln != rn {
let before_t = poly_trait(ln.clone(), lps.clone());
let before_t = poly(ln.clone(), lps.clone());
return Err(TyCheckError::re_unification_error(
line!() as usize,
&before_t,

View file

@ -12,9 +12,7 @@ use OpKind::*;
use erg_parser::ast::*;
use erg_parser::token::{Token, TokenKind};
use erg_type::constructors::{
class, enum_t, mono_proj, poly_class, poly_trait, ref_, ref_mut, refinement, subr_t,
};
use erg_type::constructors::{enum_t, mono, mono_proj, poly, ref_, ref_mut, refinement, subr_t};
use erg_type::typaram::{OpKind, TyParam};
use erg_type::value::ValueObj;
use erg_type::{HasType, Predicate, SubrKind, TyBound, Type, ValueArgs};
@ -250,7 +248,7 @@ impl Context {
name.loc(),
self.caused_by(),
name.inspect(),
&class("Subroutine"),
&mono("Subroutine"),
&obj.t(),
None,
))?
@ -565,17 +563,11 @@ impl Context {
}
Type::Ref(l) => Ok(ref_(self.eval_t_params(*l, level)?)),
Type::RefMut(l) => Ok(ref_mut(self.eval_t_params(*l, level)?)),
Type::PolyClass { name, mut params } => {
Type::Poly { name, mut params } => {
for p in params.iter_mut() {
*p = self.eval_tp(&mem::take(p))?;
}
Ok(poly_class(name, params))
}
Type::PolyTrait { name, mut params } => {
for p in params.iter_mut() {
*p = self.eval_tp(&mem::take(p))?;
}
Ok(poly_trait(name, params))
Ok(poly(name, params))
}
other if other.is_monomorphic() => Ok(other),
other => todo!("{other}"),

View file

@ -10,7 +10,7 @@ use erg_parser::ast;
use erg_parser::ast::AST;
use erg_parser::token::{Token, TokenKind};
use erg_type::constructors::{array, array_mut, class, free_var, func, poly_class, proc, quant};
use erg_type::constructors::{array, array_mut, free_var, func, mono, poly, proc, quant};
use erg_type::free::Constraint;
use erg_type::typaram::TyParam;
use erg_type::value::ValueObj;
@ -167,7 +167,7 @@ impl ASTLowerer {
match maybe_len {
Ok(v @ ValueObj::Nat(_)) => {
if elem.ref_t().is_mut() {
poly_class(
poly(
"ArrayWithMutType!",
vec![TyParam::t(elem.t()), TyParam::Value(v)],
)
@ -175,9 +175,9 @@ impl ASTLowerer {
array(elem.t(), TyParam::Value(v))
}
}
Ok(v @ ValueObj::Mut(_)) if v.class() == class("Nat!") => {
Ok(v @ ValueObj::Mut(_)) if v.class() == mono("Nat!") => {
if elem.ref_t().is_mut() {
poly_class(
poly(
"ArrayWithMutTypeAndLength!",
vec![TyParam::t(elem.t()), TyParam::Value(v)],
)
@ -189,7 +189,7 @@ impl ASTLowerer {
// REVIEW: is it ok to ignore the error?
Err(_e) => {
if elem.ref_t().is_mut() {
poly_class(
poly(
"ArrayWithMutType!",
vec![TyParam::t(elem.t()), TyParam::erased(Type::Nat)],
)

View file

@ -21,25 +21,25 @@ pub fn named_free_var(name: Str, level: usize, constraint: Constraint) -> Type {
}
pub fn array(elem_t: Type, len: TyParam) -> Type {
poly_class("Array", vec![TyParam::t(elem_t), len])
poly("Array", vec![TyParam::t(elem_t), len])
}
pub fn array_mut(elem_t: Type, len: TyParam) -> Type {
poly_class("Array!", vec![TyParam::t(elem_t), len])
poly("Array!", vec![TyParam::t(elem_t), len])
}
pub fn dict(k_t: Type, v_t: Type) -> Type {
poly_class("Dict", vec![TyParam::t(k_t), TyParam::t(v_t)])
poly("Dict", vec![TyParam::t(k_t), TyParam::t(v_t)])
}
pub fn tuple(args: Vec<Type>) -> Type {
let name = format!("Tuple{}", args.len());
poly_class(name, args.into_iter().map(TyParam::t).collect())
poly(name, args.into_iter().map(TyParam::t).collect())
}
#[inline]
pub fn range(t: Type) -> Type {
poly_class("Range", vec![TyParam::t(t)])
poly("Range", vec![TyParam::t(t)])
}
pub fn enum_t(s: Set<ValueObj>) -> Type {
@ -91,7 +91,7 @@ pub fn int_interval<P: Into<TyParam>, Q: Into<TyParam>>(op: IntervalOp, l: P, r:
}
pub fn iter(t: Type) -> Type {
poly_class("Iter", vec![TyParam::t(t)])
poly("Iter", vec![TyParam::t(t)])
}
pub fn ref_(t: Type) -> Type {
@ -103,11 +103,11 @@ pub fn ref_mut(t: Type) -> Type {
}
pub fn option(t: Type) -> Type {
poly_class("Option", vec![TyParam::t(t)])
poly("Option", vec![TyParam::t(t)])
}
pub fn option_mut(t: Type) -> Type {
poly_class("Option!", vec![TyParam::t(t)])
poly("Option!", vec![TyParam::t(t)])
}
pub fn subr_t(
@ -286,13 +286,8 @@ pub fn callable(param_ts: Vec<Type>, return_t: Type) -> Type {
}
#[inline]
pub fn class<S: Into<Str>>(name: S) -> Type {
Type::MonoClass(name.into())
}
#[inline]
pub fn trait_<S: Into<Str>>(name: S) -> Type {
Type::MonoTrait(name.into())
pub fn mono<S: Into<Str>>(name: S) -> Type {
Type::Mono(name.into())
}
#[inline]
@ -301,16 +296,8 @@ pub fn mono_q<S: Into<Str>>(name: S) -> Type {
}
#[inline]
pub fn poly_class<S: Into<Str>>(name: S, params: Vec<TyParam>) -> Type {
Type::PolyClass {
name: name.into(),
params,
}
}
#[inline]
pub fn poly_trait<S: Into<Str>>(name: S, params: Vec<TyParam>) -> Type {
Type::PolyTrait {
pub fn poly<S: Into<Str>>(name: S, params: Vec<TyParam>) -> Type {
Type::Poly {
name: name.into(),
params,
}

View file

@ -18,7 +18,7 @@ use erg_common::vis::Field;
use erg_common::{enum_unwrap, fmt_option, fmt_set_split_with, set, Str};
use crate::codeobj::CodeObj;
use crate::constructors::{and, class, int_interval, mono_q};
use crate::constructors::{and, int_interval, mono, mono_q};
use crate::free::{
fresh_varname, Constraint, Cyclicity, Free, FreeKind, FreeTyVar, HasLevel, Level,
};
@ -1149,8 +1149,7 @@ pub enum Type {
NotImplemented,
Ellipsis, // これはクラスのほうで型推論用のマーカーではない
Never, // {}
MonoClass(Str),
MonoTrait(Str),
Mono(Str),
/* Polymorphic types */
Ref(Box<Type>),
RefMut(Box<Type>),
@ -1173,14 +1172,10 @@ pub enum Type {
And(Box<Type>, Box<Type>),
Not(Box<Type>, Box<Type>),
Or(Box<Type>, Box<Type>),
PolyClass {
Poly {
name: Str,
params: Vec<TyParam>,
}, // T(params)
PolyTrait {
name: Str,
params: Vec<TyParam>,
}, // T(params)
},
/* Special types (inference-time types) */
MonoQVar(Str), // QuantifiedTyの中で使う一般化型変数、利便性のためMonoとは区別する
PolyQVar {
@ -1221,9 +1216,7 @@ impl PartialEq for Type {
| (Self::NotImplemented, Self::NotImplemented)
| (Self::Ellipsis, Self::Ellipsis)
| (Self::Never, Self::Never) => true,
(Self::MonoClass(l), Self::MonoClass(r)) | (Self::MonoTrait(l), Self::MonoTrait(r)) => {
l == r
}
(Self::Mono(l), Self::Mono(r)) => l == r,
(Self::MonoQVar(l), Self::MonoQVar(r)) => l == r,
(Self::Ref(l), Self::Ref(r)) | (Self::RefMut(l), Self::RefMut(r)) => l == r,
(Self::Subr(l), Self::Subr(r)) => l == r,
@ -1255,11 +1248,7 @@ impl PartialEq for Type {
| (Self::Not(ll, lr), Self::Not(rl, rr))
| (Self::Or(ll, lr), Self::Or(rl, rr)) => ll == rl && lr == rr,
(
Self::PolyClass {
name: ln,
params: lps,
}
| Self::PolyTrait {
Self::Poly {
name: ln,
params: lps,
}
@ -1267,11 +1256,7 @@ impl PartialEq for Type {
name: ln,
params: lps,
},
Self::PolyClass {
name: rn,
params: rps,
}
| Self::PolyTrait {
Self::Poly {
name: rn,
params: rps,
}
@ -1316,7 +1301,7 @@ impl LimitedDisplay for Type {
return write!(f, "...");
}
match self {
Self::MonoClass(name) | Self::MonoTrait(name) => write!(f, "{name}"),
Self::Mono(name) => write!(f, "{name}"),
Self::Ref(t) | Self::RefMut(t) => {
write!(f, "{}(", self.name())?;
t.limited_fmt(f, limit - 1)?;
@ -1364,7 +1349,7 @@ impl LimitedDisplay for Type {
write!(f, " or ")?;
rhs.limited_fmt(f, limit - 1)
}
Self::PolyClass { name, params } | Self::PolyTrait { name, params } => {
Self::Poly { name, params } => {
write!(f, "{name}(")?;
for (i, tp) in params.iter().enumerate() {
if i > 0 {
@ -1453,7 +1438,7 @@ impl From<&str> for Type {
"Inf" => Self::Inf,
"NegInf" => Self::NegInf,
"_" => Self::Obj,
other => Self::MonoClass(Str::rc(other)),
other => Self::Mono(Str::rc(other)),
}
}
}
@ -1483,9 +1468,7 @@ impl HasType for Type {
// Self::And(ts) | Self::Or(ts) => ,
Self::Subr(_sub) => todo!(),
Self::Callable { param_ts, .. } => param_ts.clone(),
Self::PolyClass { params, .. } | Self::PolyTrait { params, .. } => {
params.iter().filter_map(get_t_from_tp).collect()
}
Self::Poly { params, .. } => params.iter().filter_map(get_t_from_tp).collect(),
_ => vec![],
}
}
@ -1538,7 +1521,7 @@ impl HasLevel for Type {
t.update_level(level);
}
}
Self::PolyClass { params, .. } | Self::PolyTrait { params, .. } => {
Self::Poly { params, .. } => {
for p in params.iter() {
p.update_level(level);
}
@ -1592,7 +1575,7 @@ impl HasLevel for Type {
t.lift();
}
}
Self::PolyClass { params, .. } | Self::PolyTrait { params, .. } => {
Self::Poly { params, .. } => {
for p in params.iter() {
p.lift();
}
@ -1643,12 +1626,12 @@ impl Type {
fv.link(&t.mutate());
Self::FreeVar(fv)
}
Self::Int => class("Int!"),
Self::Nat => class("Nat!"),
Self::Ratio => class("Ratio!"),
Self::Float => class("Float!"),
Self::Bool => class("Bool!"),
Self::Str => class("Str!"),
Self::Int => mono("Int!"),
Self::Nat => mono("Nat!"),
Self::Ratio => mono("Ratio!"),
Self::Float => mono("Float!"),
Self::Bool => mono("Bool!"),
Self::Str => mono("Str!"),
_ => todo!(),
}
}
@ -1682,49 +1665,6 @@ impl Type {
}
}
pub fn is_class(&self) -> bool {
match self {
Self::FreeVar(fv) if fv.is_linked() => fv.crack().is_class(),
Self::Refinement(refine) => refine.t.is_class(),
Self::Obj
| Self::Int
| Self::Nat
| Self::Ratio
| Self::Float
| Self::Bool
| Self::Str
| Self::NoneType
| Self::Code
| Self::Module
| Self::Frame
| Self::Error
| Self::Inf
| Self::NegInf
| Self::Type
| Self::Class
| Self::Trait
| Self::Patch
| Self::NotImplemented
| Self::Ellipsis
| Self::Never
| Self::Subr(_)
| Self::Callable { .. }
| Self::Record(_)
| Self::Quantified(_) => true,
Self::MonoClass(_) | Self::PolyClass { .. } => true,
_ => false,
}
}
pub fn is_trait(&self) -> bool {
match self {
Self::FreeVar(fv) if fv.is_linked() => fv.crack().is_trait(),
Self::Refinement(refine) => refine.t.is_trait(),
Self::MonoTrait(_) | Self::PolyTrait { .. } => true,
_ => false,
}
}
pub fn is_mut(&self) -> bool {
match self {
Self::FreeVar(fv) => {
@ -1734,11 +1674,9 @@ impl Type {
fv.unbound_name().unwrap().ends_with('!')
}
}
Self::MonoClass(name)
| Self::MonoTrait(name)
Self::Mono(name)
| Self::MonoQVar(name)
| Self::PolyClass { name, .. }
| Self::PolyTrait { name, .. }
| Self::Poly { name, .. }
| Self::PolyQVar { name, .. }
| Self::MonoProj { rhs: name, .. } => name.ends_with('!'),
Self::Refinement(refine) => refine.t.is_mut(),
@ -1750,11 +1688,11 @@ impl Type {
match self {
Self::FreeVar(fv) if fv.is_linked() => fv.crack().is_nonelike(),
Self::NoneType => true,
Self::PolyClass { name, params } if &name[..] == "Option" || &name[..] == "Option!" => {
Self::Poly { name, params } if &name[..] == "Option" || &name[..] == "Option!" => {
let inner_t = enum_unwrap!(params.first().unwrap(), TyParam::Type);
inner_t.is_nonelike()
}
Self::PolyClass { name, params } if &name[..] == "Tuple" => params.is_empty(),
Self::Poly { name, params } if &name[..] == "Tuple" => params.is_empty(),
Self::Refinement(refine) => refine.t.is_nonelike(),
_ => false,
}
@ -1773,7 +1711,7 @@ impl Type {
.map(|(sub, sup)| sub.contains_tvar(name) || sup.contains_tvar(name))
.unwrap_or(false)
}
Self::PolyClass { params, .. } | Self::PolyTrait { params, .. } => {
Self::Poly { params, .. } => {
for param in params.iter() {
match param {
TyParam::Type(t) if t.contains_tvar(name) => {
@ -1870,7 +1808,7 @@ impl Type {
Self::Error => Str::ever("Error"),
Self::Inf => Str::ever("Inf"),
Self::NegInf => Str::ever("NegInf"),
Self::MonoClass(name) | Self::MonoTrait(name) | Self::MonoQVar(name) => name.clone(),
Self::Mono(name) | Self::MonoQVar(name) => name.clone(),
Self::And(_, _) => Str::ever("And"),
Self::Not(_, _) => Str::ever("Not"),
Self::Or(_, _) => Str::ever("Or"),
@ -1894,9 +1832,7 @@ impl Type {
}) => Str::ever("ProcMethod"),
Self::Callable { .. } => Str::ever("Callable"),
Self::Record(_) => Str::ever("Record"),
Self::PolyClass { name, .. }
| Self::PolyTrait { name, .. }
| Self::PolyQVar { name, .. } => name.clone(),
Self::Poly { name, .. } | Self::PolyQVar { name, .. } => name.clone(),
// NOTE: compiler/codegen/convert_to_python_methodでクラス名を使うため、こうすると都合が良い
Self::Refinement(refine) => refine.t.name(),
Self::Quantified(_) => Str::ever("Quantified"),
@ -1967,9 +1903,7 @@ impl Type {
quant.unbound_callable.has_unbound_var()
|| quant.bounds.iter().any(|tb| tb.has_qvar())
}
Self::PolyClass { params, .. } | Self::PolyTrait { params, .. } => {
params.iter().any(|tp| tp.has_qvar())
}
Self::Poly { params, .. } => params.iter().any(|tp| tp.has_qvar()),
Self::MonoProj { lhs, .. } => lhs.has_qvar(),
_ => false,
}
@ -2006,9 +1940,9 @@ impl Type {
Self::Quantified(quant) => {
quant.unbound_callable.is_cachable() || quant.bounds.iter().all(|b| b.is_cachable())
}
Self::PolyClass { params, .. }
| Self::PolyTrait { params, .. }
| Self::PolyQVar { params, .. } => params.iter().all(|p| p.is_cachable()),
Self::Poly { params, .. } | Self::PolyQVar { params, .. } => {
params.iter().all(|p| p.is_cachable())
}
Self::MonoProj { lhs, .. } => lhs.is_cachable(),
_ => true,
}
@ -2055,9 +1989,9 @@ impl Type {
quant.unbound_callable.has_unbound_var()
|| quant.bounds.iter().any(|b| b.has_unbound_var())
}
Self::PolyClass { params, .. }
| Self::PolyTrait { params, .. }
| Self::PolyQVar { params, .. } => params.iter().any(|p| p.has_unbound_var()),
Self::Poly { params, .. } | Self::PolyQVar { params, .. } => {
params.iter().any(|p| p.has_unbound_var())
}
Self::MonoProj { lhs, .. } => lhs.has_no_unbound_var(),
_ => false,
}
@ -2082,9 +2016,7 @@ impl Type {
+ 1,
),
Self::Callable { param_ts, .. } => Some(param_ts.len() + 1),
Self::PolyClass { params, .. }
| Self::PolyTrait { params, .. }
| Self::PolyQVar { params, .. } => Some(params.len()),
Self::Poly { params, .. } | Self::PolyQVar { params, .. } => Some(params.len()),
_ => None,
}
}
@ -2100,9 +2032,7 @@ impl Type {
}
Self::Subr(subr) => subr.typarams(),
Self::Callable { param_ts: _, .. } => todo!(),
Self::PolyClass { params, .. }
| Self::PolyTrait { params, .. }
| Self::PolyQVar { params, .. } => params.clone(),
Self::Poly { params, .. } | Self::PolyQVar { params, .. } => params.clone(),
_ => vec![],
}
}
@ -2227,7 +2157,7 @@ impl From<&Type> for TypeCode {
Type::Float => Self::Float64,
Type::Bool => Self::Bool,
Type::Str => Self::Str,
Type::MonoClass(name) => match &name[..] {
Type::Mono(name) => match &name[..] {
"Int!" => Self::Int32,
"Nat!" => Self::Nat64,
"Float!" => Self::Float64,
@ -2235,7 +2165,7 @@ impl From<&Type> for TypeCode {
"Str!" => Self::Str,
_ => Self::Other,
},
Type::PolyClass { name, .. } => match &name[..] {
Type::Poly { name, .. } => match &name[..] {
"Array" | "Array!" => Self::Array,
"Func" => Self::Func,
"Proc" => Self::Proc,
@ -2404,98 +2334,98 @@ impl TypePair {
(Type::Int, Type::Float) => Self::IntFloat,
(Type::Int, Type::Str) => Self::IntStr,
(Type::Int, Type::Bool) => Self::IntBool,
(Type::Int, Type::PolyClass { name, .. }) if &name[..] == "Array" => Self::IntArray,
(Type::Int, Type::PolyClass { name, .. }) if &name[..] == "Func" => Self::IntFunc,
(Type::Int, Type::PolyClass { name, .. }) if &name[..] == "Proc" => Self::IntProc,
(Type::Int, Type::Poly { name, .. }) if &name[..] == "Array" => Self::IntArray,
(Type::Int, Type::Poly { name, .. }) if &name[..] == "Func" => Self::IntFunc,
(Type::Int, Type::Poly { name, .. }) if &name[..] == "Proc" => Self::IntProc,
(Type::Nat, Type::Int) => Self::NatInt,
(Type::Nat, Type::Nat) => Self::NatNat,
(Type::Nat, Type::Float) => Self::NatFloat,
(Type::Nat, Type::Str) => Self::NatStr,
(Type::Nat, Type::Bool) => Self::NatBool,
(Type::Nat, Type::PolyClass { name, .. }) if &name[..] == "Array" => Self::NatArray,
(Type::Nat, Type::PolyClass { name, .. }) if &name[..] == "Func" => Self::NatFunc,
(Type::Nat, Type::PolyClass { name, .. }) if &name[..] == "Proc" => Self::NatProc,
(Type::Nat, Type::Poly { name, .. }) if &name[..] == "Array" => Self::NatArray,
(Type::Nat, Type::Poly { name, .. }) if &name[..] == "Func" => Self::NatFunc,
(Type::Nat, Type::Poly { name, .. }) if &name[..] == "Proc" => Self::NatProc,
(Type::Float, Type::Int) => Self::FloatInt,
(Type::Float, Type::Nat) => Self::FloatNat,
(Type::Float, Type::Float) => Self::FloatFloat,
(Type::Float, Type::Str) => Self::FloatStr,
(Type::Float, Type::Bool) => Self::FloatBool,
(Type::Float, Type::PolyClass { name, .. }) if &name[..] == "Array" => Self::FloatArray,
(Type::Float, Type::PolyClass { name, .. }) if &name[..] == "Func" => Self::FloatFunc,
(Type::Float, Type::PolyClass { name, .. }) if &name[..] == "Proc" => Self::FloatProc,
(Type::Float, Type::Poly { name, .. }) if &name[..] == "Array" => Self::FloatArray,
(Type::Float, Type::Poly { name, .. }) if &name[..] == "Func" => Self::FloatFunc,
(Type::Float, Type::Poly { name, .. }) if &name[..] == "Proc" => Self::FloatProc,
(Type::Bool, Type::Int) => Self::BoolInt,
(Type::Bool, Type::Nat) => Self::BoolNat,
(Type::Bool, Type::Float) => Self::BoolFloat,
(Type::Bool, Type::Str) => Self::BoolStr,
(Type::Bool, Type::Bool) => Self::BoolBool,
(Type::Bool, Type::PolyClass { name, .. }) if &name[..] == "Array" => Self::BoolArray,
(Type::Bool, Type::PolyClass { name, .. }) if &name[..] == "Func" => Self::BoolFunc,
(Type::Bool, Type::PolyClass { name, .. }) if &name[..] == "Proc" => Self::BoolProc,
(Type::Bool, Type::Poly { name, .. }) if &name[..] == "Array" => Self::BoolArray,
(Type::Bool, Type::Poly { name, .. }) if &name[..] == "Func" => Self::BoolFunc,
(Type::Bool, Type::Poly { name, .. }) if &name[..] == "Proc" => Self::BoolProc,
(Type::Str, Type::Int) => Self::StrInt,
(Type::Str, Type::Nat) => Self::StrNat,
(Type::Str, Type::Float) => Self::StrFloat,
(Type::Str, Type::Bool) => Self::StrBool,
(Type::Str, Type::Str) => Self::StrStr,
(Type::Str, Type::PolyClass { name, .. }) if &name[..] == "Array" => Self::StrArray,
(Type::Str, Type::PolyClass { name, .. }) if &name[..] == "Func" => Self::StrFunc,
(Type::Str, Type::PolyClass { name, .. }) if &name[..] == "Proc" => Self::StrProc,
(Type::Str, Type::Poly { name, .. }) if &name[..] == "Array" => Self::StrArray,
(Type::Str, Type::Poly { name, .. }) if &name[..] == "Func" => Self::StrFunc,
(Type::Str, Type::Poly { name, .. }) if &name[..] == "Proc" => Self::StrProc,
// 要素数は検査済みなので、気にする必要はない
(Type::PolyClass { name, .. }, Type::Int) if &name[..] == "Array" => Self::ArrayInt,
(Type::PolyClass { name, .. }, Type::Nat) if &name[..] == "Array" => Self::ArrayNat,
(Type::PolyClass { name, .. }, Type::Float) if &name[..] == "Array" => Self::ArrayFloat,
(Type::PolyClass { name, .. }, Type::Str) if &name[..] == "Array" => Self::ArrayStr,
(Type::PolyClass { name, .. }, Type::Bool) if &name[..] == "Array" => Self::ArrayBool,
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name, .. }, Type::Int) if &name[..] == "Array" => Self::ArrayInt,
(Type::Poly { name, .. }, Type::Nat) if &name[..] == "Array" => Self::ArrayNat,
(Type::Poly { name, .. }, Type::Float) if &name[..] == "Array" => Self::ArrayFloat,
(Type::Poly { name, .. }, Type::Str) if &name[..] == "Array" => Self::ArrayStr,
(Type::Poly { name, .. }, Type::Bool) if &name[..] == "Array" => Self::ArrayBool,
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Array" && &rn[..] == "Array" =>
{
Self::ArrayArray
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Array" && &rn[..] == "Func" =>
{
Self::ArrayFunc
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Array" && &rn[..] == "Proc" =>
{
Self::ArrayProc
}
(Type::PolyClass { name, .. }, Type::Int) if &name[..] == "Func" => Self::FuncInt,
(Type::PolyClass { name, .. }, Type::Nat) if &name[..] == "Func" => Self::FuncNat,
(Type::PolyClass { name, .. }, Type::Float) if &name[..] == "Func" => Self::FuncFloat,
(Type::PolyClass { name, .. }, Type::Str) if &name[..] == "Func" => Self::FuncStr,
(Type::PolyClass { name, .. }, Type::Bool) if &name[..] == "Func" => Self::FuncBool,
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name, .. }, Type::Int) if &name[..] == "Func" => Self::FuncInt,
(Type::Poly { name, .. }, Type::Nat) if &name[..] == "Func" => Self::FuncNat,
(Type::Poly { name, .. }, Type::Float) if &name[..] == "Func" => Self::FuncFloat,
(Type::Poly { name, .. }, Type::Str) if &name[..] == "Func" => Self::FuncStr,
(Type::Poly { name, .. }, Type::Bool) if &name[..] == "Func" => Self::FuncBool,
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Func" && &rn[..] == "Array" =>
{
Self::FuncArray
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Func" && &rn[..] == "Func" =>
{
Self::FuncFunc
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Func" && &rn[..] == "Proc" =>
{
Self::FuncProc
}
(Type::PolyClass { name, .. }, Type::Int) if &name[..] == "Proc" => Self::ProcInt,
(Type::PolyClass { name, .. }, Type::Nat) if &name[..] == "Proc" => Self::ProcNat,
(Type::PolyClass { name, .. }, Type::Float) if &name[..] == "Proc" => Self::ProcFloat,
(Type::PolyClass { name, .. }, Type::Str) if &name[..] == "Proc" => Self::ProcStr,
(Type::PolyClass { name, .. }, Type::Bool) if &name[..] == "Proc" => Self::ProcBool,
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name, .. }, Type::Int) if &name[..] == "Proc" => Self::ProcInt,
(Type::Poly { name, .. }, Type::Nat) if &name[..] == "Proc" => Self::ProcNat,
(Type::Poly { name, .. }, Type::Float) if &name[..] == "Proc" => Self::ProcFloat,
(Type::Poly { name, .. }, Type::Str) if &name[..] == "Proc" => Self::ProcStr,
(Type::Poly { name, .. }, Type::Bool) if &name[..] == "Proc" => Self::ProcBool,
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Proc" && &rn[..] == "Array" =>
{
Self::ProcArray
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Proc" && &rn[..] == "Func" =>
{
Self::ProcFunc
}
(Type::PolyClass { name: ln, .. }, Type::PolyClass { name: rn, .. })
(Type::Poly { name: ln, .. }, Type::Poly { name: rn, .. })
if &ln[..] == "Proc" && &rn[..] == "Proc" =>
{
Self::ProcProc

View file

@ -17,7 +17,7 @@ use erg_common::{fmt_iter, impl_display_from_debug, switch_lang};
use erg_common::{RcArray, Str};
use crate::codeobj::CodeObj;
use crate::constructors::{array, class, poly_class, refinement, tuple};
use crate::constructors::{array, mono, poly, refinement, tuple};
use crate::free::fresh_varname;
use crate::typaram::TyParam;
use crate::{ConstSubr, HasType, Predicate, Type};
@ -384,12 +384,12 @@ impl ValueObj {
Self::Inf => Type::Inf,
Self::NegInf => Type::NegInf,
Self::Mut(m) => match &*m.borrow() {
Self::Int(_) => class("Int!"),
Self::Nat(_) => class("Nat!"),
Self::Float(_) => class("Float!"),
Self::Str(_) => class("Str!"),
Self::Bool(_) => class("Bool!"),
Self::Array(arr) => poly_class(
Self::Int(_) => mono("Int!"),
Self::Nat(_) => mono("Nat!"),
Self::Float(_) => mono("Float!"),
Self::Str(_) => mono("Str!"),
Self::Bool(_) => mono("Bool!"),
Self::Array(arr) => poly(
"Array!",
vec![
TyParam::t(arr.iter().next().unwrap().class()),