You are on page 1of 20

Attribute Grammars

Definition of Attribute Grammar


•A context-free grammar
•Each symbol has a set of attributes
• Each production can be augmented with
a set of semantic rules
• The semantic rules specify how to
compute the value for an attribute
Expression Interpreter (Evaluates a valid expression)

Notes
• In this attribute grammar, attributes of grammar symbols on the lhs are computed
using the attributes of grammar symbols on the rhs (such attributes are called
synthesized attributes)
• The token num has a value attribute returned by the lexical analyzer
Example of an expression evaluation
Attribute Grammars
• Attributes are associated with nodes in parse tree (terminals
and non-terminals)
• Identical terms in a production are labeled for uniqueness
– E → E + T becomes E0 → E1 + T
• Rules and parse tree define an attribute dependence graph
– Dependence graph must be non-circular, otherwise
attribute values might not be computable
• Synthesized attribute: value depends on values from children
• Inherited attribute: value depends on values from siblings
and parent
Synthesized and Inherited Attributes
Another Attribute Grammar Example
Parse Tree Example
Parse Tree Example Cont.
Parse Tree Example Cont.
Example: Dependency Graph For Attributes
An Evaluation Method
• Build the parse tree
• Build the dependence graph
• Topological sort the dependence graph
• Compute the attributes in topological
order
Example: Dependence graph Example
S-Attributed Grammars
Synthesized Attributes on the Parser Stack
L-Attributed Grammars
L-Attributed Grammars
Attribute Grammars Evaluation
Addressing the Problem

You might also like