2021-08-24 17:14:34 +08:00
|
|
|
use super::*;
|
2021-08-25 13:39:55 +08:00
|
|
|
|
2021-08-24 17:14:34 +08:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub enum TypeAnnotation {
|
|
|
|
PrimitiveKind(Type),
|
2021-08-25 13:39:55 +08:00
|
|
|
// we use type vars kind at
|
|
|
|
// params to represent self type
|
|
|
|
CustomClassKind {
|
2021-08-24 17:14:34 +08:00
|
|
|
id: DefinitionId,
|
|
|
|
// can not be type var, others are all fine
|
|
|
|
// TODO: can also be type var?
|
|
|
|
params: Vec<TypeAnnotation>,
|
|
|
|
},
|
2021-08-25 13:39:55 +08:00
|
|
|
// can only be CustomClassKind
|
2021-08-24 17:14:34 +08:00
|
|
|
VirtualKind(Box<TypeAnnotation>),
|
|
|
|
// the first u32 refers to the var_id of the
|
|
|
|
// TVar returned by the symbol resolver,
|
|
|
|
// this is used to handle type vars
|
|
|
|
// associated with class/functions
|
|
|
|
// since when associating we create a copy of type vars
|
|
|
|
TypeVarKind(u32, Type),
|
|
|
|
}
|
2021-08-24 17:43:41 +08:00
|
|
|
|
2021-08-26 15:24:04 +08:00
|
|
|
/// if is typevar, this function will make a copy of it
|
2021-08-24 17:14:34 +08:00
|
|
|
pub fn parse_ast_to_type_annotation_kinds<T>(
|
2021-08-25 15:29:58 +08:00
|
|
|
resolver: &Box<dyn SymbolResolver + Send + Sync>,
|
2021-08-24 17:14:34 +08:00
|
|
|
top_level_defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
primitives: &PrimitiveStore,
|
|
|
|
expr: &ast::Expr<T>,
|
|
|
|
) -> Result<TypeAnnotation, String> {
|
2021-08-24 17:43:41 +08:00
|
|
|
match &expr.node {
|
|
|
|
ast::ExprKind::Name { id, .. } => match id.as_str() {
|
|
|
|
"int32" => Ok(TypeAnnotation::PrimitiveKind(primitives.int32)),
|
|
|
|
"int64" => Ok(TypeAnnotation::PrimitiveKind(primitives.int64)),
|
|
|
|
"float" => Ok(TypeAnnotation::PrimitiveKind(primitives.float)),
|
|
|
|
"bool" => Ok(TypeAnnotation::PrimitiveKind(primitives.bool)),
|
|
|
|
"None" => Ok(TypeAnnotation::PrimitiveKind(primitives.none)),
|
|
|
|
x => {
|
|
|
|
if let Some(obj_id) = resolver.get_identifier_def(x) {
|
|
|
|
let def = top_level_defs[obj_id.0].read();
|
2021-08-26 11:54:37 +08:00
|
|
|
if let TopLevelDef::Class { type_vars, .. } = &*def {
|
|
|
|
// also check param number here
|
|
|
|
if !type_vars.is_empty() {
|
2021-08-27 01:39:15 +08:00
|
|
|
return Err(format!(
|
|
|
|
"expect {} type variable parameter but got 0",
|
|
|
|
type_vars.len()
|
|
|
|
));
|
2021-08-26 11:54:37 +08:00
|
|
|
}
|
2021-08-27 01:39:15 +08:00
|
|
|
Ok(TypeAnnotation::CustomClassKind { id: obj_id, params: vec![] })
|
2021-08-24 17:43:41 +08:00
|
|
|
} else {
|
|
|
|
Err("function cannot be used as a type".into())
|
|
|
|
}
|
|
|
|
} else if let Some(ty) = resolver.get_symbol_type(unifier, primitives, id) {
|
2021-08-27 01:39:15 +08:00
|
|
|
if let TypeEnum::TVar { id, .. } = unifier.get_ty(ty).as_ref() {
|
2021-08-24 17:43:41 +08:00
|
|
|
// NOTE: always create a new one here
|
|
|
|
// and later unify if needed
|
2021-08-25 13:39:55 +08:00
|
|
|
// but record the var_id of the original type var
|
|
|
|
// returned by symbol resolver
|
2021-08-24 17:43:41 +08:00
|
|
|
Ok(TypeAnnotation::TypeVarKind(
|
2021-08-26 15:24:04 +08:00
|
|
|
// this id is the id of the top level type var
|
2021-08-24 17:43:41 +08:00
|
|
|
*id,
|
2021-08-27 01:39:15 +08:00
|
|
|
duplicate_type_var(unifier, ty).0,
|
2021-08-24 17:43:41 +08:00
|
|
|
))
|
|
|
|
} else {
|
|
|
|
Err("not a type variable identifier".into())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Err("name cannot be parsed as a type annotation".into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2021-08-26 11:54:37 +08:00
|
|
|
// TODO: subscript or call for virtual?
|
2021-08-24 17:43:41 +08:00
|
|
|
ast::ExprKind::Subscript { value, slice, .. }
|
|
|
|
if { matches!(&value.node, ast::ExprKind::Name { id, .. } if id == "virtual") } =>
|
|
|
|
{
|
|
|
|
let def = parse_ast_to_type_annotation_kinds(
|
|
|
|
resolver,
|
|
|
|
top_level_defs,
|
|
|
|
unifier,
|
|
|
|
primitives,
|
|
|
|
slice.as_ref(),
|
|
|
|
)?;
|
2021-08-25 13:39:55 +08:00
|
|
|
if !matches!(def, TypeAnnotation::CustomClassKind { .. }) {
|
2021-08-24 17:43:41 +08:00
|
|
|
unreachable!("must be concretized custom class kind in the virtual")
|
|
|
|
}
|
|
|
|
Ok(TypeAnnotation::VirtualKind(def.into()))
|
|
|
|
}
|
|
|
|
|
|
|
|
ast::ExprKind::Subscript { value, slice, .. } => {
|
|
|
|
if let ast::ExprKind::Name { id, .. } = &value.node {
|
|
|
|
if vec!["virtual", "Generic"].contains(&id.as_str()) {
|
|
|
|
return Err("keywords cannot be class name".into());
|
|
|
|
}
|
|
|
|
let obj_id = resolver
|
|
|
|
.get_identifier_def(id)
|
|
|
|
.ok_or_else(|| "unknown class name".to_string())?;
|
|
|
|
let def = top_level_defs[obj_id.0].read();
|
2021-08-26 11:54:37 +08:00
|
|
|
if let TopLevelDef::Class { type_vars, .. } = &*def {
|
2021-08-24 17:43:41 +08:00
|
|
|
let param_type_infos = if let ast::ExprKind::Tuple { elts, .. } = &slice.node {
|
|
|
|
elts.iter()
|
|
|
|
.map(|v| {
|
|
|
|
parse_ast_to_type_annotation_kinds(
|
|
|
|
resolver,
|
|
|
|
top_level_defs,
|
|
|
|
unifier,
|
|
|
|
primitives,
|
|
|
|
v,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.collect::<Result<Vec<_>, _>>()?
|
|
|
|
} else {
|
|
|
|
vec![parse_ast_to_type_annotation_kinds(
|
|
|
|
resolver,
|
|
|
|
top_level_defs,
|
|
|
|
unifier,
|
|
|
|
primitives,
|
|
|
|
slice,
|
|
|
|
)?]
|
|
|
|
};
|
2021-08-26 11:54:37 +08:00
|
|
|
if type_vars.len() != param_type_infos.len() {
|
|
|
|
return Err(format!(
|
|
|
|
"expect {} type parameters but got {}",
|
|
|
|
type_vars.len(),
|
|
|
|
param_type_infos.len()
|
2021-08-27 01:39:15 +08:00
|
|
|
));
|
2021-08-26 11:54:37 +08:00
|
|
|
}
|
2021-08-24 17:43:41 +08:00
|
|
|
// NOTE: allow type var in class generic application list
|
2021-08-27 01:39:15 +08:00
|
|
|
Ok(TypeAnnotation::CustomClassKind { id: obj_id, params: param_type_infos })
|
2021-08-24 17:43:41 +08:00
|
|
|
} else {
|
|
|
|
Err("function cannot be used as a type".into())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Err("unsupported expression type for class name".into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_ => Err("unsupported expression for type annotation".into()),
|
2021-08-24 17:14:34 +08:00
|
|
|
}
|
|
|
|
}
|
2021-08-24 17:43:41 +08:00
|
|
|
|
2021-08-26 15:24:04 +08:00
|
|
|
/// if is typeannotation::tvar, this function will NOT make a copy of it
|
2021-08-24 17:14:34 +08:00
|
|
|
pub fn get_type_from_type_annotation_kinds(
|
|
|
|
top_level_defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
primitives: &PrimitiveStore,
|
|
|
|
ann: &TypeAnnotation,
|
|
|
|
) -> Result<Type, String> {
|
|
|
|
match ann {
|
2021-08-25 13:39:55 +08:00
|
|
|
TypeAnnotation::CustomClassKind { id, params } => {
|
2021-08-24 17:14:34 +08:00
|
|
|
let class_def = top_level_defs[id.0].read();
|
|
|
|
if let TopLevelDef::Class { fields, methods, type_vars, .. } = &*class_def {
|
|
|
|
if type_vars.len() != params.len() {
|
|
|
|
Err(format!(
|
|
|
|
"unexpected number of type parameters: expected {} but got {}",
|
|
|
|
type_vars.len(),
|
|
|
|
params.len()
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
let param_ty = params
|
|
|
|
.iter()
|
|
|
|
.map(|x| {
|
|
|
|
get_type_from_type_annotation_kinds(
|
|
|
|
top_level_defs,
|
|
|
|
unifier,
|
|
|
|
primitives,
|
|
|
|
x,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
2021-08-27 01:39:15 +08:00
|
|
|
// NOTE: cannot directy subst type var here? need to subst types in fields/methods?
|
2021-08-24 17:14:34 +08:00
|
|
|
let subst = type_vars
|
|
|
|
.iter()
|
|
|
|
.map(|x| {
|
|
|
|
if let TypeEnum::TVar { id, .. } = unifier.get_ty(x.1).as_ref() {
|
|
|
|
// this is for the class generic application,
|
|
|
|
// we only need the information for the copied type var
|
|
|
|
// associated with the class
|
|
|
|
*id
|
|
|
|
} else {
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.zip(param_ty.into_iter())
|
|
|
|
.collect::<HashMap<u32, Type>>();
|
|
|
|
let mut tobj_fields = methods
|
|
|
|
.iter()
|
|
|
|
.map(|(name, ty, _)| {
|
|
|
|
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
|
|
|
|
(name.clone(), subst_ty)
|
|
|
|
})
|
|
|
|
.collect::<HashMap<String, Type>>();
|
|
|
|
tobj_fields.extend(fields.iter().map(|(name, ty)| {
|
|
|
|
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
|
|
|
|
(name.clone(), subst_ty)
|
|
|
|
}));
|
|
|
|
Ok(unifier.add_ty(TypeEnum::TObj {
|
|
|
|
obj_id: *id,
|
|
|
|
fields: tobj_fields.into(),
|
|
|
|
params: subst.into(),
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
unreachable!("should be class def here")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
TypeAnnotation::PrimitiveKind(ty) => Ok(*ty),
|
|
|
|
TypeAnnotation::TypeVarKind(_, ty) => Ok(*ty),
|
|
|
|
TypeAnnotation::VirtualKind(ty) => {
|
|
|
|
let ty = get_type_from_type_annotation_kinds(
|
|
|
|
top_level_defs,
|
|
|
|
unifier,
|
|
|
|
primitives,
|
|
|
|
ty.as_ref(),
|
|
|
|
)?;
|
|
|
|
Ok(unifier.add_ty(TypeEnum::TVirtual { ty }))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-08-25 13:39:55 +08:00
|
|
|
|
|
|
|
/// the first return is the duplicated type \
|
|
|
|
/// the second return is the var_id of the duplicated type \
|
|
|
|
/// the third return is the var_id of the original type
|
2021-08-27 01:39:15 +08:00
|
|
|
pub fn duplicate_type_var(unifier: &mut Unifier, type_var: Type) -> (Type, u32, u32) {
|
2021-08-25 13:39:55 +08:00
|
|
|
let ty = unifier.get_ty(type_var);
|
|
|
|
if let TypeEnum::TVar { id, range, .. } = ty.as_ref() {
|
|
|
|
let range = range.borrow();
|
|
|
|
let range = range.as_slice();
|
2021-08-25 14:59:31 +08:00
|
|
|
let dup = unifier.get_fresh_var_with_range(range);
|
|
|
|
(dup.0, dup.1, *id)
|
2021-08-25 13:39:55 +08:00
|
|
|
} else {
|
|
|
|
unreachable!("must be type var here to be duplicated");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// given an def id, return a type annotation of self \
|
|
|
|
/// ```python
|
|
|
|
/// class A(Generic[T, V]):
|
|
|
|
/// def fun(self):
|
|
|
|
/// ```
|
2021-08-26 15:24:04 +08:00
|
|
|
/// the type of `self` should be similar to `A[T, V]`, where `T`, `V`
|
|
|
|
/// considered to be type variables associated with the class \
|
|
|
|
/// \
|
|
|
|
/// But note that here we do not make a duplication of `T`, `V`, we direclty
|
|
|
|
/// use them as they are in the TopLevelDef::Class since those in the
|
|
|
|
/// TopLevelDef::Class.type_vars will be substitute later when seeing applications/instantiations
|
|
|
|
/// the Type of their fields and methods will also be subst when application/instantiation \
|
|
|
|
/// \
|
|
|
|
/// Note this implicit self type is different with seeing `A[T, V]` explicitly outside
|
|
|
|
/// the class def ast body, where it is a new instantiation of the generic class `A`,
|
|
|
|
/// but equivalent to seeing `A[T, V]` inside the class def body ast, where although we
|
|
|
|
/// create copies of `T` and `V`, we will find them out as occured type vars in the analyze_class()
|
|
|
|
/// and unify them with the class generic `T`, `V`
|
2021-08-25 13:39:55 +08:00
|
|
|
pub fn make_self_type_annotation(
|
|
|
|
top_level_defs: &[Arc<RwLock<TopLevelDef>>],
|
2021-08-27 16:38:42 +08:00
|
|
|
def_id: DefinitionId
|
2021-08-25 13:39:55 +08:00
|
|
|
) -> Result<TypeAnnotation, String> {
|
2021-08-27 01:39:15 +08:00
|
|
|
let obj_def =
|
|
|
|
top_level_defs.get(def_id.0).ok_or_else(|| "invalid definition id".to_string())?;
|
2021-08-25 13:39:55 +08:00
|
|
|
let obj_def = obj_def.read();
|
|
|
|
let obj_def = obj_def.deref();
|
|
|
|
|
|
|
|
if let TopLevelDef::Class { type_vars, .. } = obj_def {
|
|
|
|
Ok(TypeAnnotation::CustomClassKind {
|
|
|
|
id: def_id,
|
|
|
|
params: type_vars
|
|
|
|
.iter()
|
2021-08-27 01:39:15 +08:00
|
|
|
// NOTE: here the var_id also points to the var_id of
|
2021-08-26 15:24:04 +08:00
|
|
|
// the top level defined type var's var id
|
|
|
|
.map(|(var_id, ty)| TypeAnnotation::TypeVarKind(*var_id, *ty))
|
2021-08-27 01:39:15 +08:00
|
|
|
.collect_vec(),
|
2021-08-25 13:39:55 +08:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
unreachable!("must be top level class def here")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// get all the occurences of type vars contained in a type annotation
|
|
|
|
/// e.g. `A[int, B[T], V]` => [T, V]
|
2021-08-26 15:24:04 +08:00
|
|
|
/// this function will not make a duplicate of type var
|
2021-08-25 13:39:55 +08:00
|
|
|
pub fn get_type_var_contained_in_type_annotation(ann: &TypeAnnotation) -> Vec<TypeAnnotation> {
|
|
|
|
let mut result: Vec<TypeAnnotation> = Vec::new();
|
|
|
|
match ann {
|
2021-08-27 01:39:15 +08:00
|
|
|
TypeAnnotation::TypeVarKind(..) => result.push(ann.clone()),
|
|
|
|
TypeAnnotation::VirtualKind(ann) => {
|
|
|
|
result.extend(get_type_var_contained_in_type_annotation(ann.as_ref()))
|
|
|
|
}
|
2021-08-25 13:39:55 +08:00
|
|
|
TypeAnnotation::CustomClassKind { params, .. } => {
|
|
|
|
for p in params {
|
|
|
|
result.extend(get_type_var_contained_in_type_annotation(p));
|
|
|
|
}
|
2021-08-27 01:39:15 +08:00
|
|
|
}
|
|
|
|
_ => {}
|
2021-08-25 13:39:55 +08:00
|
|
|
}
|
|
|
|
result
|
|
|
|
}
|