Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does antlr automatically factor top-level alternates?

I have written the following two grammars, one grouping the arithmetic expressions (where possible) and another that doesn’t:

grammar NoPrefix;
root: (expr ';')* EOF;

expr
    : '(' expr ')'
    | expr '*' expr
    | expr '/' expr
    | expr '+' expr
    | expr '-' expr
    | Atom
    ;

Atom: [a-z]+ | [0-9]+ | '\'' Atom '\'';
WHITESPACE: [ \t\r\n] -> skip;
grammar YesPrefix;
root: (expr ';')* EOF;

expr
    : '(' expr ')'
    | expr ('*'|'/') expr
    | expr ('+'|'-') expr
    | Atom
    ;

Atom:[a-z]+ | [0-9]+ | '\'' Atom '\'';
WHITESPACE: [ \t\r\n] -> skip;

It seems that these two have almost identical runtimes, build sizes, etc. Does antlr automatically convert the two forms of alternatives to the same output, for example:

expr: expr '*' expr | expr '/' expr    <==> expr: expr ('*'|'/') expr;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No. How would Antlr know that you wanted * and / to have the same binding precedence, different from + and -? You need to be explicit about that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading