4 Context Free Grammar

Theory of Computation · Unit 4 · 9 hrs

Context Free Grammar

Exam-focused notes for Context Free Grammar (Theory of Computation, CSC262): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.

Context Free Grammar in short

This unit moves beyond regular languages to context free grammars, the formalism behind programming language syntax, covering how a grammar generates strings, how ambiguity and normal forms are handled, where grammars sit in the Chomsky hierarchy, and how the pumping lemma bounds what a context free grammar can express.

Context Free Grammar: notes

Introduction to Context Free Grammar (CFG)

A context free grammar (CFG) is a formal system for generating the strings of a language by repeatedly rewriting symbols according to a fixed set of rules, independent of the surrounding context in which a symbol appears. Formally it is the 4-tuple $$G = (V, T, P, S),$$ where $V$ is a finite set of variables (non-terminals), $T$ is a finite set of terminals (disjoint from $V$), $P$ is a finite set of production rules, and $S \in V$ is the designated start symbol. Grammars are called "context free" because every production has a single variable on its left side, so that variable can always be rewritten regardless of what symbols surround it; this is what distinguishes them from the context sensitive grammars covered later in this unit, where a rewrite may only fire in a specific surrounding context.

Components of CFG

Each of the four components of $G=(V,T,P,S)$ plays a distinct role. The variables $V$ (written conventionally in upper case) each stand for a sub-language, a set of strings; the terminals $T$ (written in lower case) are the actual alphabet symbols that appear in the final generated strings and can never be rewritten further. Each production in $P$ has the form $A \to \alpha$ where $A \in V$ is the variable being defined (the head) and $\alpha \in (V \cup T)^*$ is a string of terminals and variables (the body) describing one way to build a string of $A$'s sub-language. The start symbol $S$ names the sub-language that the whole grammar defines; every derivation begins from $S$. For example, the grammar $G = ({S}, {0,1}, {S \to 0S1 \mid \epsilon}, S)$ generates all strings with an equal number of $0$s followed by an equal number of $1$s, since every application of $S \to 0S1$ wraps one more matched pair around the previous result, and $S \to \epsilon$ stops the recursion.

Use of CFG

Context free grammars are more expressive than regular expressions: a regular expression can describe repetition but not matching, nested structure (such as balanced parentheses or matched opening and closing tags), whereas a CFG's recursive productions naturally express such nesting. This makes CFGs the standard formalism for defining the syntax of programming languages: a compiler's parser checks whether a source program is a string in the language generated by the language's grammar, and, in doing so, recovers the program's syntactic structure (via a parse tree, covered below), which subsequent compiler phases use to generate code. Regular expressions remain useful for the flat, non-recursive structure of individual tokens (identifiers, numeric literals, keywords), while CFGs handle the recursive structure that combines tokens into statements and expressions.

Context Free Language (CFL)

A context free language (CFL) is a language generated by some context free grammar, equivalently (by a theorem proved in unit 5) a language accepted by some pushdown automaton. Every regular language is context free, since a regular grammar (covered below) is a special, restricted case of a context free grammar, but not every context free language is regular; ${0^n1^n : n \geq 0}$, generated by the grammar above, is context free but was shown in unit 3 to fail the pumping lemma for regular languages, so it is a genuine example of a CFL that is not regular.

Types of derivations: Bottomup and Topdown approach

A derivation is the process of producing a terminal string from the start symbol by repeatedly replacing a variable with the body of one of its productions. There are two dual ways to build, or to recover, a derivation. A top-down derivation starts from $S$ and repeatedly expands a variable using a production, working from the head down to the body, exactly as a recursive-descent parser does. A bottom-up derivation instead starts from the terminal string and repeatedly reduces a substring that matches some production's body back to that production's head, working up from the terminals toward $S$; this is exactly how a shift-reduce parser recovers structure. Take the grammar $E \to E+E \mid EE \mid (E) \mid \text{id}$ and the string $\text{id+idid}$. A bottom-up derivation reduces the string in the following order: $$\text{id+idid} ;\Rightarrow; E{+}\text{idid} ;\Rightarrow; E{+}E{}\text{id} ;\Rightarrow; E{+}E{}E ;\Rightarrow; E{+}E ;\Rightarrow; E,$$ first reducing each $\text{id}$ to $E$ left to right, then reducing the tighter-binding $E*E$ handle before the outer $E+E$ handle. Reading this sequence backward, replacing each reduction by the corresponding production applied in the head-to-body direction, gives a valid top-down (rightmost) derivation of the same string, since bottom-up reduction is precisely the reverse of a rightmost derivation.

Leftmost and Rightmost

Because a sentential form may contain several variables at once, a derivation is disambiguated by fixing which variable is expanded at each step. A leftmost derivation always expands the leftmost variable in the current sentential form; a rightmost derivation always expands the rightmost one. For $E \to E+E \mid EE \mid (E) \mid \text{id}$ and the string $\text{id+idid}$, the leftmost derivation is $$E \Rightarrow E+E \Rightarrow \text{id}+E \Rightarrow \text{id}+EE \Rightarrow \text{id+id}E \Rightarrow \text{id+idid},$$ while the rightmost derivation is $$E \Rightarrow E+E \Rightarrow E+EE \Rightarrow E+E{}\text{id} \Rightarrow E{+}\text{idid} \Rightarrow \text{id+id*id}.$$ Both derivations use exactly the same multiset of productions and arrive at the same string, differing only in the order the two $E$'s are expanded; a string that a grammar can derive is called a sentential form at every intermediate stage, and specifically a left sentential form if it arose during a leftmost derivation, or a right sentential form if it arose during a rightmost one.

What this unit covers

  • Introduction to Context Free Grammar (CFG)
  • Components of CFG
  • Use of CFG
  • Context Free Language (CFL)
  • Types of derivations: Bottomup and Topdown approach
  • Leftmost and Rightmost
  • Language of a grammar
  • Parse tree and its construction
  • Ambiguous grammar
  • Use of parse tree to show ambiguity in grammar
  • Regular Grammars: Right Linear and Left Linear
  • Equivalence of regular grammar and finite automata
  • Simplification of CFG: Removal of Useless symbols, Nullable Symbols, and Unit Productions
  • Chomsky Normal Form (CNF)
  • Greibach Normal Form (GNF)
  • Backus-Naur Form (BNF)
  • Context Sensitive Grammar
  • Chomsky Hierarchy
  • Pumping Lemma for CFL
  • Application of Pumping Lemma
  • Closure Properties of CFL

Leftmost and Rightmost

2081 · 5 marks

Define the language of a grammar. For the grammar , show the leftmost derivation for the string 00100 with its parse tree. S→0S0∣1∣εS \rightarrow 0S0 \mid 1 \mid \varepsilonS→0S0∣1∣ε[5]

Show solved answer

Language of a Grammar and Leftmost Derivation of 00100

Given

  • Grammar $G$ with productions: $$S \rightarrow 0S0 \mid 1 \mid \varepsilon$$
  • Start symbol: $S$
  • Terminals: ${0, 1}$
  • Non-terminal: ${S}$
  • Target string: $00100$

Solution

Definition: Language of a Grammar

For a grammar $G = (V, T, P, S)$ where $V$ is the set of variables (non-terminals), $T$ the set of terminals, $P$ the set of productions, and $S$ the start symbol, the language of the grammar, written $L(G)$, is the set of all terminal strings derivable from $S$:

$$L(G) = {, w \in T^* \mid S \Rightarrow^* w ,}$$

where $\Rightarrow^*$ denotes derivation in zero or more steps. Only strings consisting entirely of terminals belong to $L(G)$.


Leftmost Derivation of 00100

In a leftmost derivation, the leftmost non-terminal is expanded at each step. Since there is only one non-terminal $S$, this is straightforward.

$$S \Rightarrow 0S0 \quad (S \rightarrow 0S0)$$ $$\Rightarrow 00S00 \quad (S \rightarrow 0S0)$$ $$\Rightarrow 00100 \quad (S \rightarrow 1)$$

Complete derivation:

$$S \Rightarrow 0S0 \Rightarrow 00S00 \Rightarrow 00100$$

Therefore $00100 \in L(G)$.

Verification of leaf string: outer pair $0\ldots0$, inner pair $0\ldots0$, centre $1$ gives $0,0,1,0,0 = 00100$ ✓


Parse Tree for 00100

          S
        / | \
       0  S  0
        / | \
       0  S  0
          |
          1

Reading the leaves left to right: $0,\ 0,\ 1,\ 0,\ 0 = 00100$ ✓


Summary Table

StepSentential FormProduction
1$S$start
2$0S0$$S \rightarrow 0S0$
3$00S00$$S \rightarrow 0S0$
4$00100$$S \rightarrow 1$

The string $00100$ is derived in 3 steps, confirming $00100 \in L(G)$.

Open this answer on its own page →

Equivalence of regular grammar and finite automata

2081 · 5 marks

Represent the following regular grammar to finite automata. S→aA∣aB∣εS \rightarrow aA \mid aB \mid \varepsilonS→aA∣aB∣εA→aA∣aSA \rightarrow aA \mid aSA→aA∣aSB→bB∣εB \rightarrow bB \mid \varepsilonB→bB∣ε[5]

Production Rules ------ S → aA \ aB \ ε A → aA \ aS B → bB \ ε --- Each non-terminal in the grammar becomes a state in the FA. We also need a dead/final state for terminals. - States: S, A, B, F (where F is the final/accepting state) - S is the start state - Since S → ε and B → ε, both S and B ar...

Open this answer on its own page →

Chomsky Normal Form

2081 · 5 marks

Convert the following grammar to CNF. S→AAB,A→aA∣ε,B→ab∣aS \rightarrow AAB, \quad A \rightarrow aA \mid \varepsilon, \quad B \rightarrow ab \mid aS→AAB,A→aA∣ε,B→ab∣a[5]

$$S \rightarrow AAB, \quad A \rightarrow aA \mid \varepsilon, \quad B \rightarrow ab \mid a$$ --- CNF requires: Every production is either of the form A → BC (two non-terminals) or A → a (single terminal). No null productions (except possibly S → ε if ε ∈ L(G)). --- Identify nullable variables: A...

Open this answer on its own page →

2080 · 10 marks

Define context free grammar with an example. Explain with example, how context free grammar is converted to Chomsky Normal Form.[10]

Show solved answer

Context Free Grammar and Conversion to Chomsky Normal Form

Given

This is a theory and derivation question. The only structural data needed is the grammar chosen for the worked example, which is:

$$ \begin{aligned} S &\to ASB \mid \varepsilon\ A &\to aAS \mid a\ B &\to SbS \mid A \mid bb \end{aligned} $$

No data is missing; the question is fully answerable.


Solution

Part 1: Context Free Grammar (CFG)

A Context Free Grammar is a 4-tuple $G = (V, T, P, S)$ where:

  • $V$ = finite set of non-terminals (variables)
  • $T$ = finite set of terminals, with $V \cap T = \varnothing$
  • $P$ = finite set of productions of the form $A \to \alpha$, where $A \in V$ and $\alpha \in (V \cup T)^*$
  • $S \in V$ = start symbol

Every production has exactly one non-terminal on the left, so it can be replaced regardless of surrounding context - hence "context free."

Example: $$S \to 0S1 \mid \varepsilon$$

  • $V={S},\ T={0,1},\ S=S$
  • Generates ${0^n1^n \mid n \ge 0} = {\varepsilon, 01, 0011, \dots}$

CFGs describe the syntax of programming languages and drive parser/compiler design.


Part 2: Chomsky Normal Form (CNF)

A CFG is in CNF if every production is of the form:

  1. $A \to BC$ (two non-terminals), or
  2. $A \to a$ (single terminal)

with the sole exception $S \to \varepsilon$ allowed if $\varepsilon$ is in the language, and $S$ must not appear on any RHS.

Conversion steps:

  1. Add a new start symbol.
  2. Eliminate $\varepsilon$-productions.
  3. Eliminate unit productions.
  4. Reduce RHS length to 2 (introduce variables).
  5. Replace terminals in long productions with new variables.

Worked Example

Original grammar: $$ S \to ASB \mid \varepsilon,\quad A \to aAS \mid a,\quad B \to SbS \mid A \mid bb $$

Step 1: New start symbol $S_0$

$$ S_0 \to S,\quad S \to ASB \mid \varepsilon,\quad A \to aAS \mid a,\quad B \to SbS \mid A \mid bb $$

Step 2: Eliminate $\varepsilon$-productions

Nullable variables: $S$ (since $S\to\varepsilon$). Insert versions with $S$ deleted:

  • $S \to ASB \Rightarrow S \to ASB \mid AB$
  • $A \to aAS \Rightarrow A \to aAS \mid aA$
  • $B \to SbS \Rightarrow B \to SbS \mid bS \mid Sb \mid b$
  • $S_0 \to S$ keeps $S_0 \to \varepsilon$ (since $\varepsilon$ is in the language)

$$ \begin{aligned} S_0 &\to S \mid \varepsilon\ S &\to ASB \mid AB\ A &\to aAS \mid aA \mid a\ B &\to SbS \mid bS \mid Sb \mid b \mid A \mid bb \end{aligned} $$

Step 3: Eliminate unit productions

Unit pairs: $S_0 \to S$, $B \to A$.

  • $S_0 \to S$: $S_0 \to ASB \mid AB$
  • $B \to A$: $B \to aAS \mid aA \mid a$

$$ \begin{aligned} S_0 &\to ASB \mid AB \mid \varepsilon\ S &\to ASB \mid AB\ A &\to aAS \mid aA \mid a\ B &\to SbS \mid bS \mid Sb \mid b \mid aAS \mid aA \mid a \mid bb \end{aligned} $$

Step 4: Replace terminals in multi-symbol productions

Introduce $X_a \to a$, $X_b \to b$. Replace terminals wherever they sit with other symbols:

$$ \begin{aligned} S_0 &\to ASB \mid AB \mid \varepsilon\ S &\to ASB \mid AB\ A &\to X_aAS \mid X_aA \mid a\ B &\to SX_bS \mid X_bS \mid SX_b \mid b \mid X_aAS \mid X_aA \mid a \mid X_bX_b\ X_a &\to a\ X_b &\to b \end{aligned} $$

Step 5: Reduce RHS length to 2

Introduce helper variables:

  • $ASB$: let $C_1 \to SB$, so $\to A C_1$
  • $X_aAS$: let $C_2 \to AS$, so $\to X_a C_2$
  • $SX_bS$: let $C_3 \to X_bS$, so $\to S C_3$

Final CNF grammar: $$ \begin{aligned} S_0 &\to AC_1 \mid AB \mid \varepsilon\ S &\to AC_1 \mid AB\ A &\to X_aC_2 \mid X_aA \mid a\ B &\to SC_3 \mid X_bS \mid SX_b \mid b \mid X_aC_2 \mid X_aA \mid a \mid X_bX_b\ C_1 &\to SB\ C_2 &\to AS\ C_3 &\to X_bS\ X_a &\to a,\qquad X_b \to b \end{aligned} $$

Every production is now $A \to BC$ or $A \to a$ (plus the permitted $S_0 \to \varepsilon$), so the grammar is in Chomsky Normal Form.

Open this answer on its own page →

2079 · 10 marks

Given the following expression grammar for simple arithmetic expression with operator + and *. Remove the left recursion from this grammar then simplify and convert to CNF.E→E+T∣TE \rightarrow E+T \mid TE→E+T∣TT→T+F∣FT \rightarrow T+F \mid FT→T+F∣FF→(E)∣aF \rightarrow (E) \mid aF→(E)∣a[10]

The grammar as literally written in the question: $$E \to E+T \mid T$$ $$T \to T+F \mid F$$ $$F \to (E) \mid a$$ Note on interpretation: The problem statement says "operators + and ", but the middle rule is written with + again. The standard expression grammar uses in the T rule. I will follow th...

Open this answer on its own page →

2078 · 5 marks

Construct the following grammar into Chomsky Normal Form. S→abSb∣a∣aAbS \rightarrow abSb \mid a \mid aAbS→abSb∣a∣aAbA→bS∣aAAb∣εA \rightarrow bS \mid aAAb \mid \varepsilonA→bS∣aAAb∣ε[5]

$$S \rightarrow abSb \mid a \mid aAbS$$ $$A \rightarrow bS \mid aAAb \mid \varepsilon$$ --- CNF requires every production to be of the form: - $A \rightarrow BC$ (two non-terminals), or - $A \rightarrow a$ (single terminal) --- Identify nullable variables: A → ε, so A is nullable. Remove

Open this answer on its own page →

2076 · 5 marks

Define Chomsky Normal Form and Greibach Normal Form in reference to CFG. Give a suitable example of each. [5]

--- A Context-Free Grammar (CFG) is said to be in Chomsky Normal Form if every production rule is of exactly one of the following two forms: A → BC (a non-terminal produces exactly two non-terminals) A → a (a non-terminal produces exactly one terminal) Where A, B, C are non-terminal symbols and a...

Open this answer on its own page →

Introduction to Context Free Grammar

2080 · 5 marks

What is the meaning of the term 'Context Free' in context free grammar? Justify with a suitable example. What is the need of a parse tree? [5]

--- The term "Context Free" means that the production rules can be applied to a non-terminal symbol regardless of the context (surrounding symbols) in which that non-terminal appears. Formally, a Context Free Grammar is defined as: G = (V, T, P, S) where the production rules are of the form: $$A ...

Open this answer on its own page →

2080.1 · 10 marks

Define CFG. Construct a CFG that generates the language of all palindromes over {a,b} that do not contain the substring aa. Show the leftmost derivation and construct the equivalent parse tree for string babbbab.[10]

Show solved answer

Context-Free Grammar - Definition and Construction

Given

  • Alphabet: $\Sigma = {a, b}$
  • Language: all palindromes over ${a,b}$ that do NOT contain substring $aa$
  • Target string for derivation and parse tree: babbbab
  • Marks: 10

All required data is present.


Solution

1. Definition of CFG

A Context-Free Grammar is a 4-tuple $G = (V, T, P, S)$ where:

  • $V$ = finite set of variables (non-terminals)
  • $T$ = finite set of terminals, with $V \cap T = \varnothing$
  • $P$ = finite set of productions of the form $A \to \alpha$, where $A \in V$ and $\alpha \in (V \cup T)^*$
  • $S \in V$ = the start symbol

Every production has exactly one non-terminal on the left, hence "context-free". CFGs generate the class of Context-Free Languages.


2. Language Analysis

$$L = {, w \in {a,b}^* \mid w = w^R \text{ and } aa \text{ is not a substring of } w ,}$$

Constraints:

  • Palindrome: $w = w^R$
  • No $aa$: two $a$'s must never be adjacent

Because $w$ is a palindrome, when we place an $a$ at both ends the inner string must not begin or end with $a$ (otherwise $aa$ would form at the junction). So an $a$-wrapped layer must contain an inner block that begins and ends with $b$ (or is a single $b$).

Sample valid strings: $\varepsilon,\ a,\ b,\ aba,\ bab,\ bbb,\ babab,\ babbbab$. Invalid: $aa,\ baab,\ aabaa$.


3. Constructing the CFG

Use two variables:

VariableMeaning
$S$any palindrome without $aa$
$B$a palindrome without $aa$ that starts and ends with $b$

Productions $P$:

$$ \begin{aligned} S &\to \varepsilon \mid a \mid b \ S &\to bSb \ S &\to aBa \ B &\to b \mid bSb \end{aligned} $$

Grammar: $G = ({S,B},\ {a,b},\ P,\ S)$.

Why $aa$ never occurs:

  • $S \to aBa$: the inner $B$ must start and end with $b$, giving $a,b\ldots b,a$, so no adjacent $a$'s at the junction.
  • $S \to bSb$ and $B \to bSb$: wrap with $b$'s, always safe.
  • No production ever places two $a$'s next to each other.

The palindrome property holds because each recursive rule adds the same terminal symmetrically on both ends.


4. Leftmost Derivation for babbbab

Structural decomposition:

$$ \underbrace{b}{\text{outer}}\ \underbrace{a}{}\ \underbrace{b\ b\ b}{\text{middle}}\ \underbrace{a}{}\ \underbrace{b}_{\text{outer}} $$

  • Outer $b\ldots b$ → $S \to bSb$
  • Inner $abbba$: $a\ldots a$ → $S \to aBa$
  • Inner $bbb$: $b\ldots b$ → $B \to bSb$
  • Center $b$ → $S \to b$

Leftmost derivation (always expand leftmost non-terminal):

StepSentential formProduction
1$S$start
2$bSb$$S \to bSb$
3$baBab$$S \to aBa$
4$babSbab$$B \to bSb$
5$babbbab$$S \to b$

$$S \Rightarrow bSb \Rightarrow baBab \Rightarrow babSbab \Rightarrow babbbab$$

Result: $babbbab$ ✓ (matches target)


5. Parse Tree for babbbab

                 S
              /  |  \
             b   S   b
               / | \
              a  B  a
               / | \
              b  S  b
                 |
                 b

Reading the leaves left to right: $b,a,b,b,b,a,b = babbbab$ ✓

The tree is symmetric about its center, confirming both the palindrome property and the absence of substring $aa$ (each $a$ is bounded by $b$'s).


Final Answer: The CFG $G = ({S,B},{a,b},P,S)$ with productions $S \to \varepsilon \mid a \mid b \mid bSb \mid aBa,\ B \to b \mid bSb$ generates the required language. The leftmost derivation for $babbbab$ uses the sequence $S \Rightarrow bSb \Rightarrow baBab \Rightarrow babSbab \Rightarrow babbbab$, with the parse tree shown above.

Open this answer on its own page →

Parse tree and its construction

2079 · 5 marks

Define the term: Parse Tree, left-most and right-most derivation, sentential form and ambiguity with example. [5]

--- A parse tree is a graphical (tree) representation of how a string is derived from a Context Free Grammar (CFG). Formally, given a CFG G = (V, T, P, S), a parse tree has the following properties: - The root is labeled by the start symbol. - Each interior node is labeled by a variable (non-term...

Open this answer on its own page →

Regular Grammars

2079 · 5 marks

Define regular grammar. Also explain the method of converting right linear grammar into equivalent finite automata. [5]

--- A regular grammar is a grammar that represents a language which can also be represented by regular expressions. The language generated by a regular grammar is called a regular language, and it is accepted by both NFA and DFA. A regular grammar is a subset of Context-Free Grammar (CFG). Regula...

Open this answer on its own page →

Chomsky Hierarchy

2078 · 5 marks

Explain about the Chomsky's Hierarchy about the language and programs. [5]

Chomsky's Hierarchy (proposed by Noam Chomsky) classifies formal languages and grammars into four levels based on their generative power and the computational model required to recognize them. Each level is a strict subset of the level above it. --- - Grammar Rule Form: No restriction on producti...

Open this answer on its own page →

Pumping Lemma for CFL

2080.1 · 5 marks

Prove that th language is not a context free grammar. $L = {a^n b^n c^n \mid n \geq 0}$ [5]

--- If A is a Context Free Language, then A has a pumping length P such that any string s where s ≥ P may be divided into 5 pieces s = uvxyz satisfying: 1. uv^i xy^i z ∈ A for every i ≥ 0 2. vy 0 (v and y are not both empty) 3. vxy ≤ P --- Assume L is Context Free. Then by the Pumping Lemma, L mu...

Open this answer on its own page →