Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Type::get_trait_impl #5716

Merged
merged 3 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
hir::comptime::{errors::IResult, value::add_token_spans, InterpreterError, Value},
hir_def::function::FunctionBody,
macros_api::{ModuleDefId, NodeInterner, Signedness},
node_interner::DefinitionKind,
node_interner::{DefinitionKind, TraitImplKind},
parser::{self},
token::{SpannedToken, Token},
QuotedType, Shared, Type,
Expand Down Expand Up @@ -93,6 +93,9 @@
"type_as_struct" => type_as_struct(arguments, return_type, location),
"type_as_tuple" => type_as_tuple(arguments, return_type, location),
"type_eq" => type_eq(arguments, location),
"type_get_trait_impl" => {
type_get_trait_impl(interner, arguments, return_type, location)
}
"type_implements" => type_implements(interner, arguments, location),
"type_is_bool" => type_is_bool(arguments, location),
"type_is_field" => type_is_field(arguments, location),
Expand Down Expand Up @@ -373,7 +376,7 @@
let argument = check_one_argument(arguments, location)?;
let typ = parse(argument, parser::parse_type(), "a type")?;
let typ =
interpreter.elaborate_item(interpreter.current_function, |elab| elab.resolve_type(typ));

Check warning on line 379 in compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elab)

Check warning on line 379 in compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elab)
Ok(Value::Type(typ))
}

Expand Down Expand Up @@ -507,6 +510,26 @@
Ok(Value::Bool(self_type == other_type))
}

// fn get_trait_impl(self, constraint: TraitConstraint) -> Option<TraitImpl>
fn type_get_trait_impl(
interner: &NodeInterner,
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
let (typ, constraint) = check_two_arguments(arguments, location)?;

let typ = get_type(typ)?;
let (trait_id, generics) = get_trait_constraint(constraint)?;

let option_value = match interner.try_lookup_trait_implementation(&typ, trait_id, &generics) {
Ok((TraitImplKind::Normal(trait_impl_id), _)) => Some(Value::TraitImpl(trait_impl_id)),
_ => None,
};

option(return_type, option_value)
}

// fn implements(self, constraint: TraitConstraint) -> bool
fn type_implements(
interner: &NodeInterner,
Expand Down
70 changes: 61 additions & 9 deletions compiler/noirc_frontend/src/hir/comptime/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ use noirc_errors::{Location, Span};
use crate::{
ast::{ArrayLiteral, ConstructorExpression, Ident, IntegerBitSize, Signedness},
hir::def_map::ModuleId,
hir_def::expr::{HirArrayLiteral, HirConstructorExpression, HirIdent, HirLambda, ImplKind},
hir_def::{
expr::{HirArrayLiteral, HirConstructorExpression, HirIdent, HirLambda, ImplKind},
traits::TraitConstraint,
},
macros_api::{
Expression, ExpressionKind, HirExpression, HirLiteral, Literal, NodeInterner, Path,
StructId,
},
node_interner::{ExprId, FuncId, TraitId},
node_interner::{ExprId, FuncId, TraitId, TraitImplId},
parser::{self, NoirParser, TopLevelStatement},
token::{SpannedToken, Token, Tokens},
QuotedType, Shared, Type, TypeBindings,
Expand Down Expand Up @@ -53,6 +56,7 @@ pub enum Value {
StructDefinition(StructId),
TraitConstraint(TraitId, /* trait generics */ Vec<Type>),
TraitDefinition(TraitId),
TraitImpl(TraitImplId),
FunctionDefinition(FuncId),
ModuleDefinition(ModuleId),
Type(Type),
Expand Down Expand Up @@ -100,6 +104,7 @@ impl Value {
}
Value::TraitConstraint { .. } => Type::Quoted(QuotedType::TraitConstraint),
Value::TraitDefinition(_) => Type::Quoted(QuotedType::TraitDefinition),
Value::TraitImpl(_) => Type::Quoted(QuotedType::TraitImpl),
Value::FunctionDefinition(_) => Type::Quoted(QuotedType::FunctionDefinition),
Value::ModuleDefinition(_) => Type::Quoted(QuotedType::Module),
Value::Type(_) => Type::Quoted(QuotedType::Type),
Expand Down Expand Up @@ -230,6 +235,7 @@ impl Value {
| Value::StructDefinition(_)
| Value::TraitConstraint(..)
| Value::TraitDefinition(_)
| Value::TraitImpl(_)
| Value::FunctionDefinition(_)
| Value::Zeroed(_)
| Value::Type(_)
Expand Down Expand Up @@ -353,6 +359,7 @@ impl Value {
| Value::StructDefinition(_)
| Value::TraitConstraint(..)
| Value::TraitDefinition(_)
| Value::TraitImpl(_)
| Value::FunctionDefinition(_)
| Value::Zeroed(_)
| Value::Type(_)
Expand Down Expand Up @@ -516,18 +523,40 @@ impl<'value, 'interner> Display for ValuePrinter<'value, 'interner> {
write!(f, "{}", def.name)
}
Value::TraitConstraint(trait_id, generics) => {
let trait_ = self.interner.get_trait(*trait_id);
let generic_string = vecmap(generics, ToString::to_string).join(", ");
if generics.is_empty() {
write!(f, "{}", trait_.name)
} else {
write!(f, "{}<{generic_string}>", trait_.name)
}
write!(f, "{}", display_trait_id_and_generics(self.interner, trait_id, generics))
}
Value::TraitDefinition(trait_id) => {
let trait_ = self.interner.get_trait(*trait_id);
write!(f, "{}", trait_.name)
}
Value::TraitImpl(trait_impl_id) => {
let trait_impl = self.interner.get_trait_implementation(*trait_impl_id);
let trait_impl = trait_impl.borrow();

let generic_string =
vecmap(&trait_impl.trait_generics, ToString::to_string).join(", ");
let generic_string = if generic_string.is_empty() {
generic_string
} else {
format!("<{}>", generic_string)
};

let where_clause = vecmap(&trait_impl.where_clause, |trait_constraint| {
display_trait_constraint(self.interner, trait_constraint)
});
let where_clause = where_clause.join(", ");
let where_clause = if where_clause.is_empty() {
where_clause
} else {
format!(" where {}", where_clause)
};

write!(
f,
"impl {}{} for {}{}",
trait_impl.ident, generic_string, trait_impl.typ, where_clause
)
}
Value::FunctionDefinition(function_id) => {
write!(f, "{}", self.interner.function_name(function_id))
}
Expand All @@ -538,3 +567,26 @@ impl<'value, 'interner> Display for ValuePrinter<'value, 'interner> {
}
}
}

fn display_trait_id_and_generics(
interner: &NodeInterner,
trait_id: &TraitId,
generics: &Vec<Type>,
) -> String {
let trait_ = interner.get_trait(*trait_id);
let generic_string = vecmap(generics, ToString::to_string).join(", ");
if generics.is_empty() {
format!("{}", trait_.name)
} else {
format!("{}<{generic_string}>", trait_.name)
}
}

fn display_trait_constraint(interner: &NodeInterner, trait_constraint: &TraitConstraint) -> String {
let trait_constraint_string = display_trait_id_and_generics(
interner,
&trait_constraint.trait_id,
&trait_constraint.trait_generics,
);
format!("{}: {}", trait_constraint.typ, trait_constraint_string)
}
2 changes: 2 additions & 0 deletions compiler/noirc_frontend/src/hir_def/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
StructDefinition,
TraitConstraint,
TraitDefinition,
TraitImpl,
FunctionDefinition,
Module,
}
Expand Down Expand Up @@ -727,6 +728,7 @@
QuotedType::StructDefinition => write!(f, "StructDefinition"),
QuotedType::TraitDefinition => write!(f, "TraitDefinition"),
QuotedType::TraitConstraint => write!(f, "TraitConstraint"),
QuotedType::TraitImpl => write!(f, "TraitImpl"),
QuotedType::FunctionDefinition => write!(f, "FunctionDefinition"),
QuotedType::Module => write!(f, "Module"),
}
Expand Down Expand Up @@ -1991,7 +1993,7 @@
}

let recur_on_binding = |id, replacement: &Type| {
// Prevent recuring forever if there's a `T := T` binding

Check warning on line 1996 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (recuring)
if replacement.type_variable_id() == Some(id) {
replacement.clone()
} else {
Expand Down Expand Up @@ -2062,7 +2064,7 @@
Type::Tuple(fields)
}
Type::Forall(typevars, typ) => {
// Trying to substitute_helper a variable de, substitute_bound_typevarsfined within a nested Forall

Check warning on line 2067 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (typevarsfined)
// is usually impossible and indicative of an error in the type checker somewhere.
for var in typevars {
assert!(!type_bindings.contains_key(&var.id()));
Expand Down Expand Up @@ -2219,7 +2221,7 @@

/// Replace any `Type::NamedGeneric` in this type with a `Type::TypeVariable`
/// using to the same inner `TypeVariable`. This is used during monomorphization
/// to bind to named generics since they are unbindable during type checking.

Check warning on line 2224 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (unbindable)
pub fn replace_named_generics_with_type_variables(&mut self) {
match self {
Type::FieldElement
Expand Down
3 changes: 3 additions & 0 deletions compiler/noirc_frontend/src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,7 @@ pub enum Keyword {
Trait,
TraitConstraint,
TraitDefinition,
TraitImpl,
Type,
TypeType,
Unchecked,
Expand Down Expand Up @@ -977,6 +978,7 @@ impl fmt::Display for Keyword {
Keyword::Trait => write!(f, "trait"),
Keyword::TraitConstraint => write!(f, "TraitConstraint"),
Keyword::TraitDefinition => write!(f, "TraitDefinition"),
Keyword::TraitImpl => write!(f, "TraitImpl"),
Keyword::Type => write!(f, "type"),
Keyword::TypeType => write!(f, "Type"),
Keyword::Unchecked => write!(f, "unchecked"),
Expand Down Expand Up @@ -1031,6 +1033,7 @@ impl Keyword {
"trait" => Keyword::Trait,
"TraitConstraint" => Keyword::TraitConstraint,
"TraitDefinition" => Keyword::TraitDefinition,
"TraitImpl" => Keyword::TraitImpl,
"type" => Keyword::Type,
"Type" => Keyword::TypeType,
"StructDefinition" => Keyword::StructDefinition,
Expand Down
6 changes: 6 additions & 0 deletions compiler/noirc_frontend/src/parser/parser/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub(super) fn parse_type_inner<'a>(
struct_definition_type(),
trait_constraint_type(),
trait_definition_type(),
trait_impl_type(),
function_definition_type(),
module_type(),
top_level_item_type(),
Expand Down Expand Up @@ -107,6 +108,11 @@ pub(super) fn trait_definition_type() -> impl NoirParser<UnresolvedType> {
})
}

pub(super) fn trait_impl_type() -> impl NoirParser<UnresolvedType> {
keyword(Keyword::TraitImpl)
.map_with_span(|_, span| UnresolvedTypeData::Quoted(QuotedType::TraitImpl).with_span(span))
}

pub(super) fn function_definition_type() -> impl NoirParser<UnresolvedType> {
keyword(Keyword::FunctionDefinition).map_with_span(|_, span| {
UnresolvedTypeData::Quoted(QuotedType::FunctionDefinition).with_span(span)
Expand Down
3 changes: 3 additions & 0 deletions noir_stdlib/src/meta/typ.nr
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ impl Type {
#[builtin(type_as_tuple)]
fn as_tuple(self) -> Option<[Type]> {}

#[builtin(type_get_trait_impl)]
fn get_trait_impl(self, constraint: TraitConstraint) -> Option<TraitImpl> {}

#[builtin(type_implements)]
fn implements(self, constraint: TraitConstraint) -> bool {}

Expand Down
4 changes: 4 additions & 0 deletions test_programs/compile_success_empty/comptime_type/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ fn main() {
let some_trait_field = quote { SomeTrait<Field> }.as_trait_constraint();
assert(!struct_implements_some_trait.implements(some_trait_field));
assert(!struct_does_not_implement_some_trait.implements(some_trait_field));

let _trait_impl = struct_implements_some_trait.get_trait_impl(some_trait_i32).unwrap();
}
}

Expand All @@ -117,5 +119,7 @@ fn function_with_where<T>(_x: T) where T: SomeTrait<i32> {
let t = quote { T }.as_type();
let some_trait_i32 = quote { SomeTrait<i32> }.as_trait_constraint();
assert(t.implements(some_trait_i32));

assert(t.get_trait_impl(some_trait_i32).is_none());
}
}
2 changes: 2 additions & 0 deletions tooling/lsp/src/requests/completion/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub(super) fn keyword_builtin_type(keyword: &Keyword) -> Option<&'static str> {
Keyword::StructDefinition => Some("StructDefinition"),
Keyword::TraitConstraint => Some("TraitConstraint"),
Keyword::TraitDefinition => Some("TraitDefinition"),
Keyword::TraitImpl => Some("TraitImpl"),
Keyword::TypeType => Some("Type"),

Keyword::As
Expand Down Expand Up @@ -116,6 +117,7 @@ pub(super) fn keyword_builtin_function(keyword: &Keyword) -> Option<BuiltInFunct
| Keyword::Trait
| Keyword::TraitConstraint
| Keyword::TraitDefinition
| Keyword::TraitImpl
| Keyword::Type
| Keyword::TypeType
| Keyword::Unchecked
Expand Down
Loading