2. BNF-Backus Naur Form
• Backus normal form (BNF) is a notation technique for context-free
grammars.
• It is often used to describe the syntax of languages used in
computing.
• Such as computer programming languages, document formats,
instruction sets and communication protocols.
• They are applied wherever exact descriptions of languages are
needed.
• John Backus, a programming language designer at IBM, proposed
a metalanguage of "metalinguistic formulas" to describe the
syntax of the new programming language IAL, known today
as ALGOL 58 (1959). His notation was first used in the ALGOL 60
report.
• It is used to formally define the grammar of a language.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
2
3. Contd…..
• It is a formal mathematical way to describe a language.
• It is used to describe the syntax of the programming languages.
• It is a way of defining syntax.
• It consists of…..
a set of terminal symbols
a set of non-terminal symbols
a set of production rules of the form
Left - Hand- Side ::= Right- Hand- Side
where the LHS is a non-terminal symbol & the RHS is a sequence
of symbols (terminals or non-terminals).
The meaning of the production rule is that the non-terminal on
the LHS may be replaced by the expression on the RHS.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
3
4. Example:-Write a BNF grammar for the language of
University of Lucknow course codes.
• Example sentences:
• CSI3125
• MAT2743
• PHY1200
• CHE6581
• CSI9999
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
4
6. Write a BNF grammar for the language of palindromes
• Examples (spaces don't count!):
• aba
• pop
• pop a pop
• elu par cette crapule
• a man a plan a canal panama
• Solution:
<palindrome> ::= a <palindrome> a | b <palindrome> b |
c <palindrome> c | d <palindrome> d |
e <palindrome> e | ...
|z <palindrome> z
<palindrome> ::= <letter>
<letter> ::= a | b | c | ... | y | z
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
6
7. Ambiguity or Ambiguous
Grammar
• A grammar G is said to be ambiguous if it has more
than one parse tree (left or right derivation) for at
least one string.
• C, C++, and Java have a large number of –
operators and – precedence levels.
• Instead of using a large grammar, we can: –
Write a smaller ambiguous grammar, and –
Give separate precedence and associativity.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
7
8. Contd……
• An Ambiguous Expression Grammar G1
Expr → Expr Op Expr | ( Expr ) | Integer
Op → + | - | * | / | % | **
Ambiguous Parse of 5-4+3
Using Grammar G1
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
8
Exp
3+
ExpOpExp
ExpOpExp
-
45
9. Contd……
• E → E + E
• E → E – E
• E → id
For the string id + id – id, the above grammar
generates two parse trees:
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
9