How Compiler distinguishes minus and negative number during parser process

亡梦爱人 提交于 2020-01-15 03:58:06

问题


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!


回答1:


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.




回答2:


You just need to add two rules:

expr
: constant {}
| id {}
| exec_expr {}
| '+' expr {}  // added
| '-' expr {}  // added

and define the appropriate precedences. I'd prefer to see this written out in full in the traditional way:

expr
: term
| term '+' term
| term '-' term
;

term
: factor
| factor '*' factor
| factor '/' factor
| factor '%' factor // if you have the % operator
;

factor
: unary
| unary '^' factor // if you have an exponentiation operator. Note right-associativity
;

unary
: primary
| '+' unary
| '-' unary
;

primary
: id
| constant
| '(' expr ')'
;

E&OE



来源:https://stackoverflow.com/questions/27478834/how-compiler-distinguishes-minus-and-negative-number-during-parser-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!