Programming Languages · Language Design and Translation
Syntax and Stages of Translation
Overview
This lesson covers how a programming language’s syntax is specified and how a source program is translated into a target program.
Syntax is described by grammars such as BNF, EBNF and syntax diagrams; the parser uses a context-free grammar to check structure and build a parse tree or AST. Translation proceeds through standard compiler phases: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, optimisation and code generation.
You need prior familiarity with sets, strings, formal languages, regular expressions, finite automata and basic compiler terminology.
Key concepts
- Syntax is the form of programs; semantics is meaning. A grammar specifies syntax, not meaning.
- BNF (Backus–Naur Form) is a metalanguage for describing the syntax of programming languages. A production is conventionally written
nonterminal ::= expression;→and->are common shorthand. Alternation is written with|. - EBNF (Extended BNF) adds convenience notation: optional part in
[ ], repetition in{ }, grouping in( ), and sometimes?for optional and*for zero-or-more. - A syntax diagram is a graphical alternative to BNF/EBNF: terminals are shown in ovals/circles, nonterminals in rectangles, sequence is read left-to-right, and alternatives branch.
- A context-free grammar (CFG) has productions
A → α, whereAis a nonterminal andαis a string of terminals and nonterminals.
CFGs are Type 2 in the Chomsky hierarchy and are exactly the languages recognised by a pushdown automaton (PDA). CFG is the standard model for programming-language syntax. - A derivation starts from the start symbol and repeatedly replaces nonterminals by production right sides.
A leftmost derivation always expands the leftmost nonterminal; a rightmost derivation always expands the rightmost. - A parse tree records the same information structurally: root is the start symbol, internal nodes are nonterminals, leaves are terminals, and children of a node are the right side of the production used.
- A grammar is ambiguous if some string has more than one parse tree, equivalently more than one leftmost derivation.
Ambiguity is a property of a grammar; a language may have an unambiguous grammar even if one grammar for it is ambiguous. An inherently ambiguous language has no unambiguous grammar at all. - A grammar is left-recursive if it has
A ⇒+ A α; direct left recursion isA → A α | β. This can loop a top-down parser. Elimination:A → β A',A' → α A' | ε. - Left factoring removes common prefixes:
A → α β1 | α β2becomesA → α A',A' → β1 | β2. - An LL(1) grammar can be parsed by a predictive parser with one lookahead token. It must be unambiguous, have no left recursion, and for each
A → α | β,FIRST(α) ∩ FIRST(β) = ∅, with the usual ε/FOLLOW condition. - Chomsky Normal Form (CNF): every production is
A → BCorA → a; the only allowed ε-production isS → εwhen ε is in the language. - Regular grammar and regular expression describe Type 3 regular languages, recognised by a finite automaton. Every regular language is context-free, but not every context-free language is regular.
- Lexical analysis converts characters into a token stream. The parser receives tokens such as
<id, ifx>,<relop, <=>. The symbol table stores identifiers and attributes and is used throughout translation. - Maximal munch: the lexer takes the longest possible token. Reserved words such as
ifare keywords, not identifiers, when the lexeme is exactly the keyword.
How it works
Translation pipeline. Standard compilation phases run in this order:
- Lexical analysis: scans characters, removes whitespace/comments, applies token patterns, and sends tokens to the parser. It may insert identifiers into the symbol table.
- Syntax analysis: parser checks the token stream against the CFG and builds a parse tree or abstract syntax tree. Syntax errors are reported here.
- Semantic analysis: checks types, scope, declarations and other static rules; constructs and consults the symbol table heavily. This phase immediately follows syntax analysis in the standard pipeline.
- Intermediate code generation: produces a machine-independent representation such as three-address code.
- Optimization: improves the intermediate code without changing meaning.
- Code generation: produces target machine code.
Grammar and ambiguity procedure.
- Write the grammar and choose a string.
- Try all legal leftmost derivations, or build all parse trees.
- If exactly one parse tree exists, the string is unambiguous in that grammar.
- If some string has two or more parse trees, the grammar is ambiguous.
- For
S → S S | a, every stringa^nwithn ≥ 1is generated, and the number of parse trees is the Catalan numberC_{n-1}.
LL parsing preparation.
- Remove left recursion.
- Apply left factoring to remove common prefixes.
- Compute FIRST and FOLLOW sets.
- Build the predictive parsing table; conflicts mean the grammar is not LL(1).
Drawing the diagram…
Formulas
-
For the ambiguous grammar
S → S S | a, the number of distinct parse trees fora^n,n ≥ 1, is
-
where
C_0=1. ThusaaahasC_2=2trees andaaaahasC_3=5trees. -
Left recursion elimination:
-
Left factoring:
-
CNF production forms:
-
plus
S → εonly ifεis in the language. -
LL(1) condition for
A → α | β: -
and if
α ⇒* ε, thenFIRST(β) ∩ FOLLOW(A) = ∅.
Worked examples
Example 1: Maximal munch. A lexer has identifier pattern [a-z][a-z0-9]*, keyword if reserved, and <= as one relational token. Tokenise ifx<=y.
- At the start, identifier can match
ifxof length 3; keywordifhas length 2. Maximal munch choosesifx. Sinceifxis not the reserved wordif, it is an identifier. - Next characters are
<=, one token. - Then
yis an identifier.
Answer:id(ifx),<=,id(y). Forif<=x, the first lexeme is exactlyif, so it is the keywordif, then<=, thenid(x).
Example 2: Counting parse trees. For S → S S | a, how many parse trees does aaaa have?
Here n=4, so the count is C_{3} = (1/4)·binom(6,3) = 20/4 = 5. The five parenthesised structures are (((aa)a)a), ((a(aa))a), ((aa)(aa)), (a((aa)a)), (a(a(aa))). Answer: 5.
Example 3: Ambiguity check. Take S → S S | a S b | ε and the string ab. One tree uses S → a S b with the inner S → ε. Another uses S → S S, giving the first S as a S b (inner S → ε) and the second S as ε.
Two distinct parse trees for one string, so the grammar is ambiguous.
Be careful with the look-alike S → a S b S | b S a S | ε: it generates the same strings (equal numbers of a and b) but is unambiguous, because in a S b S the matching b is always the one where the running count of a minus b first returns to zero.
Example 4: Unambiguous language. For S → a S b | ε, the language is {a^n b^n | n ≥ 0}. Each string has exactly one derivation: match the first a with the last b, then recurse inside. Thus the grammar is unambiguous.
The language is not regular; by the pumping lemma, pumping a string a^p b^p inside its initial a-block changes the number of as but not bs.
Example 5: CNF check. S → A B, A → a, B → b is in CNF. S → a B is not CNF because a terminal and nonterminal are mixed. S → A is not CNF because it is a unit production. S → A B C is not CNF because the right side has three nonterminals.
Comparison
| Concept | Meaning | Exam point |
|---|---|---|
| BNF | Text grammar with productions such as A ::= α | Describes syntax; ` |
| EBNF | BNF plus [optional], {repetition}, (grouping) | Optional part is inside square brackets |
| Syntax diagram | Graphical grammar notation | Equivalent to BNF/EBNF; terminals in ovals |
| Phase | Input | Output | Main job |
|---|---|---|---|
| Lexical analysis | Characters | Tokens | Longest-match tokenisation |
| Syntax analysis | Tokens | Parse tree/AST | Checks CFG structure |
| Semantic analysis | Parse tree/AST | Annotated tree | Type checking, symbol table |
| Intermediate code | Annotated tree | IR | Machine-independent code |
| Code generation | IR | Target code | Machine instructions |
| Term | Definition | Trap |
|---|---|---|
| Ambiguous grammar | Some string has two parse trees | Not the same as inherently ambiguous language |
| Unambiguous grammar | Every string has one parse tree | Grammar property, not language property |
| Inherently ambiguous language | Every grammar for it is ambiguous | Rare; do not infer from one ambiguous grammar |
| Left-recursive grammar | A ⇒+ A α | Needs elimination for top-down parsing |
| Left-factored grammar | Common prefixes removed | Helps predictive parsing |
| LL(1) grammar | One lookahead, no conflicts | Must be unambiguous and non-left-recursive |
Revision summary
- BNF describes syntax; semantics is separate.
- BNF production symbol is conventionally
::=. - EBNF optional is
[ ]; repetition is{ }. - CFG is Type 2, recognised by PDA, and is the standard model for PL syntax.
- Translation order: lexical → syntax → semantic → intermediate → optimisation → code generation.
- Lexer output is a token stream; parser output is parse tree/AST.
- Semantic analysis follows syntax analysis and heavily uses the symbol table.
- Ambiguity means two parse trees for one string.
S → S S | ais ambiguous;a^nhas CatalanC_{n-1}parse trees.S → a S b | εis unambiguous and generatesa^n b^n, which is not regular.- CNF allows
A → BC,A → a, andS → εonly if needed. - Maximal munch: longest token wins; keyword
ifbeats identifier only for exact lexemeif.
Previous-year exam insights
- Direct questions ask what BNF/EBNF describes, what
[ ]means in EBNF, and the production symbol in BNF. - Order questions ask the first translation phase and the phase immediately after syntax analysis; lexical analysis is first, semantic analysis follows syntax analysis.
- Output questions ask what the lexer passes to the parser: a token stream, not a parse tree.
- Grammar-class questions ask which class is recognised by a PDA and is standard for PL syntax: context-free grammar.
- Statement I/II/III questions test ambiguity, regularity, unambiguity and whether an ambiguous grammar implies an inherently ambiguous language.
- Match-the-list questions pair left recursion, left factoring, LL(1) and ambiguity with their parsing consequences.
- Numeric questions count parse trees for
S → S S | a, often foraaaoraaaa, using Catalan numbers. - Tokenisation questions test maximal munch, reserved words and relational operators such as
<=. - CNF questions test whether productions are binary nonterminal, terminal, or illegal mixed/unit/ternary forms.
- Common traps: confusing lexical and syntax phases; confusing grammar ambiguity with language ambiguity; mixing left recursion with left factoring; forgetting the ε exception in CNF.
Practice at PARIKSHA
You are ready for the PARIKSHA tests of this sub-topic when you can:
- Define BNF, EBNF and syntax diagrams, and identify optional and repetition notation.
- List compiler phases in order and state the input and output of each phase.
- Explain why lexical analysis comes first and what token stream the parser receives.
- Apply maximal munch with reserved words to tokenise a short string.
- Decide whether a grammar is ambiguous and justify with two parse trees or leftmost derivations.
- Count parse trees for
S → S S | ausing the Catalan formula. - Recognise unambiguous grammars such as
S → a S b | εandS → a S a | a. - Eliminate left recursion and apply left factoring to a given grammar.
- Test whether a grammar is in CNF and identify the grammar class recognised by a PDA.
- Match grammar properties such as left recursion, left factoring and LL(1) with their parsing consequences.
Attempt the sub-topic test first, then the subject test.