1. Gyanastra
  2. Artificial Intelligence
  3. Natural Language Processing
  4. Grammar Language and Parsing
Free lesson, no account needed 14 min read 24 practice questions after it

Artificial Intelligence · Natural Language Processing

Grammar Language and Parsing

Overview

Syntactic analysis is the stage of Natural Language Processing that decides which word sequences are well formed and what structure they carry. A grammar is the finite specification of that structure; a parser is the algorithm that recovers it from a sentence.
This lesson sits in the Artificial Intelligence chapter under NLP, immediately after tokenization and part-of-speech tagging and immediately before semantic analysis.
It draws on context-free languages, derivations and automata from Theory of Computation, so you must be comfortable with strings, alphabets, sets and productions before starting.
Everything here is textbook-standard: Chomsky hierarchy, context-free grammars, CYK/Earley chart parsing, and the classic top-down versus bottom-up parser families.

Key concepts

  • Language: a set of strings over an alphabet Σ\Sigma; Σ∗\Sigma^{*} denotes all finite strings including ε\varepsilon.
  • Formal grammar: a 4-tuple G=(V,T,P,S)G = (V, T, P, S) — VV = nonterminals (variables), TT = terminals, PP = productions, S∈VS \in V = start symbol. The language generated is L(G)={w∈T∗∣S⇒∗w}L(G) = \{w \in T^{*} \mid S \Rightarrow^{*} w\}.
  • Chomsky hierarchy (four classes, in decreasing power):
    • Type 0 — Unrestricted / phrase-structure: α→β\alpha \to \beta, α\alpha contains at least one nonterminal; recognised by a Turing machine.
    • Type 1 — Context-sensitive: αAβ→αγβ\alpha A \beta \to \alpha \gamma \beta with γ≠ε\gamma \neq \varepsilon; recognised by a linear-bounded automaton.
    • Type 2 — Context-free (CFG): single nonterminal on the left, A→γA \to \gamma; recognised by a pushdown automaton.
    • Type 3 — Regular: A→aBA \to aB or A→aA \to a (right-linear); recognised by a finite automaton.
  • CFG is the standard syntax formalism for natural language. It is the weakest class that can express recursion and centre-embedding (nested phrases); regular grammars cannot count nesting.
    CFG is also the workhorse for programming-language syntax.
  • Derivation: a sequence S⇒α1⇒α2⇒⋯⇒wS \Rightarrow \alpha_1 \Rightarrow \alpha_2 \Rightarrow \cdots \Rightarrow w. Leftmost derivation always expands the leftmost nonterminal; rightmost the rightmost.
    Intermediate strings are sentential forms; a sentential form containing only terminals is a sentence.
  • Parse tree (derivation tree): root =S= S, internal nodes == nonterminals, leaves == terminals read left to right. A leftmost derivation and its parse tree correspond one-to-one.
  • Ambiguity: a grammar is ambiguous if some string has two distinct parse trees (equivalently, two distinct leftmost derivations).
    Ambiguity is a property of the grammar; a language is inherently ambiguous if every grammar for it is ambiguous.
  • Structural / attachment ambiguity in NLP: "I saw the student with a telescope" — the prepositional phrase may attach to the verb or to the noun. Same word string, two trees, one grammar.
  • Chomsky Normal Form (CNF): every production is A→BCA \to BC (exactly two nonterminals) or A→aA \to a (one terminal); optionally S→εS \to \varepsilon if ε∈L(G)\varepsilon \in L(G). Required by CYK.
  • Greibach Normal Form (GNF): every production is A→aαA \to a\alpha — one terminal first, then any number of nonterminals.
  • Left recursion: A⇒+AαA \Rightarrow^{+} A\alpha — immediate form A→Aα∣βA \to A\alpha \mid \beta; also indirect via other nonterminals. Fatal to naive recursive-descent parsers (infinite loop).
  • Left factoring: rewriting A→αβ1∣αβ2A \to \alpha\beta_1 \mid \alpha\beta_2 as A→αA′A \to \alpha A', A′→β1∣β2A' \to \beta_1 \mid \beta_2. It removes a common prefix (nondeterminism), not left recursion.
  • Top-down parsing: starts at SS, expands nonterminals until the input is derived — recursive descent, predictive / LL(1) parsing.
  • Bottom-up parsing: starts at the input, reduces substrings to nonterminals until SS is reached — shift-reduce, LR(1), SLR, LALR.
  • Chart parsing: store every completed constituent in a table indexed by the span (i,j)(i,j) so a substring already parsed is never re-parsed. CYK and Earley are chart parsers; they handle ambiguity without exponential blow-up.
  • Augmented Transition Network (ATN): a directed network of states and arcs labelled with words, categories or nonterminals, augmented with registers, conditions/tests on arcs and actions that build structure.
    It is a procedural, grammar-as-program style of parser used in early NL understanding systems.

How it works

1. Deriving a sentence from a grammar (top-down direction).

  1. Write the start symbol SS as the current sentential form.
  2. Pick a nonterminal in it and replace it by the right-hand side of one of its productions.
  3. Repeat until only terminals remain. If the terminal string equals the input, the sentence is generated.
  4. Record the choices — the record is the parse tree.

2. Recovering structure from a sentence (parsing). Top-down and bottom-up are mirror images:

3. Where parsing sits in the NLP pipeline:

4. CYK algorithm (bottom-up chart parsing, requires CNF).

  1. Let input be w1w2…wnw_1 w_2 \ldots w_n.
  2. Diagonal cells: fill (i,i)(i,i) with every nonterminal AA such that A→wiA \to w_i is a rule.
  3. For spans of length L=2L = 2 to nn: for each (i,j)(i,j) with j−i+1=Lj-i+1 = L, for every split kk from ii to j−1j-1, for every B∈(i,k)B \in (i,k) and C∈(k+1,j)C \in (k+1,j), add AA to (i,j)(i,j) if A→BCA \to BC exists.
  4. Accept iff S∈(1,n)S \in (1,n).
    Because every substring result is memoised, work on shared subproblems is never repeated — that is exactly how ambiguity is handled.

5. Earley algorithm (top-down chart parsing with a dotted item A→α∙β [i,j]A \to \alpha \bullet \beta\,[i,j]).

  1. Predictor: if the dot precedes nonterminal BB, add items B→∙γB \to \bullet\gamma starting at jj.
  2. Scanner: if the dot precedes terminal matching wj+1w_{j+1}, advance the dot into the next chart set.
  3. Completer: if the dot is at the end (item completed from ii to jj), advance every item in set ii that was waiting for that nonterminal.
    Accept iff an item S→α∙ [0,n]S \to \alpha\bullet\,[0,n] appears.

6. Removing left recursion (two steps): introduce a new nonterminal A′A'; A→βA′A \to \beta A' and A′→αA′∣εA' \to \alpha A' \mid \varepsilon. For indirect recursion, first substitute the offending nonterminal to make the recursion immediate, then eliminate.

7. Left factoring: pull the longest common prefix out into a new nonterminal and leave the alternatives as its right-hand sides.

8. Recursive-descent parsing with a code fragment: each nonterminal becomes a procedure; the procedure consumes one token per terminal in the chosen alternative.
Without left-factoring, the parser may pick the wrong alternative and cannot backtrack reliably; without removing left recursion, the procedure calls itself before consuming any token and loops forever.

Figure. Notice the symmetry: top-down expansion starts at S and ends at the input sentence, while bottom-up reduction starts from input words and ends at S.
Figure. Notice that syntactic parsing uses a grammar and produces one or more parse trees; these feed the later semantic analysis step.

Formulas

  • Language generated: L(G)={ w∈T∗∣S⇒∗w }L(G) = \{\, w \in T^{*} \mid S \Rightarrow^{*} w \,\}, where TT is the terminal alphabet.
  • Number of CYK table cells for input length nn: n(n+1)2\dfrac{n(n+1)}{2} (a triangular table; nn diagonal cells).
  • CYK time complexity: O(n3⋅∣G∣)O(n^{3}\cdot |G|); space O(n2⋅∣G∣)O(n^{2}\cdot |G|), where ∣G∣|G| is grammar size.
  • Earley complexity: O(n3)O(n^{3}) general CFG, O(n2)O(n^{2}) for unambiguous grammars, O(n)O(n) for deterministic (bounded-state) grammars.
  • Number of distinct full binary parse trees with nn leaves: Catalan number Cn−1=1n(2n−2n−1)C_{n-1} = \dfrac{1}{n}\dbinom{2n-2}{n-1} — the count that measures how badly ambiguity can explode.
  • Immediate left-recursion removal: A→Aα∣βA \to A\alpha \mid \beta becomes A→βA′A \to \beta A' and A′→αA′∣εA' \to \alpha A' \mid \varepsilon.
  • Left factoring: A→αβ1∣αβ2A \to \alpha\beta_1 \mid \alpha\beta_2 becomes A→αA′A \to \alpha A' and A′→β1∣β2A' \to \beta_1 \mid \beta_2.
  • LL(1) condition: for every nonterminal AA and distinct alternatives, FIRSTFIRST sets are disjoint, and if ε∈FIRST(A)\varepsilon \in FIRST(A) then FIRST(A)∩FOLLOW(A)=∅FIRST(A)\cap FOLLOW(A)=\varnothing.

Worked examples

Example 1 (easy). Grammar: S→NP VPS \to NP\ VP, NP→Det NNP \to Det\ N, VP→V NPVP \to V\ NP, Det→theDet \to the, N→dog∣catN \to dog \mid cat, V→chasedV \to chased. Parse "the dog chased the cat".

Step 1. S⇒NP VPS \Rightarrow NP\ VP.
Step 2. NP⇒Det N⇒the N⇒the dogNP \Rightarrow Det\ N \Rightarrow the\ N \Rightarrow the\ dog.
Step 3. VP⇒V NP⇒chased NP⇒chased Det N⇒chased the catVP \Rightarrow V\ NP \Rightarrow chased\ NP \Rightarrow chased\ Det\ N \Rightarrow chased\ the\ cat.
Step 4. Leftmost derivation: S⇒NP VP⇒Det N VP⇒the N VP⇒the dog VP⇒the dog V NP⇒the dog chased NP⇒the dog chased Det N⇒the dog chased the N⇒the dog chased the catS \Rightarrow NP\,VP \Rightarrow Det\,N\,VP \Rightarrow the\,N\,VP \Rightarrow the\,dog\,VP \Rightarrow the\,dog\,V\,NP \Rightarrow the\,dog\,chased\,NP \Rightarrow the\,dog\,chased\,Det\,N \Rightarrow the\,dog\,chased\,the\,N \Rightarrow the\,dog\,chased\,the\,cat.
Answer: the grammar derives the sentence; the parse tree has root SS, two children NPNP and VPVP, and the tree is unique for this string.

Example 2 (medium, CYK). Grammar in CNF: S→ABS \to AB, A→AA∣aA \to AA \mid a, B→bB \to b. Run CYK on "aab" (n=3n=3).

Cells to compute: n(n+1)/2=3⋅4/2=6n(n+1)/2 = 3\cdot4/2 = 6.

Span (i,j)(i,j)LengthContents
(1,1)1{A}\{A\} from A→aA\to a
(2,2)1{A}\{A\} from A→aA\to a
(3,3)1{B}\{B\} from B→bB\to b
(1,2)2split k=1k=1: A∈(1,1)A\in(1,1), A∈(2,2)A\in(2,2) gives AA (via A→AAA\to AA) → {A}\{A\}
(2,3)2split k=2k=2: A∈(2,2)A\in(2,2), B∈(3,3)B\in(3,3) — rule S→ABS\to AB applies → {S}\{S\} (the substring "ab" is itself an SS)
(1,3)3k=1k=1: A∈(1,1)A\in(1,1) and S∈(2,3)S\in(2,3) — no rule A SA\,S → nothing. k=2k=2: A∈(1,2)A\in(1,2), B∈(3,3)B\in(3,3) → SS via S→ABS\to AB → {S}\{S\}

Answer: S∈(1,3)S \in (1,3), so "aab" is accepted; 6 cells were computed.

Example 3 (medium, numeric). For input length n=4n=4, how many cells does CYK fill and what is the running time order?

Cells =4⋅5/2=10= 4\cdot5/2 = 10. Time =O(n3⋅∣G∣)= O(n^{3}\cdot|G|), i.e. O(64∣G∣)O(64|G|) for n=4n=4.
Answer: 10 cells; cubic time.

Example 4 (hard, two-step: left recursion then left factoring). Take the classic expression grammar E→E+T∣TE \to E+T \mid T, T→T∗F∣FT \to T*F \mid F, F→(E)∣idF \to (E) \mid id.

Step 1 — remove immediate left recursion from EE: α=+T\alpha = +T, β=T\beta = T. Gives E→T E′E \to T\,E', E′→+T E′∣εE' \to +T\,E' \mid \varepsilon.
Step 2 — remove from TT: α=∗F\alpha = *F, β=F\beta = F. Gives T→F T′T \to F\,T', T′→∗F T′∣εT' \to *F\,T' \mid \varepsilon.
*Step 3 — FF has no left recursion; but F→(E)∣idF \to (E) \mid id has distinct first symbols, so no left factoring is needed.
Answer: E→TE′E \to T E', E′→+TE′∣εE' \to +TE' \mid \varepsilon; T→FT′T \to F T', T′→∗FT′∣εT' \to *FT' \mid \varepsilon; F→(E)∣idF \to (E) \mid id. This grammar is suitable for recursive descent.

Example 5 (statement type). Statement I: Left recursion can make a recursive-descent parser loop forever. Statement II: Left factoring is the technique that removes left recursion.

Analysis. I is true: A→AαA \to A\alpha makes procedure AA call AA before consuming any token. II is false: left factoring removes a common prefix to restore determinism; left recursion is removed by the A′A' transformation.
(Left factoring is sometimes applied after recursion removal, which is the source of the trap.)
Answer: I true, II false.

Comparison

Chomsky hierarchy at a glance

TypeGrammarRestrictionRecogniserNLP use
0Unrestrictedα→β\alpha \to \beta, α\alpha has a nonterminalTuring machineNot used in practice
1Context-sensitiveαAβ→αγβ\alpha A\beta \to \alpha\gamma\beta, γ≠ε\gamma \neq \varepsilonLinear-bounded automatonSome agreement phenomena
2Context-freeA→γA \to \gammaPushdown automatonStandard syntax of NL and PL
3RegularA→aBA \to aB, A→aA \to aFinite automatonTokens, morphology, lexicons

Parser families

ParserDirectionData structureGrammar classTypical failure
Recursive descentTop-downCall stackAny (with backtracking)Infinite loop on left recursion
Predictive LL(1)Top-downStack + 1 lookaheadLL(1)Fails on common prefixes
Shift-reduceBottom-upStack + input bufferLR-typeShift/reduce or reduce/reduce conflict
LR(1)/LALR/SLRBottom-upStack + parsing tableDeterministic CFGConflict on ambiguous grammar
CYKBottom-up chartTriangular span tableCNF CFGNeeds CNF conversion
EarleyTop-down chartItem sets per positionAny CFGSlower in general case
ATNNetwork traversalStates + registersAugmented CFGCondition failures/backtracking

Ambiguity terms

TermMeaningExample
Ambiguous grammarSome string has two parse treesPP attachment grammar
Inherently ambiguous languageNo unambiguous grammar exists{aibjck∣i=j or j=k}\{a^{i}b^{j}c^{k} \mid i=j \text{ or } j=k\}
Lexical ambiguityOne word, several categories"book" noun/verb
Structural ambiguityOne category sequence, several trees"I saw the student with a telescope"

Revision summary

  1. CFG = Type 2 = PDA; regular = Type 3 = FA. Natural-language syntax uses CFG.
  2. Top-down = start symbol → sentence; bottom-up = sentence → start symbol.
  3. Ambiguity belongs to the grammar, not to the sentence alone; count parse trees, not words.
  4. CYK needs CNF: A→BCA \to BC or A→aA \to a; time O(n3)O(n^{3}), cells n(n+1)/2n(n+1)/2.
  5. Earley is a chart parser too, but top-down with dotted items; O(n3)O(n^{3}) worst case.
  6. Left recursion → infinite loop in recursive descent; left factoring → removes common prefix.
  7. Chart parsing memoises completed constituents by span, so shared sub-parses are computed once.
  8. ATN = network of states and arcs + registers + tests/actions.
  9. Pipeline order: tokenization → POS tagging → parsing → semantics.
  10. An LR parser cannot be built for an ambiguous grammar without conflict resolution; ambiguity implies conflicts.
  11. Catalan Cn−1C_{n-1} counts the possible binary parse trees — the blow-up that charts tame.
  12. Ambiguity is not the same as nondeterminism of rule application order; only distinct trees count.

Previous-year exam insights

  • Direct concept stems dominate: "which grammar class describes natural-language syntax" (answer: context-free, Type 2), "which strategy begins with the start symbol" (top-down), "which technique stores results by span" (chart/CYK/Earley).
  • Statement I/II items pair a true property with a plausible false one — the recurring trap is left factoring vs left recursion removal, and CNF rules vs arbitrary CFG rules. Check each statement independently before judging.
  • Match List-I with List-II usually pairs parsers with data structures: recursive descent ↔ call stack, shift-reduce ↔ stack + input buffer, CYK ↔ triangular table, Earley ↔ dotted items / chart sets, ATN ↔ states and registers with conditions.
  • Assertion–Reason items on ambiguity: the assertion (ambiguous grammar → multiple trees) is true; the reason is often a true-but-unrelated statement about CFG popularity, so the answer becomes "A true, R true, but R is not the correct explanation".
  • Numeric items ask for CYK cell counts (n(n+1)/2n(n+1)/2) or the complexity class; compute the cell count first, then quote the cubic time.
  • Ordering items test the NLP pipeline and the syntax-analysis steps: tokenization, POS tagging, parsing, tree construction.
  • Code-trace items on recursive-descent fragments: simulate the call stack token by token; watch for left recursion or a missing lookahead check.
  • Distractor options often offer "regular grammar" for natural language, "top-down" for shift-reduce, or "GNF is required for CYK" (it is CNF).
    Read the required normal form carefully.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  1. State the Chomsky hierarchy with restrictions, recognisers and the class used for natural-language syntax.
  2. Write the 4-tuple definition of a grammar and compute L(G)L(G) for a small grammar.
  3. Produce a leftmost and a rightmost derivation and the corresponding parse tree for a given sentence.
  4. Explain, with the "student with a telescope" style example, why a grammar is ambiguous and distinguish grammar ambiguity from inherent language ambiguity.
  5. Convert a CFG to CNF and a GNF-style grammar, and state why CNF is needed for CYK.
  6. Run CYK on a short string, fill the triangular table, count the cells using n(n+1)/2n(n+1)/2, and state acceptance.
  7. Trace Earley's predictor, scanner and completer on a two- or three-word input.
  8. Remove immediate and indirect left recursion and apply left factoring to a dangling-else grammar.
  9. Distinguish top-down from bottom-up parsing, recursive descent from LR, and CYK from Earley, in a match-the-list format.
  10. Identify the stages of the syntax-analysis pipeline in correct order and place ATNs and chart parsers correctly in that picture.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2