/** * Calculator grammar to generate parser in Rust. */ %lex %% // ----------------------------------------------- // Lexical grammar. // // Uses regexp to produce list of tokens. // Return values is a token type. \s+ /* skip whitespace */ return ""; \d+ return "NUMBER"; "+" return "+"; "*" return "*"; "(" return "("; ")" return ")"; /lex // ----------------------------------------------- // Operator precedence. // // The `*` goes after `+`, so `2 + 2 * 2` is // correctly parsed as `2 + (2 * 2)`. // // Also both are left-associative, meaning // `2 + 2 + 2` is `(2 + 2) + 2`, which is important // when we build AST nodes. %left + %left * // ----------------------------------------------- // Module include. // // The code which is included "as is" to the generated // parser. Should at least contain `TResult` -- the // type of the final parsed value. %{ // Important: define the type of the parsing result: type TResult = i32; %} %% // ----------------------------------------------- // Syntactic grammar (BNF). Expr // --------------------------------------- // Addition : Expr + Expr { // Types of used args, and the return type. |$1: i32, $3: i32| -> i32; $$ = $1 + $3 } // --------------------------------------- // Multiplication | Expr * Expr { |$1: i32, $3: i32| -> i32; $$ = $1 * $3 } // --------------------------------------- // Simple number | NUMBER { || -> i32; $$ = yytext.parse::().unwrap() } // --------------------------------------- // Grouping in parens | ( Expr ) { $$ = $2 };