Home > Software design >  Does antlr automatically factor top-level alternates?
Does antlr automatically factor top-level alternates?

Time:08-25

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;

CodePudding user response:

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.

  • Related