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

fix(parser): fixes for the parsing of 'where' clauses #2430

Merged
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
10 changes: 9 additions & 1 deletion crates/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,12 +636,20 @@ impl Display for FunctionDefinition {
format!("{name}: {visibility} {type}")
});

let where_clause = vecmap(&self.where_clause, ToString::to_string);
let where_clause_str = if !where_clause.is_empty() {
format!("where {}", where_clause.join(", "))
} else {
"".to_string()
};

write!(
f,
"fn {}({}) -> {} {}",
"fn {}({}) -> {} {} {}",
self.name,
parameters.join(", "),
self.return_type,
where_clause_str,
self.body
)
}
Expand Down
25 changes: 23 additions & 2 deletions crates/noirc_frontend/src/ast/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,21 @@ pub struct TraitImpl {
pub items: Vec<TraitImplItem>,
}

/// Represents a trait constraint such as `where Foo: Display`
/// Represents a simple trait constraint such as `where Foo: TraitY<U, V>`
/// Complex trait constraints such as `where Foo: Display + TraitX + TraitY<U, V>` are converted
/// in the parser to a series of simple constraints:
/// `Foo: Display`
/// `Foo: TraitX`
/// `Foo: TraitY<U, V>`
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TraitConstraint {
pub typ: UnresolvedType,
pub trait_bound: TraitBound,
}

/// Represents a single trait bound, such as `TraitX` or `TraitY<U, V>`
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TraitBound {
pub trait_name: Ident,
pub trait_generics: Vec<UnresolvedType>,
}
Expand Down Expand Up @@ -158,9 +169,19 @@ impl Display for TraitItem {
}

impl Display for TraitConstraint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.typ, self.trait_bound)
}
}

impl Display for TraitBound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let generics = vecmap(&self.trait_generics, |generic| generic.to_string());
write!(f, "{}: {}<{}>", self.typ, self.trait_name, generics.join(", "))
if !generics.is_empty() {
write!(f, "{}<{}>", self.trait_name, generics.join(", "))
} else {
write!(f, "{}", self.trait_name)
}
}
}

Expand Down
53 changes: 48 additions & 5 deletions crates/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use crate::{
FunctionReturnType, Ident, IfExpression, InfixExpression, LValue, Lambda, Literal,
NoirFunction, NoirStruct, NoirTrait, NoirTypeAlias, Path, PathKind, Pattern, Recoverable,
TraitConstraint, TraitImpl, TraitImplItem, TraitItem, TypeImpl, UnaryOp,
UnresolvedTypeExpression, UseTree, UseTreeKind, Visibility,
UnresolvedTypeExpression, UseTree, UseTreeKind, Visibility, TraitBound,
};

use chumsky::prelude::*;
Expand Down Expand Up @@ -524,19 +524,46 @@ fn trait_implementation_body() -> impl NoirParser<Vec<TraitImplItem>> {
}

fn where_clause() -> impl NoirParser<Vec<TraitConstraint>> {

struct MultiTraitConstraint {
typ: UnresolvedType,
trait_bounds: Vec<TraitBound>,
}

let constraints = parse_type()
.then_ignore(just(Token::Colon))
.then(ident())
.then(generic_type_args(parse_type()))
.validate(|((typ, trait_name), trait_generics), span, emit| {
.then(trait_bounds())
.validate(|(typ, trait_bounds), span, emit| {
emit(ParserError::with_reason(ParserErrorReason::ExperimentalFeature("Traits"), span));
TraitConstraint { typ, trait_name, trait_generics }
MultiTraitConstraint { typ, trait_bounds }
});

keyword(Keyword::Where)
.ignore_then(constraints.separated_by(just(Token::Comma)))
.or_not()
.map(|option| option.unwrap_or_default())
.map(|x: Vec<MultiTraitConstraint>| {
let mut result: Vec<TraitConstraint> = Vec::new();
for constraint in x {
for bound in constraint.trait_bounds {
result.push(TraitConstraint { typ:constraint.typ.clone(), trait_bound:bound } );
}
}
result
})
}

fn trait_bounds() -> impl NoirParser<Vec<TraitBound>> {
trait_bound()
.separated_by(just(Token::Plus))
.at_least(1)
.allow_trailing()
}

fn trait_bound() -> impl NoirParser<TraitBound> {
ident()
.then(generic_type_args(parse_type()))
.map(|(trait_name, trait_generics)| TraitBound { trait_name, trait_generics })
}

fn block_expr<'a, P>(expr_parser: P) -> impl NoirParser<Expression> + 'a
Expand Down Expand Up @@ -1838,6 +1865,19 @@ mod test {
"fn f(f: pub Field, y : Field, z : comptime Field) -> u8 { x + a }",
"fn f<T>(f: pub Field, y : T, z : comptime Field) -> u8 { x + a }",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait + SomeTrait2 {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait, T: SomeTrait2 {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait<A> + SomeTrait2 {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait<A, B> + SomeTrait2 {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait<A, B> + SomeTrait2<C> {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait + SomeTrait2<C> {}",
"fn func_name<T>(f: Field, y : T) where T: SomeTrait + SomeTrait2<C> + TraitY {}",
"fn func_name<T>(f: Field, y : T, z : U) where SomeStruct<T>: SomeTrait<U> {}",
// 'where u32: SomeTrait' is allowed in Rust.
// It will result in compiler error in case SomeTrait isn't implemented for u32.
"fn func_name<T>(f: Field, y : T) where u32: SomeTrait {}",
// A trailing plus is allowed by Rust, so we support it as well.
"fn func_name<T>(f: Field, y : T) where T: SomeTrait + {}",
jfecher marked this conversation as resolved.
Show resolved Hide resolved
// The following should produce compile error on later stage. From the parser's perspective it's fine
"fn func_name<A>(f: Field, y : Field, z : Field) where T: SomeTrait {}",
],
Expand All @@ -1854,6 +1894,9 @@ mod test {
"fn func_name<T>(f: Field, y : pub Field, z : pub [u8;5],) where SomeTrait {}",
"fn func_name<T>(f: Field, y : pub Field, z : pub [u8;5],) SomeTrait {}",
"fn func_name(f: Field, y : pub Field, z : pub [u8;5],) where T: SomeTrait {}",
// A leading plus is not allowed.
"fn func_name<T>(f: Field, y : T) where T: + SomeTrait {}",
"fn func_name<T>(f: Field, y : T) where T: TraitX + <Y> {}",
],
);
}
Expand Down
Loading