Tower of Hanoi

Download Report

Transcript Tower of Hanoi

Parsers
• Grammars can be used to describe a set of strings
(Language) that have certain properties. Moreover, the
productions in a grammar can be used to “generate” strings
in the specified language.
• Given a particular string a parser can be used to determine
whether or not the string is in the language generated by a
specified grammar. A parser can produce a parse tree
which provides a derivation for the string.
• Concepts
– Parse tree
– Ambiguous grammars
– Recursive descent parsers
Parse Tree
• A derivation is conveniently stored in a tree,
where internal nodes correspond to
syntactic categories and the children of a
node correspond to the element of the rhs in
the rule that was applied
Grammars
• Grammar 1
– <number>  <digit> <number>
– <digit>  0|1|2|3|4|5|6|7|8|9
• Grammar 2
– <expr>  <expr> + <expr>
– <expr>  <number>
• Grammar 3
– <Balanced>  (<Balanced>) <Balanced>
– <Balanced>  
Example Parse Tree
<number>
/
\
<digit> <number>
|
/
\
1
<digit> <number>
|
|
2
<digit>
|
3
Ambiguous Grammars
<expr>
<expr>
/ | \
/ | \
<expr>+<expr> <expr>+<expr>
/ | \
/ | \
<expr>+<expr>
<expr>+<expr>
More Grammars
• Grammar 3
– <Balanced>  (<Balanced>)
– <Balanced>  <Balanced> <Balanced>
– <Balanced>  
• Grammar 4
– <Balanced>  (<Balanced>) <Balanced>
– <Balanced>  
Recursive Descent Parser
• For some grammars it is simple to write a
parser that recognizes strings in the
language generated by the grammar.
• Sometimes it is possible to determine which
production to apply based on the next
character in the input string. This may not
always be possible, but when it is, it is
simple to construct a parser.
Problem 1
• Using the grammar
– <Balanced>  <Balanced><Balanced>
– <Balanced>  (<Balanced>)
– <Balanced>  
• Show two different parse trees for the input
– ()()()
Problem 2
• Show the sequence of calls made by the
program in Fig. 11.27 on the inputs
– (()())
– Draw the resulting parse tree
– What happens with the input
– ())(
Problem 3
• Consider the following grammar
– <Number>  <Digit><Number>|
– <Digit>  0|1|2|3|4|5|6|7|8|9
• Design a recursive-descent parser for this
grammar; that is, write a pair of functions,
one for <Number> and the other for <Digit>