Parser - Parse program as a list of statements
This commit is contained in:
parent
402e0a10d9
commit
bf11a2b63a
1 changed files with 30 additions and 2 deletions
|
@ -19,8 +19,8 @@ impl Parser {
|
||||||
|
|
||||||
/// Parse the tokens into an AST and return it, or return nothing if a
|
/// Parse the tokens into an AST and return it, or return nothing if a
|
||||||
/// parser error occurs.
|
/// parser error occurs.
|
||||||
pub fn parse(mut self, err_hdl: &mut ErrorHandler) -> Option<ast::ExprNode> {
|
pub fn parse(mut self, err_hdl: &mut ErrorHandler) -> Option<ast::ProgramNode> {
|
||||||
match self.parse_expression() {
|
match self.parse_program() {
|
||||||
Ok(expr) => Some(expr),
|
Ok(expr) => Some(expr),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
e.report(err_hdl);
|
e.report(err_hdl);
|
||||||
|
@ -54,6 +54,34 @@ impl Parser {
|
||||||
* RECURSIVE DESCENT PARSER *
|
* RECURSIVE DESCENT PARSER *
|
||||||
* ------------------------ */
|
* ------------------------ */
|
||||||
|
|
||||||
|
/// Parse the following rule:
|
||||||
|
/// ```
|
||||||
|
/// program := statement*
|
||||||
|
/// ```
|
||||||
|
fn parse_program(&mut self) -> Result<ast::ProgramNode, ParserError> {
|
||||||
|
let mut stmts: Vec<ast::StmtNode> = Vec::new();
|
||||||
|
while !self.is_at_end() {
|
||||||
|
let stmt = self.parse_statement()?;
|
||||||
|
stmts.push(stmt);
|
||||||
|
}
|
||||||
|
Ok(ast::ProgramNode(stmts))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the following rule:
|
||||||
|
/// ```
|
||||||
|
/// statement := expression ";"
|
||||||
|
/// statement := "print" expression ";"
|
||||||
|
/// ```
|
||||||
|
fn parse_statement(&mut self) -> Result<ast::StmtNode, ParserError> {
|
||||||
|
if self.expect(&[TokenType::Print]).is_some() {
|
||||||
|
let expression = self.parse_expression()?;
|
||||||
|
Ok(ast::StmtNode::Print(expression))
|
||||||
|
} else {
|
||||||
|
let expression = self.parse_expression()?;
|
||||||
|
Ok(ast::StmtNode::Expression(expression))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Parse the following rule:
|
/// Parse the following rule:
|
||||||
/// ```
|
/// ```
|
||||||
/// expression := equality
|
/// expression := equality
|
||||||
|
|
Loading…
Reference in a new issue