# Chapter 2: Context-Free Languages

## Chapter 2.2, Pushdown Automata

### Theorem 2.20

A language is context free if and only if some pushdown automaton recognizes it.

### CFG → PDA Construction

#### Step One: Create a 3-State PDA

• The states are qstart, qloop and qaccept.
• qaccept is an accept state.
• qstart transitions to qloop with the rule ε, ε → S\$
• qloop transitions to itself with the rules ε, A → w (for each rule A → w) and a, a → ε (for each terminal a).
• qloop transitions to qaccept with the rule ε, \$ → ε

#### Step Two: Add States to Push One Symbol at a Time

For example, instead of qstart transitioning to qloop directly on rule ε, ε → S\$, it transitions to an intermediate state on rule ε, ε → \$ and the intermediate state transitions to qloop on rule ε, ε → S.

#### Active Learning Problem

Convert the following CFG to a PDA using the procedure above.

```  E → E + T | T
T → T * F | F
F → (E) | a
```

### PDA → CFG Construction

#### Preliminary Construction

Convert the original PDA to a PDA with the following characteristics.

• The PDA should have a single accept state.
• The PDA should empty its stack before accepting.
• Each transition should either push a symbol onto the stack or pop one symbol off. It should not do both at the same time.

#### Active Learning

Convert the following transition δ(r, 0, 0) → (s, 1) to meet the criteria above.

#### Construction

Construct G from P = (Q, Σ, Γ, δ, q0, {qaccept}). The variables of G are {Apq | p, q ∈ Q} and the start variable is Aq0, qaccept.

• For each p, q, r, s ∈ Q, u ∈ Γ and a,b ∈ Σε, if δ(p, a, ε) contains (r, u) and δ(s, b, u) contains (q, ε), add the following rule to G: Apq → aArsb
• For each p, q, r, s ∈ Q, add the following rule to G: Apq → AprArq
• For each p ∈ Q, add the following rule to G: App → ε

#### Active Learning

• Consider the PDA in Figure 2.18. Show at least one resulting rule for each of the three bullets above.