From 3643a0dff0499fd93e119f8120f10221560f8727 Mon Sep 17 00:00:00 2001 From: Casey Rodarmor Date: Sun, 25 Oct 2020 23:57:08 -0700 Subject: [PATCH] Add Parser::forbid (#712) --- src/parser.rs | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index 61fd004..02d9551 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -230,6 +230,20 @@ impl<'tokens, 'src> Parser<'tokens, 'src> { } } + /// Return an error if the next token is of kind `forbidden` + fn forbid(&self, forbidden: TokenKind, error: F) -> CompilationResult<'src, ()> + where + F: FnOnce(Token) -> CompilationError, + { + let next = self.next()?; + + if next.kind == forbidden { + Err(error(next)) + } else { + Ok(()) + } + } + /// Accept a token of kind `Identifier` and parse into a `Name` fn accept_name(&mut self) -> CompilationResult<'src, Option>> { if self.next_is(Identifier) { @@ -511,15 +525,11 @@ impl<'tokens, 'src> Parser<'tokens, 'src> { let variadic = if kind.is_variadic() { let variadic = self.parse_parameter(kind)?; - let next = self.next()?; - - if next.kind == Identifier { - return Err( - next.error(CompilationErrorKind::ParameterFollowsVariadicParameter { - parameter: next.lexeme(), - }), - ); - } + self.forbid(Identifier, |token| { + token.error(CompilationErrorKind::ParameterFollowsVariadicParameter { + parameter: token.lexeme(), + }) + })?; Some(variadic) } else {