nac3core: clean up and format

This commit is contained in:
ychenfo 2021-09-08 19:45:36 +08:00
parent 87f25e1c5d
commit 1300b5ebdd
7 changed files with 42 additions and 39 deletions

View File

@ -609,8 +609,7 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
ExprKind::Call { func, args, keywords } => { ExprKind::Call { func, args, keywords } => {
if let ExprKind::Name { id, .. } = &func.as_ref().node { if let ExprKind::Name { id, .. } = &func.as_ref().node {
// TODO: handle primitive casts and function pointers // TODO: handle primitive casts and function pointers
let fun = let fun = self.resolver.get_identifier_def(&id).expect("Unknown identifier");
self.resolver.get_identifier_def(&id).expect("Unknown identifier");
let mut params = let mut params =
args.iter().map(|arg| (None, self.gen_expr(arg).unwrap())).collect_vec(); args.iter().map(|arg| (None, self.gen_expr(arg).unwrap())).collect_vec();
let kw_iter = keywords.iter().map(|kw| { let kw_iter = keywords.iter().map(|kw| {

View File

@ -305,9 +305,8 @@ pub fn gen_func<'ctx>(
}; };
let symbol = &task.symbol_name; let symbol = &task.symbol_name;
let fn_val = module let fn_val =
.get_function(symbol) module.get_function(symbol).unwrap_or_else(|| module.add_function(symbol, fn_type, None));
.unwrap_or_else(|| module.add_function(symbol, fn_type, None));
let init_bb = context.append_basic_block(fn_val, "init"); let init_bb = context.append_basic_block(fn_val, "init");
builder.position_at_end(init_bb); builder.position_at_end(init_bb);

View File

@ -9,7 +9,7 @@ use crate::{
}, },
}; };
use indoc::indoc; use indoc::indoc;
use parking_lot::{Mutex, RwLock}; use parking_lot::RwLock;
use rustpython_parser::{ast::fold::Fold, parser::parse_program}; use rustpython_parser::{ast::fold::Fold, parser::parse_program};
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};

View File

@ -1,4 +1,11 @@
use std::{borrow::BorrowMut, collections::{HashMap, HashSet}, fmt::Debug, iter::FromIterator, ops::{Deref, DerefMut}, sync::Arc}; use std::{
borrow::BorrowMut,
collections::{HashMap, HashSet},
fmt::Debug,
iter::FromIterator,
ops::{Deref, DerefMut},
sync::Arc,
};
use super::typecheck::type_inferencer::PrimitiveStore; use super::typecheck::type_inferencer::PrimitiveStore;
use super::typecheck::typedef::{FunSignature, FuncArg, SharedUnifier, Type, TypeEnum, Unifier}; use super::typecheck::typedef::{FunSignature, FuncArg, SharedUnifier, Type, TypeEnum, Unifier};
@ -7,7 +14,7 @@ use crate::{
typecheck::{type_inferencer::CodeLocation, typedef::CallId}, typecheck::{type_inferencer::CodeLocation, typedef::CallId},
}; };
use itertools::{izip, Itertools}; use itertools::{izip, Itertools};
use parking_lot::{Mutex, RwLock}; use parking_lot::RwLock;
use rustpython_parser::ast::{self, Stmt}; use rustpython_parser::ast::{self, Stmt};
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Debug)] #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Debug)]

View File

@ -45,7 +45,6 @@ impl SymbolResolver for Resolver {
fn get_identifier_def(&self, id: &str) -> Option<DefinitionId> { fn get_identifier_def(&self, id: &str) -> Option<DefinitionId> {
self.0.id_to_def.lock().get(id).cloned() self.0.id_to_def.lock().get(id).cloned()
} }
} }
#[test_case( #[test_case(
@ -126,7 +125,9 @@ fn test_simple_function_analyze(source: Vec<&str>, tys: Vec<&str>, names: Vec<&s
id_to_type: Default::default(), id_to_type: Default::default(),
class_names: Default::default(), class_names: Default::default(),
}); });
let resolver = Arc::new(Box::new(Resolver(internal_resolver.clone())) as Box<dyn SymbolResolver + Send + Sync>); let resolver = Arc::new(
Box::new(Resolver(internal_resolver.clone())) as Box<dyn SymbolResolver + Send + Sync>
);
for s in source { for s in source {
let ast = parse_program(s).unwrap(); let ast = parse_program(s).unwrap();
@ -279,12 +280,14 @@ fn test_simple_class_analyze(source: Vec<&str>, res: Vec<&str>) {
let internal_resolver = Arc::new(ResolverInternal { let internal_resolver = Arc::new(ResolverInternal {
id_to_def: Default::default(), id_to_def: Default::default(),
id_to_type: Mutex::new(vec![("T".to_string(), tvar_t.0), ("V".to_string(), tvar_v.0)] id_to_type: Mutex::new(
.into_iter() vec![("T".to_string(), tvar_t.0), ("V".to_string(), tvar_v.0)].into_iter().collect(),
.collect()), ),
class_names: Default::default(), class_names: Default::default(),
}); });
let resolver = Arc::new(Box::new(Resolver(internal_resolver.clone())) as Box<dyn SymbolResolver + Send + Sync>); let resolver = Arc::new(
Box::new(Resolver(internal_resolver.clone())) as Box<dyn SymbolResolver + Send + Sync>
);
for s in source { for s in source {
let ast = parse_program(s).unwrap(); let ast = parse_program(s).unwrap();

View File

@ -35,12 +35,7 @@ pub fn parse_ast_to_type_annotation_kinds<T>(
"bool" => Ok(TypeAnnotation::PrimitiveKind(primitives.bool)), "bool" => Ok(TypeAnnotation::PrimitiveKind(primitives.bool)),
"None" => Ok(TypeAnnotation::PrimitiveKind(primitives.none)), "None" => Ok(TypeAnnotation::PrimitiveKind(primitives.none)),
x => { x => {
if let Some(obj_id) = { if let Some(obj_id) = resolver.get_identifier_def(x) {
// write this way because the lock in the if/let construct lives
// for the whole if let construct
let id = resolver.get_identifier_def(x);
id
} {
let def = top_level_defs[obj_id.0].read(); let def = top_level_defs[obj_id.0].read();
if let TopLevelDef::Class { type_vars, .. } = &*def { if let TopLevelDef::Class { type_vars, .. } = &*def {
// also check param number here // also check param number here
@ -54,10 +49,7 @@ pub fn parse_ast_to_type_annotation_kinds<T>(
} else { } else {
Err("function cannot be used as a type".into()) Err("function cannot be used as a type".into())
} }
} else if let Some(ty) = { } else if let Some(ty) = resolver.get_symbol_type(unifier, primitives, id) {
let ty = resolver.get_symbol_type(unifier, primitives, id);
ty
} {
if let TypeEnum::TVar { .. } = unifier.get_ty(ty).as_ref() { if let TypeEnum::TVar { .. } = unifier.get_ty(ty).as_ref() {
Ok(TypeAnnotation::TypeVarKind(ty)) Ok(TypeAnnotation::TypeVarKind(ty))
} else { } else {
@ -240,7 +232,8 @@ pub fn get_type_from_type_annotation_kinds(
})); }));
println!("tobj_fields: {:?}", tobj_fields); println!("tobj_fields: {:?}", tobj_fields);
println!("{:?}: {}\n", println!(
"{:?}: {}\n",
tobj_fields.get("__init__").unwrap(), tobj_fields.get("__init__").unwrap(),
unifier.stringify( unifier.stringify(
*tobj_fields.get("__init__").unwrap(), *tobj_fields.get("__init__").unwrap(),

View File

@ -7,7 +7,6 @@ use super::typedef::{Call, FunSignature, FuncArg, Type, TypeEnum, Unifier};
use super::{magic_methods::*, typedef::CallId}; use super::{magic_methods::*, typedef::CallId};
use crate::{symbol_resolver::SymbolResolver, toplevel::TopLevelContext}; use crate::{symbol_resolver::SymbolResolver, toplevel::TopLevelContext};
use itertools::izip; use itertools::izip;
use parking_lot::Mutex;
use rustpython_parser::ast::{ use rustpython_parser::ast::{
self, self,
fold::{self, Fold}, fold::{self, Fold},
@ -164,8 +163,7 @@ impl<'a> fold::Fold<()> for Inferencer<'a> {
ast::ExprKind::Constant { value, .. } => Some(self.infer_constant(value)?), ast::ExprKind::Constant { value, .. } => Some(self.infer_constant(value)?),
ast::ExprKind::Name { id, .. } => { ast::ExprKind::Name { id, .. } => {
if !self.defined_identifiers.contains(id) { if !self.defined_identifiers.contains(id) {
if self.function_data.resolver.get_identifier_def(id.as_str()).is_some() if self.function_data.resolver.get_identifier_def(id.as_str()).is_some() {
{
self.defined_identifiers.insert(id.clone()); self.defined_identifiers.insert(id.clone());
} else { } else {
return Err(format!( return Err(format!(
@ -485,7 +483,11 @@ impl<'a> Inferencer<'a> {
} else { } else {
let variable_mapping = &mut self.variable_mapping; let variable_mapping = &mut self.variable_mapping;
let unifier = &mut self.unifier; let unifier = &mut self.unifier;
Ok(self.function_data.resolver.get_symbol_type(unifier, self.primitives, id).unwrap_or_else(|| { Ok(self
.function_data
.resolver
.get_symbol_type(unifier, self.primitives, id)
.unwrap_or_else(|| {
let ty = unifier.get_fresh_var().0; let ty = unifier.get_fresh_var().0;
variable_mapping.insert(id.to_string(), ty); variable_mapping.insert(id.to_string(), ty);
ty ty