Hey I'm recently involved in a compiler developer, I've encountered a problem with minus sign(-) and negative number(-1). Suppose now I have 5--3, 5+-3, how to write a grammar rule such that during the abstract syntax tree construction, yacc will produce a correct abstract syntax tree?
My grammar is like:
expr :
constant {}
| id {}
| exec_expr {}
exec_expr :
expr PLUS expr {}
| expr MINUS expr {}
| expr MUL expr {}
| expr DIV expr {}
My thought for now is to have a UMINUS symbol with highest order (nonassociate) to deal with the case. Somehow, our compiler has to split the expression into expr and exec_expr, I've tried with the method but it doesn't work for some reasons.
What's the standard solution for dealing with this case in any other language? Especially those with LR(0) automaton. Thanks so much!
As a matter of practical engineering, usually the lexer doesn't handle signed numbers.
This means the parser can handle the minus sign, either as a subtract between two operands (the second of which may be a number), or as the negative of the the operand (of which the operand may be a number). That also makes it easy to handle odd expressions like "a- -7". So all you need is the "MINUS" token.
You can design a lexer and parser where the lexer swallows the sign character. Usually it needs feedback from the parser to know what is safe to do. That's inconvenient to organize, and thus the practical engineering approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With