1. Gyanastra
  2. Compiler Design
  3. Grammars and Ambiguity
  4. Context-Free Grammar and Constructing the Parse Tree
Free lesson, no account needed 10 min read 11 practice questions after it
Asked in past papers18 times
  • GATE CSE2024201620082004199519941993
  • ISRO20182014
  • UGC NET201820172015201420132010200920082006

Compiler Design · Grammars and Ambiguity

Context-Free Grammar and Constructing the Parse Tree

Overview

A context-free grammar (CFG) is the formalism used to describe the syntax of a programming language, and the parser (syntax analyzer) checks an input token stream against it by building a parse tree.
The parse tree then drives the later compiler phases — semantic analysis, intermediate code generation, optimization, and target code generation — so understanding how the tree is constructed explains both error detection and the structure of the back end.

Key concepts

  • Context-free grammar (CFG): the formalism used to describe the syntax of a programming language.
    The entire set of rules of a programming language can be represented in a small number of productions (rules); typically every programming language has a few hundred productions, and using these rules we can represent what a program actually is.
  • Syntax analyzer (parser): the phase that matches the program (input token stream) against the grammar rules, i.e. checks whether the input is given according to the required format. It constructs a parse tree.
  • Start symbol S: construction of the parse tree starts from S.
  • Yield of the parse tree: the tokens read left to right from the leaves.
    The yield and the input to the syntax analyzer must be the same; if they match, the input is according to the given format, otherwise there is a syntax error. Syntax errors are therefore detected at the syntax analyzer when the input is not according to the given grammar.
  • Output of the syntax analyzer: a parse tree, which is passed to the next phase, the semantic analyzer.
  • Semantic analyzer: takes the parse tree and verifies it semantically — whether it is meaningful or not. For identifier = something, the left-hand side must be a variable; it cannot be a constant, a function name, or an array name.
    The left-hand side must be a variable whose type is compatible with the type of the right-hand side. All such type checkings are done here. Its output is a semantically verified parse tree.
  • Intermediate code generator: takes the semantically verified parse tree and generates intermediate code.
    The most popular kind is three-address code, called so because in any line there are only three addresses (at most three; it can be fewer).
  • Four-address statement: a statement such as X = A + B * C; it is reduced into three addresses to form three-address code.
  • Code optimizer: takes the intermediate code and reduces the number of lines.
  • Target code generator: its main purpose is to write code that the assembler can understand.
    The assembler is a phase after the compiler and depends on the platform, so depending on which assembler is used, the target code generator has to produce that kind of code.
  • Platform independence: up to the intermediate code generator, the part is completely the same regardless of the machine the compiler runs on. Only the last two phases are platform-dependent.
Figure. The root S expands to id = E ; and E splits into E + T, with T multiplying two factors. Reading the leaves left to right gives the input token stream, so the input is accepted.

How it works

  1. The input token stream is matched against the grammar rules by the syntax analyzer (parser).
  2. The parser constructs the parse tree starting from the start symbol S, expanding productions until the leaves are tokens.
  3. The yield of the parse tree (leaves left to right) is compared with the input token stream. If they match, the input is according to the given format; otherwise there is a syntax error.
  4. The parse tree is passed to the semantic analyzer, which verifies meaning and types and outputs a semantically verified parse tree.
  5. The intermediate code generator converts the verified tree into intermediate code (typically three-address code).
  6. The code optimizer reduces the number of lines of intermediate code.
  7. The target code generator produces code the assembler can understand, depending on the platform's assembler.

Why convert to intermediate code? If a program can be converted into intermediate code, that intermediate code can be converted to machine language using the last two phases, which are platform-dependent.
To design a compiler for a new platform you need not start from scratch: take all the phases up to the intermediate code generator and change only the last two phases.
For example, if the existing compiler produces code that runs on a computer and you want code that runs on a mobile phone, just change the last two phases — you need not change everything.

In practice: theoretically this is what all the phases are supposed to do, but when it comes to the implementation of compilers, the phases are not really all separate — most of the jobs/functions are done by the syntax analyzer itself.

Formulas

  • Grammar of the running example:
S -> id = E ;
E -> E + T | T
T -> T * F | F
F -> id
  • A statement (S) can be: identifier, equal to, expression, followed by semicolon.

  • An expression (E) can be: expression plus term, or just a term.

  • A term (T) can be: term into (times) factor, or just a factor.

  • A factor (F) can be simply an identifier.

  • Three-address code form (at most three addresses per line):

T1 = B * C
T2 = A + T1
X  = T2

Worked examples

Example 1: Parse tree for id = id + id * id ;

Derivation (top-down, starting from S):

  1. S ⇒ id = E ;
  2. E ⇒ E + T
  3. T ⇒ T * F
  4. F ⇒ id (for the last factor)
  5. T ⇒ F ⇒ id (for the middle term)
  6. F ⇒ id (for the first factor)

Parse tree described in words:

  • Root: S
  • S has four children: id, =, E, ;
  • The E node has three children: E, +, T
    • The left E has one child T, which has one child F, which has one child id
    • The right T has three children: T, *, F
      • The left T has one child F, which has one child id
      • The right F has one child id

Yield of the parse tree (leaves left to right): id = id + id * id ; — this equals the input token stream, so the input is accepted (no syntax error).

Example 2: Three-address code and its optimization

Statement: X = A + B * C (a four-address statement).

Before optimization (three-address code, 3 lines):

T1 = B * C
T2 = A + T1
X  = T2

These lines multiply B and C and put the result in T1; add A to T1 and put it in T2; write T2 into X.

After code optimization (2 lines):

T1 = B * C
X  = A + T1

Optimization used: eliminating the redundant temporary T2 (copy propagation / reduction in the number of lines).

Example 3: Target code generation

Registers: R0 = A, R1 = B, R2 = C. This is just an example — it need not be the same for all compilers.

MUL R1, R2     ; R2 = B * C
ADD R0, R2     ; R2 = A + (B * C)
MOV R2, X      ; X = R2
  • Multiply R1 and R2, store the result in R2 (so R2 contains B * C).
  • Add R0 to R2 (because T2 is nothing but adding R0 to R2).
  • Move everything into X (X = A + T1, then move into X).

Comparison

PhaseInputOutputJob
Syntax analyzer (parser)Token streamParse treeChecks input against grammar; detects syntax errors; yield of parse tree must equal input
Semantic analyzerParse treeSemantically verified parse treeMeaningfulness and type checking (e.g., LHS of = must be a variable compatible with RHS type)
Intermediate code generatorSemantically verified parse treeIntermediate code (e.g., three-address code)Converts to platform-independent intermediate form
Code optimizerIntermediate codeReduced intermediate codeReduces the number of lines
Target code generatorOptimized intermediate codeAssembly-level codeProduces code the assembler can understand (platform-dependent)

Revision summary

  • The yield of the parse tree must equal the input token stream; otherwise it is a syntax error.
  • Syntax errors are detected at the syntax analyzer; semantic (type/meaning) errors at the semantic analyzer.
  • The LHS of an assignment must be a variable — not a constant, a function name, or an array name — and its type must be compatible with the RHS type.
  • Three-address code has at most three addresses per line (it can be fewer); a four-address statement is reduced to three addresses.
  • All phases up to the intermediate code generator are platform-independent; only the last two phases are platform-dependent, so a compiler for a new platform is made by changing only the last two phases.
  • The target code generator must match the platform's assembler, since the assembler is a separate, platform-dependent phase after the compiler.
  • In practice, most of these jobs are done by the syntax analyzer itself rather than as separate phases.

Previous-year exam insights

  • A grammar is context-free iff every production has a single non-terminal on the left-hand side (form A → α, A ∈ N, α ∈ (N ∪ T)*); grammars with |LHS| > 1 or a terminal on the LHS are context-sensitive/unrestricted, not context-free.
    Asked inUGC NET 2015
  • The class of context-free languages is closed under union, concatenation, Kleene star and homomorphism, but NOT closed under intersection or complementation.
    Asked inISRO 2018UGC NET 2017
  • Lexical analysis is specified by regular expressions and implemented by finite automata; syntax analysis is specified by context-free grammars and implemented by pushdown automata.
    Pushdown automata recognize exactly the context-free languages (which include the regular languages).
    Asked inUGC NET 2017UGC NET 2018
  • In Chomsky Normal Form (all productions A → BC or A → a), any derivation of a terminal string of length x uses exactly 2x − 1 productions (x − 1 binary productions plus x unit/terminal productions).
    Asked inISRO 2018
  • To decide whether a given string is generated by a CFG, and to count the number of distinct parse trees (derivations) for it, apply the productions step by step from the start symbol; the number of parse trees equals the number of distinct leftmost derivations, and an ambiguous grammar yields more than one.
    Asked inGATE 2008
  • A CFG can generate regular languages too: a grammar whose non-terminals can derive arbitrary strings on both sides of a fixed subword (e.g. X → aX | bX | λ used on both sides of a fixed string) generates the language of all strings containing that subword, i.e. (a+b)* w (a+b)*.
    Asked inUGC NET 2015
Pages 1–2 of 2