How can I add parentheses as the highest level of precedence in a simple grammar?

别等时光非礼了梦想. 提交于 2019-11-30 09:34:18

问题


I'm trying to add 2 things to my grammar:

  1. Unary minus sign, i.e. '-', and

  2. Parentheses

Here's my grammar so far:

<comp>  ::= <expr> | <comp> <op0> <expr>
<expr>  ::= <term> | <expr> <op1> <term>
<term>  ::= <darg> | <term> <op2> <darg>
<darg>  ::= <digit> | <darg> <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<op0>   ::= > | < | =< | => | =
<op1>   ::= + | -
<op2>   ::= * | /

I've tried everything and can't figure this out. How can I make the unary minus sign be at the highest level of precedence, followed by parentheses next and then the remaining operators as they are described?


回答1:


I am adding a new variable named <new> with three new production rules in your present grammar in question to add Unary minus sign and Parentheses:

<comp>  ::= <expr>   | <comp> <op0> <expr>
<expr>  ::= <term>   | <expr> <op1> <term>
<term>  ::= <new>    | <term> <op2> <darg>
<new>   ::= (<comp>) | -<darg> | <darg> 
<darg>  ::= <digit>  |  <darg> <digit>
<digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
<op0>   ::= > | < | =< | => | =
<op1>   ::= + | -
<op2>   ::= * | /

by adding Parentheses, you are adding tow new terminals in your grammar { (, ) }

Also, you can add <new> ::= ( <new> ) if you want to generate (-7), (7) and ((6+7)) like expressions.(these are valid expressions)

I would like to inform you that if you are writing compiler, use ambiguous grammar instead and add operator precedence in YACC tool that will allow efficient parsing

EDIT:

If you wants to add expression like -(7) and that is a valid expression. So <new> ::= -<new> instead of <new> ::= <drag>




回答2:


Change <term> to use <fred> instead of <darg> and define

<fred> ::= -<fred> | (<comp>) | <darg>


来源:https://stackoverflow.com/questions/14554752/how-can-i-add-parentheses-as-the-highest-level-of-precedence-in-a-simple-grammar

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