Context-Free Grammars -- Examples
CS390, Fall 2021
Abstract
Practice designing and working with CFGs, derivations, and parse trees.
1 JFLAP
-
Review the Grammar section of the Tutorial, specifically the sections titled “Enter Grammar”, “Brute Force Parser”, “User Control Parser”, and “CYK Parser”.
-
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} \]
-
Run the User Control parser to perform leftmost and rightmost derivations of “a * b + a1”.
-
Show that this grammar is ambiguous by deriving two distinct parse trees for “a * b + a1”.
-
Run the CYK parser on “a * b + a1”.
-
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
-
Give a derivation for the string:
s;
Reveal -
Give a derivation for the string
{s;}
Reveal -
Give a (left-most) derivation for the string
{s;s;}
RevealUsing 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.
-
Give a right-most derivation for the string
{s;s;}
Reveal
2.2 Parse Trees
-
Give a parse tree for the string:
s;
Reveal -
Give a parse tree for the string
{s;}
Reveal -
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}
\]
-
Show that the string
i (x) i (y) x = y; e y = x;
is in the language described by this grammar.Reveal -
Give a left-most derivation for that string.
Reveal -
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.