Title: Grammar
1Grammar
2Syntax Definition
- Syntax the form of expressions, statements and
programming units. - Grammar a formal set of rules that describes a
valid syntax of a language - Context Free Grammar (CFG) formal way of
describing syntax. - Backus-Naur Form (BNF) a particular way of
expressing CFGs.
3Context Free Grammar
- The Components of CFG
- A set of tokens, known as terminal symbols
- A set of nonterminals
- A set of productions, LHS ? RHS
- A designation of one of the nonterminals as the
start symbol - Context Free Grammar can be used to help guide
the translation of programs
4Grammars
- Like natural languages (English), programming
languages are described by their grammar - It is essential to know the grammar of the
source and target languages when writing a
compiler - Context Free Grammar (CFG) formal way of
describing syntax - Backus-Naur Form (BNF) a particular way of
expressing CFGs
5Derivation for the Example Grammar
list? list digit? list - digit digit?
digit - digit digit? 9 - digit digit? 9 - 5
digit? 9 - 5 2
This is an example leftmost derivation, because
we replacedthe leftmost nonterminal (underlined)
in each step.Likewise, a rightmost derivation
replaces the rightmostnonterminal in each step
6Parse Trees
- The root of the tree is labeled by the start
symbol - Each leaf of the tree is labeled by a terminal
(token) or ? - Each interior node is labeled by a nonterminal
- If A ? X1 X2 Xn is a production, then node A
has immediate children X1, X2, , Xn where Xi is
a (non)terminal or ? (? denotes the empty string)
7Parse Tree for the Example Grammar
Parse tree of the string 9-52 using grammar G
list
digit
list
list
digit
digit
The sequence ofleafs is called the yield of the
parse tree
9
-
5
2
8Ambiguity
Consider the following context-free grammar
G ltstring, ,-,0,1,2,3,4,5,6,7,8,9, P,
stringgt
with production P
string ? string string string - string 0
1 9
This grammar is ambiguous, because more than one
parse treerepresents the string 9-52
9Ambiguity (contd)
string
string
string
string
string
string
string
string
string
string
9
-
5
2
9
-
5
2
10Associativity of Operators
Left-associative operators have left-recursive
productions
left ? left term term
String abc has the same meaning as (ab)c
Right-associative operators have right-recursive
productions
right ? term right term
String abc has the same meaning as a(bc)
11Precedence of Operators
Operators with higher precedence bind more
tightly
expr ? expr term termterm ? term factor
factorfactor ? number ( expr )
String 235 has the same meaning as 2(35)
expr
expr
term
factor
term
term
factor
factor
number
number
number
2
3
5
12Syntax of Statements
stmt ? id expr if
expr then stmt if expr then
stmt else stmt while expr do
stmt begin opt_stmts
endopt_stmts ? stmt opt_stmts
?