R3. Attributes and Actions


Actions

Syntax is concerned with what the text of a program looks like, and with rules for constructing sensible programs.

Semantics is concerned with meaning, such as what a program does when it is run.

Semantic rules are attached, as actions, to productions of a grammar.

A bottom-up parser does a semantic action when it does a reduce.

A top-down parser has more flexibility in when it does actions. It can do something when it starts a production (on the way into recursion) and when it finishes a production (on the way out of recursion).

See this example of an action attached to a production in Bison.


Attributes

An attribute is a value that is attached to a node of a parser tree.

See this example.

Where context-free grammars form the foundation for describing syntax, attribute equations form the foundation for describing semantics.

Each node can have several attributes attached to it; each attribute has a name.

Attributes of a node are defined in terms of the attributes of its child, sibling nodes and its parent node. Definition of attributes is carried out as part of the action(s) associated with a production.


Synthesized attributes

Think of a recursive-descent parser, where there is one function for each production.

A function can take parameters and return a result. Attributes definitions are similar to that.

A synthesized attribute is similar to the value returned by a function.

A synthesized attribute of a node is defined in terms of attributes of that node's children in the parse tree. It represents information that is passed up the parse tree.

Synthesized attributes are easy to recognize in actions. When an action defines an attribute of the left-hand side of a production, it is defining a synthesized attribute.

See this example of defining synthesized attributes in an action.

You should be prepared to attach actions to productions that define synthesized attributes.


Inherited attributes

An inherited attribute is similar to a parameter passed to a function.

An inherited attribute of a node v is defined by an action that is performed at parent or sibling of v.

See this example of defining inherited attributes in an action.