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 ; denotes all finite strings including .
- Formal grammar: a 4-tuple — = nonterminals (variables), = terminals, = productions, = start symbol. The language generated is .
- Chomsky hierarchy (four classes, in decreasing power):
- Type 0 — Unrestricted / phrase-structure: , contains at least one nonterminal; recognised by a Turing machine.
- Type 1 — Context-sensitive: with ; recognised by a linear-bounded automaton.
- Type 2 — Context-free (CFG): single nonterminal on the left, ; recognised by a pushdown automaton.
- Type 3 — Regular: or (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 . 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 , 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 (exactly two nonterminals) or (one terminal); optionally if . Required by CYK.
- Greibach Normal Form (GNF): every production is — one terminal first, then any number of nonterminals.
- Left recursion: — immediate form ; also indirect via other nonterminals. Fatal to naive recursive-descent parsers (infinite loop).
- Left factoring: rewriting as , . It removes a common prefix (nondeterminism), not left recursion.
- Top-down parsing: starts at , 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 is reached — shift-reduce, LR(1), SLR, LALR.
- Chart parsing: store every completed constituent in a table indexed by the span 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).
- Write the start symbol as the current sentential form.
- Pick a nonterminal in it and replace it by the right-hand side of one of its productions.
- Repeat until only terminals remain. If the terminal string equals the input, the sentence is generated.
- 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).
- Let input be .
- Diagonal cells: fill with every nonterminal such that is a rule.
- For spans of length to : for each with , for every split from to , for every and , add to if exists.
- Accept iff .
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 ).
- Predictor: if the dot precedes nonterminal , add items starting at .
- Scanner: if the dot precedes terminal matching , advance the dot into the next chart set.
- Completer: if the dot is at the end (item completed from to ), advance every item in set that was waiting for that nonterminal.
Accept iff an item appears.
6. Removing left recursion (two steps): introduce a new nonterminal ; and . 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.
Drawing the diagram…
Drawing the diagram…
Formulas
- Language generated: , where is the terminal alphabet.
- Number of CYK table cells for input length : (a triangular table; diagonal cells).
- CYK time complexity: ; space , where is grammar size.
- Earley complexity: general CFG, for unambiguous grammars, for deterministic (bounded-state) grammars.
- Number of distinct full binary parse trees with leaves: Catalan number — the count that measures how badly ambiguity can explode.
- Immediate left-recursion removal: becomes and .
- Left factoring: becomes and .
- LL(1) condition: for every nonterminal and distinct alternatives, sets are disjoint, and if then .
Worked examples
Example 1 (easy). Grammar: , , , , , . Parse "the dog chased the cat".
Step 1. .
Step 2. .
Step 3. .
Step 4. Leftmost derivation: .
Answer: the grammar derives the sentence; the parse tree has root , two children and , and the tree is unique for this string.
Example 2 (medium, CYK). Grammar in CNF: , , . Run CYK on "aab" ().
Cells to compute: .
| Span | Length | Contents |
|---|---|---|
| (1,1) | 1 | from |
| (2,2) | 1 | from |
| (3,3) | 1 | from |
| (1,2) | 2 | split : , gives (via ) → |
| (2,3) | 2 | split : , — rule applies → (the substring "ab" is itself an ) |
| (1,3) | 3 | : and — no rule → nothing. : , → via → |
Answer: , so "aab" is accepted; 6 cells were computed.
Example 3 (medium, numeric). For input length , how many cells does CYK fill and what is the running time order?
Cells . Time , i.e. for .
Answer: 10 cells; cubic time.
Example 4 (hard, two-step: left recursion then left factoring). Take the classic expression grammar , , .
Step 1 — remove immediate left recursion from : , . Gives , .
Step 2 — remove from : , . Gives , .
*Step 3 — has no left recursion; but has distinct first symbols, so no left factoring is needed.
Answer: , ; , ; . 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: makes procedure call before consuming any token. II is false: left factoring removes a common prefix to restore determinism; left recursion is removed by the 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
| Type | Grammar | Restriction | Recogniser | NLP use |
|---|---|---|---|---|
| 0 | Unrestricted | , has a nonterminal | Turing machine | Not used in practice |
| 1 | Context-sensitive | , | Linear-bounded automaton | Some agreement phenomena |
| 2 | Context-free | Pushdown automaton | Standard syntax of NL and PL | |
| 3 | Regular | , | Finite automaton | Tokens, morphology, lexicons |
Parser families
| Parser | Direction | Data structure | Grammar class | Typical failure |
|---|---|---|---|---|
| Recursive descent | Top-down | Call stack | Any (with backtracking) | Infinite loop on left recursion |
| Predictive LL(1) | Top-down | Stack + 1 lookahead | LL(1) | Fails on common prefixes |
| Shift-reduce | Bottom-up | Stack + input buffer | LR-type | Shift/reduce or reduce/reduce conflict |
| LR(1)/LALR/SLR | Bottom-up | Stack + parsing table | Deterministic CFG | Conflict on ambiguous grammar |
| CYK | Bottom-up chart | Triangular span table | CNF CFG | Needs CNF conversion |
| Earley | Top-down chart | Item sets per position | Any CFG | Slower in general case |
| ATN | Network traversal | States + registers | Augmented CFG | Condition failures/backtracking |
Ambiguity terms
| Term | Meaning | Example |
|---|---|---|
| Ambiguous grammar | Some string has two parse trees | PP attachment grammar |
| Inherently ambiguous language | No unambiguous grammar exists | |
| Lexical ambiguity | One word, several categories | "book" noun/verb |
| Structural ambiguity | One category sequence, several trees | "I saw the student with a telescope" |
Revision summary
- CFG = Type 2 = PDA; regular = Type 3 = FA. Natural-language syntax uses CFG.
- Top-down = start symbol → sentence; bottom-up = sentence → start symbol.
- Ambiguity belongs to the grammar, not to the sentence alone; count parse trees, not words.
- CYK needs CNF: or ; time , cells .
- Earley is a chart parser too, but top-down with dotted items; worst case.
- Left recursion → infinite loop in recursive descent; left factoring → removes common prefix.
- Chart parsing memoises completed constituents by span, so shared sub-parses are computed once.
- ATN = network of states and arcs + registers + tests/actions.
- Pipeline order: tokenization → POS tagging → parsing → semantics.
- An LR parser cannot be built for an ambiguous grammar without conflict resolution; ambiguity implies conflicts.
- Catalan counts the possible binary parse trees — the blow-up that charts tame.
- 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 () 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:
- State the Chomsky hierarchy with restrictions, recognisers and the class used for natural-language syntax.
- Write the 4-tuple definition of a grammar and compute for a small grammar.
- Produce a leftmost and a rightmost derivation and the corresponding parse tree for a given sentence.
- Explain, with the "student with a telescope" style example, why a grammar is ambiguous and distinguish grammar ambiguity from inherent language ambiguity.
- Convert a CFG to CNF and a GNF-style grammar, and state why CNF is needed for CYK.
- Run CYK on a short string, fill the triangular table, count the cells using , and state acceptance.
- Trace Earley's predictor, scanner and completer on a two- or three-word input.
- Remove immediate and indirect left recursion and apply left factoring to a dangling-else grammar.
- Distinguish top-down from bottom-up parsing, recursive descent from LR, and CYK from Earley, in a match-the-list format.
- 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.