Unit 4
Unit 4
Unit 4
1
Backus-Naur form and variants
2
Backus-Naur form and variants (cont)
3
Backus-Naur form and variants (cont)
4
Example: A grammar for natural numbers
• Productions
<nat> ::= <digit> | <digit><nat>
<digit> ::= “0”|”1”|”2”|”3”|”4”|”5”|”6”|”7”|”8”|”9”
• Terminal symbols
“0", “1, “2", …..“9"
• Nonterminal symbols
<nat>, <digit>
• Start symbol
<nat>
5
Example: Grammar for ArithmeticExpressions
• Productions
<Exp> ::= “+”<Expr2>|”-”<Expr2>|<Expr2>
<Expr2> ::= <Term><Expr3>
<Expr3> ::= “+” <Term><Expr3>|
”-”<Term><Expr3>|
<Term> ::= <Factor> <Term2>
<Term2> ::= “*” <Factor> <Term2> |”/”<Factor> <Term2>|
<Factor> ::=“ident”|”number”|”(“<Exp>”)”
• Terminal symbols
simple TS: "+", "-", "*", "/", "(", ")"
terminal classes: “ident”, “number”
• Nonterminal symbols
<Expr>, <Expr2>, <Expr3>, <Term>, <Term2>, <Factor>
• Start symbol
<Expr>
6
EBNF(Extended BNF)
7
KPL Grammar in BNF
01) <Prog> ::= KW_PROGRAM TK_IDENT SB_SEMICOLON <Block> SB_PERIOD
12
KPL Grammar in BNF
76) <Expression> ::= SB_PLUS <Expression2>
77) <Expression> ::= SB_MINUS <Expression2>
78) <Expression> ::= <Expression2>
Example:
var a: integer;
a:= ReadI;
• Output: procedures
• writeI: Prints an integer. 1 parameter.
• writeC: Prints a character. 1 parameter.
• writeLn: Prints the newline character.
Example:
call writeI(a);
call writeLn;
14
Example
15
Solution 1
program solution1;
var a:integer;
b: integer;
begin
a:= readI;
b:= readI;
call writeI (a+b);
end.
16
Solution 2
Input 2 integers a and b. Compute and print out sum of them
using function sum
program solution2;
var a,b,c;
function sum (x: integer; y:integer): integer;
begin
sum:=x+y;
end;
begin
a:= readI;
b:= readI;
c:= sum(a,b);
call writeI (c);
end.
17
Syntax Diagram
18
Examples of syntax diagram
19
Syntax Diagrams of KPL (program)
20
Syntax Diagrams of KPL(block)
21
Syntax Diagrams of KPL (paramlist and constant)
22
Syntax Diagrams of KPL
23
Syntax Diagrams of KPL (statement)
24
Syntax Diagrams of KPL (variable,expression,term)
25
Syntax Diagrams of KPL (factor and condition)
26
Syntax Diagrams of KPL (identifiers)
27
Exercise: a KPL program
28
Solution 1
29
Solution 2: Use a user defined function
BEGIN
n := readI;
call writeln;
call writeI(f(n));
END. (* Factorial *)
30