Skip to content

Commit

Permalink
chore: improve error for patterns (#2004)
Browse files Browse the repository at this point in the history
* improve error for patterns

* fix error message

* Update crates/noirc_frontend/src/parser/parser.rs

* Update crates/noirc_frontend/src/parser/errors.rs

* Update crates/noirc_frontend/src/parser/errors.rs

---------

Co-authored-by: jfecher <[email protected]>
  • Loading branch information
kek kek kek and jfecher authored Jul 26, 2023
1 parent be44c7b commit 453e477
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
13 changes: 13 additions & 0 deletions crates/noirc_frontend/src/parser/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use super::labels::ParsingRuleLabel;
pub enum ParserErrorReason {
#[error("Unexpected '{0}', expected a field name")]
ExpectedFieldName(Token),
#[error("expected a pattern but found a type - {0}")]
ExpectedPatternButFoundType(Token),
#[error("Expected a ; separating these two statements")]
MissingSeparatingSemi,
#[error("constrain keyword is deprecated")]
Expand Down Expand Up @@ -70,6 +72,14 @@ impl ParserError {
error.reason = Some(reason);
error
}

pub fn found(&self) -> &Token {
&self.found
}

pub fn span(&self) -> Span {
self.span
}
}

impl std::fmt::Display for ParserError {
Expand Down Expand Up @@ -107,6 +117,9 @@ impl From<ParserError> for Diagnostic {
"The 'constrain' keyword has been deprecated. Please use the 'assert' function instead.".into(),
error.span,
),
reason @ ParserErrorReason::ExpectedPatternButFoundType(ty) => {
Diagnostic::simple_error(reason.to_string(), format!("{ty} is a type and cannot be used as a variable name"), error.span)
}
other => {

Diagnostic::simple_error(format!("{other}"), String::new(), error.span)
Expand Down
11 changes: 10 additions & 1 deletion crates/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,16 @@ where

fn pattern() -> impl NoirParser<Pattern> {
recursive(|pattern| {
let ident_pattern = ident().map(Pattern::Identifier);
let ident_pattern = ident().map(Pattern::Identifier).map_err(|mut error| {
if matches!(error.found(), Token::IntType(..)) {
error = ParserError::with_reason(
ParserErrorReason::ExpectedPatternButFoundType(error.found().clone()),
error.span(),
);
}

error
});

let mut_pattern = keyword(Keyword::Mut)
.ignore_then(pattern.clone())
Expand Down

0 comments on commit 453e477

Please sign in to comment.