Operator Precedence and Associativity

Document Sample
Operator Precedence and Associativity Powered By Docstoc
					Operator Precedence and
Associativity
• Let’s build a CFG for expressions
  consisting of:
   • elementary identifier i.
   • + and - (binary ops) have lowest
     precedence, and are left associative .
   • * and / (binary ops) have middle
     precedence, and are right associative.
   • + and - (unary ops) have highest
     precedence, and are right associative.
Sample Grammar for Expressions

E→E+T          E consists of T's,
  →E-T          separated by –’s and +'s
  →T            (lowest precedence).
T→F*T         T consists of F's,
  →F/T           separated by *'s and /'s
  →F             (next precedence).
F→-F         F consists of a single P,
  →+F              preceded by +'s and -'s.
  →P               (next precedence).
P → '(' E ')' P consists of a parenthesized E,
  →i            or a single i (highest precedence).
Operator Precedence and
Associativity (cont’d)
• Operator precedence:
  – The lower in the grammar, the higher
    the precedence.

• Operator Associativity:
  – left recursion in the grammar means
    left associativity of the operator, and
    causes left branching in the tree.
  – right recursion in the grammar means
    right associativity of the operator, and
    causes right branching in the tree.
String-to-tree Transduction Grammar

   E→E+T           => +
    →E- T          => -
    →T
   T→F*T           => *
    →F/T           => /
    →F
   F→- F           => neg
    →+F            => +
     →P
   P → '(' E ')'
     →i            => i
Sample Input : - + i - i * ( i + i ) / i + i