60 likes | 229 Views
Parsing Bottom Up. CMPS 450 J. Moloney. Bottom Up Parsing. Parse tree build up from leaves We will examine “LR” parsers – L eft-to-right, R ightmost derivation. Rightmost Parsers Use a stack. Read input from left to right. Create a rightmost derivation.
E N D
ParsingBottom Up CMPS 450 J. Moloney CMPS 450
Bottom Up Parsing • Parse tree build up from leaves • We will examine “LR” parsers – Left-to-right, Rightmost derivation • Rightmost Parsers • Use a stack. • Read input from left to right. • Create a rightmost derivation. • Reads input until entire right-hand side of a rule has been found, then reduce by that rule. • Process continues until entire input has been processed. CMPS 450
Example Stack Input <empty> abd$ a bd$ ab d$ abd $ S $ • Simple Grammar • Terminals: {a,b,c,d} • Non-Terminals {S’, S} • (0) S’ S$ • S abc • S abcd • Simple Expression Grammar • Terminals: {id, +, *} • Non-Terminals {E, T} • (0) E’ E$ • E E + T • E T • T T * id • T id Example Stack Input <empty>id + id $ id + id $ shift T + id $ R-4 E + id $ R-2 E + id $ shift E + id $ Shift E + T $ R – 4 E $ R – 1 E’ <empty> R - 0 CMPS 450
Example Stack Input <empty>id + id * id $ shift id + id * id $ R-4 T + id * id $ R - 2 E + id * id $ shift E + * id $ shift E + id * id $ R - 4 E + T * id $ shift E + T * id $ shift E + T $ R – 1 E’ $ <empty> shift E’ $ R - 0 • Simple Expression Grammar • Terminals: {id, +, *} • Non-Terminals {E, T} • (0) E’ E$ • E E + T • E T • T T * id • T id Rightmost Derivation E’ E$ E + T$ E + T * id E + id * id$ T + id * id$ id + id * id$ CMPS 450
Shift/ Reduce – LR Parse Tables • Use DFA as well as past state to determine shift or reduce. • A stack holds terminals, nonterminals and state info. • Push State 1 on top of the stack. • According to the parse table – row of the state on the top of the stack, column of the next input symbol • If there is no entry parsing fails • If the entry is “accept” , then accept the string, parsing is successful • If entry is a shift – sn – push the next symbol and State n on the stack, and go back to step 2. • If the entry is a reduce – r(n) – pop off all the symbols (and associated states) form the stack that match the right-hand side of rule (n), to get a new state according to the parse table (row of the stare on top of the stack, column of the non-terminal on the left-hand side of rule (n)). Push the non-terminal on the left-hand side of the rule and the new state on top of the stack and go to step 2. CMPS 450
Parse Table Example id + id$ id * id + id $ id id + $ id + * $ CMPS 450