Post on 04-Jan-2016
Lesson 2
CDT301 – Compiler Theory, Spring 2011Teacher: Linus Källberg
2
Outline
• Context-free languages– Context-free grammars– Parse trees– Push down automata
Grammars
S → a BB → εB → b B
• Regex: ab*• Derivation of “abb”:
S a B a b B a b b B a b b⇒ ⇒ ⇒ ⇒
3
4
Parse trees
S a B⇒ a b B⇒ a b b B⇒ a b b⇒
S
B
B
B
ε
a
b
b
Parse trees
S → a BB → εB → b B
String: “abb”
5
S
Parse trees
S → a BB → εB → b B
String: “abb”
6
S
Ba
Parse trees
S → a BB → εB → b B
String: “abb”
7
S
B
B
a
b
Parse trees
S → a BB → εB → b B
String: “abb”
8
S
B
B
B
a
b
b
Parse trees
S → a BB → εB → b B
String: “abb”
9
S
B
B
B
ε
a
b
b
Parse trees
S → a BB → εB → b B
String: “abb”
10
S
B
B
B
εa b b
Exercise (1)
• Write grammars that producea) strings over { a, b } that start and end with the
same letter. Draw the parse tree for “abaaa”.b) palindromes over { a, b }. Draw the parse tree
for “ababa”.c) valid e-mail addresses. Draw the parse tree
for “ab@c.d”. Try to derive the string “a@b@c” (this should not be possible).
• Recall: S+(.S+)*@S+(.S+)* 11
PDA
• Push down automata• FA + stack
12
PDA example
• Language: { (), (()), ((())), … }
13
Exercise (2)
• Write grammars fora) general parenthesis expressions:
{ ε, (), ()(), (()), ()(()), ((()))()(), … }.b) simple infix addition between single-digit
numbers, with support for prioritizing with parentheses:{ 7, 1 + 2, 1 + (9 + 1), ((6) + 0), … }.
c) Create PDAs for the above languages.d) Create a PDA that accepts palindromes.
14
Conclusion
• Context-free languages– Context-free grammars– Parse trees– Push down automata
15
Next time
• Specifying language syntax using CFGs• Introduction to parsing• Ambiguous grammars
16