IT603(A) • Compiler Design • Unit III

Syntax-Directed Translation

Complete RGPV exam-oriented notes on attribute grammars, dependency graphs, syntax-tree construction, top-down translation, postfix notation and bottom-up evaluation.

Start Unit 3 Notes

1. Syntax-Directed Translation 14 Marks

Syntax-directed translation is a compiler technique in which semantic actions or attribute rules are associated with grammar productions so that translation is performed according to the syntactic structure of the source program.

Basic Idea

The parser recognizes the grammar structure, while semantic rules compute values, construct trees, generate intermediate code or update the symbol table.

Source Tokens | Parser | Grammar Productions | Semantic Rules / Actions | Translation Result (Tree, Type, Value or Code)

Main Components

  • Context-free grammar
  • Attributes attached to grammar symbols
  • Semantic rules
  • Semantic actions
  • Evaluation order

Applications

  • Type checking
  • Syntax-tree construction
  • Postfix translation
  • Intermediate-code generation
  • Symbol-table creation
  • Expression evaluation

Example

Production: E → E1 + T Semantic Rule: E.val = E1.val + T.val

The production defines syntax, while the semantic rule calculates the value of E.

Advantages

  • Clear relation between grammar and translation.
  • Modular specification of semantics.
  • Supports automatic compiler construction.
  • Useful in both top-down and bottom-up parsing.
Conclusion: Syntax-directed translation combines parsing with semantic processing and provides a systematic method for producing compiler outputs from grammatical structures.

2. Syntax-Directed Definition 14 Marks

A syntax-directed definition, or SDD, is a context-free grammar augmented with attributes and semantic rules associated with productions.

Structure of an SDD

Grammar Production: A → X1 X2 ... Xn Semantic Rules: A.a = function(X1.b, X2.c, ...) Xi.d = function(A.e, Xj.f, ...)

Elements

  • Grammar symbols: terminals and non-terminals.
  • Attributes: values associated with symbol occurrences.
  • Semantic rules: formulas used to compute attributes.

Example: Expression Value

ProductionSemantic Rule
E → E1 + TE.val = E1.val + T.val
E → TE.val = T.val
T → numT.val = num.lexval

Annotated Parse Tree

A parse tree displaying attribute values at its nodes is called an annotated parse tree.

Input: 3 + 4 E.val=7 / | \ E.val=3 + T.val=4 | | T.val=3 num=4 | num=3

SDD vs Translation Scheme

SDDTranslation Scheme
Uses semantic rulesEmbeds semantic actions in production bodies
More declarativeMore implementation oriented
Evaluation order may be derivedAction position often specifies order

3. Attributes in Syntax-Directed Definitions 14 Marks

An attribute is a value associated with an occurrence of a grammar symbol in a parse tree.

Attribute Examples

  • Numerical value of an expression
  • Data type
  • Memory location
  • Generated code
  • Syntax-tree node pointer
  • Symbol-table entry

Major Types

TypeInformation DirectionTypical Use
SynthesizedChildren to parentExpression value, generated code
InheritedParent or siblings to a nodeDeclared type, scope information

Attribute Evaluation

An attribute can be evaluated only after all attributes on which it depends have been computed. These dependencies are represented by a dependency graph.

4. Synthesized Attributes 14 Marks

A synthesized attribute of a node is computed from attributes of its children and sometimes from properties of the node itself.

Information Flow

Child Attributes | v Parent Synthesized Attribute

Example

Production: E → E1 + T Rule: E.val = E1.val + T.val

Here, E.val is synthesized from E1.val and T.val.

Properties

  • Information moves upward in the parse tree.
  • Natural for bottom-up evaluation.
  • Easy to evaluate by postorder traversal.
  • Commonly used for expression values and generated code.

Applications

  • Arithmetic evaluation
  • Syntax-tree creation
  • Code generation
  • Type calculation from operands

Advantage

Synthesized attributes are simple to implement in bottom-up parsers because the children are recognized before the parent reduction.

5. Inherited Attributes 14 Marks

An inherited attribute of a grammar symbol is computed from attributes of its parent or siblings.

Information Flow

Parent / Left Sibling Attributes | v Child Inherited Attribute

Example: Declaration Type

Production: D → T L Rules: L.in = T.type T → int T.type = integer

The type computed at T is passed to L through inherited attribute L.in.

Typical Uses

  • Passing declared type to identifier lists
  • Passing scope information
  • Passing symbol-table environment
  • Passing expected type
  • Passing offsets or addresses

Challenges

  • Evaluation order is more complex.
  • Cyclic dependencies must be avoided.
  • Not every inherited definition can be evaluated in one parsing pass.

6. S-Attributed Definitions 14 Marks

An S-attributed definition is an SDD that uses only synthesized attributes.

Characteristics

  • No inherited attributes.
  • Attributes flow from children to parent.
  • Can be evaluated by postorder traversal.
  • Well suited to bottom-up LR parsing.

Example

ProductionSemantic Rule
E → E1 + TE.val = E1.val + T.val
E → TE.val = T.val
T → numT.val = num.lexval

Evaluation

Leaves First | Compute Child Attributes | Move Upward | Compute Root Attribute

Advantages

  • Simple evaluation.
  • No dependency on parent values.
  • Easy integration with shift-reduce parsing.
  • No need for complex scheduling in acyclic cases.

Limitation

It cannot naturally express information that must flow from a declaration or context down to child nodes.

7. L-Attributed Definitions 14 Marks

An L-attributed definition allows synthesized attributes and restricted inherited attributes that can be evaluated in one left-to-right traversal.

Restriction

For a production A → X1 X2 ... Xn, an inherited attribute of Xi may depend only on:

  • Inherited attributes of A.
  • Attributes of symbols X1, X2, ..., Xi-1 to the left of Xi.
  • Attributes of Xi itself, provided no cycle is created.

Example

Production: D → T L Rules: L.in = T.type D.code = L.code

Why Called L-Attributed?

Because attributes can be evaluated from left to right while traversing the parse tree.

Evaluation Order

  1. Compute inherited attributes of the parent.
  2. Visit children from left to right.
  3. Before visiting a child, compute its inherited attributes.
  4. After visiting children, compute synthesized attributes of the parent.

Applications

  • Type propagation
  • Declaration processing
  • Offset calculation
  • Scope and environment passing
  • Top-down translation

S-Attributed vs L-Attributed

FeatureS-AttributedL-Attributed
AttributesOnly synthesizedSynthesized + restricted inherited
Natural parserBottom-upTop-down
Information flowUpwardLeft-to-right and upward
PowerLess expressiveMore expressive

8. Dependency Graph 14 Marks

A dependency graph is a directed graph that represents dependencies among attribute instances in an annotated parse tree.

Graph Components

  • Each attribute instance is represented by a node.
  • An edge X → Y means Y depends on X.
  • X must be evaluated before Y.

Example

Production: E → E1 + T Rule: E.val = E1.val + T.val Dependency Edges: E1.val ----\ ---> E.val T.val ----/

Construction Steps

  1. Construct the parse tree.
  2. Create a node for each attribute occurrence.
  3. Inspect every semantic rule.
  4. Add an edge from each used attribute to the computed attribute.
  5. Repeat for all parse-tree nodes.

Cycle

If the dependency graph contains a cycle, the attributes cannot be evaluated using a simple finite order. Such an SDD is called circular.

Importance

  • Determines valid evaluation order.
  • Detects circular definitions.
  • Supports automatic attribute evaluation.
  • Clarifies data flow among grammar symbols.

9. Evaluation Order of Attributes 14 Marks

Evaluation order is the sequence in which attribute instances are computed so that every dependency is satisfied.

Topological Order

For an acyclic dependency graph, any topological ordering of graph nodes is a valid evaluation order.

Methods

  • Parse-tree traversal: preorder, postorder or left-to-right traversal.
  • Rule-based evaluation: order determined from attribute class.
  • Dependency-graph evaluation: use topological sorting.

Postorder for S-Attributed SDD

Visit Left Child Visit Right Child Compute Parent Attribute

Depth-First Evaluation for L-Attributed SDD

Compute Child Inherited Attributes | Visit Child from Left to Right | Compute Parent Synthesized Attributes

Requirements

  • All dependencies must be known.
  • No cycles should exist.
  • Every used attribute must be defined.

10. Construction of Syntax Trees 14 Marks

A syntax tree is a compact tree representation of the essential syntactic structure of a source program.

Node Types

  • Leaf node: identifier or constant.
  • Interior node: operator or language construct.

Common Functions

mkleaf(token, value) mknode(operator, left, right) mkunary(operator, child)

SDD for Expression Tree

ProductionSemantic Rule
E → E1 + TE.node = mknode('+', E1.node, T.node)
E → TE.node = T.node
T → idT.node = mkleaf(id, id.entry)
T → numT.node = mkleaf(num, num.value)

Example

Expression: a + b * c

+ / \ a * / \ b c

Advantages

  • More compact than parse tree.
  • Removes unnecessary punctuation and grammar nodes.
  • Useful for semantic analysis.
  • Useful for optimization and code generation.

11. Syntax Tree and DAG 14 Marks

A DAG, or directed acyclic graph, is a compact representation that can share identical subexpressions, unlike an ordinary syntax tree.

Example

Expression: a + a * b + a * b

A tree repeats the subexpression a*b, while a DAG can store it once and share the node.

Comparison

FeatureSyntax TreeDAG
StructureEach occurrence has separate nodeCommon subexpressions can share nodes
PurposeProgram structureOptimization
MemoryMay use more nodesMore compact
Common expression detectionNot directNatural

12. Top-Down Translation 14 Marks

Top-down translation performs semantic actions while a top-down parser expands non-terminals and scans the input from left to right.

Translation Scheme

A translation scheme embeds semantic actions inside production bodies.

E → T { print(T.val); }

Action Positions

  • An action at the beginning executes before symbols are processed.
  • An action between symbols executes after left symbols and before right symbols.
  • An action at the end executes after the complete production body.

Example: Infix to Postfix

E → T E' E' → + T { print('+'); } E' | ε T → id { print(id.lexeme); }

Working for a+b

  1. Recognize a and print a.
  2. Recognize +.
  3. Recognize b and print b.
  4. Execute action for +.
  5. Output becomes ab+.

Conditions

  • Grammar should be suitable for top-down parsing.
  • Inherited attributes must satisfy L-attributed restrictions.
  • Actions must be placed after required values become available.

13. Postfix Notation 14 Marks

In postfix notation, an operator is written after its operands. It is also called Reverse Polish Notation.

Examples

InfixPostfix
a + bab+
a + b * cabc*+
(a + b) * cab+c*

Why Postfix Is Useful

  • No parentheses are required.
  • No precedence table is required during evaluation.
  • Easy stack-based evaluation.
  • Useful as an intermediate representation.

Syntax-Directed Translation

E → E1 + T { print('+'); } E → E1 - T { print('-'); } E → T T → T1 * F { print('*'); } T → F F → ( E ) F → id { print(id.lexeme); }

Stack Evaluation

  1. Scan postfix expression left to right.
  2. Push operands onto stack.
  3. On operator, pop required operands.
  4. Apply operator and push result.
  5. Final stack value is the answer.
Postfix: 23*4+
Evaluation: 2×3=6, then 6+4=10.

14. Bottom-Up Evaluation of S-Attributed Definitions 14 Marks

Bottom-up evaluation computes synthesized attributes during reductions in a shift-reduce parser.

Basic Principle

When a production A → XYZ is reduced, attributes of X, Y and Z are already available on the parsing stack. These values are used to calculate attributes of A.

Attribute Stack

State Stack: 0 X i Y j Attribute Stack: X.val Y.val

Example

Production: E → E1 + T Semantic Rule: E.val = E1.val + T.val During reduction: Pop E1.val, '+', T.val Compute E.val Push E.val with non-terminal E

Implementation with YACC-Style Actions

E : E '+' T { $$ = $1 + $3; } | T { $$ = $1; } ; T : NUM { $$ = $1; } ;

Notation

  • $$: attribute of production head.
  • $1, $2, $3: attributes of body symbols.

Advantages

  • Natural with LR parsing.
  • Attributes are evaluated at reduction time.
  • No separate parse-tree traversal is required.
  • Efficient for expression evaluation and code generation.

Limitation

Direct bottom-up evaluation is simplest for S-attributed definitions. Inherited attributes require special transformations or stack management.

15. Important Comparisons 14 Marks

Synthesized vs Inherited Attributes

BasisSynthesizedInherited
Computed fromChildrenParent or siblings
DirectionUpwardDownward or sideways
Natural parserBottom-upTop-down
ExampleExpression valueDeclared type

SDD vs Translation Scheme

BasisSDDTranslation Scheme
FormGrammar plus semantic rulesGrammar with embedded actions
NatureDeclarativeImplementation oriented
OrderDerived from dependenciesInfluenced by action position

Unit 3 Quick Revision

  • Syntax-directed translation associates semantic processing with grammar productions.
  • An SDD contains grammar, attributes and semantic rules.
  • Synthesized attributes flow upward.
  • Inherited attributes receive information from parent or siblings.
  • S-attributed definitions use only synthesized attributes.
  • L-attributed definitions permit restricted inherited attributes.
  • Dependency graphs determine attribute evaluation order.
  • Syntax trees provide compact program representation.
  • Postfix notation places operators after operands.
  • Bottom-up parsers evaluate synthesized attributes during reductions.

Important RGPV Exam Questions

Long Answer Questions

  1. Define syntax-directed translation and explain its applications.
  2. Explain syntax-directed definitions with an example.
  3. Explain synthesized and inherited attributes with suitable examples.
  4. Explain S-attributed definitions and their evaluation.
  5. Explain L-attributed definitions and their restrictions.
  6. Compare S-attributed and L-attributed definitions.
  7. Explain dependency graph construction and attribute evaluation order.
  8. Explain construction of syntax trees using semantic rules.
  9. Differentiate between parse tree, syntax tree and DAG.
  10. Explain top-down translation with an example.
  11. Explain conversion of infix expressions to postfix notation using syntax-directed translation.
  12. Explain bottom-up evaluation of S-attributed definitions.
  13. Explain attribute-stack implementation in a shift-reduce parser.

Short Answer Questions

  1. Define an attribute grammar.
  2. What is a synthesized attribute?
  3. What is an inherited attribute?
  4. Define S-attributed SDD.
  5. Define L-attributed SDD.
  6. What is a dependency graph?
  7. What is a circular SDD?
  8. Define annotated parse tree.
  9. What is postfix notation?
  10. What does $$ represent in YACC?
Exam Strategy: Attribute questions should include a production, semantic rules, information-flow diagram, annotated tree or dependency graph and a final comparison table.

Download Study Resources

Unit 3 PDF

Printable detailed notes will be uploaded soon.

Coming Soon

Attribute Problems

Practice questions will be available soon.

Coming Soon

PYQ Analysis

Repeated Unit 3 questions will be added soon.

Coming Soon

Frequently Asked Questions

It is a translation method in which semantic actions or attribute rules are associated with grammar productions.
Only synthesized attributes are used.
They support restricted inherited attributes and can be evaluated in a left-to-right traversal, making them suitable for top-down translation.
An edge X to Y means that attribute Y depends on attribute X and X must be evaluated first.
It removes the need for parentheses and explicit precedence during stack-based evaluation.