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 6 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.len() > 0 {
nickysn marked this conversation as resolved.
Show resolved Hide resolved
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
23 changes: 20 additions & 3 deletions crates/noirc_frontend/src/ast/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,16 @@ pub struct TraitImpl {
pub items: Vec<TraitImplItem>,
}

/// Represents a trait constraint such as `where Foo: Display`
/// Represents a trait constraint such as `where Foo: Display + TraitX + TraitY<U, V>`
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TraitConstraint {
pub typ: UnresolvedType,
pub generic_type_name: Ident,
pub trait_bounds: Vec<TraitBound>,
}
nickysn marked this conversation as resolved.
Show resolved Hide resolved

/// 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 +164,20 @@ impl Display for TraitItem {
}

impl Display for TraitConstraint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let bounds = vecmap(&self.trait_bounds, |bound| bound.to_string());
write!(f, "{}: {}", self.generic_type_name, bounds.join(" + "))
}
}

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.len() > 0 {
write!(f, "{}<{}>", self.trait_name, generics.join(", "))
} else {
write!(f, "{}", self.trait_name)
}
}
}

Expand Down
36 changes: 30 additions & 6 deletions crates/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
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 @@ -331,10 +331,10 @@
}

fn self_parameter() -> impl NoirParser<(Pattern, UnresolvedType, Visibility)> {
let refmut_pattern = just(Token::Ampersand).then_ignore(keyword(Keyword::Mut));

Check warning on line 334 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (refmut)
let mut_pattern = keyword(Keyword::Mut);

refmut_pattern

Check warning on line 337 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (refmut)
.or(mut_pattern)
.map_with_span(|token, span| (token, span))
.or_not()
Expand Down Expand Up @@ -524,13 +524,12 @@
}

fn where_clause() -> impl NoirParser<Vec<TraitConstraint>> {
let constraints = parse_type()
let constraints = ident()
nickysn marked this conversation as resolved.
Show resolved Hide resolved
.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(|(generic_type_name, trait_bounds), span, emit| {
emit(ParserError::with_reason(ParserErrorReason::ExperimentalFeature("Traits"), span));
TraitConstraint { typ, trait_name, trait_generics }
TraitConstraint { generic_type_name, trait_bounds }
});

keyword(Keyword::Where)
Expand All @@ -539,6 +538,19 @@
.map(|option| option.unwrap_or_default())
}

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
where
P: ExprParser + 'a,
Expand Down Expand Up @@ -775,7 +787,7 @@
let shorthand_operators = right_shift_operator().or(one_of(shorthand_operators));
let shorthand_syntax = shorthand_operators.then_ignore(just(Token::Assign));

// Since >> is lexed as two separate greater-thans, >>= is lexed as > >=, so

Check warning on line 790 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (thans)
// we need to account for that case here as well.
let right_shift_fix =
just(Token::Greater).then(just(Token::GreaterEqual)).map(|_| Token::ShiftRight);
Expand Down Expand Up @@ -803,7 +815,7 @@

let dereferences = just(Token::Star).repeated();

let lvalues =

Check warning on line 818 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (lvalues)
l_ident.then(l_member_rhs.or(l_index).repeated()).foldl(|lvalue, rhs| match rhs {
LValueRhs::MemberAccess(field_name) => {
LValue::MemberAccess { object: Box::new(lvalue), field_name }
Expand All @@ -811,7 +823,7 @@
LValueRhs::Index(index) => LValue::Index { array: Box::new(lvalue), index },
});

dereferences.then(lvalues).foldr(|_, lvalue| LValue::Dereference(Box::new(lvalue)))

Check warning on line 826 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (lvalues)

Check warning on line 826 in crates/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (foldr)
}

fn parse_type<'a>() -> impl NoirParser<UnresolvedType> + 'a {
Expand Down Expand Up @@ -1838,6 +1850,14 @@
"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<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 {}",
// 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 +1874,10 @@
"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 {}",
"fn func_name<T>(f: Field, y : T) where u32: 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