1/31
LR(0) Parsers
CSCI 3130 Formal Languages and Automata Theory Siu On CHAN
Chinese University of Hong Kong
LR(0) Parsers CSCI 3130 Formal Languages and Automata Theory Siu On - - PowerPoint PPT Presentation
1/31 LR(0) Parsers CSCI 3130 Formal Languages and Automata Theory Siu On CHAN Chinese University of Hong Kong Fall 2016 2/31 The alphabet of Java CFG consists of tokens like Parsing computer programs if (n == 0) { return x; } First phase of
1/31
Chinese University of Hong Kong
2/31
if (n == 0) { return x; }
if ( ID == INT_LIT ) { return ID ; }
3/31
if
(
ID
==
INT_LIT )
{
return
ID ; } if (n == 0) { return x; }
4/31
Identifier: IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral Literal: IntegerLiteral FloatingPointLiteral BooleanLiteral CharacterLiteral StringLiteral NullLiteral Expression: LambdaExpression AssignmentExpression AssignmentOperator: (one of) = *= /= %= += -= <<= >>= >>>= &= ^= |=
from http:
//java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html#52996
5/31
class Point2d { /* The X and Y coordinates of the point--instance variables */ private double x; private double y; private boolean debug; // A trick to help with debugging public Point2d (double px, double py) { // Constructor x = px; y = py; debug = false; // turn off debugging } public Point2d () { // Default constructor this (0.0, 0.0); // Invokes 2 parameter Point2D constructor } // Note that a this() invocation must be the BEGINNING of // statement body of constructor public Point2d (Point2d pt) { // Another consructor x = pt.getX(); y = pt.getY(); } ... }
6/31
7/31
8/31
1 •()() 2 (•)() 3 ()•() 4
( )
5
( )
6
( ) (•) 7
( ) ()• 8
( )
( )
( )
( )
9/31
◮ Greedily reduce the recently completed rule into a variable ◮ Unique choice of reduction at any time
3 ()•()
4
( )
5
( )
10/31
✓
( )
✓
( )
11/31
3 ()•()
4
( )
7
( ) ()•
12/31
(S)
(
(S )
(S)
()
( )
()
(
) ( )
12/31
(
) ( )
13/31
(S)
(
(S )
(S)
()
( )
()
(
) ( )
13/31
(
) ( )
14/31
15/31
(
) )
( (
(
16/31
17/31
(()•)
(A ( )
18/31
(
) )
( (
(
19/31
20/31
1
$ 2 (•)()
$1 3 ()•()
$15 3
( ) ()
$ 4
( )
$1 4
( ) ()
$
5
( )
$1 6
( ) (•)
$12
21/31
7
( ) ()•
$125 7
( )
( )
$1 8
( )
( )
$12
8
( )
( )
$ 9
( )
( )
$1
22/31
a
a
# b
b
23/31
a # b # # a b b a
a b 1 2 3 4 5 6 7 8
ba#ab
$
$1
$14
$143
$143
$1435
$14
$146
24/31
25/31
a
a
b
b
26/31
a b a b b a
a b
27/31
C → •aCa C → •bCb C → •# C → #• C → a • Ca C → •aCa C → •bCb C → •# C → b • Cb C → •aCa C → •bCb C → •# C → aC • a C → bC • b C → aCa• C → bCb•
a # b # # a b b a
C C
a b
28/31
29/31
()() A() S() SA S
30/31
if (n == 0) { return x; } else { return x + 1; }
if …then
if …then …else
30/31
if (n == 0) { return x; } else { return x + 1; }
if …then
if …then …else
31/31