Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large parse tree for simple C expression

Tags:

antlr4

I'm using the C grammar here: https://github.com/antlr/grammars-v4/tree/master/c to parse the expression int a2 = 5;. ANTLR version is 4.3.

The "5" here matches a very large chain of rules: initializer->assignmentExpression->conditionalExpression->logicalOrExpression->logicalAndExpression->... around 10 more -> primaryExpression->5.

While the parsing is correct eventually, this seems like a bug in the grammar. Can someone suggest fixes or clarifications?

Image of parse tree

like image 751
Anuj Kalia Avatar asked Jul 02 '26 23:07

Anuj Kalia


1 Answers

No, it is no bug. The lower down the tree simply means the higher the precedence of the operator(s).

EDIT

The fact that the rules are chained like that is probably because Terence wrote the grammar from the C11 spec (it says so in the comments of the grammar). And in the official specs, the rules are probably written like that. You could rewrite the grammar in a more compact way however. ANTLR4 allows for direct recursive rules, making the rules:

expr
 : add
 ;

add
 : mult (('+'|'-') mult)*
 ;

mult
 : unary (('*'|'/') unary)*
 ;

unary
 : '-' atom
 | atom
 ;

atom
 : '(' expr ')'
 | NUMBER
 ;

equivalent to the following single (ANTLR4) rule:

expr
 : '-' expr
 | expr ('*'|'/') expr // higher precedence than rules starting with `expr` defined below
 | expr ('+'|'-') expr
 | '(' expr ')'
 | NUMBER
 ;
like image 106
Bart Kiers Avatar answered Jul 05 '26 16:07

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!