2021-08-27 12:36:51 +08:00
|
|
|
use std::collections::{HashMap, HashSet};
|
2021-08-05 14:55:09 +08:00
|
|
|
use std::convert::{From, TryInto};
|
2021-07-19 13:35:01 +08:00
|
|
|
use std::iter::once;
|
2021-08-05 14:55:09 +08:00
|
|
|
use std::{cell::RefCell, sync::Arc};
|
2021-07-19 13:35:01 +08:00
|
|
|
|
2021-07-20 11:34:32 +08:00
|
|
|
use super::typedef::{Call, FunSignature, FuncArg, Type, TypeEnum, Unifier};
|
2021-08-13 13:33:59 +08:00
|
|
|
use super::{magic_methods::*, typedef::CallId};
|
2021-08-24 17:14:34 +08:00
|
|
|
use crate::{symbol_resolver::SymbolResolver, toplevel::TopLevelContext};
|
2021-07-19 13:35:01 +08:00
|
|
|
use itertools::izip;
|
2021-11-03 17:11:00 +08:00
|
|
|
use nac3parser::ast::{
|
2021-07-20 11:34:32 +08:00
|
|
|
self,
|
|
|
|
fold::{self, Fold},
|
2021-11-06 22:48:08 +08:00
|
|
|
Arguments, Comprehension, ExprContext, ExprKind, Located, Location, StrRef,
|
2021-07-20 11:34:32 +08:00
|
|
|
};
|
2021-07-19 13:35:01 +08:00
|
|
|
|
2021-07-21 15:36:35 +08:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test;
|
|
|
|
|
2021-07-30 11:01:11 +08:00
|
|
|
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
|
|
|
|
pub struct CodeLocation {
|
|
|
|
row: usize,
|
|
|
|
col: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Location> for CodeLocation {
|
|
|
|
fn from(loc: Location) -> CodeLocation {
|
2021-08-05 14:55:09 +08:00
|
|
|
CodeLocation { row: loc.row(), col: loc.column() }
|
2021-07-30 11:01:11 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-02 11:28:05 +08:00
|
|
|
#[derive(Clone, Copy)]
|
2021-07-19 13:35:01 +08:00
|
|
|
pub struct PrimitiveStore {
|
2021-07-21 15:36:35 +08:00
|
|
|
pub int32: Type,
|
|
|
|
pub int64: Type,
|
|
|
|
pub float: Type,
|
|
|
|
pub bool: Type,
|
|
|
|
pub none: Type,
|
2021-10-23 23:53:36 +08:00
|
|
|
pub range: Type,
|
2021-11-02 23:22:37 +08:00
|
|
|
pub str: Type,
|
2022-02-12 21:09:23 +08:00
|
|
|
pub exception: Type,
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
2021-07-28 17:25:19 +08:00
|
|
|
pub struct FunctionData {
|
2021-10-16 18:08:13 +08:00
|
|
|
pub resolver: Arc<dyn SymbolResolver + Send + Sync>,
|
2021-07-28 17:25:19 +08:00
|
|
|
pub return_type: Option<Type>,
|
|
|
|
pub bound_variables: Vec<Type>,
|
|
|
|
}
|
|
|
|
|
2021-07-19 13:35:01 +08:00
|
|
|
pub struct Inferencer<'a> {
|
2021-08-11 17:28:29 +08:00
|
|
|
pub top_level: &'a TopLevelContext,
|
2021-09-22 17:19:27 +08:00
|
|
|
pub defined_identifiers: HashSet<StrRef>,
|
2021-07-28 17:25:19 +08:00
|
|
|
pub function_data: &'a mut FunctionData,
|
2021-07-21 15:36:35 +08:00
|
|
|
pub unifier: &'a mut Unifier,
|
2021-07-28 17:25:19 +08:00
|
|
|
pub primitives: &'a PrimitiveStore,
|
2021-07-27 11:58:35 +08:00
|
|
|
pub virtual_checks: &'a mut Vec<(Type, Type)>,
|
2021-09-22 17:19:27 +08:00
|
|
|
pub variable_mapping: HashMap<StrRef, Type>,
|
2021-08-13 13:33:59 +08:00
|
|
|
pub calls: &'a mut HashMap<CodeLocation, CallId>,
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
2021-07-20 16:56:04 +08:00
|
|
|
struct NaiveFolder();
|
|
|
|
impl fold::Fold<()> for NaiveFolder {
|
|
|
|
type TargetU = Option<Type>;
|
|
|
|
type Error = String;
|
|
|
|
fn map_user(&mut self, _: ()) -> Result<Self::TargetU, Self::Error> {
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-31 17:16:21 +08:00
|
|
|
fn report_error<T>(msg: &str, location: Location) -> Result<T, String> {
|
|
|
|
Err(format!("{} at {}", msg, location))
|
|
|
|
}
|
|
|
|
|
2021-07-19 17:26:51 +08:00
|
|
|
impl<'a> fold::Fold<()> for Inferencer<'a> {
|
2021-07-19 13:35:01 +08:00
|
|
|
type TargetU = Option<Type>;
|
|
|
|
type Error = String;
|
|
|
|
|
|
|
|
fn map_user(&mut self, _: ()) -> Result<Self::TargetU, Self::Error> {
|
|
|
|
Ok(None)
|
|
|
|
}
|
2021-07-19 17:26:51 +08:00
|
|
|
|
2021-11-06 22:48:08 +08:00
|
|
|
fn fold_stmt(
|
|
|
|
&mut self,
|
|
|
|
mut node: ast::Stmt<()>,
|
|
|
|
) -> Result<ast::Stmt<Self::TargetU>, Self::Error> {
|
2021-07-20 16:56:04 +08:00
|
|
|
let stmt = match node.node {
|
|
|
|
// we don't want fold over type annotation
|
2021-11-06 22:48:08 +08:00
|
|
|
ast::StmtKind::AnnAssign { mut target, annotation, value, simple, config_comment } => {
|
2021-08-27 11:13:43 +08:00
|
|
|
self.infer_pattern(&target)?;
|
2021-11-06 22:48:08 +08:00
|
|
|
// fix parser problem...
|
|
|
|
if let ExprKind::Attribute { ctx, .. } = &mut target.node {
|
|
|
|
*ctx = ExprContext::Store;
|
|
|
|
}
|
|
|
|
|
2021-07-28 10:44:58 +08:00
|
|
|
let target = Box::new(self.fold_expr(*target)?);
|
2021-07-20 16:56:04 +08:00
|
|
|
let value = if let Some(v) = value {
|
2021-07-28 10:44:58 +08:00
|
|
|
let ty = Box::new(self.fold_expr(*v)?);
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(target.custom.unwrap(), ty.custom.unwrap(), &node.location)?;
|
2021-07-20 16:56:04 +08:00
|
|
|
Some(ty)
|
|
|
|
} else {
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error(
|
|
|
|
"declaration without definition is not yet supported",
|
|
|
|
node.location,
|
|
|
|
);
|
2021-07-20 16:56:04 +08:00
|
|
|
};
|
2021-08-23 10:34:11 +08:00
|
|
|
let top_level_defs = self.top_level.definitions.read();
|
2021-09-08 19:27:32 +08:00
|
|
|
let annotation_type = self.function_data.resolver.parse_type_annotation(
|
2021-08-23 10:34:11 +08:00
|
|
|
top_level_defs.as_slice(),
|
2021-08-11 17:28:29 +08:00
|
|
|
self.unifier,
|
2021-10-16 18:08:13 +08:00
|
|
|
self.primitives,
|
2021-08-11 17:28:29 +08:00
|
|
|
annotation.as_ref(),
|
|
|
|
)?;
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(annotation_type, target.custom.unwrap(), &node.location)?;
|
2021-07-20 16:56:04 +08:00
|
|
|
let annotation = Box::new(NaiveFolder().fold_expr(*annotation)?);
|
|
|
|
Located {
|
|
|
|
location: node.location,
|
|
|
|
custom: None,
|
2021-11-06 22:48:08 +08:00
|
|
|
node: ast::StmtKind::AnnAssign {
|
|
|
|
target,
|
|
|
|
annotation,
|
|
|
|
value,
|
|
|
|
simple,
|
|
|
|
config_comment,
|
|
|
|
},
|
2021-07-20 16:56:04 +08:00
|
|
|
}
|
|
|
|
}
|
2021-12-12 05:39:48 +08:00
|
|
|
ast::StmtKind::For { target, iter, body, orelse, config_comment, type_comment } => {
|
|
|
|
self.infer_pattern(&target)?;
|
|
|
|
let target = self.fold_expr(*target)?;
|
|
|
|
let iter = self.fold_expr(*iter)?;
|
|
|
|
if self.unifier.unioned(iter.custom.unwrap(), self.primitives.range) {
|
|
|
|
self.unify(self.primitives.int32, target.custom.unwrap(), &target.location)?;
|
|
|
|
} else {
|
|
|
|
let list = self.unifier.add_ty(TypeEnum::TList { ty: target.custom.unwrap() });
|
|
|
|
self.unify(list, iter.custom.unwrap(), &iter.location)?;
|
|
|
|
}
|
|
|
|
let body = body
|
|
|
|
.into_iter()
|
|
|
|
.map(|b| self.fold_stmt(b))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
let orelse = orelse
|
|
|
|
.into_iter()
|
|
|
|
.map(|o| self.fold_stmt(o))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
Located {
|
|
|
|
location: node.location,
|
|
|
|
node: ast::StmtKind::For {
|
|
|
|
target: Box::new(target),
|
|
|
|
iter: Box::new(iter),
|
|
|
|
body,
|
|
|
|
orelse,
|
|
|
|
config_comment,
|
|
|
|
type_comment,
|
|
|
|
},
|
|
|
|
custom: None
|
|
|
|
}
|
2021-08-27 11:13:43 +08:00
|
|
|
}
|
2021-11-06 22:48:08 +08:00
|
|
|
ast::StmtKind::Assign { ref mut targets, ref config_comment, .. } => {
|
|
|
|
for target in targets.iter_mut() {
|
|
|
|
if let ExprKind::Attribute { ctx, .. } = &mut target.node {
|
|
|
|
*ctx = ExprContext::Store;
|
|
|
|
}
|
|
|
|
}
|
2021-09-22 19:25:47 +08:00
|
|
|
if targets.iter().all(|t| matches!(t.node, ast::ExprKind::Name { .. })) {
|
|
|
|
if let ast::StmtKind::Assign { targets, value, .. } = node.node {
|
|
|
|
let value = self.fold_expr(*value)?;
|
|
|
|
let value_ty = value.custom.unwrap();
|
2021-10-06 16:07:42 +08:00
|
|
|
let targets: Result<Vec<_>, _> = targets
|
|
|
|
.into_iter()
|
|
|
|
.map(|target| {
|
|
|
|
if let ast::ExprKind::Name { id, ctx } = target.node {
|
|
|
|
self.defined_identifiers.insert(id);
|
|
|
|
let target_ty = if let Some(ty) = self.variable_mapping.get(&id)
|
|
|
|
{
|
|
|
|
*ty
|
|
|
|
} else {
|
|
|
|
let unifier = &mut self.unifier;
|
|
|
|
self.function_data
|
|
|
|
.resolver
|
|
|
|
.get_symbol_type(
|
|
|
|
unifier,
|
|
|
|
&self.top_level.definitions.read(),
|
|
|
|
self.primitives,
|
|
|
|
id,
|
|
|
|
)
|
2022-01-13 03:14:06 +08:00
|
|
|
.unwrap_or_else(|_| {
|
2021-10-06 16:07:42 +08:00
|
|
|
self.variable_mapping.insert(id, value_ty);
|
|
|
|
value_ty
|
|
|
|
})
|
|
|
|
};
|
|
|
|
let location = target.location;
|
|
|
|
self.unifier.unify(value_ty, target_ty).map(|_| Located {
|
|
|
|
location,
|
|
|
|
node: ast::ExprKind::Name { id, ctx },
|
|
|
|
custom: Some(target_ty),
|
|
|
|
})
|
2021-09-22 19:25:47 +08:00
|
|
|
} else {
|
2021-10-06 16:07:42 +08:00
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect();
|
2021-09-22 19:25:47 +08:00
|
|
|
let targets = targets?;
|
|
|
|
return Ok(Located {
|
|
|
|
location: node.location,
|
|
|
|
node: ast::StmtKind::Assign {
|
|
|
|
targets,
|
|
|
|
value: Box::new(value),
|
|
|
|
type_comment: None,
|
2021-11-06 22:48:08 +08:00
|
|
|
config_comment: config_comment.clone(),
|
2021-09-22 19:25:47 +08:00
|
|
|
},
|
2021-10-06 16:07:42 +08:00
|
|
|
custom: None,
|
2021-09-22 19:25:47 +08:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
}
|
2021-08-27 11:13:43 +08:00
|
|
|
for target in targets {
|
|
|
|
self.infer_pattern(target)?;
|
|
|
|
}
|
|
|
|
fold::fold_stmt(self, node)?
|
|
|
|
}
|
2021-10-31 17:16:21 +08:00
|
|
|
ast::StmtKind::With { ref items, .. } => {
|
|
|
|
for item in items.iter() {
|
|
|
|
if let Some(var) = &item.optional_vars {
|
|
|
|
self.infer_pattern(var)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fold::fold_stmt(self, node)?
|
|
|
|
}
|
2021-07-20 16:56:04 +08:00
|
|
|
_ => fold::fold_stmt(self, node)?,
|
|
|
|
};
|
|
|
|
match &stmt.node {
|
2021-12-12 05:39:48 +08:00
|
|
|
ast::StmtKind::For { .. } => {}
|
2021-07-20 16:56:04 +08:00
|
|
|
ast::StmtKind::If { test, .. } | ast::StmtKind::While { test, .. } => {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(test.custom.unwrap(), self.primitives.bool, &test.location)?;
|
2021-07-20 16:56:04 +08:00
|
|
|
}
|
|
|
|
ast::StmtKind::Assign { targets, value, .. } => {
|
|
|
|
for target in targets.iter() {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(target.custom.unwrap(), value.custom.unwrap(), &target.location)?;
|
2021-07-20 16:56:04 +08:00
|
|
|
}
|
|
|
|
}
|
2021-07-21 15:59:01 +08:00
|
|
|
ast::StmtKind::AnnAssign { .. } | ast::StmtKind::Expr { .. } => {}
|
2021-11-06 22:48:08 +08:00
|
|
|
ast::StmtKind::Break { .. }
|
|
|
|
| ast::StmtKind::Continue { .. }
|
|
|
|
| ast::StmtKind::Pass { .. } => {}
|
2021-10-31 17:16:21 +08:00
|
|
|
ast::StmtKind::With { items, .. } => {
|
|
|
|
for item in items.iter() {
|
|
|
|
let ty = item.context_expr.custom.unwrap();
|
|
|
|
// if we can simply unify without creating new types...
|
|
|
|
let mut fast_path = false;
|
|
|
|
if let TypeEnum::TObj { fields, .. } = &*self.unifier.get_ty(ty) {
|
|
|
|
let fields = fields.borrow();
|
|
|
|
fast_path = true;
|
|
|
|
if let Some(enter) = fields.get(&"__enter__".into()).cloned() {
|
2021-11-06 22:48:08 +08:00
|
|
|
if let TypeEnum::TFunc(signature) = &*self.unifier.get_ty(enter.0) {
|
2021-10-31 17:16:21 +08:00
|
|
|
let signature = signature.borrow();
|
|
|
|
if !signature.args.is_empty() {
|
|
|
|
return report_error(
|
|
|
|
"__enter__ method should take no argument other than self",
|
2021-11-06 22:48:08 +08:00
|
|
|
stmt.location,
|
|
|
|
);
|
2021-10-31 17:16:21 +08:00
|
|
|
}
|
|
|
|
if let Some(var) = &item.optional_vars {
|
|
|
|
if signature.vars.is_empty() {
|
2021-11-06 22:48:08 +08:00
|
|
|
self.unify(
|
|
|
|
signature.ret,
|
|
|
|
var.custom.unwrap(),
|
|
|
|
&stmt.location,
|
|
|
|
)?;
|
2021-10-31 17:16:21 +08:00
|
|
|
} else {
|
|
|
|
fast_path = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fast_path = false;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return report_error(
|
|
|
|
"__enter__ method is required for context manager",
|
2021-11-06 22:48:08 +08:00
|
|
|
stmt.location,
|
2021-10-31 17:16:21 +08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
if let Some(exit) = fields.get(&"__exit__".into()).cloned() {
|
2021-11-06 22:48:08 +08:00
|
|
|
if let TypeEnum::TFunc(signature) = &*self.unifier.get_ty(exit.0) {
|
2021-10-31 17:16:21 +08:00
|
|
|
let signature = signature.borrow();
|
|
|
|
if !signature.args.is_empty() {
|
|
|
|
return report_error(
|
|
|
|
"__exit__ method should take no argument other than self",
|
2021-11-06 22:48:08 +08:00
|
|
|
stmt.location,
|
|
|
|
);
|
2021-10-31 17:16:21 +08:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fast_path = false;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return report_error(
|
|
|
|
"__exit__ method is required for context manager",
|
2021-11-06 22:48:08 +08:00
|
|
|
stmt.location,
|
2021-10-31 17:16:21 +08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !fast_path {
|
|
|
|
let enter = TypeEnum::TFunc(RefCell::new(FunSignature {
|
|
|
|
args: vec![],
|
2021-11-06 22:48:08 +08:00
|
|
|
ret: item.optional_vars.as_ref().map_or_else(
|
|
|
|
|| self.unifier.get_fresh_var().0,
|
|
|
|
|var| var.custom.unwrap(),
|
|
|
|
),
|
|
|
|
vars: Default::default(),
|
2021-10-31 17:16:21 +08:00
|
|
|
}));
|
|
|
|
let enter = self.unifier.add_ty(enter);
|
|
|
|
let exit = TypeEnum::TFunc(RefCell::new(FunSignature {
|
|
|
|
args: vec![],
|
|
|
|
ret: self.unifier.get_fresh_var().0,
|
2021-11-06 22:48:08 +08:00
|
|
|
vars: Default::default(),
|
2021-10-31 17:16:21 +08:00
|
|
|
}));
|
|
|
|
let exit = self.unifier.add_ty(exit);
|
|
|
|
let mut fields = HashMap::new();
|
2021-11-06 22:48:08 +08:00
|
|
|
fields.insert("__enter__".into(), (enter, false));
|
|
|
|
fields.insert("__exit__".into(), (exit, false));
|
2021-10-31 17:16:21 +08:00
|
|
|
let record = self.unifier.add_record(fields);
|
|
|
|
self.unify(ty, record, &stmt.location)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-04 15:02:51 +08:00
|
|
|
ast::StmtKind::Return { value, .. } => match (value, self.function_data.return_type) {
|
2021-07-22 15:36:37 +08:00
|
|
|
(Some(v), Some(v1)) => {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(v.custom.unwrap(), v1, &v.location)?;
|
2021-07-22 11:49:00 +08:00
|
|
|
}
|
2021-07-22 15:36:37 +08:00
|
|
|
(Some(_), None) => {
|
2021-10-31 17:16:21 +08:00
|
|
|
return report_error("Unexpected return value", stmt.location);
|
2021-07-22 15:36:37 +08:00
|
|
|
}
|
|
|
|
(None, Some(_)) => {
|
2021-10-31 17:16:21 +08:00
|
|
|
return report_error("Expected return value", stmt.location);
|
2021-07-22 15:36:37 +08:00
|
|
|
}
|
|
|
|
(None, None) => {}
|
|
|
|
},
|
2021-11-12 01:44:12 +08:00
|
|
|
ast::StmtKind::AugAssign { target, op, value, .. } => {
|
|
|
|
let res_ty = self.infer_bin_ops(stmt.location, target, op, value)?;
|
|
|
|
self.unify(res_ty, target.custom.unwrap(), &stmt.location)?;
|
|
|
|
}
|
2021-10-31 17:16:21 +08:00
|
|
|
_ => return report_error("Unsupported statement type", stmt.location),
|
2021-07-20 16:56:04 +08:00
|
|
|
};
|
|
|
|
Ok(stmt)
|
|
|
|
}
|
|
|
|
|
2021-07-19 17:26:51 +08:00
|
|
|
fn fold_expr(&mut self, node: ast::Expr<()>) -> Result<ast::Expr<Self::TargetU>, Self::Error> {
|
2021-07-20 11:34:32 +08:00
|
|
|
let expr = match node.node {
|
2021-07-23 15:25:44 +08:00
|
|
|
ast::ExprKind::Call { func, args, keywords } => {
|
2021-07-22 17:07:49 +08:00
|
|
|
return self.fold_call(node.location, *func, args, keywords);
|
|
|
|
}
|
2021-07-20 11:34:32 +08:00
|
|
|
ast::ExprKind::Lambda { args, body } => {
|
2021-07-22 17:07:49 +08:00
|
|
|
return self.fold_lambda(node.location, *args, *body);
|
2021-07-20 11:34:32 +08:00
|
|
|
}
|
2021-07-20 13:45:17 +08:00
|
|
|
ast::ExprKind::ListComp { elt, generators } => {
|
2021-07-22 17:07:49 +08:00
|
|
|
return self.fold_listcomp(node.location, *elt, generators);
|
2021-07-20 13:45:17 +08:00
|
|
|
}
|
2021-07-19 17:26:51 +08:00
|
|
|
_ => fold::fold_expr(self, node)?,
|
|
|
|
};
|
|
|
|
let custom = match &expr.node {
|
2022-01-14 03:05:11 +08:00
|
|
|
ast::ExprKind::Constant { value, .. } =>
|
|
|
|
Some(self.infer_constant(value, &expr.location)?),
|
2021-08-27 11:13:43 +08:00
|
|
|
ast::ExprKind::Name { id, .. } => {
|
|
|
|
if !self.defined_identifiers.contains(id) {
|
2022-01-13 03:14:06 +08:00
|
|
|
match self.function_data.resolver.get_symbol_type(
|
|
|
|
self.unifier,
|
|
|
|
&self.top_level.definitions.read(),
|
|
|
|
self.primitives,
|
|
|
|
*id,
|
|
|
|
) {
|
|
|
|
Ok(_) => {
|
|
|
|
self.defined_identifiers.insert(*id);
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
return report_error(
|
2022-01-14 16:56:23 +08:00
|
|
|
&format!("type error at identifier `{}` ({})", id, e),
|
2022-01-13 03:14:06 +08:00
|
|
|
expr.location,
|
|
|
|
);
|
|
|
|
}
|
2021-08-27 11:13:43 +08:00
|
|
|
}
|
|
|
|
}
|
2021-09-22 17:19:27 +08:00
|
|
|
Some(self.infer_identifier(*id)?)
|
2021-08-27 11:13:43 +08:00
|
|
|
}
|
2021-07-19 17:26:51 +08:00
|
|
|
ast::ExprKind::List { elts, .. } => Some(self.infer_list(elts)?),
|
|
|
|
ast::ExprKind::Tuple { elts, .. } => Some(self.infer_tuple(elts)?),
|
2021-11-06 22:48:08 +08:00
|
|
|
ast::ExprKind::Attribute { value, attr, ctx } => {
|
|
|
|
Some(self.infer_attribute(value, *attr, ctx)?)
|
2021-07-23 15:25:44 +08:00
|
|
|
}
|
2021-07-22 15:36:37 +08:00
|
|
|
ast::ExprKind::BoolOp { values, .. } => Some(self.infer_bool_ops(values)?),
|
2021-09-22 15:56:53 +08:00
|
|
|
ast::ExprKind::BinOp { left, op, right } => {
|
|
|
|
Some(self.infer_bin_ops(expr.location, left, op, right)?)
|
|
|
|
}
|
2021-07-19 17:26:51 +08:00
|
|
|
ast::ExprKind::UnaryOp { op, operand } => Some(self.infer_unary_ops(op, operand)?),
|
2021-07-23 15:25:44 +08:00
|
|
|
ast::ExprKind::Compare { left, ops, comparators } => {
|
|
|
|
Some(self.infer_compare(left, ops, comparators)?)
|
|
|
|
}
|
2021-07-20 13:45:17 +08:00
|
|
|
ast::ExprKind::Subscript { value, slice, .. } => {
|
|
|
|
Some(self.infer_subscript(value.as_ref(), slice.as_ref())?)
|
|
|
|
}
|
2021-07-19 17:26:51 +08:00
|
|
|
ast::ExprKind::IfExp { test, body, orelse } => {
|
|
|
|
Some(self.infer_if_expr(test, body.as_ref(), orelse.as_ref())?)
|
|
|
|
}
|
2021-07-20 16:13:43 +08:00
|
|
|
ast::ExprKind::ListComp { .. }
|
|
|
|
| ast::ExprKind::Lambda { .. }
|
|
|
|
| ast::ExprKind::Call { .. } => expr.custom, // already computed
|
2021-07-19 17:26:51 +08:00
|
|
|
ast::ExprKind::Slice { .. } => None, // we don't need it for slice
|
2022-01-14 03:05:11 +08:00
|
|
|
_ => return report_error("not supported", expr.location),
|
2021-07-19 17:26:51 +08:00
|
|
|
};
|
2021-07-23 15:25:44 +08:00
|
|
|
Ok(ast::Expr { custom, location: expr.location, node: expr.node })
|
2021-07-19 17:26:51 +08:00
|
|
|
}
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type InferenceResult = Result<Type, String>;
|
|
|
|
|
|
|
|
impl<'a> Inferencer<'a> {
|
2021-07-19 17:05:48 +08:00
|
|
|
/// Constrain a <: b
|
|
|
|
/// Currently implemented as unification
|
2021-08-21 14:51:46 +08:00
|
|
|
fn constrain(&mut self, a: Type, b: Type, location: &Location) -> Result<(), String> {
|
|
|
|
self.unifier.unify(a, b).map_err(|old| format!("{} at {}", old, location))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn unify(&mut self, a: Type, b: Type, location: &Location) -> Result<(), String> {
|
|
|
|
self.unifier.unify(a, b).map_err(|old| format!("{} at {}", old, location))
|
2021-07-19 17:05:48 +08:00
|
|
|
}
|
|
|
|
|
2021-08-27 11:13:43 +08:00
|
|
|
fn infer_pattern(&mut self, pattern: &ast::Expr<()>) -> Result<(), String> {
|
|
|
|
match &pattern.node {
|
|
|
|
ExprKind::Name { id, .. } => {
|
|
|
|
if !self.defined_identifiers.contains(id) {
|
2021-09-22 17:56:48 +08:00
|
|
|
self.defined_identifiers.insert(*id);
|
2021-08-27 11:13:43 +08:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
ExprKind::Tuple { elts, .. } => {
|
|
|
|
for elt in elts.iter() {
|
|
|
|
self.infer_pattern(elt)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
_ => Ok(()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-19 13:35:01 +08:00
|
|
|
fn build_method_call(
|
|
|
|
&mut self,
|
2021-08-07 10:41:53 +08:00
|
|
|
location: Location,
|
2021-09-22 17:19:27 +08:00
|
|
|
method: StrRef,
|
2021-07-19 13:35:01 +08:00
|
|
|
obj: Type,
|
|
|
|
params: Vec<Type>,
|
2021-09-22 15:43:44 +08:00
|
|
|
ret: Option<Type>,
|
2021-07-19 13:35:01 +08:00
|
|
|
) -> InferenceResult {
|
2021-09-22 15:43:44 +08:00
|
|
|
if let TypeEnum::TObj { params: class_params, fields, .. } = &*self.unifier.get_ty(obj) {
|
|
|
|
if class_params.borrow().is_empty() {
|
|
|
|
if let Some(ty) = fields.borrow().get(&method) {
|
2021-11-06 22:48:08 +08:00
|
|
|
let ty = ty.0;
|
|
|
|
if let TypeEnum::TFunc(sign) = &*self.unifier.get_ty(ty) {
|
2021-09-22 15:43:44 +08:00
|
|
|
let sign = sign.borrow();
|
|
|
|
if sign.vars.is_empty() {
|
2021-09-22 17:45:21 +08:00
|
|
|
let call = Call {
|
2021-09-22 17:26:19 +08:00
|
|
|
posargs: params,
|
|
|
|
kwargs: HashMap::new(),
|
|
|
|
ret: sign.ret,
|
|
|
|
fun: RefCell::new(None),
|
2021-09-22 17:45:21 +08:00
|
|
|
};
|
2021-09-22 15:43:44 +08:00
|
|
|
if let Some(ret) = ret {
|
|
|
|
self.unifier.unify(sign.ret, ret).unwrap();
|
|
|
|
}
|
2021-09-22 17:45:21 +08:00
|
|
|
let required: Vec<_> = sign
|
|
|
|
.args
|
|
|
|
.iter()
|
|
|
|
.filter(|v| v.default_value.is_none())
|
|
|
|
.map(|v| v.name)
|
|
|
|
.rev()
|
|
|
|
.collect();
|
|
|
|
self.unifier
|
2021-11-06 22:48:08 +08:00
|
|
|
.unify_call(&call, ty, &sign, &required)
|
2021-09-22 17:45:21 +08:00
|
|
|
.map_err(|old| format!("{} at {}", old, location))?;
|
2021-09-22 15:56:53 +08:00
|
|
|
return Ok(sign.ret);
|
2021-09-22 15:43:44 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let ret = ret.unwrap_or_else(|| self.unifier.get_fresh_var().0);
|
|
|
|
|
2021-08-13 13:33:59 +08:00
|
|
|
let call = self.unifier.add_call(Call {
|
2021-08-05 14:55:09 +08:00
|
|
|
posargs: params,
|
|
|
|
kwargs: HashMap::new(),
|
|
|
|
ret,
|
|
|
|
fun: RefCell::new(None),
|
|
|
|
});
|
2021-08-13 13:33:59 +08:00
|
|
|
self.calls.insert(location.into(), call);
|
2021-07-23 15:25:44 +08:00
|
|
|
let call = self.unifier.add_ty(TypeEnum::TCall(vec![call].into()));
|
2021-11-06 22:48:08 +08:00
|
|
|
let fields = once((method, (call, false))).collect();
|
2021-07-23 15:25:44 +08:00
|
|
|
let record = self.unifier.add_record(fields);
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(obj, record, &location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(ret)
|
|
|
|
}
|
|
|
|
|
2021-07-20 11:34:32 +08:00
|
|
|
fn fold_lambda(
|
|
|
|
&mut self,
|
|
|
|
location: Location,
|
|
|
|
args: Arguments,
|
|
|
|
body: ast::Expr<()>,
|
|
|
|
) -> Result<ast::Expr<Option<Type>>, String> {
|
|
|
|
if !args.posonlyargs.is_empty()
|
|
|
|
|| args.vararg.is_some()
|
|
|
|
|| !args.kwonlyargs.is_empty()
|
|
|
|
|| args.kwarg.is_some()
|
|
|
|
|| !args.defaults.is_empty()
|
|
|
|
{
|
|
|
|
// actually I'm not sure whether programs violating this is a valid python program.
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error(
|
|
|
|
"We only support positional or keyword arguments without defaults for lambdas",
|
|
|
|
if args.args.is_empty() { body.location } else { args.args[0].location },
|
2021-07-20 11:34:32 +08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-08-27 11:13:43 +08:00
|
|
|
let mut defined_identifiers = self.defined_identifiers.clone();
|
|
|
|
for arg in args.args.iter() {
|
|
|
|
let name = &arg.node.arg;
|
|
|
|
if !defined_identifiers.contains(name) {
|
2021-09-22 17:56:48 +08:00
|
|
|
defined_identifiers.insert(*name);
|
2021-08-27 11:13:43 +08:00
|
|
|
}
|
|
|
|
}
|
2021-10-06 16:07:42 +08:00
|
|
|
let fn_args: Vec<_> =
|
|
|
|
args.args.iter().map(|v| (v.node.arg, self.unifier.get_fresh_var().0)).collect();
|
2021-07-20 11:34:32 +08:00
|
|
|
let mut variable_mapping = self.variable_mapping.clone();
|
|
|
|
variable_mapping.extend(fn_args.iter().cloned());
|
|
|
|
let ret = self.unifier.get_fresh_var().0;
|
2021-08-27 11:13:43 +08:00
|
|
|
|
2021-07-20 11:34:32 +08:00
|
|
|
let mut new_context = Inferencer {
|
2021-07-28 17:25:19 +08:00
|
|
|
function_data: self.function_data,
|
2021-07-20 11:34:32 +08:00
|
|
|
unifier: self.unifier,
|
2021-07-28 17:25:19 +08:00
|
|
|
primitives: self.primitives,
|
2021-07-27 11:58:35 +08:00
|
|
|
virtual_checks: self.virtual_checks,
|
2021-07-30 11:01:11 +08:00
|
|
|
calls: self.calls,
|
2021-08-11 17:28:29 +08:00
|
|
|
top_level: self.top_level,
|
2021-08-27 11:13:43 +08:00
|
|
|
defined_identifiers,
|
2021-07-20 11:34:32 +08:00
|
|
|
variable_mapping,
|
|
|
|
};
|
|
|
|
let fun = FunSignature {
|
|
|
|
args: fn_args
|
|
|
|
.iter()
|
2021-09-22 17:56:48 +08:00
|
|
|
.map(|(k, ty)| FuncArg { name: *k, ty: *ty, default_value: None })
|
2021-07-20 11:34:32 +08:00
|
|
|
.collect(),
|
|
|
|
ret,
|
|
|
|
vars: Default::default(),
|
|
|
|
};
|
|
|
|
let body = new_context.fold_expr(body)?;
|
2021-08-21 14:51:46 +08:00
|
|
|
new_context.unify(fun.ret, body.custom.unwrap(), &location)?;
|
2021-07-20 11:34:32 +08:00
|
|
|
let mut args = new_context.fold_arguments(args)?;
|
|
|
|
for (arg, (name, ty)) in args.args.iter_mut().zip(fn_args.iter()) {
|
|
|
|
assert_eq!(&arg.node.arg, name);
|
|
|
|
arg.custom = Some(*ty);
|
|
|
|
}
|
|
|
|
Ok(Located {
|
|
|
|
location,
|
2021-07-23 15:25:44 +08:00
|
|
|
node: ExprKind::Lambda { args: args.into(), body: body.into() },
|
2021-08-16 13:49:10 +08:00
|
|
|
custom: Some(self.unifier.add_ty(TypeEnum::TFunc(fun.into()))),
|
2021-07-20 11:34:32 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-07-20 13:45:17 +08:00
|
|
|
fn fold_listcomp(
|
|
|
|
&mut self,
|
|
|
|
location: Location,
|
|
|
|
elt: ast::Expr<()>,
|
|
|
|
mut generators: Vec<Comprehension>,
|
|
|
|
) -> Result<ast::Expr<Option<Type>>, String> {
|
|
|
|
if generators.len() != 1 {
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error(
|
|
|
|
"Only 1 generator statement for list comprehension is supported",
|
|
|
|
generators[0].target.location,
|
2021-07-20 13:45:17 +08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
let variable_mapping = self.variable_mapping.clone();
|
2021-08-27 11:13:43 +08:00
|
|
|
let defined_identifiers = self.defined_identifiers.clone();
|
2021-07-20 13:45:17 +08:00
|
|
|
let mut new_context = Inferencer {
|
2021-07-28 17:25:19 +08:00
|
|
|
function_data: self.function_data,
|
2021-07-20 13:45:17 +08:00
|
|
|
unifier: self.unifier,
|
2021-07-27 11:58:35 +08:00
|
|
|
virtual_checks: self.virtual_checks,
|
2021-08-11 17:28:29 +08:00
|
|
|
top_level: self.top_level,
|
2021-07-20 13:45:17 +08:00
|
|
|
variable_mapping,
|
|
|
|
primitives: self.primitives,
|
2021-07-30 11:01:11 +08:00
|
|
|
calls: self.calls,
|
2021-08-27 11:13:43 +08:00
|
|
|
defined_identifiers,
|
2021-07-20 13:45:17 +08:00
|
|
|
};
|
|
|
|
let generator = generators.pop().unwrap();
|
|
|
|
if generator.is_async {
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error("Async iterator not supported", generator.target.location);
|
2021-07-20 13:45:17 +08:00
|
|
|
}
|
2021-08-27 11:13:43 +08:00
|
|
|
new_context.infer_pattern(&generator.target)?;
|
2021-07-20 13:45:17 +08:00
|
|
|
let target = new_context.fold_expr(*generator.target)?;
|
|
|
|
let iter = new_context.fold_expr(*generator.iter)?;
|
2021-10-23 23:53:36 +08:00
|
|
|
if new_context.unifier.unioned(iter.custom.unwrap(), new_context.primitives.range) {
|
2021-11-06 22:48:08 +08:00
|
|
|
new_context.unify(
|
|
|
|
target.custom.unwrap(),
|
|
|
|
new_context.primitives.int32,
|
|
|
|
&target.location,
|
|
|
|
)?;
|
2021-10-23 23:53:36 +08:00
|
|
|
} else {
|
|
|
|
let list = new_context.unifier.add_ty(TypeEnum::TList { ty: target.custom.unwrap() });
|
|
|
|
new_context.unify(iter.custom.unwrap(), list, &iter.location)?;
|
|
|
|
}
|
2021-07-20 13:45:17 +08:00
|
|
|
let ifs: Vec<_> = generator
|
|
|
|
.ifs
|
|
|
|
.into_iter()
|
|
|
|
.map(|v| new_context.fold_expr(v))
|
|
|
|
.collect::<Result<_, _>>()?;
|
|
|
|
|
2021-10-16 15:56:13 +08:00
|
|
|
let elt = new_context.fold_expr(elt)?;
|
2021-07-20 13:45:17 +08:00
|
|
|
// iter should be a list of targets...
|
|
|
|
// actually it should be an iterator of targets, but we don't have iter type for now
|
|
|
|
// if conditions should be bool
|
|
|
|
for v in ifs.iter() {
|
2021-08-21 14:51:46 +08:00
|
|
|
new_context.unify(v.custom.unwrap(), new_context.primitives.bool, &v.location)?;
|
2021-07-20 13:45:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Located {
|
|
|
|
location,
|
2021-07-23 15:25:44 +08:00
|
|
|
custom: Some(new_context.unifier.add_ty(TypeEnum::TList { ty: elt.custom.unwrap() })),
|
2021-07-20 13:45:17 +08:00
|
|
|
node: ExprKind::ListComp {
|
|
|
|
elt: Box::new(elt),
|
|
|
|
generators: vec![ast::Comprehension {
|
|
|
|
target: Box::new(target),
|
|
|
|
iter: Box::new(iter),
|
|
|
|
ifs,
|
|
|
|
is_async: false,
|
|
|
|
}],
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-07-20 16:13:43 +08:00
|
|
|
fn fold_call(
|
|
|
|
&mut self,
|
|
|
|
location: Location,
|
|
|
|
func: ast::Expr<()>,
|
|
|
|
mut args: Vec<ast::Expr<()>>,
|
|
|
|
keywords: Vec<Located<ast::KeywordData>>,
|
|
|
|
) -> Result<ast::Expr<Option<Type>>, String> {
|
2021-07-23 15:25:44 +08:00
|
|
|
let func =
|
|
|
|
if let Located { location: func_location, custom, node: ExprKind::Name { id, ctx } } =
|
|
|
|
func
|
|
|
|
{
|
|
|
|
// handle special functions that cannot be typed in the usual way...
|
2021-09-22 17:19:27 +08:00
|
|
|
if id == "virtual".into() {
|
2021-07-23 15:25:44 +08:00
|
|
|
if args.is_empty() || args.len() > 2 || !keywords.is_empty() {
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error(
|
|
|
|
"`virtual` can only accept 1/2 positional arguments",
|
|
|
|
func_location,
|
2021-07-23 15:25:44 +08:00
|
|
|
);
|
2021-07-20 16:13:43 +08:00
|
|
|
}
|
2021-07-23 15:25:44 +08:00
|
|
|
let arg0 = self.fold_expr(args.remove(0))?;
|
|
|
|
let ty = if let Some(arg) = args.pop() {
|
2021-08-23 10:34:11 +08:00
|
|
|
let top_level_defs = self.top_level.definitions.read();
|
2021-09-08 19:27:32 +08:00
|
|
|
self.function_data.resolver.parse_type_annotation(
|
2021-08-23 10:34:11 +08:00
|
|
|
top_level_defs.as_slice(),
|
2021-08-11 17:28:29 +08:00
|
|
|
self.unifier,
|
|
|
|
self.primitives,
|
|
|
|
&arg,
|
|
|
|
)?
|
2021-07-23 15:25:44 +08:00
|
|
|
} else {
|
|
|
|
self.unifier.get_fresh_var().0
|
|
|
|
};
|
2021-07-27 11:58:35 +08:00
|
|
|
self.virtual_checks.push((arg0.custom.unwrap(), ty));
|
2021-07-23 15:25:44 +08:00
|
|
|
let custom = Some(self.unifier.add_ty(TypeEnum::TVirtual { ty }));
|
2021-07-20 16:13:43 +08:00
|
|
|
return Ok(Located {
|
2021-07-23 15:25:44 +08:00
|
|
|
location,
|
2021-07-20 16:13:43 +08:00
|
|
|
custom,
|
2021-07-23 15:25:44 +08:00
|
|
|
node: ExprKind::Call {
|
|
|
|
func: Box::new(Located {
|
|
|
|
custom: None,
|
|
|
|
location: func.location,
|
|
|
|
node: ExprKind::Name { id, ctx },
|
|
|
|
}),
|
|
|
|
args: vec![arg0],
|
|
|
|
keywords: vec![],
|
2021-07-20 16:13:43 +08:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
2021-07-23 15:25:44 +08:00
|
|
|
// int64 is special because its argument can be a constant larger than int32
|
2021-09-22 17:19:27 +08:00
|
|
|
if id == "int64".into() && args.len() == 1 {
|
2021-07-23 15:25:44 +08:00
|
|
|
if let ExprKind::Constant { value: ast::Constant::Int(val), kind } =
|
|
|
|
&args[0].node
|
|
|
|
{
|
2021-12-26 00:23:54 +08:00
|
|
|
let custom = Some(self.primitives.int64);
|
|
|
|
if val.is_none() {
|
2022-01-14 03:05:11 +08:00
|
|
|
return report_error("Integer out of bound", args[0].location);
|
2021-07-23 15:25:44 +08:00
|
|
|
}
|
|
|
|
return Ok(Located {
|
|
|
|
location: args[0].location,
|
|
|
|
custom,
|
|
|
|
node: ExprKind::Constant {
|
2022-01-09 01:05:17 +08:00
|
|
|
value: ast::Constant::Int(*val),
|
2021-07-23 15:25:44 +08:00
|
|
|
kind: kind.clone(),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Located { location: func_location, custom, node: ExprKind::Name { id, ctx } }
|
|
|
|
} else {
|
|
|
|
func
|
|
|
|
};
|
2021-07-20 16:13:43 +08:00
|
|
|
let func = Box::new(self.fold_expr(func)?);
|
2021-07-23 15:25:44 +08:00
|
|
|
let args = args.into_iter().map(|v| self.fold_expr(v)).collect::<Result<Vec<_>, _>>()?;
|
2021-07-20 16:13:43 +08:00
|
|
|
let keywords = keywords
|
|
|
|
.into_iter()
|
|
|
|
.map(|v| fold::fold_keyword(self, v))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
2021-09-22 15:43:44 +08:00
|
|
|
|
|
|
|
if let TypeEnum::TFunc(sign) = &*self.unifier.get_ty(func.custom.unwrap()) {
|
|
|
|
let sign = sign.borrow();
|
|
|
|
if sign.vars.is_empty() {
|
2021-09-22 17:45:21 +08:00
|
|
|
let call = Call {
|
2021-09-22 17:26:19 +08:00
|
|
|
posargs: args.iter().map(|v| v.custom.unwrap()).collect(),
|
|
|
|
kwargs: keywords
|
|
|
|
.iter()
|
2021-09-22 17:56:48 +08:00
|
|
|
.map(|v| (*v.node.arg.as_ref().unwrap(), v.custom.unwrap()))
|
2021-09-22 17:26:19 +08:00
|
|
|
.collect(),
|
|
|
|
fun: RefCell::new(None),
|
|
|
|
ret: sign.ret,
|
2021-09-22 17:45:21 +08:00
|
|
|
};
|
|
|
|
let required: Vec<_> = sign
|
|
|
|
.args
|
|
|
|
.iter()
|
|
|
|
.filter(|v| v.default_value.is_none())
|
|
|
|
.map(|v| v.name)
|
|
|
|
.rev()
|
|
|
|
.collect();
|
|
|
|
self.unifier
|
|
|
|
.unify_call(&call, func.custom.unwrap(), &sign, &required)
|
|
|
|
.map_err(|old| format!("{} at {}", old, location))?;
|
2021-09-22 15:56:53 +08:00
|
|
|
return Ok(Located {
|
|
|
|
location,
|
|
|
|
custom: Some(sign.ret),
|
|
|
|
node: ExprKind::Call { func, args, keywords },
|
2021-09-22 15:43:44 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-20 16:13:43 +08:00
|
|
|
let ret = self.unifier.get_fresh_var().0;
|
2021-08-13 13:33:59 +08:00
|
|
|
let call = self.unifier.add_call(Call {
|
2021-07-20 16:13:43 +08:00
|
|
|
posargs: args.iter().map(|v| v.custom.unwrap()).collect(),
|
|
|
|
kwargs: keywords
|
|
|
|
.iter()
|
2021-09-22 17:56:48 +08:00
|
|
|
.map(|v| (*v.node.arg.as_ref().unwrap(), v.custom.unwrap()))
|
2021-07-20 16:13:43 +08:00
|
|
|
.collect(),
|
|
|
|
fun: RefCell::new(None),
|
|
|
|
ret,
|
|
|
|
});
|
2021-08-13 13:33:59 +08:00
|
|
|
self.calls.insert(location.into(), call);
|
2021-07-23 15:25:44 +08:00
|
|
|
let call = self.unifier.add_ty(TypeEnum::TCall(vec![call].into()));
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(func.custom.unwrap(), call, &func.location)?;
|
2021-07-20 16:13:43 +08:00
|
|
|
|
2021-07-23 15:25:44 +08:00
|
|
|
Ok(Located { location, custom: Some(ret), node: ExprKind::Call { func, args, keywords } })
|
2021-07-20 16:13:43 +08:00
|
|
|
}
|
|
|
|
|
2021-09-22 17:19:27 +08:00
|
|
|
fn infer_identifier(&mut self, id: StrRef) -> InferenceResult {
|
|
|
|
if let Some(ty) = self.variable_mapping.get(&id) {
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(*ty)
|
|
|
|
} else {
|
2021-09-06 19:23:04 +08:00
|
|
|
let variable_mapping = &mut self.variable_mapping;
|
|
|
|
let unifier = &mut self.unifier;
|
2021-09-08 19:45:36 +08:00
|
|
|
Ok(self
|
|
|
|
.function_data
|
|
|
|
.resolver
|
2021-10-06 16:07:42 +08:00
|
|
|
.get_symbol_type(unifier, &self.top_level.definitions.read(), self.primitives, id)
|
2022-01-13 03:14:06 +08:00
|
|
|
.unwrap_or_else(|_| {
|
2021-09-08 19:45:36 +08:00
|
|
|
let ty = unifier.get_fresh_var().0;
|
2021-09-22 17:19:27 +08:00
|
|
|
variable_mapping.insert(id, ty);
|
2021-09-08 19:45:36 +08:00
|
|
|
ty
|
|
|
|
}))
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-14 03:05:11 +08:00
|
|
|
fn infer_constant(&mut self, constant: &ast::Constant, loc: &Location) -> InferenceResult {
|
2021-07-19 13:35:01 +08:00
|
|
|
match constant {
|
|
|
|
ast::Constant::Bool(_) => Ok(self.primitives.bool),
|
|
|
|
ast::Constant::Int(val) => {
|
2021-12-26 00:23:54 +08:00
|
|
|
match val {
|
|
|
|
Some(val) => {
|
|
|
|
let int32: Result<i32, _> = (*val).try_into();
|
|
|
|
// int64 is handled separately in functions
|
|
|
|
if int32.is_ok() {
|
|
|
|
Ok(self.primitives.int32)
|
|
|
|
} else {
|
2022-01-14 03:05:11 +08:00
|
|
|
report_error("Integer out of bound", *loc)
|
2021-12-26 00:23:54 +08:00
|
|
|
}
|
|
|
|
},
|
2022-01-14 03:05:11 +08:00
|
|
|
None => report_error("Integer out of bound", *loc)
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
ast::Constant::Float(_) => Ok(self.primitives.float),
|
|
|
|
ast::Constant::Tuple(vals) => {
|
2022-01-14 03:05:11 +08:00
|
|
|
let ty: Result<Vec<_>, _> =
|
|
|
|
vals.iter().map(|x| self.infer_constant(x, loc)).collect();
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(self.unifier.add_ty(TypeEnum::TTuple { ty: ty? }))
|
|
|
|
}
|
2021-11-02 23:22:37 +08:00
|
|
|
ast::Constant::Str(_) => Ok(self.primitives.str),
|
2022-01-14 03:05:11 +08:00
|
|
|
_ => report_error("not supported", *loc),
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_list(&mut self, elts: &[ast::Expr<Option<Type>>]) -> InferenceResult {
|
|
|
|
let (ty, _) = self.unifier.get_fresh_var();
|
|
|
|
for t in elts.iter() {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.unify(ty, t.custom.unwrap(), &t.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
2021-07-21 16:06:06 +08:00
|
|
|
Ok(self.unifier.add_ty(TypeEnum::TList { ty }))
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_tuple(&mut self, elts: &[ast::Expr<Option<Type>>]) -> InferenceResult {
|
|
|
|
let ty = elts.iter().map(|x| x.custom.unwrap()).collect();
|
|
|
|
Ok(self.unifier.add_ty(TypeEnum::TTuple { ty }))
|
|
|
|
}
|
|
|
|
|
2021-09-22 17:19:27 +08:00
|
|
|
fn infer_attribute(
|
|
|
|
&mut self,
|
|
|
|
value: &ast::Expr<Option<Type>>,
|
|
|
|
attr: StrRef,
|
2021-11-06 22:48:08 +08:00
|
|
|
ctx: &ExprContext,
|
2021-09-22 17:19:27 +08:00
|
|
|
) -> InferenceResult {
|
2021-11-06 22:48:08 +08:00
|
|
|
let ty = value.custom.unwrap();
|
|
|
|
if let TypeEnum::TObj { fields, .. } = &*self.unifier.get_ty(ty) {
|
|
|
|
// just a fast path
|
|
|
|
let fields = fields.borrow();
|
|
|
|
match (fields.get(&attr), ctx == &ExprContext::Store) {
|
|
|
|
(Some((ty, true)), _) => Ok(*ty),
|
|
|
|
(Some((ty, false)), false) => Ok(*ty),
|
|
|
|
(Some((_, false)), true) => {
|
|
|
|
report_error(&format!("Field {} should be immutable", attr), value.location)
|
|
|
|
}
|
|
|
|
(None, _) => report_error(&format!("No such field {}", attr), value.location),
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let (attr_ty, _) = self.unifier.get_fresh_var();
|
|
|
|
let fields = once((attr, (attr_ty, ctx == &ExprContext::Store))).collect();
|
|
|
|
let record = self.unifier.add_record(fields);
|
|
|
|
self.constrain(value.custom.unwrap(), record, &value.location)?;
|
|
|
|
Ok(attr_ty)
|
|
|
|
}
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_bool_ops(&mut self, values: &[ast::Expr<Option<Type>>]) -> InferenceResult {
|
|
|
|
let b = self.primitives.bool;
|
|
|
|
for v in values {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(v.custom.unwrap(), b, &v.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
Ok(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_bin_ops(
|
|
|
|
&mut self,
|
2021-09-20 15:50:38 +08:00
|
|
|
location: Location,
|
2021-07-19 13:35:01 +08:00
|
|
|
left: &ast::Expr<Option<Type>>,
|
|
|
|
op: &ast::Operator,
|
|
|
|
right: &ast::Expr<Option<Type>>,
|
|
|
|
) -> InferenceResult {
|
2021-09-22 17:19:27 +08:00
|
|
|
let method = binop_name(op).into();
|
2021-07-19 13:35:01 +08:00
|
|
|
self.build_method_call(
|
2021-09-20 15:50:38 +08:00
|
|
|
location,
|
2021-09-22 17:19:27 +08:00
|
|
|
method,
|
2021-07-19 13:35:01 +08:00
|
|
|
left.custom.unwrap(),
|
|
|
|
vec![right.custom.unwrap()],
|
2021-09-22 15:43:44 +08:00
|
|
|
None,
|
2021-07-19 13:35:01 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_unary_ops(
|
|
|
|
&mut self,
|
|
|
|
op: &ast::Unaryop,
|
|
|
|
operand: &ast::Expr<Option<Type>>,
|
|
|
|
) -> InferenceResult {
|
2021-09-22 17:19:27 +08:00
|
|
|
let method = unaryop_name(op).into();
|
|
|
|
self.build_method_call(operand.location, method, operand.custom.unwrap(), vec![], None)
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_compare(
|
|
|
|
&mut self,
|
|
|
|
left: &ast::Expr<Option<Type>>,
|
|
|
|
ops: &[ast::Cmpop],
|
|
|
|
comparators: &[ast::Expr<Option<Type>>],
|
|
|
|
) -> InferenceResult {
|
|
|
|
let boolean = self.primitives.bool;
|
|
|
|
for (a, b, c) in izip!(once(left).chain(comparators), comparators, ops) {
|
2021-07-23 15:25:44 +08:00
|
|
|
let method =
|
2021-09-22 17:19:27 +08:00
|
|
|
comparison_name(c).ok_or_else(|| "unsupported comparator".to_string())?.into();
|
2021-08-07 17:25:14 +08:00
|
|
|
self.build_method_call(
|
|
|
|
a.location,
|
|
|
|
method,
|
|
|
|
a.custom.unwrap(),
|
|
|
|
vec![b.custom.unwrap()],
|
2021-09-22 15:43:44 +08:00
|
|
|
Some(boolean),
|
2021-08-07 17:25:14 +08:00
|
|
|
)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
Ok(boolean)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_subscript(
|
|
|
|
&mut self,
|
|
|
|
value: &ast::Expr<Option<Type>>,
|
|
|
|
slice: &ast::Expr<Option<Type>>,
|
|
|
|
) -> InferenceResult {
|
|
|
|
let ty = self.unifier.get_fresh_var().0;
|
|
|
|
match &slice.node {
|
|
|
|
ast::ExprKind::Slice { lower, upper, step } => {
|
2021-07-23 15:25:44 +08:00
|
|
|
for v in [lower.as_ref(), upper.as_ref(), step.as_ref()].iter().flatten() {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(v.custom.unwrap(), self.primitives.int32, &v.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
let list = self.unifier.add_ty(TypeEnum::TList { ty });
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(value.custom.unwrap(), list, &value.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(list)
|
|
|
|
}
|
2021-07-23 15:25:44 +08:00
|
|
|
ast::ExprKind::Constant { value: ast::Constant::Int(val), .. } => {
|
2021-07-19 17:05:48 +08:00
|
|
|
// the index is a constant, so value can be a sequence.
|
2021-12-26 00:23:54 +08:00
|
|
|
let ind: Option<i32> = match val {
|
|
|
|
Some(val) => (*val).try_into().ok(),
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
let ind = ind.ok_or_else(|| "Index must be int32".to_string())?;
|
2021-07-19 13:35:01 +08:00
|
|
|
let map = once((ind, ty)).collect();
|
2021-07-23 15:25:44 +08:00
|
|
|
let seq = self.unifier.add_sequence(map);
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(value.custom.unwrap(), seq, &value.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(ty)
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
// the index is not a constant, so value can only be a list
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(slice.custom.unwrap(), self.primitives.int32, &slice.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
let list = self.unifier.add_ty(TypeEnum::TList { ty });
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(value.custom.unwrap(), list, &value.location)?;
|
2021-07-19 13:35:01 +08:00
|
|
|
Ok(ty)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn infer_if_expr(
|
|
|
|
&mut self,
|
|
|
|
test: &ast::Expr<Option<Type>>,
|
2021-07-19 17:26:51 +08:00
|
|
|
body: &ast::Expr<Option<Type>>,
|
|
|
|
orelse: &ast::Expr<Option<Type>>,
|
2021-07-19 13:35:01 +08:00
|
|
|
) -> InferenceResult {
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(test.custom.unwrap(), self.primitives.bool, &test.location)?;
|
2021-07-19 17:05:48 +08:00
|
|
|
let ty = self.unifier.get_fresh_var().0;
|
2021-08-21 14:51:46 +08:00
|
|
|
self.constrain(body.custom.unwrap(), ty, &body.location)?;
|
|
|
|
self.constrain(orelse.custom.unwrap(), ty, &orelse.location)?;
|
2021-07-19 17:05:48 +08:00
|
|
|
Ok(ty)
|
2021-07-19 13:35:01 +08:00
|
|
|
}
|
|
|
|
}
|