简体   繁体   中英

Make this Expression Grammar unambiguous for LL(1)

How can we make this Expression grammar unambiguous for LL(1) parsing?

The grammar is very similar to expressions used in most C like languages.

Note: Strings in <> are non-terminals, while those in Upper Case are terminals.


 <expression> -->  <arithmeticExpr> | <booleanExpr>

 <arithmeticExpr> -->  <arithmeticExpr> <op1> <term> | <term> 

 <term> -->  <term> <op2> <factor> 
 <term> -->  <factor>

 <factor> -->  BO <arithmeticExpr> BC 
 <factor> -->  <var> 

 <op1> -->  PLUS | MINUS

 <op2> -->  MUL | DIV  

 <booleanExpr> -->  <booleanExpr> <logicalOp> <booleanExpr> 
 <booleanExpr> -->  <arithmeticExpr> <relationalOp> <arithmeticExpr> 
 <booleanExpr> -->   BO <booleanExpr> BC

 <logicalOp> -->  AND | OR 

 <relationalOp> -->   LT | LE | GT | GE | EQ | NE

 <var> --> ID <whichId> | NUM | RNUM 

 <whichId> --> SQBO ID SQBC | ε

PS: I coudn't find any question on Stackoverflow that handled Boolean Expressions.

First you need to disambiguate the rule

<booleanExpr> -->  <booleanExpr> <logicalOp> <booleanExpr>

How should it handle inputs like a AND b OR c and a OR b AND c ? There are multiple possible interpretations; you need to decide which you want.

Then, you'll have a grammar that is unambiguous, but not LL(1). To make it LL(1) you need to left-factor it.

@Chris, your issue is probably rectified as following. Yet ambiguity of the complete grammar does not vanish.
Also, left factoring in its standard form is not possible here.
We get left common factors (like BO in <booleanExpr> ) only when we try to find the FIRST sets of <booleanExpr> and <expression>


<booleanExpr> -->  <arithmeticExpr> <relationalOp> <arithmeticExpr> <BooleanX>
<booleanExpr> -->   BO <booleanExpr> BC <BooleanX>

<BooleanX> -->  <logicalOp> <booleanExpr> <BooleanX> | ε

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM