# Context-Free Grammars -- Examples

Abstract

Practice designing and working with CFGs, derivations, and parse trees.

# 1 JFLAP

1. Review the Grammar section of the Tutorial, specifically the sections titled “Enter Grammar”, “Brute Force Parser”, “User Control Parser”, and “CYK Parser”.

2. Enter the grammar

\begin{align} E &\rightarrow I \\ E &\rightarrow E + E \\ E &\rightarrow E * E \\ I &\rightarrow a \\ I &\rightarrow b \\ I &\rightarrow Ia \\ I &\rightarrow Ib \\ I &\rightarrow I0 \\ I &\rightarrow I1 \\ \end{align}

3. Run the User Control parser to perform leftmost and rightmost derivations of “a * b + a1”.

4. Show that this grammar is ambiguous by deriving two distinct parse trees for “a * b + a1”.

5. Run the CYK parser on “a * b + a1”.

6. Do Exercises 5.1.2a,b,c from your textbook.

# 2 Sample Problems

The problems in this section are all concerned with the following grammar:

\begin{align} P \rightarrow & S \\ L \rightarrow & S L | S\\ S \rightarrow & s ; | \{ L \} \\ \end{align}

A discussion of what this grammar “means” and how to read it:

## 2.1 Derivations

1. Give a derivation for the string: s;

Reveal
2. Give a derivation for the string {s;}

Reveal
3. Give a (left-most) derivation for the string {s;s;}

Reveal

Using recursion in context-free grammars to describe lists of things is a very common pattern, one that you should try to keep in mind both when reading grammars and when writing your own.

4. Give a right-most derivation for the string {s;s;}

Reveal

## 2.2 Parse Trees

1. Give a parse tree for the string: s;

2. Give a parse tree for the string {s;}

Reveal
3. Give a parse tree for the string {s;s;}

Reveal

The grammar we have used in these examples was intended to be reminiscent of the idea of a program (P) consisting of either a single statement (S) or a list of statements (L) enclosed in brackets. We can actually expand on this idea to make rhe relationship clearer by replacing the simple idea that a “statement” is simply a single token (s) by the idea that s could go on to derive any of a number of more familiar forms of programming language constructs.

# 3 Sample Problems – Ambiguity

We’ll continue working with the grammar:

\begin{align} P \rightarrow & S \\ L \rightarrow & S L \; | \; S\\ S \rightarrow & s ; \\ & | \, \{ L \} \\ & | \, i \, ( \, E \, ) \, S \\ & | \, i \, ( \, E \, ) \, S \, e \, S \\ E \rightarrow & x | y \end{align}

1. Show that the string i (x) i (y) x = y; e y = x; is in the language described by this grammar.

Reveal
2. Give a left-most derivation for that string.

Reveal
3. Using that same string, show that the grammar is ambiguous

Reveal

Some discussion of why ambiguity is both important and can be hard to prove/disprove.