cs212 Lect05 63 Inter
cs212 Lect05 63 Inter
PROGRAMMING LANGUAGES
BACKUS NAUR FORM
EBNF:
<expression> ::=
<expression> <term> {{ (+|-)
::= <term> (+|-) <term>
<term> }}
<term> ::=
<term> ::= <factor> {{ (*|/)
<factor> (*|/)
<factor> }}
<factor>
factor
factor '(' <expression>
'(' <expression> ')'
')'
|| <id>
<id> || <number>
<number> 9
NOTES ON USE OF EBNF
Semantic Analysis
Intermediate code
17
LEXICAL STRUCTURE
• Lexemes are the smallest lexical unit of a language, grouped
according to syntactic usage. Some types of lexemes in
computer languages are:
19
LEXICAL STRUCTURE
23
when scanning “ temp := temp + 1 ”
The first token should be temp.
From start state, then go to state q1 and loop in
state q1 until get “ : ” . It will stop and return the
first token “temp” then start to get the next token.
Try scanning “ x := (y+10) * z1; ”
24
PARSING ALGORITHMS
• Broadly divided into LL and LR.
• LL algorithms match input directly to left-side
symbols, then choose a right-side production that
matches the tokens. This is top-down parsing
••Look
Lookahead:
ahead:
••algorithms
algorithmsmust
mustlook
lookatatnext
nexttoken(s)
token(s)totodecide
decide
between alternate productions for current tokens
between alternate productions for current tokens
••LL(1)
LL(1)means
meansLL
LLwith
with11token
tokenlook-ahead
look-ahead
••LL algorithms are simpler and easier to visualize.
LL algorithms are simpler and easier to visualize.
••LR
LRalgorithms
algorithmsare
aremore
morepowerful:
powerful:can
canparse
parsesome
some
grammars that LL cannot, such as left recursion.
grammars that LL cannot, such as left recursion. 26
TOP-DOWN PARSING EXAMPLE (LL)
Input String : x – 2 * y
27
Tokens : id – number * id
28
29
30
31
32
33
34
35
36
37
38
39
TOP-DOWN PARSING EXAMPLE (LL)
Input String : x – 2 * y
40
Tokens : id – number * id
41
42
ELIMINATION OF LEFT RECURSION
43
ELIMINATION OF LEFT RECURSION
Here is the grammar again:
S ::= A | B
A ::= ABc | AAdd | a | aa
B ::= Bee | b
An equivalent right-recursive grammar:
S ::= A | B
A ::= aA′ | aaA′
A′ ::= BcA′ | AddA′ |
B ::= bB′
44
B′ ::= eeB′ |
ELIMINATING LEFT RECURSION
45
LL PARSING EXAMPLE
46
Rul Sentential Form Input
e
- Goal x – 2 * y
Expr x – 2 * y
Term Expr x – 2 * y
Factor Term Expr x – 2 * y
<id,x> Term Expr x – 2 * y
<id,x> Expr x – 2 * y
<id,x> +Term Expr x – 2 * y
47
Rule Sentential Form Input
- Goal x – 2 * y
Expr x – 2 * y
Term Expr x – 2 * y
Factor Term Expr x – 2 * y
<id,x> Term Expr x – 2 * y
<id,x> Expr x – 2 * y
<id,x> - Term Expr x – 2 * y
<id,x> - Factor Term Expr x – 2 * y
<id,x> - <number,2> Term Expr x –2*y
<id,x> - <number,2> * Factor Term Expr x –2*y
<id,x> - <number,2> * <id,y> Term Expr x –2*y
<id,x> - <number,2> * <id,y> Expr x –2*y
<id,x> - <number,2> * <id,y> x –2*y
<id,x> - <number,2> * <id,y> x –2*y
48