2021-10-06 16:07:42 +08:00
|
|
|
use inkwell::{types::BasicType, values::BasicValueEnum, AddressSpace};
|
2021-09-23 19:30:03 +08:00
|
|
|
use nac3core::{
|
2021-12-27 22:55:51 +08:00
|
|
|
codegen::{CodeGenContext, CodeGenerator},
|
2021-11-27 21:29:27 +08:00
|
|
|
symbol_resolver::{StaticValue, SymbolResolver, SymbolValue, ValueEnum},
|
2021-10-06 16:07:42 +08:00
|
|
|
toplevel::{DefinitionId, TopLevelDef},
|
2021-09-23 19:30:03 +08:00
|
|
|
typecheck::{
|
|
|
|
type_inferencer::PrimitiveStore,
|
2021-10-06 16:07:42 +08:00
|
|
|
typedef::{Type, TypeEnum, Unifier},
|
2021-09-23 19:30:03 +08:00
|
|
|
},
|
|
|
|
};
|
2021-11-27 21:29:27 +08:00
|
|
|
use nac3parser::ast::{self, StrRef};
|
2021-09-30 22:30:54 +08:00
|
|
|
use parking_lot::{Mutex, RwLock};
|
2021-10-06 16:07:42 +08:00
|
|
|
use pyo3::{
|
2021-12-05 20:30:03 +08:00
|
|
|
types::{PyDict, PyTuple},
|
2021-10-06 16:07:42 +08:00
|
|
|
PyAny, PyObject, PyResult, Python,
|
|
|
|
};
|
|
|
|
use std::{
|
|
|
|
collections::{HashMap, HashSet},
|
|
|
|
sync::Arc,
|
|
|
|
};
|
|
|
|
|
|
|
|
use crate::PrimitivePythonId;
|
2021-09-23 19:30:03 +08:00
|
|
|
|
2021-12-05 20:30:03 +08:00
|
|
|
pub enum PrimitiveValue {
|
|
|
|
I32(i32),
|
|
|
|
I64(i64),
|
2022-03-05 03:45:09 +08:00
|
|
|
U32(u32),
|
|
|
|
U64(u64),
|
2021-12-05 20:30:03 +08:00
|
|
|
F64(f64),
|
|
|
|
Bool(bool),
|
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
pub struct InnerResolver {
|
2021-12-05 20:30:03 +08:00
|
|
|
pub id_to_type: RwLock<HashMap<StrRef, Type>>,
|
|
|
|
pub id_to_def: RwLock<HashMap<StrRef, DefinitionId>>,
|
|
|
|
pub id_to_pyval: RwLock<HashMap<StrRef, (u64, PyObject)>>,
|
|
|
|
pub id_to_primitive: RwLock<HashMap<u64, PrimitiveValue>>,
|
|
|
|
pub field_to_val: RwLock<HashMap<(u64, StrRef), Option<(u64, PyObject)>>>,
|
|
|
|
pub global_value_ids: Arc<RwLock<HashSet<u64>>>,
|
2021-09-24 09:58:58 +08:00
|
|
|
pub class_names: Mutex<HashMap<StrRef, Type>>,
|
2021-09-30 22:30:54 +08:00
|
|
|
pub pyid_to_def: Arc<RwLock<HashMap<u64, DefinitionId>>>,
|
|
|
|
pub pyid_to_type: Arc<RwLock<HashMap<u64, Type>>>,
|
2021-10-06 16:07:42 +08:00
|
|
|
pub primitive_ids: PrimitivePythonId,
|
2021-11-20 21:15:15 +08:00
|
|
|
pub helper: PythonHelper,
|
2022-02-12 21:17:37 +08:00
|
|
|
pub string_store: Arc<RwLock<HashMap<String, i32>>>,
|
2022-03-05 00:26:35 +08:00
|
|
|
pub exception_ids: Arc<RwLock<HashMap<usize, usize>>>,
|
2021-09-30 22:30:54 +08:00
|
|
|
// module specific
|
|
|
|
pub name_to_pyid: HashMap<StrRef, u64>,
|
2021-10-06 16:07:42 +08:00
|
|
|
pub module: PyObject,
|
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
pub struct Resolver(pub Arc<InnerResolver>);
|
|
|
|
|
2021-12-04 22:57:48 +08:00
|
|
|
#[derive(Clone)]
|
2021-11-20 21:15:15 +08:00
|
|
|
pub struct PythonHelper {
|
|
|
|
pub type_fn: PyObject,
|
|
|
|
pub len_fn: PyObject,
|
|
|
|
pub id_fn: PyObject,
|
2021-12-01 22:44:53 +08:00
|
|
|
pub origin_ty_fn: PyObject,
|
|
|
|
pub args_ty_fn: PyObject,
|
2022-02-12 21:17:37 +08:00
|
|
|
pub store_obj: PyObject,
|
|
|
|
pub store_str: PyObject,
|
2021-11-20 21:15:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
struct PythonValue {
|
|
|
|
id: u64,
|
|
|
|
value: PyObject,
|
2022-02-12 21:17:37 +08:00
|
|
|
store_obj: PyObject,
|
2021-11-20 21:15:15 +08:00
|
|
|
resolver: Arc<InnerResolver>,
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
impl StaticValue for PythonValue {
|
|
|
|
fn get_unique_identifier(&self) -> u64 {
|
|
|
|
self.id
|
|
|
|
}
|
|
|
|
|
2022-02-12 21:17:37 +08:00
|
|
|
fn get_const_obj<'ctx, 'a>(
|
|
|
|
&self,
|
|
|
|
ctx: &mut CodeGenContext<'ctx, 'a>,
|
|
|
|
_: &mut dyn CodeGenerator,
|
|
|
|
) -> BasicValueEnum<'ctx> {
|
|
|
|
ctx.module
|
|
|
|
.get_global(self.id.to_string().as_str())
|
|
|
|
.map(|val| val.as_pointer_value().into())
|
|
|
|
.unwrap_or_else(|| {
|
|
|
|
Python::with_gil(|py| -> PyResult<BasicValueEnum<'ctx>> {
|
|
|
|
let id: u32 = self.store_obj.call1(py, (self.value.clone(),))?.extract(py)?;
|
|
|
|
let struct_type = ctx.ctx.struct_type(&[ctx.ctx.i32_type().into()], false);
|
2022-02-21 18:27:46 +08:00
|
|
|
let global = ctx.module.add_global(
|
|
|
|
struct_type,
|
|
|
|
None,
|
|
|
|
format!("{}_const", self.id).as_str(),
|
|
|
|
);
|
2022-02-12 21:17:37 +08:00
|
|
|
global.set_constant(true);
|
|
|
|
global.set_initializer(&ctx.ctx.const_struct(
|
|
|
|
&[ctx.ctx.i32_type().const_int(id as u64, false).into()],
|
|
|
|
false,
|
|
|
|
));
|
2022-02-21 18:27:46 +08:00
|
|
|
let global2 = ctx.module.add_global(
|
|
|
|
struct_type.ptr_type(AddressSpace::Generic),
|
|
|
|
None,
|
|
|
|
format!("{}_const2", self.id).as_str(),
|
|
|
|
);
|
2022-02-12 21:17:37 +08:00
|
|
|
global2.set_initializer(&global.as_pointer_value());
|
|
|
|
Ok(global2.as_pointer_value().into())
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
fn to_basic_value_enum<'ctx, 'a>(
|
|
|
|
&self,
|
|
|
|
ctx: &mut CodeGenContext<'ctx, 'a>,
|
2021-12-27 22:55:51 +08:00
|
|
|
generator: &mut dyn CodeGenerator,
|
2022-02-28 23:09:14 +08:00
|
|
|
) -> Result<BasicValueEnum<'ctx>, String> {
|
2021-12-05 20:30:03 +08:00
|
|
|
if let Some(val) = self.resolver.id_to_primitive.read().get(&self.id) {
|
2022-02-28 23:09:14 +08:00
|
|
|
return Ok(match val {
|
2021-12-05 20:30:03 +08:00
|
|
|
PrimitiveValue::I32(val) => ctx.ctx.i32_type().const_int(*val as u64, false).into(),
|
|
|
|
PrimitiveValue::I64(val) => ctx.ctx.i64_type().const_int(*val as u64, false).into(),
|
2022-03-05 03:45:09 +08:00
|
|
|
PrimitiveValue::U32(val) => ctx.ctx.i32_type().const_int(*val as u64, false).into(),
|
|
|
|
PrimitiveValue::U64(val) => ctx.ctx.i64_type().const_int(*val as u64, false).into(),
|
2021-12-05 20:30:03 +08:00
|
|
|
PrimitiveValue::F64(val) => ctx.ctx.f64_type().const_float(*val).into(),
|
|
|
|
PrimitiveValue::Bool(val) => {
|
|
|
|
ctx.ctx.bool_type().const_int(*val as u64, false).into()
|
|
|
|
}
|
2022-02-28 23:09:14 +08:00
|
|
|
});
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
|
|
|
if let Some(global) = ctx.module.get_global(&self.id.to_string()) {
|
2022-02-28 23:09:14 +08:00
|
|
|
return Ok(global.as_pointer_value().into());
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
Python::with_gil(|py| -> PyResult<BasicValueEnum<'ctx>> {
|
|
|
|
self.resolver
|
2021-12-27 22:55:51 +08:00
|
|
|
.get_obj_value(py, self.value.as_ref(py), ctx, generator)
|
2021-11-20 21:15:15 +08:00
|
|
|
.map(Option::unwrap)
|
2022-02-28 23:09:14 +08:00
|
|
|
}).map_err(|e| e.to_string())
|
2021-11-20 21:15:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn get_field<'ctx, 'a>(
|
|
|
|
&self,
|
|
|
|
name: StrRef,
|
|
|
|
ctx: &mut CodeGenContext<'ctx, 'a>,
|
|
|
|
) -> Option<ValueEnum<'ctx>> {
|
2021-12-05 20:30:03 +08:00
|
|
|
{
|
|
|
|
let field_to_val = self.resolver.field_to_val.read();
|
|
|
|
field_to_val.get(&(self.id, name)).cloned()
|
|
|
|
}
|
|
|
|
.unwrap_or_else(|| {
|
|
|
|
Python::with_gil(|py| -> PyResult<Option<(u64, PyObject)>> {
|
|
|
|
let helper = &self.resolver.helper;
|
|
|
|
let ty = helper.type_fn.call1(py, (&self.value,))?;
|
|
|
|
let ty_id: u64 = helper.id_fn.call1(py, (ty,))?.extract(py)?;
|
|
|
|
let def_id = { *self.resolver.pyid_to_def.read().get(&ty_id).unwrap() };
|
|
|
|
let mut mutable = true;
|
|
|
|
let defs = ctx.top_level.definitions.read();
|
|
|
|
if let TopLevelDef::Class { fields, .. } = &*defs[def_id.0].read() {
|
|
|
|
for (field_name, _, is_mutable) in fields.iter() {
|
|
|
|
if field_name == &name {
|
|
|
|
mutable = *is_mutable;
|
|
|
|
break;
|
|
|
|
}
|
2021-11-20 21:15:15 +08:00
|
|
|
}
|
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
let result = if mutable {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let obj = self.value.getattr(py, &name.to_string())?;
|
|
|
|
let id = self.resolver.helper.id_fn.call1(py, (&obj,))?.extract(py)?;
|
|
|
|
Some((id, obj))
|
|
|
|
};
|
2022-02-21 18:27:46 +08:00
|
|
|
self.resolver.field_to_val.write().insert((self.id, name), result.clone());
|
2021-12-05 20:30:03 +08:00
|
|
|
Ok(result)
|
2021-11-20 21:15:15 +08:00
|
|
|
})
|
2021-12-05 20:30:03 +08:00
|
|
|
.unwrap()
|
|
|
|
})
|
|
|
|
.map(|(id, obj)| {
|
|
|
|
ValueEnum::Static(Arc::new(PythonValue {
|
|
|
|
id,
|
|
|
|
value: obj,
|
2022-02-12 21:17:37 +08:00
|
|
|
store_obj: self.store_obj.clone(),
|
2021-12-05 20:30:03 +08:00
|
|
|
resolver: self.resolver.clone(),
|
|
|
|
}))
|
2021-11-20 21:15:15 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl InnerResolver {
|
2021-10-06 16:07:42 +08:00
|
|
|
fn get_list_elem_type(
|
|
|
|
&self,
|
2021-11-20 21:15:15 +08:00
|
|
|
py: Python,
|
2021-10-06 16:07:42 +08:00
|
|
|
list: &PyAny,
|
|
|
|
len: usize,
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
primitives: &PrimitiveStore,
|
2022-01-13 03:14:06 +08:00
|
|
|
) -> PyResult<Result<Type, String>> {
|
|
|
|
let mut ty = match self.get_obj_type(py, list.get_item(0)?, unifier, defs, primitives)? {
|
|
|
|
Ok(t) => t,
|
2022-02-21 18:27:46 +08:00
|
|
|
Err(e) => return Ok(Err(format!("type error ({}) at element #0 of the list", e))),
|
2022-01-13 03:14:06 +08:00
|
|
|
};
|
|
|
|
for i in 1..len {
|
|
|
|
let b = match list
|
2021-10-06 16:07:42 +08:00
|
|
|
.get_item(i)
|
2022-02-21 18:27:46 +08:00
|
|
|
.map(|elem| self.get_obj_type(py, elem, unifier, defs, primitives))??
|
|
|
|
{
|
|
|
|
Ok(t) => t,
|
|
|
|
Err(e) => {
|
|
|
|
return Ok(Err(format!("type error ({}) at element #{} of the list", e, i)))
|
|
|
|
}
|
|
|
|
};
|
2022-01-13 03:14:06 +08:00
|
|
|
ty = match unifier.unify(ty, b) {
|
|
|
|
Ok(_) => ty,
|
2022-02-21 18:27:46 +08:00
|
|
|
Err(e) => {
|
|
|
|
return Ok(Err(format!(
|
|
|
|
"inhomogeneous type ({}) at element #{} of the list",
|
|
|
|
e.to_display(unifier).to_string(),
|
|
|
|
i
|
|
|
|
)))
|
|
|
|
}
|
2022-01-13 03:14:06 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
Ok(Ok(ty))
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
|
2021-12-01 22:44:53 +08:00
|
|
|
// handle python objects that represent types themselves
|
|
|
|
// primitives and class types should be themselves, use `ty_id` to check,
|
|
|
|
// TypeVars and GenericAlias(`A[int, bool]`) should use `ty_ty_id` to check
|
|
|
|
// the `bool` value returned indicates whether they are instantiated or not
|
|
|
|
fn get_pyty_obj_type(
|
2021-10-06 16:07:42 +08:00
|
|
|
&self,
|
2021-11-20 21:15:15 +08:00
|
|
|
py: Python,
|
2021-12-01 22:44:53 +08:00
|
|
|
pyty: &PyAny,
|
2021-10-06 16:07:42 +08:00
|
|
|
unifier: &mut Unifier,
|
|
|
|
defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
primitives: &PrimitiveStore,
|
2021-12-01 22:44:53 +08:00
|
|
|
) -> PyResult<Result<(Type, bool), String>> {
|
2021-12-05 20:30:03 +08:00
|
|
|
let ty_id: u64 = self.helper.id_fn.call1(py, (pyty,))?.extract(py)?;
|
2022-02-21 18:27:46 +08:00
|
|
|
let ty_ty_id: u64 =
|
|
|
|
self.helper.id_fn.call1(py, (self.helper.type_fn.call1(py, (pyty,))?,))?.extract(py)?;
|
2021-10-06 16:07:42 +08:00
|
|
|
|
|
|
|
if ty_id == self.primitive_ids.int || ty_id == self.primitive_ids.int32 {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(Ok((primitives.int32, true)))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.int64 {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(Ok((primitives.int64, true)))
|
2022-03-05 03:45:09 +08:00
|
|
|
} else if ty_id == self.primitive_ids.uint32 {
|
|
|
|
Ok(Ok((primitives.uint32, true)))
|
|
|
|
} else if ty_id == self.primitive_ids.uint64 {
|
|
|
|
Ok(Ok((primitives.uint64, true)))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.bool {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(Ok((primitives.bool, true)))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.float {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(Ok((primitives.float, true)))
|
2022-02-12 21:17:37 +08:00
|
|
|
} else if ty_id == self.primitive_ids.exception {
|
|
|
|
Ok(Ok((primitives.exception, true)))
|
2022-02-21 18:27:46 +08:00
|
|
|
} else if ty_id == self.primitive_ids.list {
|
2021-12-01 22:44:53 +08:00
|
|
|
// do not handle type var param and concrete check here
|
2022-02-21 17:52:34 +08:00
|
|
|
let var = unifier.get_dummy_var().0;
|
2021-12-01 22:44:53 +08:00
|
|
|
let list = unifier.add_ty(TypeEnum::TList { ty: var });
|
|
|
|
Ok(Ok((list, false)))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.tuple {
|
2021-12-01 22:44:53 +08:00
|
|
|
// do not handle type var param and concrete check here
|
|
|
|
Ok(Ok((unifier.add_ty(TypeEnum::TTuple { ty: vec![] }), false)))
|
|
|
|
} else if let Some(def_id) = self.pyid_to_def.read().get(&ty_id).cloned() {
|
2021-10-07 15:57:45 +08:00
|
|
|
let def = defs[def_id.0].read();
|
2022-02-21 18:27:46 +08:00
|
|
|
if let TopLevelDef::Class { object_id, type_vars, fields, methods, .. } = &*def {
|
2021-12-01 22:44:53 +08:00
|
|
|
// do not handle type var param and concrete check here, and no subst
|
|
|
|
Ok(Ok({
|
|
|
|
let ty = TypeEnum::TObj {
|
|
|
|
obj_id: *object_id,
|
2022-02-21 17:52:34 +08:00
|
|
|
params: type_vars
|
2022-02-21 18:27:46 +08:00
|
|
|
.iter()
|
|
|
|
.map(|x| {
|
|
|
|
if let TypeEnum::TVar { id, .. } = &*unifier.get_ty(*x) {
|
|
|
|
(*id, *x)
|
|
|
|
} else {
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect(),
|
2022-02-21 17:52:34 +08:00
|
|
|
fields: {
|
2021-12-01 22:44:53 +08:00
|
|
|
let mut res = methods
|
|
|
|
.iter()
|
|
|
|
.map(|(iden, ty, _)| (*iden, (*ty, false)))
|
|
|
|
.collect::<HashMap<_, _>>();
|
|
|
|
res.extend(fields.clone().into_iter().map(|x| (x.0, (x.1, x.2))));
|
|
|
|
res
|
2022-02-21 17:52:34 +08:00
|
|
|
},
|
2021-12-01 22:44:53 +08:00
|
|
|
};
|
|
|
|
// here also false, later instantiation use python object to check compatible
|
|
|
|
(unifier.add_ty(ty), false)
|
|
|
|
}))
|
|
|
|
} else {
|
|
|
|
// only object is supported, functions are not supported
|
|
|
|
unreachable!("function type is not supported, should not be queried")
|
|
|
|
}
|
|
|
|
} else if ty_ty_id == self.primitive_ids.typevar {
|
2022-02-21 17:52:34 +08:00
|
|
|
let name: &str = pyty.getattr("__name__").unwrap().extract().unwrap();
|
2021-12-01 22:44:53 +08:00
|
|
|
let constraint_types = {
|
|
|
|
let constraints = pyty.getattr("__constraints__").unwrap();
|
|
|
|
let mut result: Vec<Type> = vec![];
|
|
|
|
for i in 0.. {
|
|
|
|
if let Ok(constr) = constraints.get_item(i) {
|
|
|
|
result.push({
|
|
|
|
match self.get_pyty_obj_type(py, constr, unifier, defs, primitives)? {
|
|
|
|
Ok((ty, _)) => {
|
|
|
|
if unifier.is_concrete(ty, &[]) {
|
|
|
|
ty
|
|
|
|
} else {
|
|
|
|
return Ok(Err(format!(
|
|
|
|
"the {}th constraint of TypeVar `{}` is not concrete",
|
|
|
|
i + 1,
|
|
|
|
pyty.getattr("__name__")?.extract::<String>()?
|
2021-12-05 20:30:03 +08:00
|
|
|
)));
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
|
|
|
Err(err) => return Ok(Err(err)),
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
result
|
|
|
|
};
|
2022-02-21 18:27:46 +08:00
|
|
|
let res =
|
|
|
|
unifier.get_fresh_var_with_range(&constraint_types, Some(name.into()), None).0;
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(Ok((res, true)))
|
2021-12-05 20:30:03 +08:00
|
|
|
} else if ty_ty_id == self.primitive_ids.generic_alias.0
|
|
|
|
|| ty_ty_id == self.primitive_ids.generic_alias.1
|
|
|
|
{
|
2021-12-01 22:44:53 +08:00
|
|
|
let origin = self.helper.origin_ty_fn.call1(py, (pyty,))?;
|
|
|
|
let args = self.helper.args_ty_fn.call1(py, (pyty,))?;
|
|
|
|
let args: &PyTuple = args.cast_as(py)?;
|
2021-12-05 20:30:03 +08:00
|
|
|
let origin_ty =
|
|
|
|
match self.get_pyty_obj_type(py, origin.as_ref(py), unifier, defs, primitives)? {
|
|
|
|
Ok((ty, false)) => ty,
|
|
|
|
Ok((_, true)) => {
|
|
|
|
return Ok(Err("instantiated type does not take type parameters".into()))
|
|
|
|
}
|
|
|
|
Err(err) => return Ok(Err(err)),
|
|
|
|
};
|
2021-12-01 22:44:53 +08:00
|
|
|
|
|
|
|
match &*unifier.get_ty(origin_ty) {
|
|
|
|
TypeEnum::TList { .. } => {
|
|
|
|
if args.len() == 1 {
|
2021-12-05 20:30:03 +08:00
|
|
|
let ty = match self.get_pyty_obj_type(
|
|
|
|
py,
|
|
|
|
args.get_item(0),
|
|
|
|
unifier,
|
|
|
|
defs,
|
|
|
|
primitives,
|
|
|
|
)? {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(ty) => ty,
|
2021-12-05 20:30:03 +08:00
|
|
|
Err(err) => return Ok(Err(err)),
|
2021-12-01 22:44:53 +08:00
|
|
|
};
|
|
|
|
if !unifier.is_concrete(ty.0, &[]) && !ty.1 {
|
2022-01-13 03:14:06 +08:00
|
|
|
return Ok(Err(
|
2022-02-21 18:27:46 +08:00
|
|
|
"type list should take concrete parameters in typevar range".into(),
|
2022-01-13 03:14:06 +08:00
|
|
|
));
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
Ok(Ok((unifier.add_ty(TypeEnum::TList { ty: ty.0 }), true)))
|
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
return Ok(Err(format!(
|
|
|
|
"type list needs exactly 1 type parameters, found {}",
|
|
|
|
args.len()
|
|
|
|
)));
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
2021-12-01 22:44:53 +08:00
|
|
|
TypeEnum::TTuple { .. } => {
|
|
|
|
let args = match args
|
|
|
|
.iter()
|
|
|
|
.map(|x| self.get_pyty_obj_type(py, x, unifier, defs, primitives))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?
|
|
|
|
.into_iter()
|
|
|
|
.collect::<Result<Vec<_>, _>>() {
|
|
|
|
Ok(args) if !args.is_empty() => args
|
|
|
|
.into_iter()
|
|
|
|
.map(|(x, check)| if !unifier.is_concrete(x, &[]) && !check {
|
|
|
|
panic!("type tuple should take concrete parameters in type var ranges")
|
|
|
|
} else {
|
|
|
|
x
|
|
|
|
}
|
|
|
|
)
|
|
|
|
.collect::<Vec<_>>(),
|
|
|
|
Err(err) => return Ok(Err(err)),
|
|
|
|
_ => return Ok(Err("tuple type needs at least 1 type parameters".to_string()))
|
|
|
|
};
|
|
|
|
Ok(Ok((unifier.add_ty(TypeEnum::TTuple { ty: args }), true)))
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
2021-12-01 22:44:53 +08:00
|
|
|
TypeEnum::TObj { params, obj_id, .. } => {
|
|
|
|
let subst = {
|
|
|
|
if params.len() != args.len() {
|
|
|
|
return Ok(Err(format!(
|
|
|
|
"for class #{}, expect {} type parameters, got {}.",
|
|
|
|
obj_id.0,
|
|
|
|
params.len(),
|
|
|
|
args.len(),
|
2021-12-05 20:30:03 +08:00
|
|
|
)));
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
let args = match args
|
|
|
|
.iter()
|
|
|
|
.map(|x| self.get_pyty_obj_type(py, x, unifier, defs, primitives))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?
|
|
|
|
.into_iter()
|
|
|
|
.collect::<Result<Vec<_>, _>>() {
|
|
|
|
Ok(args) => args
|
|
|
|
.into_iter()
|
|
|
|
.map(|(x, check)| if !unifier.is_concrete(x, &[]) && !check {
|
|
|
|
panic!("type class should take concrete parameters in type var ranges")
|
|
|
|
} else {
|
|
|
|
x
|
|
|
|
}
|
|
|
|
)
|
|
|
|
.collect::<Vec<_>>(),
|
|
|
|
Err(err) => return Ok(Err(err)),
|
|
|
|
};
|
|
|
|
params
|
|
|
|
.iter()
|
|
|
|
.zip(args.iter())
|
|
|
|
.map(|((id, _), ty)| (*id, *ty))
|
|
|
|
.collect::<HashMap<_, _>>()
|
|
|
|
};
|
2022-02-21 18:27:46 +08:00
|
|
|
Ok(Ok((unifier.subst(origin_ty, &subst).unwrap_or(origin_ty), true)))
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
2021-12-01 22:44:53 +08:00
|
|
|
TypeEnum::TVirtual { .. } => {
|
|
|
|
if args.len() == 1 {
|
2021-12-05 20:30:03 +08:00
|
|
|
let ty = match self.get_pyty_obj_type(
|
|
|
|
py,
|
|
|
|
args.get_item(0),
|
|
|
|
unifier,
|
|
|
|
defs,
|
|
|
|
primitives,
|
|
|
|
)? {
|
2021-12-01 22:44:53 +08:00
|
|
|
Ok(ty) => ty,
|
2021-12-05 20:30:03 +08:00
|
|
|
Err(err) => return Ok(Err(err)),
|
2021-12-01 22:44:53 +08:00
|
|
|
};
|
|
|
|
if !unifier.is_concrete(ty.0, &[]) && !ty.1 {
|
2021-12-05 20:30:03 +08:00
|
|
|
panic!(
|
|
|
|
"virtual class should take concrete parameters in type var ranges"
|
|
|
|
)
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
Ok(Ok((unifier.add_ty(TypeEnum::TVirtual { ty: ty.0 }), true)))
|
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
return Ok(Err(format!(
|
|
|
|
"virtual class needs exactly 1 type parameters, found {}",
|
|
|
|
args.len()
|
|
|
|
)));
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
_ => unimplemented!(),
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
} else if ty_id == self.primitive_ids.virtual_id {
|
2021-12-05 20:30:03 +08:00
|
|
|
Ok(Ok((
|
|
|
|
{
|
2022-02-21 18:27:46 +08:00
|
|
|
let ty = TypeEnum::TVirtual { ty: unifier.get_dummy_var().0 };
|
2021-12-05 20:30:03 +08:00
|
|
|
unifier.add_ty(ty)
|
|
|
|
},
|
|
|
|
false,
|
|
|
|
)))
|
2021-12-01 22:44:53 +08:00
|
|
|
} else {
|
2022-02-21 18:27:46 +08:00
|
|
|
let str_fn =
|
|
|
|
pyo3::types::PyModule::import(py, "builtins").unwrap().getattr("repr").unwrap();
|
2022-02-21 17:52:34 +08:00
|
|
|
let str_repr: String = str_fn.call1((pyty,)).unwrap().extract().unwrap();
|
2022-02-21 18:27:46 +08:00
|
|
|
Ok(Err(format!(
|
2022-02-28 11:10:33 +08:00
|
|
|
"{} is not registered with NAC3 (@nac3 decorator missing?)",
|
2022-02-21 18:27:46 +08:00
|
|
|
str_repr
|
|
|
|
)))
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_obj_type(
|
|
|
|
&self,
|
|
|
|
py: Python,
|
|
|
|
obj: &PyAny,
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
primitives: &PrimitiveStore,
|
2022-01-13 03:14:06 +08:00
|
|
|
) -> PyResult<Result<Type, String>> {
|
2021-12-01 22:44:53 +08:00
|
|
|
let ty = self.helper.type_fn.call1(py, (obj,)).unwrap();
|
2022-02-28 23:08:42 +08:00
|
|
|
let ty_id: u64 = self.helper.id_fn.call1(py, (ty.clone(),))?.extract(py)?;
|
|
|
|
if let Some(ty) = self.pyid_to_type.read().get(&ty_id) {
|
|
|
|
return Ok(Ok(*ty))
|
|
|
|
}
|
2021-12-01 22:44:53 +08:00
|
|
|
let (extracted_ty, inst_check) = match self.get_pyty_obj_type(
|
|
|
|
py,
|
|
|
|
{
|
2021-12-05 20:30:03 +08:00
|
|
|
if [
|
|
|
|
self.primitive_ids.typevar,
|
2021-12-01 22:44:53 +08:00
|
|
|
self.primitive_ids.generic_alias.0,
|
2021-12-05 20:30:03 +08:00
|
|
|
self.primitive_ids.generic_alias.1,
|
|
|
|
]
|
2022-02-21 18:27:46 +08:00
|
|
|
.contains(&self.helper.id_fn.call1(py, (ty.clone(),))?.extract::<u64>(py)?)
|
|
|
|
{
|
2021-12-01 22:44:53 +08:00
|
|
|
obj
|
|
|
|
} else {
|
|
|
|
ty.as_ref(py)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
unifier,
|
|
|
|
defs,
|
2021-12-05 20:30:03 +08:00
|
|
|
primitives,
|
2021-12-01 22:44:53 +08:00
|
|
|
)? {
|
|
|
|
Ok(s) => s,
|
2022-01-13 03:14:06 +08:00
|
|
|
Err(e) => return Ok(Err(e)),
|
2021-12-01 22:44:53 +08:00
|
|
|
};
|
2022-03-18 01:07:44 +08:00
|
|
|
match (&*unifier.get_ty(extracted_ty), inst_check) {
|
2021-12-01 22:44:53 +08:00
|
|
|
// do the instantiation for these three types
|
|
|
|
(TypeEnum::TList { ty }, false) => {
|
|
|
|
let len: usize = self.helper.len_fn.call1(py, (obj,))?.extract(py)?;
|
|
|
|
if len == 0 {
|
|
|
|
assert!(matches!(
|
|
|
|
&*unifier.get_ty(extracted_ty),
|
2022-02-21 17:52:34 +08:00
|
|
|
TypeEnum::TVar { fields: None, range, .. }
|
|
|
|
if range.is_empty()
|
2021-12-01 22:44:53 +08:00
|
|
|
));
|
2022-01-13 03:14:06 +08:00
|
|
|
Ok(Ok(extracted_ty))
|
2021-12-01 22:44:53 +08:00
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
let actual_ty =
|
|
|
|
self.get_list_elem_type(py, obj, len, unifier, defs, primitives)?;
|
2022-01-13 03:14:06 +08:00
|
|
|
match actual_ty {
|
|
|
|
Ok(t) => match unifier.unify(*ty, t) {
|
2022-02-21 18:27:46 +08:00
|
|
|
Ok(_) => Ok(Ok(unifier.add_ty(TypeEnum::TList { ty: *ty }))),
|
|
|
|
Err(e) => Ok(Err(format!(
|
|
|
|
"type error ({}) for the list",
|
|
|
|
e.to_display(unifier).to_string()
|
|
|
|
))),
|
|
|
|
},
|
2022-01-13 03:14:06 +08:00
|
|
|
Err(e) => Ok(Err(e)),
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
(TypeEnum::TTuple { .. }, false) => {
|
|
|
|
let elements: &PyTuple = obj.cast_as()?;
|
2022-01-13 03:14:06 +08:00
|
|
|
let types: Result<Result<Vec<_>, _>, _> = elements
|
2021-10-08 22:43:23 +08:00
|
|
|
.iter()
|
2021-12-01 22:44:53 +08:00
|
|
|
.map(|elem| self.get_obj_type(py, elem, unifier, defs, primitives))
|
2021-10-08 22:43:23 +08:00
|
|
|
.collect();
|
2021-12-01 22:44:53 +08:00
|
|
|
let types = types?;
|
|
|
|
Ok(types.map(|types| unifier.add_ty(TypeEnum::TTuple { ty: types })))
|
|
|
|
}
|
2022-03-18 01:07:44 +08:00
|
|
|
(TypeEnum::TObj { params: var_map, fields, .. }, false) => {
|
2022-02-28 23:08:42 +08:00
|
|
|
self.pyid_to_type.write().insert(ty_id, extracted_ty);
|
2022-03-02 21:39:45 +08:00
|
|
|
let mut instantiate_obj = || {
|
|
|
|
// loop through non-function fields of the class to get the instantiated value
|
|
|
|
for field in fields.iter() {
|
|
|
|
let name: String = (*field.0).into();
|
|
|
|
if let TypeEnum::TFunc(..) = &*unifier.get_ty(field.1 .0) {
|
|
|
|
continue;
|
2021-12-01 22:44:53 +08:00
|
|
|
} else {
|
2022-03-02 21:39:45 +08:00
|
|
|
let field_data = obj.getattr(&name)?;
|
|
|
|
let ty = match self
|
|
|
|
.get_obj_type(py, field_data, unifier, defs, primitives)?
|
|
|
|
{
|
2022-01-13 03:14:06 +08:00
|
|
|
Ok(t) => t,
|
2022-02-21 18:27:46 +08:00
|
|
|
Err(e) => {
|
|
|
|
return Ok(Err(format!(
|
|
|
|
"error when getting type of field `{}` ({})",
|
|
|
|
name, e
|
|
|
|
)))
|
|
|
|
}
|
2022-01-13 03:14:06 +08:00
|
|
|
};
|
2022-03-02 21:39:45 +08:00
|
|
|
let field_ty =
|
|
|
|
unifier.subst(field.1 .0, &var_map).unwrap_or(field.1 .0);
|
|
|
|
if let Err(e) = unifier.unify(ty, field_ty) {
|
|
|
|
// field type mismatch
|
|
|
|
return Ok(Err(format!(
|
|
|
|
"error when getting type of field `{}` ({})",
|
|
|
|
name,
|
|
|
|
e.to_display(unifier).to_string()
|
|
|
|
)));
|
|
|
|
}
|
2021-12-01 22:44:53 +08:00
|
|
|
}
|
2021-10-07 15:57:45 +08:00
|
|
|
}
|
2022-03-02 21:39:45 +08:00
|
|
|
for (_, ty) in var_map.iter() {
|
|
|
|
// must be concrete type
|
|
|
|
if !unifier.is_concrete(*ty, &[]) {
|
|
|
|
return Ok(Err("object is not of concrete type".into()));
|
|
|
|
}
|
2021-10-07 15:57:45 +08:00
|
|
|
}
|
2022-03-18 01:07:44 +08:00
|
|
|
Ok(Ok(extracted_ty))
|
2022-03-02 21:39:45 +08:00
|
|
|
};
|
|
|
|
let result = instantiate_obj();
|
|
|
|
// do not cache the type if there are errors
|
|
|
|
if matches!(result, Err(_) | Ok(Err(_))) {
|
|
|
|
self.pyid_to_type.write().remove(&ty_id);
|
2021-10-07 15:57:45 +08:00
|
|
|
}
|
2022-03-02 21:39:45 +08:00
|
|
|
result
|
2021-10-07 15:57:45 +08:00
|
|
|
}
|
2022-01-13 03:14:06 +08:00
|
|
|
_ => Ok(Ok(extracted_ty)),
|
2022-03-18 01:07:44 +08:00
|
|
|
}
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn get_obj_value<'ctx, 'a>(
|
|
|
|
&self,
|
2021-11-20 21:15:15 +08:00
|
|
|
py: Python,
|
2021-10-06 16:07:42 +08:00
|
|
|
obj: &PyAny,
|
|
|
|
ctx: &mut CodeGenContext<'ctx, 'a>,
|
2021-12-27 22:55:51 +08:00
|
|
|
generator: &mut dyn CodeGenerator,
|
2021-10-06 16:07:42 +08:00
|
|
|
) -> PyResult<Option<BasicValueEnum<'ctx>>> {
|
2022-02-21 18:27:46 +08:00
|
|
|
let ty_id: u64 =
|
|
|
|
self.helper.id_fn.call1(py, (self.helper.type_fn.call1(py, (obj,))?,))?.extract(py)?;
|
2021-12-05 20:30:03 +08:00
|
|
|
let id: u64 = self.helper.id_fn.call1(py, (obj,))?.extract(py)?;
|
2021-10-06 16:07:42 +08:00
|
|
|
if ty_id == self.primitive_ids.int || ty_id == self.primitive_ids.int32 {
|
2022-02-28 23:09:14 +08:00
|
|
|
let val: i32 = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of int32", obj)))?;
|
2022-02-21 18:27:46 +08:00
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::I32(val));
|
2021-10-06 16:07:42 +08:00
|
|
|
Ok(Some(ctx.ctx.i32_type().const_int(val as u64, false).into()))
|
|
|
|
} else if ty_id == self.primitive_ids.int64 {
|
2022-02-28 23:09:14 +08:00
|
|
|
let val: i64 = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of int64", obj)))?;
|
2022-02-21 18:27:46 +08:00
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::I64(val));
|
2021-10-06 16:07:42 +08:00
|
|
|
Ok(Some(ctx.ctx.i64_type().const_int(val as u64, false).into()))
|
2022-03-05 03:45:09 +08:00
|
|
|
} else if ty_id == self.primitive_ids.uint32 {
|
|
|
|
let val: u32 = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of uint32", obj)))?;
|
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::U32(val));
|
|
|
|
Ok(Some(ctx.ctx.i32_type().const_int(val as u64, false).into()))
|
|
|
|
} else if ty_id == self.primitive_ids.uint64 {
|
|
|
|
let val: u64 = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of uint64", obj)))?;
|
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::U64(val));
|
|
|
|
Ok(Some(ctx.ctx.i64_type().const_int(val, false).into()))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.bool {
|
2022-02-28 23:09:14 +08:00
|
|
|
let val: bool = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of bool", obj)))?;
|
2022-02-21 18:27:46 +08:00
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::Bool(val));
|
|
|
|
Ok(Some(ctx.ctx.bool_type().const_int(val as u64, false).into()))
|
2021-10-06 16:07:42 +08:00
|
|
|
} else if ty_id == self.primitive_ids.float {
|
2022-02-28 23:09:14 +08:00
|
|
|
let val: f64 = obj.extract().map_err(|_| super::CompileError::new_err(
|
|
|
|
format!("{} is not in the range of float64", obj)))?;
|
2022-02-21 18:27:46 +08:00
|
|
|
self.id_to_primitive.write().insert(id, PrimitiveValue::F64(val));
|
2021-10-06 16:07:42 +08:00
|
|
|
Ok(Some(ctx.ctx.f64_type().const_float(val).into()))
|
|
|
|
} else if ty_id == self.primitive_ids.list {
|
|
|
|
let id_str = id.to_string();
|
2021-12-05 20:30:03 +08:00
|
|
|
|
|
|
|
if let Some(global) = ctx.module.get_global(&id_str) {
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
}
|
|
|
|
|
2021-11-20 21:15:15 +08:00
|
|
|
let len: usize = self.helper.len_fn.call1(py, (obj,))?.extract(py)?;
|
2021-10-07 15:57:45 +08:00
|
|
|
let ty = if len == 0 {
|
|
|
|
ctx.primitives.int32
|
|
|
|
} else {
|
|
|
|
self.get_list_elem_type(
|
2021-11-20 21:15:15 +08:00
|
|
|
py,
|
2021-10-06 16:07:42 +08:00
|
|
|
obj,
|
|
|
|
len,
|
|
|
|
&mut ctx.unifier,
|
|
|
|
&ctx.top_level.definitions.read(),
|
|
|
|
&ctx.primitives,
|
|
|
|
)?
|
2021-10-07 15:57:45 +08:00
|
|
|
.unwrap()
|
|
|
|
};
|
2021-12-27 22:56:07 +08:00
|
|
|
let ty = ctx.get_llvm_type(generator, ty);
|
2021-12-27 22:55:51 +08:00
|
|
|
let size_t = generator.get_size_type(ctx.ctx);
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr_ty = ctx
|
|
|
|
.ctx
|
|
|
|
.struct_type(&[ty.ptr_type(AddressSpace::Generic).into(), size_t.into()], false);
|
2021-10-06 16:07:42 +08:00
|
|
|
|
|
|
|
{
|
2021-12-05 20:30:03 +08:00
|
|
|
if self.global_value_ids.read().contains(&id) {
|
2021-10-06 16:07:42 +08:00
|
|
|
let global = ctx.module.get_global(&id_str).unwrap_or_else(|| {
|
2022-02-21 18:27:46 +08:00
|
|
|
ctx.module.add_global(arr_ty, Some(AddressSpace::Generic), &id_str)
|
2021-10-06 16:07:42 +08:00
|
|
|
});
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
self.global_value_ids.write().insert(id);
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let arr: Result<Option<Vec<_>>, _> = (0..len)
|
|
|
|
.map(|i| {
|
2022-02-28 23:09:14 +08:00
|
|
|
obj.get_item(i).and_then(|elem| self.get_obj_value(py, elem, ctx, generator).map_err(
|
|
|
|
|e| super::CompileError::new_err(format!("Error getting element {}: {}", i, e))))
|
2021-10-06 16:07:42 +08:00
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
let arr = arr?.unwrap();
|
|
|
|
|
|
|
|
let arr_global = ctx.module.add_global(
|
|
|
|
ty.array_type(len as u32),
|
|
|
|
Some(AddressSpace::Generic),
|
|
|
|
&(id_str.clone() + "_"),
|
|
|
|
);
|
|
|
|
let arr: BasicValueEnum = if ty.is_int_type() {
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr: Vec<_> = arr.into_iter().map(BasicValueEnum::into_int_value).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
ty.into_int_type().const_array(&arr)
|
|
|
|
} else if ty.is_float_type() {
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr: Vec<_> = arr.into_iter().map(BasicValueEnum::into_float_value).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
ty.into_float_type().const_array(&arr)
|
|
|
|
} else if ty.is_array_type() {
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr: Vec<_> = arr.into_iter().map(BasicValueEnum::into_array_value).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
ty.into_array_type().const_array(&arr)
|
|
|
|
} else if ty.is_struct_type() {
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr: Vec<_> = arr.into_iter().map(BasicValueEnum::into_struct_value).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
ty.into_struct_type().const_array(&arr)
|
|
|
|
} else if ty.is_pointer_type() {
|
2022-02-21 18:27:46 +08:00
|
|
|
let arr: Vec<_> = arr.into_iter().map(BasicValueEnum::into_pointer_value).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
ty.into_pointer_type().const_array(&arr)
|
|
|
|
} else {
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
.into();
|
|
|
|
arr_global.set_initializer(&arr);
|
|
|
|
|
|
|
|
let val = arr_ty.const_named_struct(&[
|
2022-02-21 18:27:46 +08:00
|
|
|
arr_global.as_pointer_value().const_cast(ty.ptr_type(AddressSpace::Generic)).into(),
|
2021-12-27 22:55:51 +08:00
|
|
|
size_t.const_int(len as u64, false).into(),
|
2021-10-06 16:07:42 +08:00
|
|
|
]);
|
|
|
|
|
2022-02-21 18:27:46 +08:00
|
|
|
let global = ctx.module.add_global(arr_ty, Some(AddressSpace::Generic), &id_str);
|
2021-10-06 16:07:42 +08:00
|
|
|
global.set_initializer(&val);
|
|
|
|
|
|
|
|
Ok(Some(global.as_pointer_value().into()))
|
|
|
|
} else if ty_id == self.primitive_ids.tuple {
|
|
|
|
let id_str = id.to_string();
|
2021-12-05 20:30:03 +08:00
|
|
|
|
|
|
|
if let Some(global) = ctx.module.get_global(&id_str) {
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
}
|
|
|
|
|
2021-10-06 16:07:42 +08:00
|
|
|
let elements: &PyTuple = obj.cast_as()?;
|
2022-01-13 03:14:06 +08:00
|
|
|
let types: Result<Result<Vec<_>, _>, _> = elements
|
2021-10-06 16:07:42 +08:00
|
|
|
.iter()
|
2022-02-28 23:09:14 +08:00
|
|
|
.enumerate()
|
|
|
|
.map(|(i, elem)| {
|
2021-10-06 16:07:42 +08:00
|
|
|
self.get_obj_type(
|
2021-11-20 21:15:15 +08:00
|
|
|
py,
|
2021-10-06 16:07:42 +08:00
|
|
|
elem,
|
|
|
|
&mut ctx.unifier,
|
|
|
|
&ctx.top_level.definitions.read(),
|
|
|
|
&ctx.primitives,
|
|
|
|
)
|
2022-02-28 23:09:14 +08:00
|
|
|
.map_err(|e| super::CompileError::new_err(format!("Error getting element {}: {}", i, e)))
|
2021-12-27 22:56:07 +08:00
|
|
|
.map(|ty| ty.map(|ty| ctx.get_llvm_type(generator, ty)))
|
2021-10-06 16:07:42 +08:00
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
let types = types?.unwrap();
|
|
|
|
let ty = ctx.ctx.struct_type(&types, false);
|
|
|
|
|
|
|
|
{
|
2021-12-05 20:30:03 +08:00
|
|
|
if self.global_value_ids.read().contains(&id) {
|
2021-10-06 16:07:42 +08:00
|
|
|
let global = ctx.module.get_global(&id_str).unwrap_or_else(|| {
|
2022-02-21 18:27:46 +08:00
|
|
|
ctx.module.add_global(ty, Some(AddressSpace::Generic), &id_str)
|
2021-10-06 16:07:42 +08:00
|
|
|
});
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
self.global_value_ids.write().insert(id);
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-21 18:27:46 +08:00
|
|
|
let val: Result<Option<Vec<_>>, _> =
|
2022-02-28 23:09:14 +08:00
|
|
|
elements.iter().enumerate().map(|(i, elem)| self.get_obj_value(py, elem, ctx, generator).map_err(|e|
|
|
|
|
super::CompileError::new_err(format!("Error getting element {}: {}", i, e)))).collect();
|
2021-10-06 16:07:42 +08:00
|
|
|
let val = val?.unwrap();
|
|
|
|
let val = ctx.ctx.const_struct(&val, false);
|
2022-02-21 18:27:46 +08:00
|
|
|
let global = ctx.module.add_global(ty, Some(AddressSpace::Generic), &id_str);
|
2021-10-06 16:07:42 +08:00
|
|
|
global.set_initializer(&val);
|
|
|
|
Ok(Some(global.as_pointer_value().into()))
|
|
|
|
} else {
|
2021-10-07 15:57:45 +08:00
|
|
|
let id_str = id.to_string();
|
2021-12-05 20:30:03 +08:00
|
|
|
|
|
|
|
if let Some(global) = ctx.module.get_global(&id_str) {
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
}
|
|
|
|
|
2021-10-07 15:57:45 +08:00
|
|
|
let top_level_defs = ctx.top_level.definitions.read();
|
|
|
|
let ty = self
|
2021-11-20 21:15:15 +08:00
|
|
|
.get_obj_type(py, obj, &mut ctx.unifier, &top_level_defs, &ctx.primitives)?
|
2021-10-07 15:57:45 +08:00
|
|
|
.unwrap();
|
|
|
|
let ty = ctx
|
2021-12-27 22:56:07 +08:00
|
|
|
.get_llvm_type(generator, ty)
|
2021-10-07 15:57:45 +08:00
|
|
|
.into_pointer_type()
|
|
|
|
.get_element_type()
|
2022-02-12 21:17:37 +08:00
|
|
|
.into_struct_type();
|
2021-10-07 15:57:45 +08:00
|
|
|
{
|
2021-12-05 20:30:03 +08:00
|
|
|
if self.global_value_ids.read().contains(&id) {
|
2021-10-07 15:57:45 +08:00
|
|
|
let global = ctx.module.get_global(&id_str).unwrap_or_else(|| {
|
2022-02-21 18:27:46 +08:00
|
|
|
ctx.module.add_global(ty, Some(AddressSpace::Generic), &id_str)
|
2021-10-07 15:57:45 +08:00
|
|
|
});
|
|
|
|
return Ok(Some(global.as_pointer_value().into()));
|
|
|
|
} else {
|
2021-12-05 20:30:03 +08:00
|
|
|
self.global_value_ids.write().insert(id);
|
2021-10-07 15:57:45 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// should be classes
|
2022-02-21 18:27:46 +08:00
|
|
|
let definition =
|
|
|
|
top_level_defs.get(self.pyid_to_def.read().get(&ty_id).unwrap().0).unwrap().read();
|
2021-10-07 15:57:45 +08:00
|
|
|
if let TopLevelDef::Class { fields, .. } = &*definition {
|
|
|
|
let values: Result<Option<Vec<_>>, _> = fields
|
|
|
|
.iter()
|
2021-11-06 22:48:08 +08:00
|
|
|
.map(|(name, _, _)| {
|
2022-02-28 23:09:14 +08:00
|
|
|
self.get_obj_value(py, obj.getattr(&name.to_string())?, ctx, generator).map_err(|e|
|
|
|
|
super::CompileError::new_err(format!("Error getting field {}: {}", name, e)))
|
2021-10-07 15:57:45 +08:00
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
let values = values?;
|
|
|
|
if let Some(values) = values {
|
2022-02-12 21:17:37 +08:00
|
|
|
let val = ty.const_named_struct(&values);
|
2022-02-21 18:27:46 +08:00
|
|
|
let global = ctx.module.add_global(ty, Some(AddressSpace::Generic), &id_str);
|
2021-10-07 15:57:45 +08:00
|
|
|
global.set_initializer(&val);
|
|
|
|
Ok(Some(global.as_pointer_value().into()))
|
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
unreachable!()
|
|
|
|
}
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
|
|
|
}
|
2021-11-23 07:32:09 +08:00
|
|
|
|
2021-11-27 21:29:27 +08:00
|
|
|
fn get_default_param_obj_value(
|
|
|
|
&self,
|
|
|
|
py: Python,
|
|
|
|
obj: &PyAny,
|
|
|
|
) -> PyResult<Result<SymbolValue, String>> {
|
2022-02-21 18:27:46 +08:00
|
|
|
let ty_id: u64 =
|
|
|
|
self.helper.id_fn.call1(py, (self.helper.type_fn.call1(py, (obj,))?,))?.extract(py)?;
|
|
|
|
Ok(if ty_id == self.primitive_ids.int || ty_id == self.primitive_ids.int32 {
|
|
|
|
let val: i32 = obj.extract()?;
|
|
|
|
Ok(SymbolValue::I32(val))
|
|
|
|
} else if ty_id == self.primitive_ids.int64 {
|
|
|
|
let val: i64 = obj.extract()?;
|
|
|
|
Ok(SymbolValue::I64(val))
|
|
|
|
} else if ty_id == self.primitive_ids.bool {
|
|
|
|
let val: bool = obj.extract()?;
|
|
|
|
Ok(SymbolValue::Bool(val))
|
|
|
|
} else if ty_id == self.primitive_ids.float {
|
|
|
|
let val: f64 = obj.extract()?;
|
|
|
|
Ok(SymbolValue::Double(val))
|
|
|
|
} else if ty_id == self.primitive_ids.tuple {
|
|
|
|
let elements: &PyTuple = obj.cast_as()?;
|
|
|
|
let elements: Result<Result<Vec<_>, String>, _> =
|
|
|
|
elements.iter().map(|elem| self.get_default_param_obj_value(py, elem)).collect();
|
|
|
|
let elements = match elements? {
|
|
|
|
Ok(el) => el,
|
|
|
|
Err(err) => return Ok(Err(err)),
|
|
|
|
};
|
|
|
|
Ok(SymbolValue::Tuple(elements))
|
|
|
|
} else {
|
|
|
|
Err("only primitives values and tuple can be default parameter value".into())
|
|
|
|
})
|
2021-11-23 07:32:09 +08:00
|
|
|
}
|
2021-09-23 19:30:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl SymbolResolver for Resolver {
|
2021-11-27 21:29:27 +08:00
|
|
|
fn get_default_param_value(&self, expr: &ast::Expr) -> Option<SymbolValue> {
|
2021-11-23 07:32:09 +08:00
|
|
|
match &expr.node {
|
|
|
|
ast::ExprKind::Name { id, .. } => {
|
2021-11-27 21:29:27 +08:00
|
|
|
Python::with_gil(|py| -> PyResult<Option<SymbolValue>> {
|
|
|
|
let obj: &PyAny = self.0.module.extract(py)?;
|
2021-12-05 20:30:03 +08:00
|
|
|
let members: &PyDict = obj.getattr("__dict__").unwrap().cast_as().unwrap();
|
2021-11-27 21:29:27 +08:00
|
|
|
let mut sym_value = None;
|
2021-12-05 20:30:03 +08:00
|
|
|
for (key, val) in members.iter() {
|
|
|
|
let key: &str = key.extract()?;
|
2021-11-27 21:29:27 +08:00
|
|
|
if key == id.to_string() {
|
2022-02-21 18:27:46 +08:00
|
|
|
sym_value =
|
|
|
|
Some(self.0.get_default_param_obj_value(py, val).unwrap().unwrap());
|
2021-11-27 21:29:27 +08:00
|
|
|
break;
|
2021-11-23 07:32:09 +08:00
|
|
|
}
|
|
|
|
}
|
2021-11-27 21:29:27 +08:00
|
|
|
Ok(sym_value)
|
|
|
|
})
|
2021-11-23 07:32:09 +08:00
|
|
|
.unwrap()
|
|
|
|
}
|
2021-11-27 21:29:27 +08:00
|
|
|
_ => unimplemented!("other type of expr not supported at {}", expr.location),
|
2021-11-23 07:32:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-06 16:07:42 +08:00
|
|
|
fn get_symbol_type(
|
|
|
|
&self,
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
defs: &[Arc<RwLock<TopLevelDef>>],
|
|
|
|
primitives: &PrimitiveStore,
|
|
|
|
str: StrRef,
|
2022-01-13 03:14:06 +08:00
|
|
|
) -> Result<Type, String> {
|
|
|
|
match {
|
2021-12-05 20:30:03 +08:00
|
|
|
let id_to_type = self.0.id_to_type.read();
|
|
|
|
id_to_type.get(&str).cloned()
|
2022-01-13 03:14:06 +08:00
|
|
|
} {
|
|
|
|
Some(ty) => Ok(ty),
|
|
|
|
None => {
|
|
|
|
let id = match self.0.name_to_pyid.get(&str) {
|
|
|
|
Some(id) => id,
|
|
|
|
None => return Err(format!("cannot find symbol `{}`", str)),
|
|
|
|
};
|
|
|
|
let result = match {
|
2021-12-05 20:30:03 +08:00
|
|
|
let pyid_to_type = self.0.pyid_to_type.read();
|
|
|
|
pyid_to_type.get(id).copied()
|
2022-01-13 03:14:06 +08:00
|
|
|
} {
|
|
|
|
Some(t) => Ok(t),
|
|
|
|
None => Python::with_gil(|py| -> PyResult<Result<Type, String>> {
|
2021-11-20 21:15:15 +08:00
|
|
|
let obj: &PyAny = self.0.module.extract(py)?;
|
2022-01-13 03:14:06 +08:00
|
|
|
let mut sym_ty = Err(format!("cannot find symbol `{}`", str));
|
2021-12-05 20:30:03 +08:00
|
|
|
let members: &PyDict = obj.getattr("__dict__").unwrap().cast_as().unwrap();
|
|
|
|
for (key, val) in members.iter() {
|
|
|
|
let key: &str = key.extract()?;
|
2021-10-06 16:07:42 +08:00
|
|
|
if key == str.to_string() {
|
2021-12-05 20:30:03 +08:00
|
|
|
sym_ty = self.0.get_obj_type(py, val, unifier, defs, primitives)?;
|
2021-10-06 16:07:42 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2022-01-13 03:14:06 +08:00
|
|
|
if let Ok(t) = sym_ty {
|
|
|
|
self.0.pyid_to_type.write().insert(*id, t);
|
|
|
|
}
|
2021-10-06 16:07:42 +08:00
|
|
|
Ok(sym_ty)
|
|
|
|
})
|
2022-01-13 03:14:06 +08:00
|
|
|
.unwrap(),
|
|
|
|
};
|
|
|
|
if let Ok(t) = &result {
|
|
|
|
self.0.id_to_type.write().insert(str, *t);
|
|
|
|
}
|
|
|
|
result
|
2021-09-30 22:30:54 +08:00
|
|
|
}
|
2022-01-13 03:14:06 +08:00
|
|
|
}
|
2021-09-23 19:30:03 +08:00
|
|
|
}
|
|
|
|
|
2021-10-06 16:07:42 +08:00
|
|
|
fn get_symbol_value<'ctx, 'a>(
|
|
|
|
&self,
|
|
|
|
id: StrRef,
|
2021-11-20 21:15:15 +08:00
|
|
|
_: &mut CodeGenContext<'ctx, 'a>,
|
2021-11-20 19:50:25 +08:00
|
|
|
) -> Option<ValueEnum<'ctx>> {
|
2021-12-05 20:30:03 +08:00
|
|
|
let sym_value = {
|
|
|
|
let id_to_val = self.0.id_to_pyval.read();
|
|
|
|
id_to_val.get(&id).cloned()
|
|
|
|
}
|
|
|
|
.or_else(|| {
|
|
|
|
Python::with_gil(|py| -> PyResult<Option<(u64, PyObject)>> {
|
|
|
|
let obj: &PyAny = self.0.module.extract(py)?;
|
|
|
|
let mut sym_value: Option<(u64, PyObject)> = None;
|
|
|
|
let members: &PyDict = obj.getattr("__dict__").unwrap().cast_as().unwrap();
|
|
|
|
for (key, val) in members.iter() {
|
|
|
|
let key: &str = key.extract()?;
|
|
|
|
if key == id.to_string() {
|
|
|
|
let id = self.0.helper.id_fn.call1(py, (val,))?.extract(py)?;
|
|
|
|
sym_value = Some((id, val.extract()?));
|
|
|
|
break;
|
|
|
|
}
|
2021-10-06 16:07:42 +08:00
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
if let Some((pyid, val)) = &sym_value {
|
|
|
|
self.0.id_to_pyval.write().insert(id, (*pyid, val.clone()));
|
|
|
|
}
|
|
|
|
Ok(sym_value)
|
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
});
|
|
|
|
sym_value.map(|(id, v)| {
|
|
|
|
ValueEnum::Static(Arc::new(PythonValue {
|
|
|
|
id,
|
|
|
|
value: v,
|
2022-02-12 21:17:37 +08:00
|
|
|
store_obj: self.0.helper.store_obj.clone(),
|
2021-12-05 20:30:03 +08:00
|
|
|
resolver: self.0.clone(),
|
|
|
|
}))
|
2021-10-06 16:07:42 +08:00
|
|
|
})
|
2021-09-23 19:30:03 +08:00
|
|
|
}
|
|
|
|
|
2022-02-21 17:52:34 +08:00
|
|
|
fn get_identifier_def(&self, id: StrRef) -> Result<DefinitionId, String> {
|
2021-12-05 20:30:03 +08:00
|
|
|
{
|
|
|
|
let id_to_def = self.0.id_to_def.read();
|
2022-02-21 17:52:34 +08:00
|
|
|
id_to_def.get(&id).cloned().ok_or_else(|| "".to_string())
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|
2022-02-21 17:52:34 +08:00
|
|
|
.or_else(|_| {
|
2022-02-21 18:27:46 +08:00
|
|
|
let py_id =
|
|
|
|
self.0.name_to_pyid.get(&id).ok_or(format!("Undefined identifier `{}`", id))?;
|
2022-02-21 17:52:34 +08:00
|
|
|
let result = self.0.pyid_to_def.read().get(py_id).copied().ok_or(format!(
|
2022-02-28 11:10:33 +08:00
|
|
|
"`{}` is not registered with NAC3 (@nac3 decorator missing?)",
|
2022-02-21 17:52:34 +08:00
|
|
|
id
|
|
|
|
))?;
|
|
|
|
self.0.id_to_def.write().insert(id, result);
|
|
|
|
Ok(result)
|
2021-09-30 22:30:54 +08:00
|
|
|
})
|
2021-09-23 19:30:03 +08:00
|
|
|
}
|
2022-02-12 21:17:37 +08:00
|
|
|
|
|
|
|
fn get_string_id(&self, s: &str) -> i32 {
|
|
|
|
let mut string_store = self.0.string_store.write();
|
|
|
|
if let Some(id) = string_store.get(s) {
|
|
|
|
*id
|
|
|
|
} else {
|
|
|
|
let id = Python::with_gil(|py| -> PyResult<i32> {
|
2022-02-21 18:27:46 +08:00
|
|
|
self.0.helper.store_str.call1(py, (s,))?.extract(py)
|
|
|
|
})
|
|
|
|
.unwrap();
|
2022-02-12 21:17:37 +08:00
|
|
|
string_store.insert(s.into(), id);
|
|
|
|
id
|
|
|
|
}
|
|
|
|
}
|
2022-03-05 00:26:35 +08:00
|
|
|
|
|
|
|
fn get_exception_id(&self, tyid: usize) -> usize {
|
|
|
|
let exn_ids = self.0.exception_ids.read();
|
|
|
|
exn_ids.get(&tyid).cloned().unwrap_or(0)
|
|
|
|
}
|
2021-12-05 20:30:03 +08:00
|
|
|
}
|