CFG Lab Questions
Tim Dawborn
These set of lab questions are designed to help you fine tune your knowledge of cfgs, parsing,
and recursive descent parsing. By the end of this tutorial, you should be able to fully implement
your own regular expresion library.
All of the material from todays lecture will be useful for this tutorial. You are able to download
the slides from http://ncss.edu.au/slides/cfg.pdf.
Have one of your tutors or Tim check over your answers once you have completed some of the
problems.
Question 1
Here is a grammar for a made-up programming language.
1
2
3
4
5
6
7
8
<sent> ::= <sent> ";" <sent>
<sent> ::= <ident> ":=" <expr>
<sent> ::= "while" <expr> <sent>
<expr> ::= <expr> "-" <expr>
<expr> ::= <ident>
<expr> ::= <integer>
<ident> ::= ( "a" | "b" | ... | "z" )+
<integer> ::= ( "0" | "1" | ... | "9" )+
Construct the parse tree for the input string:
a := 100;
while a
a := a - 1
Question 2
1
2
3
4
5
6
7
8
<s>
<s>
<s>
<s>
<s>
<s>
<s>
<s>
::=
::=
::=
::=
::=
::=
::=
::=
"x"
"y"
"z"
<s>
<s>
<s>
<s>
"("
"+"
"-"
"*"
"/"
<s>
<s>
<s>
<s>
<s>
")"
Construct the parse tree for the input string ( x + y ) * x - z * y / ( x + x )
1
Question 3
1
2
3
4
<e1>
<e2>
<e3>
<e3>
::=
::=
::=
::=
<e2> ( "+" <e1> )?
<e3> ( "*" <e2> )?
"-"? ( "0" | "1" | ... | "9" )+
"(" <e1> ")"
Implement in Python a recursive descent parer for this mini-calculator language. Have a Node
subclass for each type of expression (e.g. MultNode, AddNode, LiteralNode), and construct an
object tree during the parsing process. We covered this in the second lecture on the first day.
Add an evaluate method to your Node class hierarchy.
1
2
3
import your_calculator
tree = your_calculator.parse(['1', '+', '2', '*', '3'])
print(tree.evaluate()) # 7
Question 4
The following grammar is the grammar you should use for your regular expressions language.
Write a recursive descent parser for this grammar, constructing the appropriate nfas at each
non-terminal.
1
2
3
4
5
6
<re>
<simple-re>
<basic-re>
<elem-re>
<elem-re>
<elem-re>
::=
::=
::=
::=
::=
::=
<simple-re> ( "|" <re> )?
<basic-re>+
<elem-re> "*"?
"(" <re> ")"
"\" ( "*" | "(" | ")" | "|" | "\" )
¬( "*" | "(" | ")" | "|" | "\" )
By this stage, assuming you have completed the fsa tutorial, you should be able to do the full
regular expression pipeline. A tutor should be able to enter a regular expression and compile
it to a dfa (re → nfa → dfa). They then should be able to use the dfa to accept or reject
strings.
1
TESTS = ('ae', 'adddde', 'abce', 'abcdddddbcddde', 'chicken', 'abde', 'a', '', 'abcd')
2
3
4
5
6
import your_regex
dfa_state = your_regex.compile(r'a(bc|d*)*e')
for test in TESTS:
print(dfa_state.accepts(test))
2
© Copyright 2026 Paperzz