From dee378aa23c9dcef2790d67b206bdf0006a01960 Mon Sep 17 00:00:00 2001 From: Christoph Burgdorf Date: Fri, 3 Jun 2022 13:34:33 +0200 Subject: [PATCH] First bits of traits and generic function params --- crates/analyzer/src/context.rs | 2 +- crates/analyzer/src/db.rs | 12 +- crates/analyzer/src/db/queries.rs | 1 + crates/analyzer/src/db/queries/functions.rs | 53 +++++- crates/analyzer/src/db/queries/module.rs | 43 ++++- crates/analyzer/src/db/queries/traits.rs | 11 ++ crates/analyzer/src/namespace/items.rs | 157 ++++++++++++++++++ crates/analyzer/src/namespace/types.rs | 47 +++++- crates/analyzer/src/operations.rs | 2 + crates/analyzer/src/traversal/call_args.rs | 36 +++- crates/analyzer/src/traversal/expressions.rs | 27 ++- crates/analyzer/tests/analysis.rs | 2 +- crates/analyzer/tests/errors.rs | 5 + ...neric_function_with_unsatisfied_bound.snap | 18 ++ ...contract_function_with_generic_params.snap | 14 ++ .../errors__invalid_generic_bound.snap | 12 ++ .../errors__invalid_impl_location.snap | 12 ++ .../snapshots/errors__invalid_impl_type.snap | 12 ++ .../snapshots/errors__map_constructor.snap | 2 +- crates/library/std/src/traits.fe | 15 ++ crates/mir/src/db.rs | 6 + crates/mir/src/db/queries/function.rs | 24 ++- crates/mir/src/db/queries/types.rs | 4 + crates/mir/src/ir/function.rs | 3 + crates/mir/src/lower/function.rs | 100 ++++++++--- crates/mir/src/lower/types.rs | 6 + crates/parser/src/ast.rs | 46 ++++- crates/parser/src/grammar/functions.rs | 9 +- crates/parser/src/grammar/module.rs | 6 +- crates/parser/src/grammar/types.rs | 97 ++++++++++- crates/parser/src/lexer/token.rs | 6 + .../cases__parse_ast__fn_def_generic.snap | 6 +- ...generic_function_with_unsatisfied_bound.fe | 16 ++ .../contract_function_with_generic_params.fe | 5 + .../compile_errors/invalid_generic_bound.fe | 3 + .../compile_errors/invalid_impl_location.fe | 3 + .../compile_errors/invalid_impl_type.fe | 3 + .../fixtures/features/generic_functions.fe | 23 +++ crates/tests/src/features.rs | 8 + 39 files changed, 795 insertions(+), 62 deletions(-) create mode 100644 crates/analyzer/src/db/queries/traits.rs create mode 100644 crates/analyzer/tests/snapshots/errors__call_generic_function_with_unsatisfied_bound.snap create mode 100644 crates/analyzer/tests/snapshots/errors__contract_function_with_generic_params.snap create mode 100644 crates/analyzer/tests/snapshots/errors__invalid_generic_bound.snap create mode 100644 crates/analyzer/tests/snapshots/errors__invalid_impl_location.snap create mode 100644 crates/analyzer/tests/snapshots/errors__invalid_impl_type.snap create mode 100644 crates/library/std/src/traits.fe create mode 100644 crates/test-files/fixtures/compile_errors/call_generic_function_with_unsatisfied_bound.fe create mode 100644 crates/test-files/fixtures/compile_errors/contract_function_with_generic_params.fe create mode 100644 crates/test-files/fixtures/compile_errors/invalid_generic_bound.fe create mode 100644 crates/test-files/fixtures/compile_errors/invalid_impl_location.fe create mode 100644 crates/test-files/fixtures/compile_errors/invalid_impl_type.fe create mode 100644 crates/test-files/fixtures/features/generic_functions.fe diff --git a/crates/analyzer/src/context.rs b/crates/analyzer/src/context.rs index fa6e3c5ef7..cf7dcab96d 100644 --- a/crates/analyzer/src/context.rs +++ b/crates/analyzer/src/context.rs @@ -508,7 +508,7 @@ impl CallType { // check that this is the `Context` struct defined in `std` // this should be deleted once associated functions are supported and we can // define unsafe constructors in Fe - struct_.name == "Context" && struct_.id.module(db).ingot(db).name(db) == "std" + struct_.name == "Context" && struct_.id.module(db).is_in_std(db) } else { self.function().map(|id| id.is_unsafe(db)).unwrap_or(false) } diff --git a/crates/analyzer/src/db.rs b/crates/analyzer/src/db.rs index bbcc476a90..6181ae463b 100644 --- a/crates/analyzer/src/db.rs +++ b/crates/analyzer/src/db.rs @@ -1,8 +1,8 @@ use crate::context::{Analysis, Constant, FunctionBody}; use crate::errors::{ConstEvalError, TypeError}; use crate::namespace::items::{ - self, ContractFieldId, ContractId, DepGraphWrapper, EventId, FunctionId, IngotId, Item, - ModuleConstantId, ModuleId, StructFieldId, StructId, TypeAliasId, + self, ContractFieldId, ContractId, DepGraphWrapper, EventId, FunctionId, Impl, IngotId, Item, + ModuleConstantId, ModuleId, StructFieldId, StructId, TraitId, TypeAliasId, }; use crate::namespace::types; use fe_common::db::{SourceDb, SourceDbStorage, Upcast, UpcastMut}; @@ -24,6 +24,8 @@ pub trait AnalyzerDb: SourceDb + Upcast + UpcastMut #[salsa::interned] fn intern_struct(&self, data: Rc) -> StructId; #[salsa::interned] + fn intern_trait(&self, data: Rc) -> TraitId; + #[salsa::interned] fn intern_struct_field(&self, data: Rc) -> StructFieldId; #[salsa::interned] fn intern_type_alias(&self, data: Rc) -> TypeAliasId; @@ -60,6 +62,8 @@ pub trait AnalyzerDb: SourceDb + Upcast + UpcastMut fn module_is_incomplete(&self, module: ModuleId) -> bool; #[salsa::invoke(queries::module::module_all_items)] fn module_all_items(&self, module: ModuleId) -> Rc<[Item]>; + #[salsa::invoke(queries::module::module_all_impls)] + fn module_all_impls(&self, module: ModuleId) -> Rc<[Impl]>; #[salsa::invoke(queries::module::module_item_map)] fn module_item_map(&self, module: ModuleId) -> Analysis>>; #[salsa::invoke(queries::module::module_contracts)] @@ -154,6 +158,10 @@ pub trait AnalyzerDb: SourceDb + Upcast + UpcastMut #[salsa::invoke(queries::structs::struct_dependency_graph)] fn struct_dependency_graph(&self, id: StructId) -> Analysis; + // Trait + #[salsa::invoke(queries::traits::trait_type)] + fn trait_type(&self, id: TraitId) -> Rc; + // Event #[salsa::invoke(queries::events::event_type)] fn event_type(&self, event: EventId) -> Analysis>; diff --git a/crates/analyzer/src/db/queries.rs b/crates/analyzer/src/db/queries.rs index f6c5db8ad6..59519f493f 100644 --- a/crates/analyzer/src/db/queries.rs +++ b/crates/analyzer/src/db/queries.rs @@ -4,4 +4,5 @@ pub mod functions; pub mod ingots; pub mod module; pub mod structs; +pub mod traits; pub mod types; diff --git a/crates/analyzer/src/db/queries/functions.rs b/crates/analyzer/src/db/queries/functions.rs index 055dd56e44..ac7c8906bc 100644 --- a/crates/analyzer/src/db/queries/functions.rs +++ b/crates/analyzer/src/db/queries/functions.rs @@ -1,9 +1,11 @@ use crate::context::{AnalyzerContext, CallType, FunctionBody}; use crate::db::{Analysis, AnalyzerDb}; use crate::errors::TypeError; -use crate::namespace::items::{DepGraph, DepGraphWrapper, DepLocality, FunctionId, Item, TypeDef}; +use crate::namespace::items::{ + Class, DepGraph, DepGraphWrapper, DepLocality, FunctionId, Item, TypeDef, +}; use crate::namespace::scopes::{BlockScope, BlockScopeType, FunctionScope, ItemScope}; -use crate::namespace::types::{self, Contract, CtxDecl, SelfDecl, Struct, Type}; +use crate::namespace::types::{self, Contract, CtxDecl, Generic, SelfDecl, Struct, Type}; use crate::traversal::functions::traverse_statements; use crate::traversal::types::type_desc; use fe_common::diagnostics::Label; @@ -30,6 +32,17 @@ pub fn function_signature( let mut names = HashMap::new(); let mut labels = HashMap::new(); + if let (Some(Class::Contract(_)), true) = (fn_parent, function.is_generic(db)) { + scope.fancy_error( + "generic function parameters aren't yet supported in contract functions", + vec![Label::primary( + function.data(db).ast.kind.generic_params.span, + "This can not appear here", + )], + vec!["Hint: Struct functions can have generic parameters".into()], + ); + } + let params = def .args .iter() @@ -55,7 +68,7 @@ pub fn function_signature( None } ast::FunctionArg::Regular(reg) => { - let typ = type_desc(&mut scope, ®.typ).and_then(|typ| match typ { + let typ = resolve_function_param_type(db, function, &mut scope, ®.typ).and_then(|typ| match typ { typ if typ.has_fixed_size() => Ok(typ), _ => Err(TypeError::new(scope.error( "function parameter types must have fixed size", @@ -192,6 +205,40 @@ pub fn function_signature( } } +pub fn resolve_function_param_type( + db: &dyn AnalyzerDb, + function: FunctionId, + context: &mut dyn AnalyzerContext, + desc: &Node, +) -> Result { + // First check if the param type is a local generic of the function. This won't hold when in the future + // generics can appear on the contract, struct or module level but it could be good enough for now. + if let ast::TypeDesc::Base { base } = &desc.kind { + if let Some(val) = function.generic_param(db, base) { + let bounds = match val { + ast::GenericParameter::Unbounded(_) => vec![], + ast::GenericParameter::Bounded { bound, .. } => match type_desc(context, &bound)? { + Type::Trait(trait_ty) => vec![trait_ty.id], + other => { + context.error( + &format!("expected trait, found type `{}`", other), + bound.span, + "not a trait", + ); + vec![] + } + }, + }; + + return Ok(Type::Generic(Generic { + name: base.clone(), + bounds, + })); + } + } + type_desc(context, desc) +} + /// Gather context information for a function body and check for type errors. pub fn function_body(db: &dyn AnalyzerDb, function: FunctionId) -> Analysis> { let def = &function.data(db).ast.kind; diff --git a/crates/analyzer/src/db/queries/module.rs b/crates/analyzer/src/db/queries/module.rs index dea539886f..f8d59a9552 100644 --- a/crates/analyzer/src/db/queries/module.rs +++ b/crates/analyzer/src/db/queries/module.rs @@ -2,8 +2,8 @@ use crate::context::{Analysis, AnalyzerContext, Constant}; use crate::db::AnalyzerDb; use crate::errors::{self, ConstEvalError, TypeError}; use crate::namespace::items::{ - Contract, ContractId, Event, Function, Item, ModuleConstant, ModuleConstantId, ModuleId, - ModuleSource, Struct, StructId, TypeAlias, TypeDef, + Contract, ContractId, Event, Function, Impl, Item, ModuleConstant, ModuleConstantId, ModuleId, + ModuleSource, Struct, StructId, Trait, TypeAlias, TypeDef, }; use crate::namespace::scopes::ItemScope; use crate::namespace::types::{self, Type}; @@ -59,7 +59,6 @@ pub fn module_is_incomplete(db: &dyn AnalyzerDb, module: ModuleId) -> bool { pub fn module_all_items(db: &dyn AnalyzerDb, module: ModuleId) -> Rc<[Item]> { let body = &module.ast(db).body; - body.iter() .filter_map(|stmt| match stmt { ast::ModuleStmt::TypeAlias(node) => Some(Item::Type(TypeDef::Alias( @@ -94,8 +93,13 @@ pub fn module_all_items(db: &dyn AnalyzerDb, module: ModuleId) -> Rc<[Item]> { parent: None, })))) } - ast::ModuleStmt::Pragma(_) => None, - ast::ModuleStmt::Use(_) => None, + ast::ModuleStmt::Trait(node) => Some(Item::Type(TypeDef::Trait(db.intern_trait( + Rc::new(Trait { + ast: node.clone(), + module, + }), + )))), + ast::ModuleStmt::Pragma(_) | ast::ModuleStmt::Use(_) | ast::ModuleStmt::Impl(_) => None, ast::ModuleStmt::Event(node) => Some(Item::Event(db.intern_event(Rc::new(Event { ast: node.clone(), module, @@ -106,6 +110,35 @@ pub fn module_all_items(db: &dyn AnalyzerDb, module: ModuleId) -> Rc<[Item]> { .collect() } +pub fn module_all_impls(db: &dyn AnalyzerDb, module: ModuleId) -> Rc<[Impl]> { + let body = &module.ast(db).body; + body.iter() + .filter_map(|stmt| match stmt { + ast::ModuleStmt::Impl(impl_node) => { + let treit = module + .items(db) + .get(&impl_node.kind.impl_trait.kind) + .cloned(); + + let mut scope = ItemScope::new(db, module); + let receiver_type = type_desc(&mut scope, &impl_node.kind.receiver).unwrap(); + + if let Some(Item::Type(TypeDef::Trait(val))) = treit { + Some(Impl { + trait_id: val, + receiver: receiver_type, + ast: impl_node.clone(), + module, + }) + } else { + None + } + } + _ => None, + }) + .collect() +} + pub fn module_item_map( db: &dyn AnalyzerDb, module: ModuleId, diff --git a/crates/analyzer/src/db/queries/traits.rs b/crates/analyzer/src/db/queries/traits.rs new file mode 100644 index 0000000000..e0a4cbd2f5 --- /dev/null +++ b/crates/analyzer/src/db/queries/traits.rs @@ -0,0 +1,11 @@ +use crate::namespace::items::TraitId; +use crate::namespace::types; +use crate::AnalyzerDb; +use std::rc::Rc; + +pub fn trait_type(db: &dyn AnalyzerDb, trait_: TraitId) -> Rc { + Rc::new(types::Trait { + name: trait_.name(db), + id: trait_, + }) +} diff --git a/crates/analyzer/src/namespace/items.rs b/crates/analyzer/src/namespace/items.rs index 8cb18eb6d1..944d6bf3c4 100644 --- a/crates/analyzer/src/namespace/items.rs +++ b/crates/analyzer/src/namespace/items.rs @@ -1,4 +1,5 @@ use crate::context; +use fe_common::diagnostics::Label; use crate::context::{Analysis, Constant}; use crate::errors::{self, IncompleteItem, TypeError}; @@ -9,6 +10,7 @@ use crate::{builtins, errors::ConstEvalError}; use fe_common::diagnostics::Diagnostic; use fe_common::files::{common_prefix, Utf8Path}; use fe_common::{impl_intern_key, FileKind, SourceFileId}; +use fe_parser::ast::GenericParameter; use fe_parser::node::{Node, Span}; use fe_parser::{ast, node::NodeId}; use indexmap::{indexmap, IndexMap}; @@ -17,6 +19,8 @@ use std::ops::Deref; use std::rc::Rc; use strum::IntoEnumIterator; +use super::types::Type; + /// A named item. This does not include things inside of /// a function body. #[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)] @@ -469,11 +473,20 @@ impl ModuleId { db.module_is_incomplete(*self) } + pub fn is_in_std(&self, db: &dyn AnalyzerDb) -> bool { + self.ingot(db).name(db) == "std" + } + /// Includes duplicate names pub fn all_items(&self, db: &dyn AnalyzerDb) -> Rc<[Item]> { db.module_all_items(*self) } + /// Includes duplicate names + pub fn all_impls(&self, db: &dyn AnalyzerDb) -> Rc<[Impl]> { + db.module_all_impls(*self) + } + /// Returns a map of the named items in the module pub fn items(&self, db: &dyn AnalyzerDb) -> Rc> { db.module_item_map(*self).value @@ -669,6 +682,10 @@ impl ModuleId { self.all_items(db) .iter() .for_each(|id| id.sink_diagnostics(db, sink)); + + self.all_impls(db) + .iter() + .for_each(|val| val.sink_diagnostics(db, sink)); } #[doc(hidden)] @@ -747,6 +764,7 @@ impl ModuleConstantId { pub enum TypeDef { Alias(TypeAliasId), Struct(StructId), + Trait(TraitId), Contract(ContractId), Primitive(types::Base), } @@ -778,6 +796,7 @@ impl TypeDef { match self { TypeDef::Alias(id) => id.name(db), TypeDef::Struct(id) => id.name(db), + TypeDef::Trait(id) => id.name(db), TypeDef::Contract(id) => id.name(db), TypeDef::Primitive(typ) => typ.name(), } @@ -787,6 +806,7 @@ impl TypeDef { match self { TypeDef::Alias(id) => Some(id.name_span(db)), TypeDef::Struct(id) => Some(id.name_span(db)), + TypeDef::Trait(id) => Some(id.name_span(db)), TypeDef::Contract(id) => Some(id.name_span(db)), TypeDef::Primitive(_) => None, } @@ -800,6 +820,10 @@ impl TypeDef { name: id.name(db), field_count: id.fields(db).len(), // for the EvmSized trait })), + TypeDef::Trait(id) => Ok(types::Type::Trait(types::Trait { + id: *id, + name: id.name(db), + })), TypeDef::Contract(id) => Ok(types::Type::Contract(types::Contract { id: *id, name: id.name(db), @@ -812,6 +836,7 @@ impl TypeDef { match self { Self::Alias(id) => id.is_public(db), Self::Struct(id) => id.is_public(db), + Self::Trait(id) => id.is_public(db), Self::Contract(id) => id.is_public(db), Self::Primitive(_) => true, } @@ -821,6 +846,7 @@ impl TypeDef { match self { TypeDef::Alias(id) => Some(id.parent(db)), TypeDef::Struct(id) => Some(id.parent(db)), + TypeDef::Trait(id) => Some(id.parent(db)), TypeDef::Contract(id) => Some(id.parent(db)), TypeDef::Primitive(_) => None, } @@ -830,6 +856,7 @@ impl TypeDef { match self { TypeDef::Alias(id) => id.sink_diagnostics(db, sink), TypeDef::Struct(id) => id.sink_diagnostics(db, sink), + TypeDef::Trait(id) => id.sink_diagnostics(db, sink), TypeDef::Contract(id) => id.sink_diagnostics(db, sink), TypeDef::Primitive(_) => {} } @@ -1097,6 +1124,7 @@ impl FunctionId { pub fn takes_self(&self, db: &dyn AnalyzerDb) -> bool { self.signature(db).self_decl.is_some() } + pub fn self_span(&self, db: &dyn AnalyzerDb) -> Option { if self.takes_self(db) { self.data(db) @@ -1110,6 +1138,25 @@ impl FunctionId { } } + pub fn is_generic(&self, db: &dyn AnalyzerDb) -> bool { + !self.data(db).ast.kind.generic_params.kind.is_empty() + } + + pub fn generic_params(&self, db: &dyn AnalyzerDb) -> Vec { + self.data(db).ast.kind.generic_params.kind.clone() + } + + pub fn generic_param(&self, db: &dyn AnalyzerDb, param_name: &str) -> Option { + self.generic_params(db) + .iter() + .find(|param| match param { + GenericParameter::Unbounded(name) if name.kind == param_name => true, + GenericParameter::Bounded { name, .. } if name.kind == param_name => true, + _ => false, + }) + .cloned() + } + pub fn is_public(&self, db: &dyn AnalyzerDb) -> bool { self.pub_span(db).is_some() } @@ -1324,6 +1371,116 @@ impl StructFieldId { } } +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub struct Impl { + pub trait_id: TraitId, + pub receiver: Type, + pub module: ModuleId, + pub ast: Node, +} + +impl Impl { + fn validate_type_or_trait_is_in_ingot( + &self, + db: &dyn AnalyzerDb, + sink: &mut impl DiagnosticSink, + module: Option, + ) { + let is_allowed = match module { + None => self.module == self.trait_id.module(db), + Some(type_module) => { + type_module == self.module || self.trait_id.module(db) == self.module + } + }; + + if !is_allowed { + sink.push(&errors::fancy_error( + "illegal `impl`. Either type or trait must be in the same ingot as the `impl`", + vec![Label::primary( + self.ast.span, + format!( + "Neither `{}` nor `{}` are in the ingot of the `impl` block", + self.receiver, + self.trait_id.name(db) + ), + )], + vec![], + )) + } + } + + pub fn sink_diagnostics(&self, db: &dyn AnalyzerDb, sink: &mut impl DiagnosticSink) { + match &self.receiver { + Type::Contract(_) + | Type::Map(_) + | Type::SelfContract(_) + | Type::Trait(_) + | Type::Generic(_) => sink.push(&errors::fancy_error( + format!("`impl` blocks aren't allowed for {}", self.receiver), + vec![Label::primary(self.ast.span, "illegal `impl` block")], + vec![], + )), + Type::Base(_) | Type::Array(_) | Type::Tuple(_) | Type::String(_) => { + self.validate_type_or_trait_is_in_ingot(db, sink, None) + } + Type::Struct(val) => { + self.validate_type_or_trait_is_in_ingot(db, sink, Some(val.id.module(db))) + } + } + } +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub struct Trait { + pub ast: Node, + pub module: ModuleId, +} + +#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)] +pub struct TraitId(pub(crate) u32); +impl_intern_key!(TraitId); +impl TraitId { + pub fn data(&self, db: &dyn AnalyzerDb) -> Rc { + db.lookup_intern_trait(*self) + } + pub fn span(&self, db: &dyn AnalyzerDb) -> Span { + self.data(db).ast.span + } + pub fn name(&self, db: &dyn AnalyzerDb) -> SmolStr { + self.data(db).ast.name().into() + } + pub fn name_span(&self, db: &dyn AnalyzerDb) -> Span { + self.data(db).ast.kind.name.span + } + + pub fn is_public(&self, db: &dyn AnalyzerDb) -> bool { + self.data(db).ast.kind.pub_qual.is_some() + } + + pub fn module(&self, db: &dyn AnalyzerDb) -> ModuleId { + self.data(db).module + } + + pub fn is_implemented_for(&self, db: &dyn AnalyzerDb, ty: &Type) -> bool { + self.module(db) + .all_impls(db) + .iter() + .any(|val| &val.trait_id == self && &val.receiver == ty) + } + + pub fn typ(&self, db: &dyn AnalyzerDb) -> Rc { + db.trait_type(*self) + } + pub fn is_in_std(&self, db: &dyn AnalyzerDb) -> bool { + self.module(db).is_in_std(db) + } + + pub fn parent(&self, db: &dyn AnalyzerDb) -> Item { + Item::Module(self.data(db).module) + } + pub fn sink_diagnostics(&self, _db: &dyn AnalyzerDb, _sink: &mut impl DiagnosticSink) {} +} + #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub struct Event { pub ast: Node, diff --git a/crates/analyzer/src/namespace/types.rs b/crates/analyzer/src/namespace/types.rs index cee6eba1d0..602073667c 100644 --- a/crates/analyzer/src/namespace/types.rs +++ b/crates/analyzer/src/namespace/types.rs @@ -1,5 +1,6 @@ use crate::context::AnalyzerContext; use crate::errors::TypeError; +use crate::namespace::items::TraitId; use crate::namespace::items::{Class, ContractId, StructId}; use crate::AnalyzerDb; @@ -47,6 +48,8 @@ pub enum Type { /// of `self` within a contract function. SelfContract(Contract), Struct(Struct), + Trait(Trait), + Generic(Generic), } #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -125,6 +128,26 @@ impl Struct { } } +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Trait { + pub name: SmolStr, + pub id: TraitId, +} +impl Trait { + pub fn from_id(id: TraitId, db: &dyn AnalyzerDb) -> Self { + Self { + name: id.name(db), + id, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Generic { + pub name: SmolStr, + pub bounds: Vec, +} + #[derive(Clone, PartialEq, Eq, Hash)] pub struct Contract { pub name: SmolStr, @@ -388,6 +411,8 @@ impl Type { Type::Tuple(inner) => inner.to_string().into(), Type::String(inner) => inner.to_string().into(), Type::Struct(inner) => inner.name.clone(), + Type::Trait(inner) => inner.name.clone(), + Type::Generic(inner) => inner.name.clone(), Type::Contract(inner) | Type::SelfContract(inner) => inner.name.clone(), } } @@ -456,8 +481,9 @@ impl Type { | Type::Tuple(_) | Type::String(_) | Type::Struct(_) + | Type::Generic(_) | Type::Contract(_) => true, - Type::Map(_) | Type::SelfContract(_) => false, + Type::Map(_) | Type::SelfContract(_) | Type::Trait(_) => false, } } } @@ -637,6 +663,8 @@ impl fmt::Display for Type { Type::Contract(inner) => inner.fmt(f), Type::SelfContract(inner) => inner.fmt(f), Type::Struct(inner) => inner.fmt(f), + Type::Trait(inner) => inner.fmt(f), + Type::Generic(inner) => inner.fmt(f), } } } @@ -730,6 +758,23 @@ impl fmt::Debug for Struct { } } +impl fmt::Display for Trait { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name) + } +} +impl fmt::Debug for Trait { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Struct").field("name", &self.name).finish() + } +} + +impl fmt::Display for Generic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name) + } +} + impl FromStr for Base { type Err = strum::ParseError; diff --git a/crates/analyzer/src/operations.rs b/crates/analyzer/src/operations.rs index 21814d90c9..e1ab87c00f 100644 --- a/crates/analyzer/src/operations.rs +++ b/crates/analyzer/src/operations.rs @@ -15,6 +15,8 @@ pub fn index(value: Type, index: Type) -> Result { | Type::String(_) | Type::Contract(_) | Type::SelfContract(_) + | Type::Trait(_) + | Type::Generic(_) | Type::Struct(_) => Err(IndexingError::NotSubscriptable), } } diff --git a/crates/analyzer/src/traversal/call_args.rs b/crates/analyzer/src/traversal/call_args.rs index 9238a0a045..b89b69a8a9 100644 --- a/crates/analyzer/src/traversal/call_args.rs +++ b/crates/analyzer/src/traversal/call_args.rs @@ -1,6 +1,6 @@ use crate::context::{AnalyzerContext, DiagnosticVoucher}; use crate::errors::{FatalError, TypeError}; -use crate::namespace::types::{EventField, FunctionParam, Type}; +use crate::namespace::types::{EventField, FunctionParam, Generic, Type}; use crate::traversal::expressions::assignable_expr; use fe_common::{diagnostics::Label, utils::humanize::pluralize_conditionally}; use fe_common::{Span, Spanned}; @@ -151,7 +151,7 @@ pub fn validate_named_args( let param_type = param.typ()?; let val_attrs = assignable_expr(context, &arg.kind.value, Some(¶m_type.clone()))?; - if param_type != val_attrs.typ { + if !validate_arg_type(context, arg, &val_attrs.typ, ¶m_type) { let msg = if let Some(label) = param.label() { format!("incorrect type for `{}` argument `{}`", name, label) } else { @@ -165,3 +165,35 @@ pub fn validate_named_args( } Ok(()) } + +fn validate_arg_type( + context: &mut dyn AnalyzerContext, + arg: &Node, + arg_type: &Type, + param_type: &Type, +) -> bool { + if let Type::Generic(Generic { bounds, .. }) = param_type { + for bound in bounds { + if !bound.is_implemented_for(context.db(), arg_type) { + context.error( + &format!( + "the trait bound `{}: {}` is not satisfied", + arg_type, + bound.name(context.db()) + ), + arg.span, + &format!( + "the trait `{}` is not implemented for `{}`", + bound.name(context.db()), + arg_type + ), + ); + + return false; + } + } + true + } else { + arg_type == param_type + } +} diff --git a/crates/analyzer/src/traversal/expressions.rs b/crates/analyzer/src/traversal/expressions.rs index 30e061c07f..d015aebbf6 100644 --- a/crates/analyzer/src/traversal/expressions.rs +++ b/crates/analyzer/src/traversal/expressions.rs @@ -179,7 +179,7 @@ pub fn assignable_expr( attributes.move_location = Some(Location::Value); } } - Array(_) | Tuple(_) | String(_) | Struct(_) => { + Array(_) | Tuple(_) | String(_) | Struct(_) | Trait(_) | Generic(_) => { if attributes.final_location() != Location::Memory { context.fancy_error( "value must be copied to memory", @@ -1123,27 +1123,18 @@ fn expr_call_type_constructor( Type::Struct(struct_type) => { return expr_call_struct_constructor(context, name_span, struct_type, args) } - Type::Base(Base::Bool) => { + Type::Base(Base::Bool) + | Type::Array(_) + | Type::Map(_) + | Type::Generic(_) + | Type::Trait(_) => { return Err(FatalError::new(context.error( - "`bool` type is not callable", - name_span, - "", - ))) - } - Type::Map(_) => { - return Err(FatalError::new(context.error( - "`Map` type is not callable", - name_span, - "", - ))) - } - Type::Array(_) => { - return Err(FatalError::new(context.error( - "`Array` type is not callable", + &format!("`{}` type is not callable", typ.name()), name_span, "", ))) } + _ => {} } @@ -1223,6 +1214,8 @@ fn expr_call_type_constructor( Type::Struct(_) => unreachable!(), // handled above Type::Map(_) => unreachable!(), // handled above Type::Array(_) => unreachable!(), // handled above + Type::Trait(_) => unreachable!(), // handled above + Type::Generic(_) => unreachable!(), // handled above Type::SelfContract(_) => unreachable!(), /* unnameable; contract names all become * Type::Contract */ }; diff --git a/crates/analyzer/tests/analysis.rs b/crates/analyzer/tests/analysis.rs index 439d83ea14..e0fd946aca 100644 --- a/crates/analyzer/tests/analysis.rs +++ b/crates/analyzer/tests/analysis.rs @@ -345,7 +345,7 @@ fn build_snapshot(db: &dyn AnalyzerDb, module: items::ModuleId) -> String { .collect(), ] .concat(), - + Item::Type(TypeDef::Trait(_)) => vec![], // TODO: fill in when traits are allowed to have functions Item::Function(id) => function_diagnostics(*id, db), Item::Constant(id) => vec![build_display_diagnostic(id.span(db), &id.typ(db).unwrap())], Item::Event(id) => event_diagnostics(*id, db), diff --git a/crates/analyzer/tests/errors.rs b/crates/analyzer/tests/errors.rs index 426c6bded2..d60b9e4817 100644 --- a/crates/analyzer/tests/errors.rs +++ b/crates/analyzer/tests/errors.rs @@ -216,6 +216,7 @@ test_file! { bad_string } test_file! { bad_tuple_attr1 } test_file! { bad_tuple_attr2 } test_file! { bad_tuple_attr3 } +test_file! { call_generic_function_with_unsatisfied_bound} test_file! { call_builtin_object } test_file! { call_create_with_wrong_type } test_file! { call_create2_with_wrong_type } @@ -247,11 +248,15 @@ test_file! { duplicate_var_in_for_loop } test_file! { emit_bad_args } test_file! { external_call_type_error } test_file! { external_call_wrong_number_of_params } +test_file! { contract_function_with_generic_params } test_file! { indexed_event } test_file! { invalid_compiler_version } test_file! { invalid_block_field } test_file! { invalid_chain_field } test_file! { invalid_contract_field } +test_file! { invalid_generic_bound } +test_file! { invalid_impl_type } +test_file! { invalid_impl_location } test_file! { invalid_msg_field } test_file! { invalid_string_field } test_file! { invalid_struct_field } diff --git a/crates/analyzer/tests/snapshots/errors__call_generic_function_with_unsatisfied_bound.snap b/crates/analyzer/tests/snapshots/errors__call_generic_function_with_unsatisfied_bound.snap new file mode 100644 index 0000000000..7e91beb201 --- /dev/null +++ b/crates/analyzer/tests/snapshots/errors__call_generic_function_with_unsatisfied_bound.snap @@ -0,0 +1,18 @@ +--- +source: crates/analyzer/tests/errors.rs +expression: "error_string(&path, test_files::fixture(path))" + +--- +error: the trait bound `bool: IsNumeric` is not satisfied + ┌─ compile_errors/call_generic_function_with_unsatisfied_bound.fe:14:13 + │ +14 │ foo.bar(true) + │ ^^^^ the trait `IsNumeric` is not implemented for `bool` + +error: incorrect type for `bar` argument at position 0 + ┌─ compile_errors/call_generic_function_with_unsatisfied_bound.fe:14:13 + │ +14 │ foo.bar(true) + │ ^^^^ this has type `bool`; expected type `T` + + diff --git a/crates/analyzer/tests/snapshots/errors__contract_function_with_generic_params.snap b/crates/analyzer/tests/snapshots/errors__contract_function_with_generic_params.snap new file mode 100644 index 0000000000..810727eaa3 --- /dev/null +++ b/crates/analyzer/tests/snapshots/errors__contract_function_with_generic_params.snap @@ -0,0 +1,14 @@ +--- +source: crates/analyzer/tests/errors.rs +expression: "error_string(&path, test_files::fixture(path))" + +--- +error: generic function parameters aren't yet supported in contract functions + ┌─ compile_errors/contract_function_with_generic_params.fe:4:15 + │ +4 │ pub fn bar(val: T) {} + │ ^^^^^^^^^^^^^^ This can not appear here + │ + = Hint: Struct functions can have generic parameters + + diff --git a/crates/analyzer/tests/snapshots/errors__invalid_generic_bound.snap b/crates/analyzer/tests/snapshots/errors__invalid_generic_bound.snap new file mode 100644 index 0000000000..61fb23cfc0 --- /dev/null +++ b/crates/analyzer/tests/snapshots/errors__invalid_generic_bound.snap @@ -0,0 +1,12 @@ +--- +source: crates/analyzer/tests/errors.rs +expression: "error_string(&path, test_files::fixture(path))" + +--- +error: expected trait, found type `bool` + ┌─ compile_errors/invalid_generic_bound.fe:2:19 + │ +2 │ pub fn bar(val: T) {} + │ ^^^^ not a trait + + diff --git a/crates/analyzer/tests/snapshots/errors__invalid_impl_location.snap b/crates/analyzer/tests/snapshots/errors__invalid_impl_location.snap new file mode 100644 index 0000000000..5009464436 --- /dev/null +++ b/crates/analyzer/tests/snapshots/errors__invalid_impl_location.snap @@ -0,0 +1,12 @@ +--- +source: crates/analyzer/tests/errors.rs +expression: "error_string(&path, test_files::fixture(path))" + +--- +error: illegal `impl`. Either type or trait must be in the same ingot as the `impl` + ┌─ compile_errors/invalid_impl_location.fe:3:1 + │ +3 │ impl IsNumeric for u8 {} + │ ^^^^^^^^^^^^^^^^^^^^^ Neither `u8` nor `IsNumeric` are in the ingot of the `impl` block + + diff --git a/crates/analyzer/tests/snapshots/errors__invalid_impl_type.snap b/crates/analyzer/tests/snapshots/errors__invalid_impl_type.snap new file mode 100644 index 0000000000..14c71a7d97 --- /dev/null +++ b/crates/analyzer/tests/snapshots/errors__invalid_impl_type.snap @@ -0,0 +1,12 @@ +--- +source: crates/analyzer/tests/errors.rs +expression: "error_string(&path, test_files::fixture(path))" + +--- +error: `impl` blocks aren't allowed for Map + ┌─ compile_errors/invalid_impl_type.fe:3:1 + │ +3 │ impl SomeTrait for Map {} + │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ illegal `impl` block + + diff --git a/crates/analyzer/tests/snapshots/errors__map_constructor.snap b/crates/analyzer/tests/snapshots/errors__map_constructor.snap index 94105f7492..e572c4063e 100644 --- a/crates/analyzer/tests/snapshots/errors__map_constructor.snap +++ b/crates/analyzer/tests/snapshots/errors__map_constructor.snap @@ -3,7 +3,7 @@ source: crates/analyzer/tests/errors.rs expression: "error_string(\"[snippet]\", &src)" --- -error: `Map` type is not callable +error: `Map` type is not callable ┌─ [snippet]:3:3 │ 3 │ Map() diff --git a/crates/library/std/src/traits.fe b/crates/library/std/src/traits.fe new file mode 100644 index 0000000000..15ea592387 --- /dev/null +++ b/crates/library/std/src/traits.fe @@ -0,0 +1,15 @@ +# Marker trait that all numeric types implement +pub trait IsNumeric {} + +impl IsNumeric for u8 {} +impl IsNumeric for u16 {} +impl IsNumeric for u32 {} +impl IsNumeric for u64 {} +impl IsNumeric for u128 {} +impl IsNumeric for u256 {} +impl IsNumeric for i8 {} +impl IsNumeric for i16 {} +impl IsNumeric for i32 {} +impl IsNumeric for i64 {} +impl IsNumeric for i128 {} +impl IsNumeric for i256 {} diff --git a/crates/mir/src/db.rs b/crates/mir/src/db.rs index e2c2525a7f..11cc30612b 100644 --- a/crates/mir/src/db.rs +++ b/crates/mir/src/db.rs @@ -51,6 +51,12 @@ pub trait MirDb: AnalyzerDb + Upcast + UpcastMut &self, analyzer_func: analyzer_items::FunctionId, ) -> ir::FunctionId; + #[salsa::invoke(queries::function::mir_lowered_monomorphized_func_signature)] + fn mir_lowered_monomorphized_func_signature( + &self, + analyzer_func: analyzer_items::FunctionId, + concrete_args: Vec, + ) -> ir::FunctionId; #[salsa::invoke(queries::function::mir_lowered_func_body)] fn mir_lowered_func_body(&self, func: ir::FunctionId) -> Rc; } diff --git a/crates/mir/src/db/queries/function.rs b/crates/mir/src/db/queries/function.rs index d863f36d18..7c32cb8470 100644 --- a/crates/mir/src/db/queries/function.rs +++ b/crates/mir/src/db/queries/function.rs @@ -1,12 +1,13 @@ use std::rc::Rc; use fe_analyzer::namespace::items as analyzer_items; +use fe_analyzer::namespace::types as analyzer_types; use smol_str::SmolStr; use crate::{ db::MirDb, ir::{self, function::Linkage, FunctionSignature, TypeId}, - lower::function::{lower_func_body, lower_func_signature}, + lower::function::{lower_func_body, lower_func_signature, lower_monomorphized_func_signature}, }; pub fn mir_lowered_func_signature( @@ -16,6 +17,14 @@ pub fn mir_lowered_func_signature( lower_func_signature(db, analyzer_func) } +pub fn mir_lowered_monomorphized_func_signature( + db: &dyn MirDb, + analyzer_func: analyzer_items::FunctionId, + concrete_args: Vec, +) -> ir::FunctionId { + lower_monomorphized_func_signature(db, analyzer_func, &concrete_args) +} + pub fn mir_lowered_func_body(db: &dyn MirDb, func: ir::FunctionId) -> Rc { lower_func_body(db, func) } @@ -60,11 +69,20 @@ impl ir::FunctionId { let analyzer_func = self.analyzer_func(db); let func_name = analyzer_func.name(db.upcast()); + // Construct a suffix for any monomorphized generic function parameters + let type_suffix = self + .signature(db) + .resolved_generics + .values() + .fold(String::new(), |acc, param| { + format!("{}_{}", acc, param.name()) + }); + if let Some(class) = analyzer_func.class(db.upcast()) { let class_name = class.name(db.upcast()); - format!("{}::{}", class_name, func_name).into() + format!("{}::{}{}", class_name, func_name, type_suffix).into() } else { - func_name + format!("{}{}", func_name, type_suffix).into() } } diff --git a/crates/mir/src/db/queries/types.rs b/crates/mir/src/db/queries/types.rs index 5a97972c07..82dc89982a 100644 --- a/crates/mir/src/db/queries/types.rs +++ b/crates/mir/src/db/queries/types.rs @@ -27,6 +27,10 @@ impl TypeId { db.lookup_mir_intern_type(self) } + pub fn analyzer_ty(self, db: &dyn MirDb) -> Option { + self.data(db).analyzer_ty.clone() + } + pub fn projection_ty(self, db: &dyn MirDb, access: &Value) -> TypeId { let ty = self.deref(db); match &ty.data(db).as_ref().kind { diff --git a/crates/mir/src/ir/function.rs b/crates/mir/src/ir/function.rs index 1943b8345f..7fefda79bb 100644 --- a/crates/mir/src/ir/function.rs +++ b/crates/mir/src/ir/function.rs @@ -1,9 +1,11 @@ use fe_analyzer::namespace::items as analyzer_items; +use fe_analyzer::namespace::types as analyzer_types; use fe_common::impl_intern_key; use fxhash::FxHashMap; use id_arena::Arena; use num_bigint::BigInt; use smol_str::SmolStr; +use std::collections::BTreeMap; use crate::db::MirDb; @@ -20,6 +22,7 @@ use super::{ #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FunctionSignature { pub params: Vec, + pub resolved_generics: BTreeMap, pub return_type: Option, pub module_id: analyzer_items::ModuleId, pub analyzer_func_id: analyzer_items::FunctionId, diff --git a/crates/mir/src/lower/function.rs b/crates/mir/src/lower/function.rs index 2c0fd7a0fb..7562523816 100644 --- a/crates/mir/src/lower/function.rs +++ b/crates/mir/src/lower/function.rs @@ -1,9 +1,12 @@ -use std::rc::Rc; +use std::{collections::BTreeMap, rc::Rc}; use fe_analyzer::{ builtins::{ContractTypeMethod, GlobalFunction, ValueMethod}, context::CallType as AnalyzerCallType, - namespace::{items as analyzer_items, types as analyzer_types}, + namespace::{ + items as analyzer_items, + types::{self as analyzer_types, Type}, + }, }; use fe_common::numeric::Literal; use fe_parser::{ast, node::Node}; @@ -28,20 +31,52 @@ use crate::{ type ScopeId = Id; pub fn lower_func_signature(db: &dyn MirDb, func: analyzer_items::FunctionId) -> FunctionId { + lower_monomorphized_func_signature(db, func, &[]) +} +pub fn lower_monomorphized_func_signature( + db: &dyn MirDb, + func: analyzer_items::FunctionId, + concrete_args: &[Type], +) -> FunctionId { // TODO: Remove this when an analyzer's function signature contains `self` type. let mut params = vec![]; + let mut concrete_args: &[Type] = concrete_args; let has_self = func.takes_self(db.upcast()); if has_self { let self_ty = func.self_typ(db.upcast()).unwrap(); let source = self_arg_source(db, func); params.push(make_param(db, "self", self_ty, source)); + // similarly, when in the future analyzer params contain `self` we won't need to adjust the concrete args anymore + if !concrete_args.is_empty() { + concrete_args = &concrete_args[1..] + } } - let analyzer_signature = func.signature(db.upcast()); - params.extend(analyzer_signature.params.iter().map(|param| { + let mut resolved_generics: BTreeMap = BTreeMap::new(); + + for (index, param) in analyzer_signature.params.iter().enumerate() { let source = arg_source(db, func, ¶m.name); - make_param(db, param.name.clone(), param.typ.clone().unwrap(), source) - })); + let provided_type = concrete_args + .get(index) + .cloned() + .unwrap_or_else(|| param.typ.clone().unwrap()); + + params.push(make_param( + db, + param.clone().name, + provided_type.clone(), + source, + )); + + if let analyzer_types::FunctionParam { + typ: Ok(Type::Generic(generic)), + .. + } = param + { + resolved_generics.insert(generic.clone(), provided_type); + } + } + let return_type = db.mir_lowered_type(analyzer_signature.return_type.clone().unwrap()); let linkage = if func.is_public(db.upcast()) { @@ -56,6 +91,7 @@ pub fn lower_func_signature(db: &dyn MirDb, func: analyzer_items::FunctionId) -> let sig = FunctionSignature { params, + resolved_generics, return_type: Some(return_type), module_id: func.module(db.upcast()), analyzer_func_id: func, @@ -79,6 +115,7 @@ struct BodyLowerHelper<'db, 'a> { db: &'db dyn MirDb, builder: BodyBuilder, ast: &'a Node, + func: FunctionId, analyzer_body: &'a fe_analyzer::context::FunctionBody, scopes: Arena, current_scope: ScopeId, @@ -98,17 +135,33 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { // constants. let root = Scope::root(db, func, &mut builder); let current_scope = scopes.alloc(root); - Self { db, builder, ast, + func, analyzer_body, scopes, current_scope, } } + fn lower_analyzer_type(&self, analyzer_ty: analyzer_types::Type) -> TypeId { + // If the analyzer type is generic we first need to resolve it to its concrete type before lowering to a MIR type + if let analyzer_types::Type::Generic(generic) = analyzer_ty { + let resolved_type = self + .func + .signature(self.db) + .resolved_generics + .get(&generic) + .expect("expected generic to be resolved") + .clone(); + return self.db.mir_lowered_type(resolved_type); + } + + self.db.mir_lowered_type(analyzer_ty) + } + fn lower(mut self) -> FunctionBody { for stmt in &self.ast.kind.body { self.lower_stmt(stmt) @@ -141,9 +194,7 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { } ast::FuncStmt::ConstantDecl { name, value, .. } => { - let ty = self - .db - .mir_lowered_type(self.analyzer_body.var_types[&name.id].clone()); + let ty = self.lower_analyzer_type(self.analyzer_body.var_types[&name.id].clone()); let value = self.analyzer_body.expressions[&value.id] .const_value @@ -310,9 +361,7 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { ) { match &var.kind { ast::VarDeclTarget::Name(name) => { - let ty = self - .db - .mir_lowered_type(self.analyzer_body.var_types[&var.id].clone()); + let ty = self.lower_analyzer_type(self.analyzer_body.var_types[&var.id].clone()); let local = Local::user_local(name.clone(), ty, var.into()); let value = self.builder.declare(local); @@ -353,9 +402,7 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { ) { match &var.kind { ast::VarDeclTarget::Name(name) => { - let ty = self - .db - .mir_lowered_type(self.analyzer_body.var_types[&var.id].clone()); + let ty = self.lower_analyzer_type(self.analyzer_body.var_types[&var.id].clone()); let local = Local::user_local(name.clone(), ty, var.into()); let lhs = self.builder.declare(local); @@ -453,7 +500,7 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { let entry_bb = self.builder.make_block(); let exit_bb = self.builder.make_block(); let iter_elem_ty = self.analyzer_body.var_types[&loop_variable.id].clone(); - let iter_elem_ty = self.db.mir_lowered_type(iter_elem_ty); + let iter_elem_ty = self.lower_analyzer_type(iter_elem_ty); self.builder.jump(preheader_bb, SourceInfo::dummy()); @@ -701,7 +748,7 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { fn expr_ty(&self, expr: &Node) -> TypeId { let analyzer_ty = self.analyzer_body.expressions[&expr.id].typ.clone(); - self.db.mir_lowered_type(analyzer_ty) + self.lower_analyzer_type(analyzer_ty) } fn lower_bool_op( @@ -848,7 +895,22 @@ impl<'db, 'a> BodyLowerHelper<'db, 'a> { let mut method_args = vec![self.lower_method_receiver(func)]; method_args.append(&mut args); - let func_id = self.db.mir_lowered_func_signature(*method); + let func_id = if method.is_generic(self.db.upcast()) { + let concrete_args = method_args + .iter() + .map(|val| { + self.builder + .value_ty(*val) + .analyzer_ty(self.db) + .expect("invalid parameter") + }) + .collect::>(); + self.db + .mir_lowered_monomorphized_func_signature(*method, concrete_args) + } else { + self.db.mir_lowered_func_signature(*method) + }; + self.builder .call(func_id, method_args, CallType::Internal, source) } diff --git a/crates/mir/src/lower/types.rs b/crates/mir/src/lower/types.rs index b53a89600e..a49e8dca0f 100644 --- a/crates/mir/src/lower/types.rs +++ b/crates/mir/src/lower/types.rs @@ -18,6 +18,12 @@ pub fn lower_type(db: &dyn MirDb, analyzer_ty: &analyzer_types::Type) -> TypeId analyzer_types::Type::Contract(_) => TypeKind::Address, analyzer_types::Type::SelfContract(contract) => lower_contract(db, contract), analyzer_types::Type::Struct(struct_) => lower_struct(db, struct_), + analyzer_types::Type::Trait(_) => { + panic!("traits should only appear in generic bounds for now") + } + analyzer_types::Type::Generic(_) => { + panic!("should be lowered in `lower_types_in_functions`") + } }; intern_type(db, ty_kind, Some(analyzer_ty)) diff --git a/crates/parser/src/ast.rs b/crates/parser/src/ast.rs index d91784a14e..cad4a21915 100644 --- a/crates/parser/src/ast.rs +++ b/crates/parser/src/ast.rs @@ -21,6 +21,8 @@ pub enum ModuleStmt { Contract(Node), Constant(Node), Struct(Node), + Trait(Node), + Impl(Node), Function(Node), Event(Node), ParseError(Span), @@ -87,6 +89,18 @@ pub struct Struct { pub pub_qual: Option, } +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] +pub struct Trait { + pub name: Node, + pub pub_qual: Option, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] +pub struct Impl { + pub impl_trait: Node, + pub receiver: Node, +} + #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] pub enum TypeDesc { Unit, @@ -128,7 +142,7 @@ pub enum GenericParameter { Unbounded(Node), Bounded { name: Node, - bound: Node, + bound: Node, }, } @@ -370,6 +384,12 @@ impl Node { } } +impl Node { + pub fn name(&self) -> &str { + &self.kind.name.kind + } +} + impl Node { pub fn name(&self) -> &str { &self.kind.name.kind @@ -415,6 +435,8 @@ impl Spanned for ModuleStmt { match self { ModuleStmt::Pragma(inner) => inner.span, ModuleStmt::Use(inner) => inner.span, + ModuleStmt::Trait(inner) => inner.span, + ModuleStmt::Impl(inner) => inner.span, ModuleStmt::TypeAlias(inner) => inner.span, ModuleStmt::Contract(inner) => inner.span, ModuleStmt::Constant(inner) => inner.span, @@ -461,6 +483,8 @@ impl fmt::Display for ModuleStmt { match self { ModuleStmt::Pragma(node) => write!(f, "{}", node.kind), ModuleStmt::Use(node) => write!(f, "{}", node.kind), + ModuleStmt::Trait(node) => write!(f, "{}", node.kind), + ModuleStmt::Impl(node) => write!(f, "{}", node.kind), ModuleStmt::TypeAlias(node) => write!(f, "{}", node.kind), ModuleStmt::Contract(node) => write!(f, "{}", node.kind), ModuleStmt::Constant(node) => write!(f, "{}", node.kind), @@ -534,6 +558,26 @@ impl fmt::Display for ConstantDecl { } } +impl fmt::Display for Trait { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + writeln!(f, "trait {}:", self.name.kind)?; + + Ok(()) + } +} + +impl fmt::Display for Impl { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + writeln!( + f, + "impl {} for {}", + self.impl_trait.kind, self.receiver.kind + )?; + + Ok(()) + } +} + impl fmt::Display for TypeAlias { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let TypeAlias { diff --git a/crates/parser/src/grammar/functions.rs b/crates/parser/src/grammar/functions.rs index 0ab78b9028..e0c872f270 100644 --- a/crates/parser/src/grammar/functions.rs +++ b/crates/parser/src/grammar/functions.rs @@ -3,7 +3,7 @@ use super::types::parse_type_desc; use crate::ast::{ BinOperator, Expr, FuncStmt, Function, FunctionArg, GenericParameter, RegularFunctionArg, - VarDeclTarget, + TypeDesc, VarDeclTarget, }; use crate::node::{Node, Span}; use crate::{Label, ParseFailed, ParseResult, Parser, TokenKind}; @@ -115,7 +115,12 @@ pub fn parse_generic_param(par: &mut Parser) -> ParseResult { let bound = par.assert(Name); Ok(GenericParameter::Bounded { name: Node::new(name.text.into(), name.span), - bound: Node::new(bound.text.into(), bound.span), + bound: Node::new( + TypeDesc::Base { + base: bound.text.into(), + }, + bound.span, + ), }) } None => Ok(GenericParameter::Unbounded(Node::new( diff --git a/crates/parser/src/grammar/module.rs b/crates/parser/src/grammar/module.rs index 283f5acb89..b322eb0a1f 100644 --- a/crates/parser/src/grammar/module.rs +++ b/crates/parser/src/grammar/module.rs @@ -2,7 +2,8 @@ use super::contracts::parse_contract_def; use super::expressions::parse_expr; use super::functions::parse_fn_def; use super::types::{ - parse_event_def, parse_path_tail, parse_struct_def, parse_type_alias, parse_type_desc, + parse_event_def, parse_impl_def, parse_path_tail, parse_struct_def, parse_trait_def, + parse_type_alias, parse_type_desc, }; use crate::ast::{ConstantDecl, Module, ModuleStmt, Pragma, Use, UseTree}; use crate::node::{Node, Span}; @@ -42,6 +43,8 @@ pub fn parse_module_stmt(par: &mut Parser) -> ParseResult { TokenKind::Use => ModuleStmt::Use(parse_use(par)?), TokenKind::Contract => ModuleStmt::Contract(parse_contract_def(par, None)?), TokenKind::Struct => ModuleStmt::Struct(parse_struct_def(par, None)?), + TokenKind::Trait => ModuleStmt::Trait(parse_trait_def(par, None)?), + TokenKind::Impl => ModuleStmt::Impl(parse_impl_def(par)?), TokenKind::Type => ModuleStmt::TypeAlias(parse_type_alias(par, None)?), TokenKind::Const => ModuleStmt::Constant(parse_constant(par, None)?), @@ -54,6 +57,7 @@ pub fn parse_module_stmt(par: &mut Parser) -> ParseResult { ModuleStmt::Function(parse_fn_def(par, Some(pub_span))?) } TokenKind::Struct => ModuleStmt::Struct(parse_struct_def(par, Some(pub_span))?), + TokenKind::Trait => ModuleStmt::Trait(parse_trait_def(par, Some(pub_span))?), TokenKind::Type => ModuleStmt::TypeAlias(parse_type_alias(par, Some(pub_span))?), TokenKind::Const => ModuleStmt::Constant(parse_constant(par, Some(pub_span))?), TokenKind::Contract => { diff --git a/crates/parser/src/grammar/types.rs b/crates/parser/src/grammar/types.rs index 3353df8245..afcf98e3fe 100644 --- a/crates/parser/src/grammar/types.rs +++ b/crates/parser/src/grammar/types.rs @@ -1,4 +1,4 @@ -use crate::ast::{self, EventField, Field, GenericArg, Path, TypeAlias, TypeDesc}; +use crate::ast::{self, EventField, Field, GenericArg, Impl, Path, Trait, TypeAlias, TypeDesc}; use crate::grammar::expressions::parse_expr; use crate::grammar::functions::parse_fn_def; use crate::node::{Node, Span}; @@ -64,6 +64,101 @@ pub fn parse_struct_def( )) } +/// Parse a trait definition. +/// # Panics +/// Panics if the next token isn't `trait`. +pub fn parse_trait_def(par: &mut Parser, trait_pub_qual: Option) -> ParseResult> { + let trait_tok = par.assert(TokenKind::Trait); + + // trait Event {} + let trait_name = par.expect_with_notes( + TokenKind::Name, + "failed to parse trait definition", + |_| vec!["Note: `trait` must be followed by a name, which must start with a letter and contain only letters, numbers, or underscores".into()], + )?; + + let header_span = trait_tok.span + trait_name.span; + par.enter_block(header_span, "trait definition")?; + + loop { + match par.peek_or_err()? { + TokenKind::Fn => { + // TODO: parse trait functions + } + TokenKind::BraceClose => { + par.next()?; + break; + } + _ => { + let tok = par.next()?; + par.unexpected_token_error(&tok, "failed to parse trait definition body", vec![]); + return Err(ParseFailed); + } + }; + } + + let span = header_span + trait_pub_qual; + Ok(Node::new( + Trait { + name: Node::new(trait_name.text.into(), trait_name.span), + pub_qual: trait_pub_qual, + }, + span, + )) +} + +/// Parse an impl block. +/// # Panics +/// Panics if the next token isn't `impl`. +pub fn parse_impl_def(par: &mut Parser) -> ParseResult> { + let impl_tok = par.assert(TokenKind::Impl); + + // impl SomeTrait for SomeType {} + let trait_name = + par.expect_with_notes(TokenKind::Name, "failed to parse `impl` definition", |_| { + vec!["Note: `impl` must be followed by the name of a trait".into()] + })?; + + let for_tok = + par.expect_with_notes(TokenKind::For, "failed to parse `impl` definition", |_| { + vec![format!( + "Note: `impl {}` must be followed by the keyword `for`", + trait_name.text + )] + })?; + + let receiver = parse_type_desc(par)?; + + let header_span = impl_tok.span + trait_name.span + for_tok.span + receiver.span; + + par.enter_block(header_span, "impl definition")?; + + loop { + match par.peek_or_err()? { + TokenKind::Fn => { + // TODO: parse impl functions + } + TokenKind::BraceClose => { + par.next()?; + break; + } + _ => { + let tok = par.next()?; + par.unexpected_token_error(&tok, "failed to parse `impl` definition body", vec![]); + return Err(ParseFailed); + } + }; + } + + Ok(Node::new( + Impl { + impl_trait: Node::new(trait_name.text.into(), trait_name.span), + receiver, + }, + header_span, + )) +} + /// Parse a type alias definition, e.g. `type MyMap = Map`. /// # Panics /// Panics if the next token isn't `type`. diff --git a/crates/parser/src/lexer/token.rs b/crates/parser/src/lexer/token.rs index c5d8d65f3c..561afda918 100644 --- a/crates/parser/src/lexer/token.rs +++ b/crates/parser/src/lexer/token.rs @@ -79,6 +79,8 @@ pub enum TokenKind { Idx, #[token("if")] If, + #[token("impl")] + Impl, #[token("pragma")] Pragma, #[token("for")] @@ -93,6 +95,8 @@ pub enum TokenKind { SelfValue, #[token("struct")] Struct, + #[token("trait")] + Trait, #[token("type")] Type, #[token("unsafe")] @@ -230,6 +234,7 @@ impl TokenKind { Event => "keyword `event`", Idx => "keyword `idx`", If => "keyword `if`", + Impl => "keyword `impl`", Pragma => "keyword `pragma`", For => "keyword `for`", Pub => "keyword `pub`", @@ -237,6 +242,7 @@ impl TokenKind { Revert => "keyword `revert`", SelfValue => "keyword `self`", Struct => "keyword `struct`", + Trait => "keyword `trait`", Type => "keyword `type`", Unsafe => "keyword `unsafe`", While => "keyword `while`", diff --git a/crates/parser/tests/cases/snapshots/cases__parse_ast__fn_def_generic.snap b/crates/parser/tests/cases/snapshots/cases__parse_ast__fn_def_generic.snap index ae957dd09f..43a5edaf1f 100644 --- a/crates/parser/tests/cases/snapshots/cases__parse_ast__fn_def_generic.snap +++ b/crates/parser/tests/cases/snapshots/cases__parse_ast__fn_def_generic.snap @@ -1,6 +1,6 @@ --- source: crates/parser/tests/cases/parse_ast.rs -expression: "ast_string(stringify!(fn_def_generic), try_parse_module,\n \"fn foo(this: T, that: R, _ val: u64) -> bool { false }\")" +expression: "ast_string(stringify!(fn_def_generic), try_parse_module,\n \"fn foo(this: T, that: R, _ val: u64) -> bool { false }\")" --- Node( @@ -35,7 +35,9 @@ Node( ), ), bound: Node( - kind: "Event", + kind: Base( + base: "Event", + ), span: Span( start: 13, end: 18, diff --git a/crates/test-files/fixtures/compile_errors/call_generic_function_with_unsatisfied_bound.fe b/crates/test-files/fixtures/compile_errors/call_generic_function_with_unsatisfied_bound.fe new file mode 100644 index 0000000000..5cca0e114e --- /dev/null +++ b/crates/test-files/fixtures/compile_errors/call_generic_function_with_unsatisfied_bound.fe @@ -0,0 +1,16 @@ +use std::traits::IsNumeric + +struct Foo { + + pub fn bar(self, _ x: T) -> bool { + return true + } +} + +contract Meh { + + pub fn call_bar(self) { + let foo: Foo = Foo(); + foo.bar(true) + } +} diff --git a/crates/test-files/fixtures/compile_errors/contract_function_with_generic_params.fe b/crates/test-files/fixtures/compile_errors/contract_function_with_generic_params.fe new file mode 100644 index 0000000000..758cc31b64 --- /dev/null +++ b/crates/test-files/fixtures/compile_errors/contract_function_with_generic_params.fe @@ -0,0 +1,5 @@ +use std::traits::IsNumeric + +contract Foo { + pub fn bar(val: T) {} +} diff --git a/crates/test-files/fixtures/compile_errors/invalid_generic_bound.fe b/crates/test-files/fixtures/compile_errors/invalid_generic_bound.fe new file mode 100644 index 0000000000..5d67b8364e --- /dev/null +++ b/crates/test-files/fixtures/compile_errors/invalid_generic_bound.fe @@ -0,0 +1,3 @@ +struct Foo { + pub fn bar(val: T) {} +} \ No newline at end of file diff --git a/crates/test-files/fixtures/compile_errors/invalid_impl_location.fe b/crates/test-files/fixtures/compile_errors/invalid_impl_location.fe new file mode 100644 index 0000000000..648e4b2ea9 --- /dev/null +++ b/crates/test-files/fixtures/compile_errors/invalid_impl_location.fe @@ -0,0 +1,3 @@ +use std::traits::IsNumeric + +impl IsNumeric for u8 {} diff --git a/crates/test-files/fixtures/compile_errors/invalid_impl_type.fe b/crates/test-files/fixtures/compile_errors/invalid_impl_type.fe new file mode 100644 index 0000000000..befc605985 --- /dev/null +++ b/crates/test-files/fixtures/compile_errors/invalid_impl_type.fe @@ -0,0 +1,3 @@ +trait SomeTrait {} + +impl SomeTrait for Map {} \ No newline at end of file diff --git a/crates/test-files/fixtures/features/generic_functions.fe b/crates/test-files/fixtures/features/generic_functions.fe new file mode 100644 index 0000000000..1e56d96e09 --- /dev/null +++ b/crates/test-files/fixtures/features/generic_functions.fe @@ -0,0 +1,23 @@ +use std::traits::IsNumeric + +struct Bar { + + pub fn bar(self, x: T, y: u256) -> bool { + return true + } + + pub fn call_me_maybe(self) { + self.bar(x: 1, y: 1) + self.bar(x: i8(-1), y:1) + } +} + + +contract Foo { + + pub fn call_me_maybe(self) { + let bar: Bar = Bar(); + bar.bar(x: 1, y: 1) + bar.bar(x: i8(-1), y:1) + } +} diff --git a/crates/tests/src/features.rs b/crates/tests/src/features.rs index a68fbf2a79..c319201456 100644 --- a/crates/tests/src/features.rs +++ b/crates/tests/src/features.rs @@ -2017,3 +2017,11 @@ fn ctx_init_in_call() { } }); } + +#[test] +fn generics() { + with_executor(&|mut executor| { + // This isn't testing much yet. It soon will when traits and impls are fully implemented + deploy_contract(&mut executor, "generic_functions.fe", "Foo", &[]); + }); +}