
1
CMSC 330: Organization of
Programming Languages
Context Free Grammars
CMSC 330 2
Where We Are
Programming languages
•
Ruby
•
OCaml
Implementing programming languages
•
Scanner
Uses regular expressions
Finite automata
•
Parser
Uses context free grammars
Pushdown automata
CMSC 330 3
This Lecture
Program syntax
•
Regular expressions & grammars
Context free grammars (CFGs )
•
Definition
•
Derivations (leftmost)
•
Parse tree
•
Ambiguity
•
Associativity & precedence
CMSC 330 4
Programming Languages
Syntax
•
What a program looks like
•
Needs to be very precise
Semantics
•
What a program means
•
How different parts of a program behave
CMSC 330 5
Motivation for Grammars
Programs are just strings of text
•
But they’re strings that have a certain structure
Informal description of structure of a C program
•
A C program is a list of declarations and definitions
•
A function definition contains parameters and a body
•
A function body is a sequence of statements
•
A statement is either an expression, a while loop, etc…
•
An expression may be assignment, addition, etc…
CMSC 330 6
Motivation for Grammars (cont.)
We want to describe program structure precisely
Regular expressions are not enough
•
No regular expression for balanced pairs of ( )’s
{ “( )”, “(( ))”, “((( )))”, “(((( ))))”, … } is not a regular language
Need to use context free gram mar (CFG)