Dana Vrajitoru
C311 Programming Languages

Parsers

Parsing

LL and LR Grammars

Example

----- A: LL(1)--------
P -> ( P )
P -> R
R -> [ R ]
R -> e

----- B: non-LL--------
P -> ( P ) 
P -> P P
P -> e

----- C: LL(2)--------
R -> [ R ]
R -> [ ]
R -> P
P -> ( P )
P -> ( R )
P -> e

Languages Accepted by the Above Grammars

LL Parsing

More Examples LL Grammars

A Non-LL Grammar
This grammar is non-LL because to choose between the two rules expanding UN one must find if there is a preiod in the string or not. For that the parser must search forward through all the digits. No matter what constant k we choose, it is possible to have a number having more than k digits to the left of the period, in which case the parser would fail to make a decision. So the grammar is not LL(k) for any constant k, and so it is not an LL grammar.

N => { + | - | e } UN
UN => UI . UI
UN => UI
UI => digit UI
UI => digit

LL - LR Parsing

Example

Parse Tree

LR Parsing

Example Bottom-Up

Example LR

Parse Tree

Backus-Naur Notation

Arithmetic Expression

expr => term term_tail				1
term_tail => add_op term term_tail | e		2|3
term => factor factor_tail				4
factor_tail => mult_op factor factor_tail | e	5|6
factor => ( expr ) | id | number			7|8|9
add_op => + | -					10|11
mult_op => * | /					12|13

Discriminating Terminals

Parsing Process

2 + a * ( 5 – b )
E ->T  TT ->F  FT  TT -> (F 2) FT  TT -> (F 2) TT ->
(F 2) AO  T  TT -> (F 2) (AO +) T  TT -> (F 2) (AO +) F  FT  TT ->
(F 2) (AO +) (F a) FT  TT -> (F 2) (AO +) (F a) MO  F  FT  TT ->
(F 2) (AO +) (F a) (MO *)  F  FT  TT ->
(F 2) (AO +) (F a) (MO *)  (E)  FT  TT ->
(F 2) (AO +) (F a) (MO *)  (T TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  (F FT TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) FT TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) TT)  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) AO T TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) (AO -) T TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) (AO -) F FT TT )  FT  TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) (AO -) (F b) FT TT ) FT TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) (AO -) (F b) TT) FT TT ->
(F 2) (AO +) (F a) (MO *)  ( (F 5) (AO -) (F b)  )

Parse Tree