Presentation is loading. Please wait.

Presentation is loading. Please wait.

Operator Precedence and Associativity

Similar presentations


Presentation on theme: "Operator Precedence and Associativity"— Presentation transcript:

1 Operator Precedence and Associativity
COP4620 – Programming Language Translators Dr. Manuel E. Bermudez

2 Operator precedence Let’s build a CFG for expressions consisting of:
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 (E), → i or a single i (highest precedence). 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.

3 Operator Precedence and Associativity
The lower in the grammar, the higher the precedence. Operator Associativity: Tie breaker for precedence. Left recursion in the grammar means left associativity of the operator, left branching in the tree. Right recursion in the grammar means right associativity of the operator, right branching in the tree.

4 Building Derivation Trees
Sample Input : - + i - i * ( i + i ) / i + i (Human) derivation tree construction: Bottom-up. First pass: scan entire expression, process operators with highest precedence (parentheses are highest). Each subsequent pass: process operators on next level. Lowest precedence operators are last, at the top of tree.

5 E → E + T → E - T → T T → F * T → F / T → F F → - F → + F → P P → '(' E ')' → i

6 The abstract syntax tree (AST)
E → E + T => + → E -T => - → T T → F * T => * → F / T => / → F F → - F => neg → + F => + → P P → '(' E ')' → i => i AST is a condensed version of the derivation tree. No noise (intermediate nodes). String-to-tree transduction grammar: rules of the form A → ω => 's'. Build 's' tree node, with one child per tree from each nonterminal in ω.

7 The abstract syntax tree (AST)
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


Download ppt "Operator Precedence and Associativity"

Similar presentations


Ads by Google