Ambiguity( Cont) aA grammar is ambiguous D if it has more than one parse tree for any string ■ Ambiguity is bad lEaves meaning of some programs ill-defined Ambiguity is common in programming languages D Arithmetic expressions 口|F-THEN-ELSE
6 Ambiguity (Cont.) ◼ A grammar is ambiguous if it has more than one parse tree for any string ◼ Ambiguity is bad Leaves meaning of some programs ill-defined ◼ Ambiguity is common in programming languages Arithmetic expressions IF-THEN-ELSE
Dealing with Ambiguity There are two ways to remove ambiguity 1)Rewrite the grammar into a unambiguous grammar EE+T T TT*int int I(E) 口 Enforces precedence(优先级)of*over+ 口 Enforces left- associativity(左结合)of+and* 2) Declarations: instruct parser to pick desired parse trees a using %left, %right, %prec declarations
7 Dealing with Ambiguity There are two ways to remove ambiguity: 1) Rewrite the grammar into a unambiguous grammar E E + T | T T T * int | int | ( E ) Enforces precedence(优先级) of * over + Enforces left-associativity(左结合) of + and * 2) Declarations: instruct parser to pick desired parse trees using %left, %right, %prec declarations