Syntax-directed translation
Syntax-directed translation: using grammar-linked attributes and semantic actions to translate source programs into intermediate code, values or other representations during parsing.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Syntax-directed translation is how compilers and many system tools attach meaning to source code as they parse its structure. An engineer uses it when implementing the semantic phase of a compiler (intermediate code generation, type checking, name resolution) and when adding features to parsers such as automatic code-generation in assemblers, linkers or interpreters.
Key ideas
Attribute — a named value associated with a grammar symbol in a parse tree node. Attributes may store types, values, code, addresses, etc. Definition: if X is a grammar symbol, then attributes(X) = {a1, a2, ...}. Attributes are evaluated per parse tree node.
Synthesized attribute — an attribute whose value at a node is computed from the attribute values of its children (and token values at leaf children). Exact: For node N with production N -> X1 X2 ... Xk, attribute s of N is synthesized if its semantic rule uses only attributes of X1..Xk and token values at those children.
Inherited attribute — an attribute whose value at a node is computed from attributes of the parent or siblings (left or right, depending on grammar). Exact: For node Ni (a child in production P: A -> X1...Xn), an attribute h of Xi is inherited if its semantic rule depends on attributes of A (the parent) and/or attributes of Xj for j != i.
S-attributed SDD — an SDD that uses only synthesized attributes. These are easy to evaluate bottom-up: evaluate children before parent. Exact property: every attribute in the SDD is synthesized.
L-attributed SDD — an SDD where, for a production A -> X1 X2 ... Xn, each inherited attribute of Xi depends only on attributes of A and/or attributes of X1..X(i-1) (left side). Exact property used to allow single left-to-right evaluation during top-down parsing or when scanning an RHS left to right in bottom-up parsers with embedded actions. Typical use: propagate context such as declared types or environments down the tree; e.g., in a declaration grammar D -> T L, set L.inh = T.type so identifiers in L inherit the declared type.
Translation scheme (SDT) — semantic actions are placed at specific positions in the right-hand side of productions. Exact: An SDT is written by inserting executable actions (in braces, e.g., { action }) into productions; actions execute when the parser recognizes them during a parse (the precise time depends on parser type).
Semantic action — a piece of code or instruction (e.g., emit a TAC) inserted into a grammar production. In a top-down parser the action executes when its position is reached in left-to-right derivation; in bottom-up parsing it must be placed so that action executes when needed (usually encoded as a new nonterminal or executed on reduce).
Dependency graph and evaluation order — for a given parse tree and SDD, construct a directed graph whose nodes are attribute occurrences and edges show dependence (u -> v if v depends on u). Exact rule: attributes can be evaluated iff the dependency graph has no directed cycle; a valid evaluation order is any topological ordering of this graph.
How to integrate with parsing methods: Reference to other topics — lexical analysis provides tokens, parsing (top-down or bottom-up) recognises structure and triggers SDT actions; intermediate code generation and optimisations connect to SDT for producing code that later phases will optimise.
Describe the diagram to draw for an exam: draw a parse tree for the expression grammar. Nodes: label each internal node with its nonterminal (E, T, F). At each node draw small boxes to the right labelled with attributes (e.g., val, code). Draw directed arrows from child attributes used in semantic rules to the parent attribute they compute. This is the dependency graph on the parse tree.
Formulas
Syntax / snippets to remember (each on its own line):
Production with semantic rules: A -> X1 X2 ... Xn { A.attr = f(X1.attr1, X3.attr2, token.val) }
- A.attr: attribute of nonterminal A
- Xi.attrj: attribute of child Xi
- token.val: lexeme or token semantic value provided by lexer
- Applies to SDDs (semantic rules) and SDTs (translation schemes with embedded actions).
Synthesized-only (S-attributed) form: A -> X1 X2 ... Xn { A.s = g(X1.s, X2.s, ...) }
- Use for bottom-up evaluation.
L-attributed left-to-right rule: for i from 1 to n compute inherited attributes of Xi using attributes of A and X1..X(i-1), then compute synthesized attributes. Do not use attributes of right siblings Xj for j>i.
- Use for top-down or single-pass left-to-right evaluation.
Dependency graph evaluation: if graph G has nodes = attribute occurrences and edges u->v for 'v depends on u', then any topological sort of G gives a safe evaluation order if and only if G is acyclic.
Worked examples
Example 1 — compute value and postfix for expression a + b * c using an S-attributed SDT.
Grammar: E -> E + T | T T -> T * F | F F -> id
Semantic rules (S-attributed):
- For production E -> E1 + T: E.val = E1.val + T.val; E.post = E1.post T.post "+"
- E -> T: E.val = T.val; E.post = T.post
- T -> T1 * F: T.val = T1.val * F.val; T.post = T1.post F.post "*"
- T -> F: T.val = F.val; T.post = F.post
- F -> id: F.val = value(id); F.post = id
Input tokens with values (from symbol table): a=2, b=3, c=4
Steps (parse and evaluate bottom-up):
- Recognise F -> id("a"); compute F.val = 2; F.post = "a".
- Reduce T -> F; T.val = 2; T.post = "a".
- For RHS T * F for b * c, similarly compute F(b) -> 3, F(c) -> 4, T(bc). But full derivation yields overall tree where subtree for bc gives T.post = "b c *" and T.val = 12.
- Now E -> E + T reduces with left E.val = 2, right T.val = 12 -> E.val = 14.
- Postfix computed as E.post = "a b c * +".
Final answers: value = 14, postfix = a b c * +.
Example 2 — produce three-address code (TAC) using an SDT with synthesized attributes (no inherited attributes needed).
Grammar (simplified): S -> E E -> E + T | T T -> T * F | F F -> id
We want to generate TAC with temporary names using a synthesized attribute place. Use semantic actions that allocate a temp and emit code after children.
Translation scheme (embedded actions): E -> E1 + T { E.place = newtemp(); emit(E.place "=" E1.place "+" T.place) } E -> T { E.place = T.place } T -> T1 * F { T.place = newtemp(); emit(T.place "=" T1.place "*" F.place) } T -> F { T.place = F.place } F -> id { F.place = id }
Trace for a + b * c: 0. F -> id(a) => F.place = a
- F -> id(b) => F.place = b
- T -> T1 * F: T1.place = b, F.place = c => create t1 = b * c; emit: t1 = b * c; T.place = t1
- E -> E1 + T: E1.place = a, T.place = t1 => create t2 = a + t1; emit: t2 = a + t1; E.place = t2
Emitted TAC (in order):
- t1 = b * c
- t2 = a + t1
Example 3 — dependency graph and topological order (short)
Given production A -> B C with semantic rules: B.x = A.y + 1; C.z = B.x * 2; A.w = C.z - 3.
Build nodes: A.y (assumed given), B.x, C.z, A.w. Edges: A.y -> B.x; B.x -> C.z; C.z -> A.w. Graph is linear; topological order: A.y, B.x, C.z, A.w. Evaluate in that order.
Common mistakes
- Assuming every SDD is L-attributed: not true. Check the L-attributed condition (inherited attributes of Xi only depend on A and X1..X(i-1)).
- Putting semantic actions at the wrong positions for bottom-up parsers: in LR parsing actions must appear at points that are executed on reduce; embedding actions naively can make attributes unavailable at action time.
- Circular dependencies in semantic rules: forget to check for cycles in the dependency graph.
- Not distinguishing token values (from lexer) and attributes: token semantic values (like numeric literal value) must be treated as leaf attributes.
For your exam
Types of questions you will see:
- Definitions and short notes: define SDT, SDD, synthesized/inherited attributes, S-attributed, L-attributed. A full-marks answer gives the formal property (see Key ideas), an example and why it matters.
- Derivation/evaluation questions: given an SDD and a parse tree, draw dependency graph and give a valid evaluation order. Full answer: draw graph with nodes as attribute occurrences, show edges for dependencies, check acyclicity, give a topological ordering.
- Translation-scheme/programming questions: write semantic actions to generate postfix or three-address code for an expression grammar. Full answer: show grammar, semantic rules or embedded actions, and trace on an example input producing final code and temporaries.
- Algorithm question: describe topological sort on dependency graph or prove when S-attributed and L-attributed SDDs are single-pass. Full answer: state algorithm, complexity O(V+E), and link to parser type (bottom-up/top-down).
- Diagram question: draw parse tree with attribute boxes and dependency arrows (describe exactly what you draw). Full answer: properly labelled nodes, attributes, edges and final evaluation order.
What full-marks answers must include: exact definitions (use terms above), explicit semantic rules or actions, step-by-step evaluation trace with intermediate values/temps, and a dependency graph if evaluation order is relevant. If generating code, show emitted code lines in the order they are produced.
Quick check
- What is a synthesized attribute?
- State the L-attributed condition in one sentence.
- Why are S-attributed SDDs easy to implement with bottom-up parsers?
Answers: 1) An attribute computed from values of a node's children (and token values at leaves), 2) In a production A -> X1..Xn, each inherited attribute of Xi may depend only on attributes of A and X1..X(i-1), 3) Because synthesized attributes depend only on children so evaluating them after reducing a production (children known) gives a single natural bottom-up order.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?