Parser - Support for function calls

This commit is contained in:
Emmanuel BENOîT 2023-01-02 15:15:34 +01:00
parent 2e7a897c47
commit acbce309fa

View file

@ -525,6 +525,7 @@ impl Parser {
/// primary := "(" expression ")" /// primary := "(" expression ")"
/// primary := FALSE | TRUE | NIL | STRING | NUMBER /// primary := FALSE | TRUE | NIL | STRING | NUMBER
/// primary := IDENTIFIER /// primary := IDENTIFIER
/// primary := call
/// ``` /// ```
fn parse_primary(&mut self) -> ParserResult<ast::ExprNode> { fn parse_primary(&mut self) -> ParserResult<ast::ExprNode> {
if self.expect(&[TokenType::LeftParen]).is_some() { if self.expect(&[TokenType::LeftParen]).is_some() {
@ -542,14 +543,46 @@ impl Parser {
TokenType::Number(_) | &TokenType::String(_) => Ok(ast::ExprNode::Litteral { TokenType::Number(_) | &TokenType::String(_) => Ok(ast::ExprNode::Litteral {
value: self.advance().clone(), value: self.advance().clone(),
}), }),
TokenType::Identifier(_) => Ok(ast::ExprNode::Variable { TokenType::Identifier(_) => {
name: self.advance().clone(), let identifier = self.advance().clone();
}), if self.expect(&[TokenType::LeftParen]).is_some() {
self.parse_call(identifier)
} else {
Ok(ast::ExprNode::Variable { name: identifier })
}
}
_ => Err(ParserError::new(self.peek(), "expected expression")), _ => Err(ParserError::new(self.peek(), "expected expression")),
} }
} }
} }
/// Parse the following rules:
/// ```
/// call := IDENTIFIER "(" arguments? ")"
/// arguments := expression ( "," expression )*
/// ```
/// The `identifier` has already been read and is provided to the method;
/// the opening parenthesis has already been skipped.
fn parse_call(&mut self, name: Token) -> Result<ast::ExprNode, ParserError> {
let mut arguments = Vec::new();
if !self.check(&TokenType::RightParen) {
loop {
arguments.push(self.parse_expression()?);
if self.expect(&[TokenType::Comma]).is_some() {
break;
}
}
}
let right_paren = self
.consume(&TokenType::RightParen, "')' expected after arguments")?
.clone();
Ok(ast::ExprNode::Call {
name,
right_paren,
arguments,
})
}
/* -------------- * /* -------------- *
* HELPER METHODS * * HELPER METHODS *
* -------------- */ * -------------- */