Skip to content

Instantly share code, notes, and snippets.

@mattmcd
Created March 30, 2013 18:46
Show Gist options
  • 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;
@Kraballa
Copy link

point of note, the order only matters for expressions that are ambiguous in their resolution. so here that would be lines 9 and 10 ONLY.

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