Dup Ver Goto 📝

Simple Maths Expression Parser

PT2/lang/parsers/antlr/toy-examples does not exist
To
26 lines, 104 words, 550 chars Page 'MathExpression' does not exist.

Aim

Parse each of the following lines

1 + 2
(1 + 2) * 3
4 * (5 - 6)
7 + 8 + 9
5 / (3 + 1)

Notes

Antlr4 has the mandatory convention that lexer patterns begin with a Capital Letter and syntactic patterns start with a lowercase letter.

Example Grammar

This is my first attempt.

grammar Expr;

DIGIT: [0-9] ;
NUMBER: DIGIT+ ;

expr: expr ('+'|'-') term | term ;
term: term ('*'|'/') NUMBER | NUMBER | '(' expr ')';

Problems:

  1. It doesn't handle whitespace (probably want WHITESPACE: [ \t\r\n] -> skip;).