SlideShare uma empresa Scribd logo
1 de 9
Baixar para ler offline
Predictive Parsing (finish) &
             Bottom-Up Parsing

                                      CS2210
                                      Lecture 5




                               CS2210 Compiler Design 2004/05




    Non-recursive Predictive
    Parsers
    ■    Avoid recursion for efficiency reasons
    ■    Typically built automatically by tools
              Input           a + b $

          X                 Predictive Parsing                  output
Stack     Y                     Program
          Z
          $                                         M[A,a]gives production
                              Parsing Table         A symbol on stack
                                    M               a input symbol (and $)
                              CS2210 Compiler Design 2004/05




    Parsing Algorithm
    ■         X symbol on top of stack, a current input symbol
          ■      Stack contents and remaining input called parser
                 configuration (initially $S on stack and complete input
                 string)
    1.        If X=a=$ halt and announce success
    2.        If X=a ≠ $ pop X off stack advance input to next symbol
    3.        If X is a nonterminal use M[X,a] which contains production
              X->rhs or error
              replace X on stack with rhs or call error routine, respectively, e.g. X-
              >UVW replace X with WVU (U on top) output the production (or
              augment parse tree)




                              CS2210 Compiler Design 2004/05




                                                                                         1
Construction of Parsing Table
Helpers (1)
■   First(α) : =set of terminals that begin
    strings derived from α
    ■   First(X) = {X} for terminal X
    ■   If X-> ε a production add ε to First(X)
    ■   For X->Y1…Yk place a in First(X) if a in
        First(Y i) and ε ∈First(Yj) for j=1…i-1, if ε
        ∈First(Yj) j=1…k add ε to First(X)


                     CS2210 Compiler Design 2004/05




Construction of Parsing Table
Helpers (2)
■   Follow(A) := set of terminals a that can appear
    immediately to the right of A in some sentential form
    i.e., S =>* α Aaβ for some α,β (a can include $)
    ■   Place $ in Follow(S), S start symbol, $ right end marker
    ■   If there is a production A-> αBβ put everything in First(β)
        except ε in Follow(B)
    ■   If there is a production A-> αB or A->αBβ where ε is in
        First(β) then everything in Follow(A) is in Follow(B)




                     CS2210 Compiler Design 2004/05




Construction Algorithm
Input: Grammar G
Output: Parsing table M

For each production A -> α do
   For each terminal a in FIRST(α) add
   A-> α to M[A, a]
   If ε is in FIRST(α) add A-> α to M[A,b]
   for each terminal b in FOLLOW(A).
   ($ counts as a terminal in this step)
Make each undefined entry in M to error


                     CS2210 Compiler Design 2004/05




                                                                      2
Example
E -> TE’
                                               Id +
E’ -> +TE’ | ε                                        * (   ) $
T ->FT’
T’ -> *FT’ | ε                         E
F -> (E) | id
FIRST(E) = FIRST(T) = FIRST(F)         E’
   ={(,id}
FIRST(E’) = {+, ε}                     T
FIRST(T’) = {*, ε}
                                       T’
FOLLOW(E)=FOLLOW(E’)={),$}
FOLLOW(T)=FOLLOW(T’)={+,),$}           F
FOLLOW(F) ={+,*,),$}


                   CS2210 Compiler Design 2004/05




LL(1)
■   A grammar whose parsing table has no
    multiply defined entries is said to be LL(1)
    ■   First L = left to right input scanning
    ■   Second L = leftmost derivation
    ■   (1) = 1 token lookahead
■   Not all grammars can be brought to LL(1)
    form, i.e., there are languages that do not fall
    into the LL(1) class


                   CS2210 Compiler Design 2004/05




Bottom Up Parsing




                    CS2210 Compiler Design 2004/05




                                                                  3
Shift-Reduce Parsing
■    Two actions
     ■    Reduce -> replace an input substring that
          matches the rhs of a production with the lhs
          nonterminal
     ■    Shift -> read one more input token
■    Two forms
     ■    Operator precedence parsing
     ■    LR parsing
           ■   Left-to-right scanning
           ■   Rightmost derivation

                        CS2210 Compiler Design 2004/05




Implementation with a stack
                          STACK                INPUT          ACTION
Grammar:                  $                    id1+id2*id3$   shift
                          $id1                 +id2*id3$      reduce: E->id
                          $E                   +id2*id3$      shift
1.    E   ->    E+E       $E+                  id2*id3$       shift
                          $E+id2               *id3$          reduce: E->id
2.    E   ->    E*E       $E+E                 *id3$          shift
                          $E+E*                id3$           shift
3.    E   ->    (E)       $E+E*id3             $              reduce: E->id
4.    E   ->    id        $E+E*E               $              reduce: E->E*E
                          $E+E                 $              reduce: E->E+E
                          $E                   $              accept




                        CS2210 Compiler Design 2004/05




Shift-reduce Conflicts
■    stmt -> if expr then stmt |
               if expr then stmt else stmt |
               other
■    Stack: … if expr then stmt
     Input: else …$
     ■    Don’t know whether to reduce or shift
     ■    Grammar not LR(1) (ambiguous)
     ■    Change grammar or resolve by shifting (tools such
          as yacc do this)


                        CS2210 Compiler Design 2004/05




                                                                               4
LR Parsing
    ■    Can be constructed for almost all
         programming languages constructs
    ■    LR most general non-backtracking shift-
         reduce method and efficiently implementable
    ■    LR ⊃ LL, i.e., can parse more grammars than
         predictive parsers
    ■    Detects syntax errors as early as possible in a
         left-to-right scan
    ■    But: difficult to construct by hand

                           CS2210 Compiler Design 2004/05




    LR Parsers

                                                            action[sm , ai]=
                                                            1. Shift s
                          a1 … a i … an $                   2. Reduce A->β
Stack        Input                                          3. Accept
                                                            4. Error
        sm                  LR Parsing
        Xm                                                  output
                             Program
        sm-1
                                                      Xi grammar symbol
        Xm-1
        …                action      goto             si state symbol
        s0
                           CS2210 Compiler Design 2004/05




    Actions
    ■    Configuration:
         ■     (s0 X1 s1 X2 s2 … Xm sm, a i a i+1 … a n$)
    ■    shift s
         ■     (s0 X1 s1 X2 s2 … Xm sm a i s, ai+1 … an$)
    ■    reduce A->β (r = |β|)
         ■     (s0 X1 s1 X2 s2 … Xm-r sm-r A s, ai ai+1 … an$)
               s = goto[sm-r,A]
               Xm-r+1 … Xm = β
    ■    accept
    ■    error
                           CS2210 Compiler Design 2004/05




                                                                               5
(1) E->E+T
     Parsing Example                                              (2) E->T
State    id    +      *    (       )     $     E     T      F
                                                                  (3) T->T*F

0        S5                S4                  1     2      3     (4) T->F
1              S6                        acc                      (5) F->(E)
2              R2     S7           R2    R2
                                                                  (6) F->id
3              R4     R4           R4    R4
4        S5                S4                  8     2      3
5              R6     R6           R6    R6
6        S5                S4                        9      3
7        S5                S4                               10
                                                                 Input: id*id+id$
8              S6                  S11
9              R1     S7           R1    R1                      Stack: 0
10             R3     R3           R3    R3
11             R5     R5           R5    R5

Action                                             Goto
                               CS2210 Compiler Design 2004/05




     Parsing Example (2)
     ■   LR parse for id*id+id




                               CS2210 Compiler Design 2004/05




     LR Grammars
     ■   = a grammar for which a LR parsing table
         can be constructed
     ■   LR(0) and LR(1) typically of interest
         ■    What about LL(0)?
     ■   Parsing tables from LR grammars
         ■    SLR (simple LR) tables
               ■   Many grammars for which it is not possible
         ■    Canonical LR tables
               ■   Works on “most” grammars
         ■    LALR (= lookahead LR) tables
               ■   Often used in practice because significantly smaller than
                   canonical CS2210 Compiler Design 2004/05
                             LR




                                                                                    6
LR(0) items
■   A->XYZ
■   Items:
    ■   A->.XYZ
    ■   A->X.YZ
    ■   A->XY.Z
    ■   A->XYZ.
■   Represents how much of a production
    we have seen in parsing

                      CS2210 Compiler Design 2004/05




Parse Table Construction
■   Build a DFA to recognize viable prefixes
    ■   = set of prefixes of right sentential forms that can
        appear on the stack of a shift-reduce parser
    ■   Items are ~ states of an NFA for viable prefixes
         ■   Group items together (subset construction) to get DFA
         ■   Define a canonical collection of LR(0) items
■   Helpers:
    ■   Augmented grammar
         ■   S start symbol of G, S’->S new start symbol S’
    ■   Closure function
    ■   Goto function
                      CS2210 Compiler Design 2004/05




Closure
■   I set of items of G
■   Closure(I)
    ■   Initially I
    ■   Repeat
         ■ If A->α.Bβ in closure(I) and B->γ is a production add
         B->.γ to closure
    ■   Until no new items get added




                      CS2210 Compiler Design 2004/05




                                                                     7
Goto
■   Goto(I,X), I set of items, X grammar
    symbol
■   Goto(I,X) :=
    closure({A->αX.β| A->α.Xβ ∈ I})
■   For valid items I for viable prefix γ ,
    then goto(I,X) = valid items for viable
    prefix γX

              CS2210 Compiler Design 2004/05




Sets of Items Construction
procedure items(G’);
begin
  C := closure({S->.S});
  repeat
      for each set of items I in C and each
  grammar symbol X such that goto(I,X) is not
  empty and not in C do
            add goto(I,X) to C
  until no more changes to C
end




              CS2210 Compiler Design 2004/05




Sets of Items Construction
Example
E’ -> E                          I0 =
                                 I1 =
E -> E + T | T                   I2 =
                                 I3 =
T -> T * F | F
                                 I4 =
F -> (E) | id                    I5 =
                                 I6 =
                                 I7 =
                                 I8 =
                                 I9 =
                                 I10 =
                                 I11 =

              CS2210 Compiler Design 2004/05




                                                8
SLR Table Construction
     Input G’ augmented grammar
     1.        Construct C ={I 0 ,…,In}, collection of LR(0) items
     2.        State i is constructed from I i with parsing actions:
               a) if A->α.aβ is in Ii and goto(I i,a) = Ij then action[i,a]
               := shift jγβ (a must be a terminal)
               b) if A-> α. is in Iithen action[i,a] := reduce A-> α for
               all a in Follow(A)
               c) if S’->S is in Ii then set action[I,$] = accept
     3.        Goto transitions for state I are constructed for all
               nonterminal A as follows: if goto(Ii,A) = Ij then
               goto[i,A] := j
     4.        Undefined entries are set to error
     5.        The initial state of the parser is the on constructed
               from the items containing S’->.S



                               CS2210 Compiler Design 2004/05




     SLR Table Example
     Same grammar…




                               CS2210 Compiler Design 2004/05




                                                                (1) E->E+T
     Parsing Example                                            (2) E->T
State     id     +    *    (       )     $     E     T      F
                                                                (3) T->T*F
0                                                               (4) T->F
1                                                               (5) F->(E)
2
                                                                (6) F->id
3
4
5
6
7
8
9
10
11

Action                                             Goto
                               CS2210 Compiler Design 2004/05




                                                                              9

Mais conteúdo relacionado

Mais procurados

Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfixSenthil Kumar
 
Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14IIUM
 
Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14IIUM
 
C++ Overview
C++ OverviewC++ Overview
C++ Overviewkelleyc3
 
CBSE Class XI Programming in C++
CBSE Class XI Programming in C++CBSE Class XI Programming in C++
CBSE Class XI Programming in C++Pranav Ghildiyal
 
verilog code for logic gates
verilog code for logic gatesverilog code for logic gates
verilog code for logic gatesRakesh kumar jha
 
Verilog full adder in dataflow & gate level modelling style.
Verilog full adder in dataflow  & gate level modelling style.Verilog full adder in dataflow  & gate level modelling style.
Verilog full adder in dataflow & gate level modelling style.Omkar Rane
 
Issues in the design of Code Generator
Issues in the design of Code GeneratorIssues in the design of Code Generator
Issues in the design of Code GeneratorDarshan sai Reddy
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfixSelf-Employed
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++guestf0562b
 
1344 Alp Of 8086
1344 Alp Of 80861344 Alp Of 8086
1344 Alp Of 8086techbed
 

Mais procurados (19)

C++
C++C++
C++
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfix
 
04 comb ex
04 comb ex04 comb ex
04 comb ex
 
Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14
 
Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14Csc1100 lecture03 ch03-pt1-s14
Csc1100 lecture03 ch03-pt1-s14
 
[ASM] Lab1
[ASM] Lab1[ASM] Lab1
[ASM] Lab1
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Assembler
AssemblerAssembler
Assembler
 
CBSE Class XI Programming in C++
CBSE Class XI Programming in C++CBSE Class XI Programming in C++
CBSE Class XI Programming in C++
 
verilog code for logic gates
verilog code for logic gatesverilog code for logic gates
verilog code for logic gates
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
 
Manipulators
ManipulatorsManipulators
Manipulators
 
Verilog full adder in dataflow & gate level modelling style.
Verilog full adder in dataflow  & gate level modelling style.Verilog full adder in dataflow  & gate level modelling style.
Verilog full adder in dataflow & gate level modelling style.
 
Issues in the design of Code Generator
Issues in the design of Code GeneratorIssues in the design of Code Generator
Issues in the design of Code Generator
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Eecs 317 20010209
Eecs 317 20010209Eecs 317 20010209
Eecs 317 20010209
 
1344 Alp Of 8086
1344 Alp Of 80861344 Alp Of 8086
1344 Alp Of 8086
 

Destaque

全球定位 行動村里說明-20140101-pdf
全球定位 行動村里說明-20140101-pdf全球定位 行動村里說明-20140101-pdf
全球定位 行動村里說明-20140101-pdfSteve Good-Jobs
 
失學平台Starving no more
失學平台Starving no more失學平台Starving no more
失學平台Starving no moreSteve Good-Jobs
 
The definitive guide_to_the_mediterranean_diet
The definitive guide_to_the_mediterranean_dietThe definitive guide_to_the_mediterranean_diet
The definitive guide_to_the_mediterranean_dietANTHONY FERNANDES
 
17support一起幫-公益暨社會企業整合平台簡介 20140305
17support一起幫-公益暨社會企業整合平台簡介 2014030517support一起幫-公益暨社會企業整合平台簡介 20140305
17support一起幫-公益暨社會企業整合平台簡介 20140305Steve Good-Jobs
 
Tarea nº13 ana patricia nole leon de panta
Tarea nº13  ana patricia nole leon de pantaTarea nº13  ana patricia nole leon de panta
Tarea nº13 ana patricia nole leon de pantaPATRICIANOLELEONDEPANTA
 
Reveiw of 10 20 for sleep
Reveiw of 10 20 for sleepReveiw of 10 20 for sleep
Reveiw of 10 20 for sleepmsartelle
 
Impossible tw socialcrowdfunding-120901
Impossible tw socialcrowdfunding-120901Impossible tw socialcrowdfunding-120901
Impossible tw socialcrowdfunding-120901Steve Good-Jobs
 
Comsharepoint2013pdf
Comsharepoint2013pdfComsharepoint2013pdf
Comsharepoint2013pdfKamal Pandey
 
Edamus condensed business_plan_1217_cn
Edamus condensed business_plan_1217_cnEdamus condensed business_plan_1217_cn
Edamus condensed business_plan_1217_cnSteve Good-Jobs
 
Enzotech presentation May 2013
Enzotech presentation May 2013Enzotech presentation May 2013
Enzotech presentation May 2013enzotechslides
 
Enzotech presentation july12
Enzotech presentation july12Enzotech presentation july12
Enzotech presentation july12enzotechslides
 
Gimp μαθημα 1
Gimp μαθημα 1Gimp μαθημα 1
Gimp μαθημα 1maikl29
 
Final review
Final reviewFinal review
Final reviewmsartelle
 

Destaque (15)

全球定位 行動村里說明-20140101-pdf
全球定位 行動村里說明-20140101-pdf全球定位 行動村里說明-20140101-pdf
全球定位 行動村里說明-20140101-pdf
 
失學平台Starving no more
失學平台Starving no more失學平台Starving no more
失學平台Starving no more
 
The definitive guide_to_the_mediterranean_diet
The definitive guide_to_the_mediterranean_dietThe definitive guide_to_the_mediterranean_diet
The definitive guide_to_the_mediterranean_diet
 
雲林農博小旅行
雲林農博小旅行雲林農博小旅行
雲林農博小旅行
 
17support一起幫-公益暨社會企業整合平台簡介 20140305
17support一起幫-公益暨社會企業整合平台簡介 2014030517support一起幫-公益暨社會企業整合平台簡介 20140305
17support一起幫-公益暨社會企業整合平台簡介 20140305
 
Tarea nº13 ana patricia nole leon de panta
Tarea nº13  ana patricia nole leon de pantaTarea nº13  ana patricia nole leon de panta
Tarea nº13 ana patricia nole leon de panta
 
Reveiw of 10 20 for sleep
Reveiw of 10 20 for sleepReveiw of 10 20 for sleep
Reveiw of 10 20 for sleep
 
Impossible tw socialcrowdfunding-120901
Impossible tw socialcrowdfunding-120901Impossible tw socialcrowdfunding-120901
Impossible tw socialcrowdfunding-120901
 
Comsharepoint2013pdf
Comsharepoint2013pdfComsharepoint2013pdf
Comsharepoint2013pdf
 
Edamus condensed business_plan_1217_cn
Edamus condensed business_plan_1217_cnEdamus condensed business_plan_1217_cn
Edamus condensed business_plan_1217_cn
 
Enzotech presentation May 2013
Enzotech presentation May 2013Enzotech presentation May 2013
Enzotech presentation May 2013
 
Enzotech presentation july12
Enzotech presentation july12Enzotech presentation july12
Enzotech presentation july12
 
Gimp μαθημα 1
Gimp μαθημα 1Gimp μαθημα 1
Gimp μαθημα 1
 
Final review
Final reviewFinal review
Final review
 
Access
AccessAccess
Access
 

Semelhante a Lecture4 (20)

PARSING.ppt
PARSING.pptPARSING.ppt
PARSING.ppt
 
Assemblers
AssemblersAssemblers
Assemblers
 
CS17604_TOP Parser Compiler Design Techniques
CS17604_TOP Parser Compiler Design TechniquesCS17604_TOP Parser Compiler Design Techniques
CS17604_TOP Parser Compiler Design Techniques
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
BOTTOM UP PARSING GROUP 3.pptx
BOTTOM UP PARSING GROUP 3.pptxBOTTOM UP PARSING GROUP 3.pptx
BOTTOM UP PARSING GROUP 3.pptx
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
 
Syntaxdirected
SyntaxdirectedSyntaxdirected
Syntaxdirected
 
Syntaxdirected (1)
Syntaxdirected (1)Syntaxdirected (1)
Syntaxdirected (1)
 
11CS10033.pptx
11CS10033.pptx11CS10033.pptx
11CS10033.pptx
 
12IRGeneration.pdf
12IRGeneration.pdf12IRGeneration.pdf
12IRGeneration.pdf
 
Interm codegen
Interm codegenInterm codegen
Interm codegen
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Sp chap2
Sp chap2Sp chap2
Sp chap2
 
Compiler Design Material 2
Compiler Design Material 2Compiler Design Material 2
Compiler Design Material 2
 
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
 
Pcd(Mca)
Pcd(Mca)Pcd(Mca)
Pcd(Mca)
 
PCD ?s(MCA)
PCD ?s(MCA)PCD ?s(MCA)
PCD ?s(MCA)
 
Principles of Compiler Design
Principles of Compiler DesignPrinciples of Compiler Design
Principles of Compiler Design
 
Pcd(Mca)
Pcd(Mca)Pcd(Mca)
Pcd(Mca)
 
Sdt
SdtSdt
Sdt
 

Último

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 

Último (20)

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 

Lecture4

  • 1. Predictive Parsing (finish) & Bottom-Up Parsing CS2210 Lecture 5 CS2210 Compiler Design 2004/05 Non-recursive Predictive Parsers ■ Avoid recursion for efficiency reasons ■ Typically built automatically by tools Input a + b $ X Predictive Parsing output Stack Y Program Z $ M[A,a]gives production Parsing Table A symbol on stack M a input symbol (and $) CS2210 Compiler Design 2004/05 Parsing Algorithm ■ X symbol on top of stack, a current input symbol ■ Stack contents and remaining input called parser configuration (initially $S on stack and complete input string) 1. If X=a=$ halt and announce success 2. If X=a ≠ $ pop X off stack advance input to next symbol 3. If X is a nonterminal use M[X,a] which contains production X->rhs or error replace X on stack with rhs or call error routine, respectively, e.g. X- >UVW replace X with WVU (U on top) output the production (or augment parse tree) CS2210 Compiler Design 2004/05 1
  • 2. Construction of Parsing Table Helpers (1) ■ First(α) : =set of terminals that begin strings derived from α ■ First(X) = {X} for terminal X ■ If X-> ε a production add ε to First(X) ■ For X->Y1…Yk place a in First(X) if a in First(Y i) and ε ∈First(Yj) for j=1…i-1, if ε ∈First(Yj) j=1…k add ε to First(X) CS2210 Compiler Design 2004/05 Construction of Parsing Table Helpers (2) ■ Follow(A) := set of terminals a that can appear immediately to the right of A in some sentential form i.e., S =>* α Aaβ for some α,β (a can include $) ■ Place $ in Follow(S), S start symbol, $ right end marker ■ If there is a production A-> αBβ put everything in First(β) except ε in Follow(B) ■ If there is a production A-> αB or A->αBβ where ε is in First(β) then everything in Follow(A) is in Follow(B) CS2210 Compiler Design 2004/05 Construction Algorithm Input: Grammar G Output: Parsing table M For each production A -> α do For each terminal a in FIRST(α) add A-> α to M[A, a] If ε is in FIRST(α) add A-> α to M[A,b] for each terminal b in FOLLOW(A). ($ counts as a terminal in this step) Make each undefined entry in M to error CS2210 Compiler Design 2004/05 2
  • 3. Example E -> TE’ Id + E’ -> +TE’ | ε * ( ) $ T ->FT’ T’ -> *FT’ | ε E F -> (E) | id FIRST(E) = FIRST(T) = FIRST(F) E’ ={(,id} FIRST(E’) = {+, ε} T FIRST(T’) = {*, ε} T’ FOLLOW(E)=FOLLOW(E’)={),$} FOLLOW(T)=FOLLOW(T’)={+,),$} F FOLLOW(F) ={+,*,),$} CS2210 Compiler Design 2004/05 LL(1) ■ A grammar whose parsing table has no multiply defined entries is said to be LL(1) ■ First L = left to right input scanning ■ Second L = leftmost derivation ■ (1) = 1 token lookahead ■ Not all grammars can be brought to LL(1) form, i.e., there are languages that do not fall into the LL(1) class CS2210 Compiler Design 2004/05 Bottom Up Parsing CS2210 Compiler Design 2004/05 3
  • 4. Shift-Reduce Parsing ■ Two actions ■ Reduce -> replace an input substring that matches the rhs of a production with the lhs nonterminal ■ Shift -> read one more input token ■ Two forms ■ Operator precedence parsing ■ LR parsing ■ Left-to-right scanning ■ Rightmost derivation CS2210 Compiler Design 2004/05 Implementation with a stack STACK INPUT ACTION Grammar: $ id1+id2*id3$ shift $id1 +id2*id3$ reduce: E->id $E +id2*id3$ shift 1. E -> E+E $E+ id2*id3$ shift $E+id2 *id3$ reduce: E->id 2. E -> E*E $E+E *id3$ shift $E+E* id3$ shift 3. E -> (E) $E+E*id3 $ reduce: E->id 4. E -> id $E+E*E $ reduce: E->E*E $E+E $ reduce: E->E+E $E $ accept CS2210 Compiler Design 2004/05 Shift-reduce Conflicts ■ stmt -> if expr then stmt | if expr then stmt else stmt | other ■ Stack: … if expr then stmt Input: else …$ ■ Don’t know whether to reduce or shift ■ Grammar not LR(1) (ambiguous) ■ Change grammar or resolve by shifting (tools such as yacc do this) CS2210 Compiler Design 2004/05 4
  • 5. LR Parsing ■ Can be constructed for almost all programming languages constructs ■ LR most general non-backtracking shift- reduce method and efficiently implementable ■ LR ⊃ LL, i.e., can parse more grammars than predictive parsers ■ Detects syntax errors as early as possible in a left-to-right scan ■ But: difficult to construct by hand CS2210 Compiler Design 2004/05 LR Parsers action[sm , ai]= 1. Shift s a1 … a i … an $ 2. Reduce A->β Stack Input 3. Accept 4. Error sm LR Parsing Xm output Program sm-1 Xi grammar symbol Xm-1 … action goto si state symbol s0 CS2210 Compiler Design 2004/05 Actions ■ Configuration: ■ (s0 X1 s1 X2 s2 … Xm sm, a i a i+1 … a n$) ■ shift s ■ (s0 X1 s1 X2 s2 … Xm sm a i s, ai+1 … an$) ■ reduce A->β (r = |β|) ■ (s0 X1 s1 X2 s2 … Xm-r sm-r A s, ai ai+1 … an$) s = goto[sm-r,A] Xm-r+1 … Xm = β ■ accept ■ error CS2210 Compiler Design 2004/05 5
  • 6. (1) E->E+T Parsing Example (2) E->T State id + * ( ) $ E T F (3) T->T*F 0 S5 S4 1 2 3 (4) T->F 1 S6 acc (5) F->(E) 2 R2 S7 R2 R2 (6) F->id 3 R4 R4 R4 R4 4 S5 S4 8 2 3 5 R6 R6 R6 R6 6 S5 S4 9 3 7 S5 S4 10 Input: id*id+id$ 8 S6 S11 9 R1 S7 R1 R1 Stack: 0 10 R3 R3 R3 R3 11 R5 R5 R5 R5 Action Goto CS2210 Compiler Design 2004/05 Parsing Example (2) ■ LR parse for id*id+id CS2210 Compiler Design 2004/05 LR Grammars ■ = a grammar for which a LR parsing table can be constructed ■ LR(0) and LR(1) typically of interest ■ What about LL(0)? ■ Parsing tables from LR grammars ■ SLR (simple LR) tables ■ Many grammars for which it is not possible ■ Canonical LR tables ■ Works on “most” grammars ■ LALR (= lookahead LR) tables ■ Often used in practice because significantly smaller than canonical CS2210 Compiler Design 2004/05 LR 6
  • 7. LR(0) items ■ A->XYZ ■ Items: ■ A->.XYZ ■ A->X.YZ ■ A->XY.Z ■ A->XYZ. ■ Represents how much of a production we have seen in parsing CS2210 Compiler Design 2004/05 Parse Table Construction ■ Build a DFA to recognize viable prefixes ■ = set of prefixes of right sentential forms that can appear on the stack of a shift-reduce parser ■ Items are ~ states of an NFA for viable prefixes ■ Group items together (subset construction) to get DFA ■ Define a canonical collection of LR(0) items ■ Helpers: ■ Augmented grammar ■ S start symbol of G, S’->S new start symbol S’ ■ Closure function ■ Goto function CS2210 Compiler Design 2004/05 Closure ■ I set of items of G ■ Closure(I) ■ Initially I ■ Repeat ■ If A->α.Bβ in closure(I) and B->γ is a production add B->.γ to closure ■ Until no new items get added CS2210 Compiler Design 2004/05 7
  • 8. Goto ■ Goto(I,X), I set of items, X grammar symbol ■ Goto(I,X) := closure({A->αX.β| A->α.Xβ ∈ I}) ■ For valid items I for viable prefix γ , then goto(I,X) = valid items for viable prefix γX CS2210 Compiler Design 2004/05 Sets of Items Construction procedure items(G’); begin C := closure({S->.S}); repeat for each set of items I in C and each grammar symbol X such that goto(I,X) is not empty and not in C do add goto(I,X) to C until no more changes to C end CS2210 Compiler Design 2004/05 Sets of Items Construction Example E’ -> E I0 = I1 = E -> E + T | T I2 = I3 = T -> T * F | F I4 = F -> (E) | id I5 = I6 = I7 = I8 = I9 = I10 = I11 = CS2210 Compiler Design 2004/05 8
  • 9. SLR Table Construction Input G’ augmented grammar 1. Construct C ={I 0 ,…,In}, collection of LR(0) items 2. State i is constructed from I i with parsing actions: a) if A->α.aβ is in Ii and goto(I i,a) = Ij then action[i,a] := shift jγβ (a must be a terminal) b) if A-> α. is in Iithen action[i,a] := reduce A-> α for all a in Follow(A) c) if S’->S is in Ii then set action[I,$] = accept 3. Goto transitions for state I are constructed for all nonterminal A as follows: if goto(Ii,A) = Ij then goto[i,A] := j 4. Undefined entries are set to error 5. The initial state of the parser is the on constructed from the items containing S’->.S CS2210 Compiler Design 2004/05 SLR Table Example Same grammar… CS2210 Compiler Design 2004/05 (1) E->E+T Parsing Example (2) E->T State id + * ( ) $ E T F (3) T->T*F 0 (4) T->F 1 (5) F->(E) 2 (6) F->id 3 4 5 6 7 8 9 10 11 Action Goto CS2210 Compiler Design 2004/05 9