Skip to content

Instantly share code, notes, and snippets.

@mattmcd
Created March 30, 2013 18:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattmcd/5277890 to your computer and use it in GitHub Desktop.
Save mattmcd/5277890 to your computer and use it in GitHub Desktop.
ANTLR4 simple expression grammar. Note that left recursion is now allowed and operator precedence is just order of definition.
grammar Expr;
// Need to call recursive rule expr from non-recursive rule
r : expr+ ;
// ANTLR4 : Left recursion!
// Operator precedence matches order of definition
expr : '-' expr // Unary minus
| expr ('*' | '/' ) expr
| expr ('+' | '-' ) expr
| '(' expr ')'
| INT
| ID
;
INT : [0-9]+ ;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip;
@mattmcd
Copy link
Author

mattmcd commented Mar 30, 2013

Testing:

>> grun Expr r -tree
1 - -2
^D
(r (expr (expr 1) - (expr - (expr 2))))

@junkkerrigan
Copy link

Thank you a lot, I couldn't deal with right order of operations for a long time, and now after I run into your example, it finally works as I expected!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment