Context-Free Grammars
Write a grammar, derive strings one replacement at a time, and see the parse tree each derivation defines.
- Lecture reference: Introduction to Parsing
Grammar
One production per line; | separates alternatives, also at the start of a
continuation line. Type -> for →, and write ε for
an empty right-hand side. The first left-hand side is the start symbol.
Open in LL(1) Parsing Table, Shift-Reduce Parsing, LR(1) Parser Builder or Conflicts & Precedence
Four-tuple G = (N, T, S, P)
- Nnon-terminals
- = { E }
- Tterminals
- = { int, +, *, (, ) }
- Sstart symbol
- = E
- P4 productions
- 1. E → int
- 2. E → E + E not of the form V → w | wU
- 3. E → E * E not of the form V → w | wU
- 4. E → ( E ) not of the form V → w | wU
From the slides
The productions viewed as rewrite rules: E → E * E → ( E ) * E → ( E + E ) * E → … → ( int + int ) * int. The builder holds the whole chain; the slide leaves out the three steps E → int.
Derivation 6 steps
Sentential form
Step 6: production 1, E → int, replaces symbol 7 of ( int + int ) * E. Sentential form: ( int + int ) * int. Only terminals remain.
Derivation leftmost derivation
- E
- E * E
- ( E ) * E
- ( E + E ) * E
- ( int + E ) * E
- ( int + int ) * E
- ( int + int ) * int
Parse tree
- Added by the last step
- Non-terminal to replace
Membership is the string in L(G)?
It has one parse tree.
Leftmost derivation
- E
- E * E
- ( E ) * E
- ( E + E ) * E
- ( int + E ) * E
- ( int + int ) * E
- ( int + int ) * int
( int + int ) * int is in L(G).
Test strings
- in L(G)
- in L(G)
- in L(G)
Language the sentences of L(G)
L(G) = { a1a2 … an | S →* a1a2 … an and ai ∈ T }
| 1 token | |
|---|---|
| 3 tokens | |
| 5 tokens |
Shorter sentences first; within one length, in the order of T. A sentence opens in the Membership panel when it is selected. Arrow keys move between the sentences.
No sentence drawn yet.
Starting from the start symbol, each non-terminal is replaced with one of its productions, picked at random down to depth 6; deeper non-terminals take their shortest expansion.