antlr / grammars-v4

Grammars written for ANTLR v4; expectation that the grammars are free of actions.
MIT License
10.15k stars 3.7k forks source link

[C] antlr4 (or C grammar) mishandles "(addr) + 1;" #2047

Open jirislaby opened 3 years ago

jirislaby commented 3 years ago

If I comment typedefName in typeSpecifier https://github.com/antlr/grammars-v4/blob/4c783b6b0f10927485c4e63007088ddbb3f777c0/c/C.g4#L240 to avoid #1979, antlr4's generated C grammar fails to parse:

void fun()
{
        (void *)(addr) + 1;
}

It says:

line 3:10 no viable alternative at input 'addr'

It only tries castExpression for the (addr) part and considers + as unary operator: antlr4_parse_tree

But + should take precedence and the whole tree should start splitting at additiveExpression already.

I am not sure whether this is the grammar issue or antlr4's one.

jirislaby commented 3 years ago

Note that passing (void *)addr + 1 (i.e. no parentheses around addr) to additiveExpression produces a good result: no_paren1 As well as passing (void *)(addr) (i.e. no + part) to castExpression: cast

jirislaby commented 3 years ago

If I switch the order of castExpression alternatives, see https://github.com/jirislaby/grammars-v4/commit/624417a, it works. But the order should not matter in this case, the grammar should backtrack and try the other alternative, right?