Search code examples
parsinggrammarcontext-free-grammarparenthesesoperator-precedence

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


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?


Solution

  • 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>