Attribute Grammars 4 Recall the yacc program expr
Attribute Grammars 4 Recall the yacc program expr : expr '+' expr {$$ = $1 + $3; } | expr '-' expr {$$ = $1 - $3; } | expr '*' expr {$$ = $1 * $3; } | expr '/' expr {$$ = $1 / $3; } | '(' expr ')' {$$ = $2; } | NUMBER ; – Parse a given expression – Evaluate it by Neng-Fa Zhou
Attributes and Attribute Grammars 4 Attributes – variables (type, offset, first or last occurrence, . . . ) – constants (type, value, scope, . . . ) 4 Attribute grammar(Syntax-directed definition) – A generalization of CFG in which each grammar symbol has an associated set of attributes – Semantics rules for computing attribute values by Neng-Fa Zhou
Synthesized Attributes 4 Synthesized Attributes – The value is computed from the values of attributes of the children – S-attributed grammar - synthesized attributes only – Bottom-up propagation 4 Example – values of expressions – types of expressions by Neng-Fa Zhou
S-Attributed Grammars Example by Neng-Fa Zhou
The Annotated Parse Tree by Neng-Fa Zhou
Inherited Attributes 4 Inherited Attributes – The value is computed from the values of attributes of the siblings and parent – Top-down propagation 4 Example – type information – where does a variable occurs? lhs or rhs by Neng-Fa Zhou
Inherited Attributes Example by Neng-Fa Zhou
The Annotated Parser Tree by Neng-Fa Zhou
Converting Binary to Decimal N : : = BIN N. v = BIN. v BIN. r = 0 BIN 0 : : = BIN 1 B BIN 1. r = BIN 0. r + 1 B. r = BIN 0. r BIN 0. v = BIN 1. v+B. v BIN : : = B BIN. v = B. v B. r = BIN. r B : : = '1' B : : = '0' B. v = 2 B. r B. v =0 by Neng-Fa Zhou
Dependency Graphs 4 Each node represents an attribute of a node in the parse tree 4 Each arc represents the dependence relationship (flow of values) by Neng-Fa Zhou
Computing Attribute Values 4 1. Compute while parsing – Oblivious methods • Fast (one pass) • Complicated • Some attribute values cannot be computed 4 2. Compute after parsing – Parse-tree methods (sort dependency graphs) – Rule-based methods (data-flow or fix-point) by Neng-Fa Zhou
- Slides: 11