Professional Documents
Culture Documents
Lecture 4
Lecture 4
Describing Syntax
Analysis
Program execution
1-2
Introduction
1-3
Chomsky hierarchy
1-4
Chomsky hierarchy
1-5
BNF and Context-Free Grammars
• Context-Free Grammars
– Developed by Noam Chomsky in the mid-1950s
– Language generators, meant to describe the
syntax of natural languages
– Define a class of languages called context-free
languages
1-7
Describing Lists
1-8
An Example Grammar
<program> <stmts>
<stmts> <stmt> | <stmt> ; <stmts>
<stmt> <var> = <expr>
<var> a | b | c | d
<expr> <term> + <term> | <term> - <term>
<term> <var> | const
<program> => <stmts> => <stmt>
=> <var> = <expr>
=> a = <expr>
=> a = <term> + <term>
=> a = <var> + <term>
=> a = b + <term>
=> a = b + const
1-9
Recursive Grammars
1) S->SaS
S->b
The language(set of strings) generated by the above
grammar is :{b, bab, babab,…}, which is infinite.
2) S-> Aa
A->Ab|c
The language generated by the above grammar is :{ca,
cba, cbba …}, which is infinite.
S->Aa
A->b|c
The language generated by the above grammar is :{ba,
ca}, which is finite.
1-11
Parse Tree
• A hierarchical representation of a derivation
<program>
<stmts>
<stmt>
<var> = <expr>
a <term> + <term>
<var> const
b
1-12
An Ambiguous Expression Grammar
<expr> <expr>
1-13
An Unambiguous Expression Grammar
<expr>
<expr> - <term>
const const
1-14
Unambiguous Grammar for Selector
• if-then-else grammar
<if_stmt> -> if (<logic_expr>) <stmt>
| if (<logic_expr>) <stmt> else <stmt>
Ambiguous!
- An unambiguous grammar for if-then-else
1-15
Removal of Ambiguity in Grammar
1-16
Removal of Ambiguity in Grammar
1-17
Removal of Ambiguity in Grammar
2. Associativity –
If the same precedence operators are in production, then we will
have to consider the associativity.
•If the associativity is left to right, then we have to prompt a left
recursion in the production. The parse tree will also be left
recursive and grow on the left side.
+, -, *, / are left associative operators.
•If the associativity is right to left, then we have to prompt the right
recursion in the productions. The parse tree will also be right
recursive and grow on the right side.
^ is a right associative operator.
1-18
Removal of Ambiguity in Grammar
The language in the grammar will contain { id, id-id, id-id-id, ….}
If we want to derive the string id-id-id. Let’s consider a single
value of id=3 to get more insights. The result should be :
3-3-3 =-3
1-19
Parse Tree
1-20
Removal of Ambiguity in Grammar
E -> E – P | P
P -> id
1-21
Another Operator
P -> id
1-22
Task
E -> E + E | E * E | id
1-24
BNF and EBNF
• BNF
<expr> <expr> + <term>
| <expr> - <term>
| <term>
<term> <term> * <factor>
| <term> / <factor>
| <factor>
• EBNF
<expr> <term> {(+ | -) <term>}
<term> <factor> {(* | /) <factor>}
1-25