Professional Documents
Culture Documents
14.context Free Grammars
14.context Free Grammars
Arles Rodríguez
aerodriguezp@unal.edu.co
Facultad de Ciencias
Departamento de Matemáticas
Universidad Nacional de Colombia
Motivation
• Not all strings of tokens are valid programs.
• The parser must tell the difference.
– Must distinguish between valid and invalid strings
of tokens.
• We need:
– A way to describe valid strings of tokens
(language)
– A method for distinguishing valid from invalid
strings of tokens (algorithm)
Programming languages have recursive
structure
• In cool by example:
– An expression EXPR can be many things:
• We have a production:
• So we can replace:
CFGs
• Multiple steps can be represented as
application of rewriting over strings
• Nested expressions:
– if while id loop id pool then id else
id fi
– if if id then id else id fi then id
else id fi
CFGs: Elements
• Simple arithmetic expressions
E -> E + E
| E * E
| (E)
| id
CFGs: Elements
• Simple arithmetic expressions
E -> E + E
| E * E
| (E)
| id
• Following are valid expressions:
id
id + id
id + id * id
( id + id ) * id
Exercise
CFG
• As we defined CFGs output is yes or no,
representing membership in a language.
• We need a method to build a Parse Tree of the
input.
• In cases when the String is not in the language,
we must be able to handle errors gracefully
giving some kind of feedback to the programmer.
• Need to use an implementation of CFG (e.g.
bison)
CFG
• The form of the grammar can be important
– Tools are sensitive to the way you write the
grammar.
– While there are many ways to write the grammar
there are cases where it is necessary to modify the
grammar to get the tools accept it.
¡Thank you!
References
• Aho et al. Compilers: principles, techniques, and
tools. Torczon et al. (2014) (Section 4.2)
• Slides are based on the design of Aiken Alex. CS 143.
https://web.stanford.edu/class/cs143/