Bottom-Up Syntax Anaysis

Size: px
Start display at page:

Download "Bottom-Up Syntax Anaysis"

Transcription

1 Implementation of Parsers Bottom-Up Syntax Anaysis Educational Objectives: General Principles of LR(k) Analysis Resolving Conflicts in Parser Generation Connection between CFGs and push-down automata Ina Schaefer Context-Free Analysis 59

2 Implementation of Parsers Basic Ideas: Bottom-Up Analysis is more powerful than top-down analysis, since production is chosen at the end of the analysis while in top-down analysis the production is selected up front. LR: Read input from left (L) and search for right derivations (R) Ina Schaefer Context-Free Analysis 60

3 Implementation of Parsers Principles of LR Parsing 1. Reduce from sentence to axiom 2. Construct sentential forms from prefixes in (N T ) and input rests in T. Prefixes are right sentential forms of grammar. Such prefixes are called viable prefixes. This prefix property has to hold invariantly to avoid dead ends. 3. Reductions are always made at the left-most possible position. Ina Schaefer Context-Free Analysis 61

4 Viable Prefix Implementation of Parsers Definition Let S rm βau rm βαu a right sentential form of Γ. Then α is called handle or redex of the right sentential for βαu. Each prefix of βα is a viable prefix of Γ. Ina Schaefer Context-Free Analysis 62

5 Implementation of Parsers Regularity of Viable Prefixes Theorem The language of viable prefixes of a grammar Γ is regular. Proof. Cf. Wilhelm, Maurer Thm and Corrollary (pp. 361, 362), Essential proof steps are illustrated in the following by construction of LR DFA(Γ). Ina Schaefer Context-Free Analysis 63

6 Implementation of Parsers LR Parsing: Examples Consider Γ 1 S acd C b D a b Analysis of aba can lead to an dead end. (cf. Lecture). Considering viable prefixes can avoid this. Ina Schaefer Context-Free Analysis 64

7 Implementation of Parsers LR Parsing: Examples (2) Consider Γ 2 S E# E a (E) EE Analysis of ( ( a ) ) ( a) # (cf. Lecture) Stack can manage prefixes already read. Ina Schaefer Context-Free Analysis 65

8 Implementation of Parsers LR Parsing: Examples (3) Consider Γ 3 S E# E E + T T T ID Analysis of ID + ID + ID # (cf. Lecture) Ina Schaefer Context-Free Analysis 66

9 Implementation of Parsers LR Parsing: Shift and Reduce Schematic syntax tree for input xay with a T, x, y T and start symbol S:! x a y Read Lesezeiger Pointer Ina Schaefer Context-Free Analysis 67

10 Implementation of Parsers LR Parsing: Shift and Reduce (2) Shift step: Reduce step: "$!a =>! = "# x a y Lesezeiger Read Pointer x a y Lesezeiger Read Pointer Ina Schaefer Context-Free Analysis 68

11 Implementation of Parsers LR Parsing: Shift and Reduce (3) Main Problems: Reductions can only be performed if remaining prefix is still a viable prefix. When to shift? When to reduce? Which production to use? Solution: For each grammar Γ construct LR DFA(Γ) automaton (also called LR(0) automaton), that describes the viable prefixes. Ina Schaefer Context-Free Analysis 69

12 Implementation of Parsers Construction of LR-DFA Let Γ=( T, N, Π, S) be a CFG. For each non-terminal n N, construct Item Automaton Build union of item automata: Start state is the start state of item automaton for S, Final states are final states of item automata Add ɛ transitions from each state which contains the position point in front for a non-terminal A to the starting state of the item automaton of A If all states of the LR-DFA automaton are considered as final states, the accepted language is the language of viable prefixes. Ina Schaefer Context-Free Analysis 70

13 Implementation of Parsers Construction of LR-DFA: Example Γ 3 : S E#, E E + T T, T ID E # [S.E #] [S E.# ] [S E#.] [E.E+T] [E.T ] " " E + T [E E.+T] [E E+.T] [E E+T.] T [E T.] " " [T.ID ] ID [T ID.] Ina Schaefer Context-Free Analysis 71

14 Implementation of Parsers Construction of LR-DFA: Example (2) Determinisation: q0 [S.E #] [E.E+T] [E.T ] [T.ID ] T ID q1 E [S E.# ] # [E E.+T] + Error Fehler q5 [E T.] [T ID.] q7 ID q6 q2 [S E#.] q3 [E E+.T] [T.ID ] T [E E+T.] q4 Error Transitions bezeichnet Fehlerkanten Viable prefixes of maximal length: E#, T, ID, E + ID, E + T Ina Schaefer Context-Free Analysis 72

15 Implementation of Parsers Construction of LR-DFA: Example (3) Remarks: In the example, each final state contains one completely read production, this is in general not the case. If a final state contains more than one completely read productions, we have a reduce/reduce conflict. If a final state contains a completely read and an uncompletely read production with a terminal after the position point, we have a shift/reduce conflict. Ina Schaefer Context-Free Analysis 73

16 Implementation of Parsers Analysis with LR-DFA Analysis of ID + ID + ID # with LR-DFA (the viable prefix is underlined) ID + ID + ID # <= T + ID + ID # <= E + ID + ID # <= E + T + ID # <= E + ID # <= E + T # <= E # <= S Ina Schaefer Context-Free Analysis 74

17 Implementation of Parsers Analysis with LR-DFA (2) Note: The sentential forms always consist of a viable prefix and a remaining input. If an LR-DFA is used, after each reduction the sentential form has to be read from the beginning. Thus: Use pushdown automaton for analysis. Ina Schaefer Context-Free Analysis 75

18 Implementation of Parsers LR pushdown automaton Definition Let Γ=( N, T, Π, S) be a CFG. The LR-DFA pushdown automaton for Γ contains: a finite set of state Q (the states of the LR-DFA(Γ)) a set of actions Act = {shift, accept, error} red(π), where red(π) contains an action reduce(a α) for each production A α. an action table at : Q Act. a successor table succ : P (N T ) Q with P = {q Q at(q) =shift} Ina Schaefer Context-Free Analysis 76

19 Implementation of Parsers LR pushdown automaton (2) Remarks: The LR-DFA pushdown automaton is a variant of pushdown automata particularly designed for LR parsing. States encode the read left context. If there are no conflicts, the action table can be directly constructed from the LR-DFA: accept: final state of item automaton of start symbol reduce: all other final states error: error state shift: all other states Ina Schaefer Context-Free Analysis 77

20 Implementation of Parsers Execution of Pushdown Automaton Configuration: Q T where variable stack denotes the sequence of states and variable inr denotes the remaining input Start configuration: (q 0, input), where q 0 is the start state of the LR-DFA Interpretation Procedure: (stack, inr) := (q0,input); do { step(stack,inr); } while ( at(top(stack))!= accept and at(top(stack))! = error ); if (( at (top(stack)) == error) return error; with Ina Schaefer Context-Free Analysis 78

21 Implementation of Parsers Execution of Push-Down Automaton (2) void step ( var StateSeq stack, var SymbolSeq inr) { State tk: = top(stack); switch ( at(tk) ) { case shift: stack: = push ( succ (tk,top(inr)), keller); inr := tail(inr); break; case reduce A -> a: stack := mpop( length(a),stack); stack := push (succ(top(stack), A), stack); break; } } Ina Schaefer Context-Free Analysis 79

22 Implementation of Parsers LR push down automaton: Example LR-DFA with states q 0,..., q 7 for grammar Γ 3 Action Table Aktionstabelle: q0 schieben shift q1 schieben shift q2 akzeptieren accept q3 schieben shift q4 reduzieren reduce E E+T q5 reduzieren reduce E T q6 reduzieren reduce T ID q7 fehler error Successor Table ID + # E T q0 q6 q7 q7 q1 q5 q1 q7 q3 q2 q7 q7 q2 q3 q6 q7 q7 q7 q4 q4 q5 q6 q7 Ina Schaefer Context-Free Analysis 80

23 Implementation of Parsers LR push down automaton: Example (2) Computation for Input ID + ID + ID # Stack Input Rest Action Keller Eingaberest Aktion q0 q0 q6 q0 q5 q0 q1 q0 q1 q3 q0 q1 q3 q6 q0 q1 q3 q4 q0 q1 q0 q1 q3 q0 q1 q3 q6 q0 q1 q3 q4 q0 q1 q0 q1 q2 ID + ID + ID # schieben shift + ID + ID # reduce reduzieren T ID + ID + ID # reduce reduzieren E T + ID + ID # shift schieben ID + ID # schieben shift + ID # reduce reduzieren T ID + ID # reduce reduzieren E E+T + ID # shift schieben ID # shift schieben # reduce reduzieren T ID # reduce reduzieren E E+T # shift schieben accept akzeptieren Ina Schaefer Context-Free Analysis 81

24 Implementation of Parsers LR-DFA Construction Questions: Does LR-DFA construction work for all unambiguous grammars? For which grammars does the construction work? How can the construction be generalized / made more expressive? Ina Schaefer Context-Free Analysis 82

25 Example LR-DFA Implementation of Parsers LR-DFA for Γ 6 : S E#, E T + E T, T ID N(), N ID q0 q1 q2 # q3 [S E.# ] [S E#.] [E T+E.] E [S.E #] [E.T+E] [E.T ] [T.ID ] [T [N.N( ) ].ID ] N T ID [E T.+E] [E T. ] [T ID.] [N ID.] q4 q6 + T ID N E q5 [E T+.E] [E.T+E] [E.T ] [T.ID ] [T.N( ) ] [N.ID ] q10 error Fehler [ T N.( ) ] [ T N(.) ] ( ) [ T N( ). ] q7 q8 q9 Error Transitions bezeichnet Fehlerkanten Ina Schaefer Context-Free Analysis 83

26 Implementation of Parsers LR Parsing Conflicts 2 Kinds of Conflicts: Shift/Reduce Conflicts (q 4 in example) Reduce/Reduce Conflicts (q 6 in example) Ina Schaefer Context-Free Analysis 84

27 LR Parsing Theory Implementation of Parsers Definition Let Γ=( N, T, Π, S) be a CFG and k N. Γ is an LR(k) grammar if for any two right derivations S rm αau rm αβu S rm γbv rm αβw it holds that: If prefix(k, u) =prefix(k, w) then α = γ, A = B and v = w Ina Schaefer Context-Free Analysis 85

28 Implementation of Parsers LR Parsing Theory (2) Remarks: While for LL grammars the selection of the production depends on the non-terminal to be derived, for LR grammars it depends on the complete left context. For LL grammars, the look ahead considers the language to be generated from the non-terminal. For LR grammars, the look ahead considers the language generated from not yet read non-terminals. Ina Schaefer Context-Free Analysis 86

29 Implementation of Parsers Characterization of LR(0) Theorem A reduced CFG Γ is LR(0) if-and-only-if the LR-DFA(Γ) contains no conflicts. Proof. cf. Lecture Ina Schaefer Context-Free Analysis 87

30 Implementation of Parsers Characterization of LR(0) (2) Example: Application of LR(0)-Chracterization Show (using the above theorem) that Γ 5 is LR(0). Γ 5 : S A B A aab 0 B abbb 1 Ina Schaefer Context-Free Analysis 88

31 Implementation of Parsers Expressiveness of LR(k) For each context-free language L with prefix property (i.e. v, w L: v is no prefix of w), there exists an LR(0) grammar. Grammar Γ 5 is not LL(k), but LR(0). Methods for LR(1) can be generalized to LR(k), SLR(k) and LALR(k). Ina Schaefer Context-Free Analysis 89

32 Implementation of Parsers Resolving Conflicts by Look Ahead Compute look ahead sets from (N T ) k for items. The look ahead set of an item approximates the set of prefixes of length k with which the input rest at this item can start. If the look ahead sets at an item are disjoint, then the action to be executed (shift, reduce) can be determined by k symbols look ahead. For an item, select the action whose look ahead set contains the prefix of the input rest. Action table has to be extended. For computation of look ahead sets, there are different methods. Ina Schaefer Context-Free Analysis 90

33 Implementation of Parsers Common Methods for Look Ahead Computation SLR(k) uses LR-DFA and FOLLOW k of conflicting items for look ahead LALR(k) - look ahead LR - uses LR-DFA with state-dependent look ahead sets LR(k) integrates computation of look ahead sets in automata construction (LR(k) automaton) Ina Schaefer Context-Free Analysis 91

34 Implementation of Parsers SLR Grammars Definition (SLR(1) grammar) Let Γ=( N, T, Π, S) be a CFG and LA([A α.]) = FOLLOW 1 (A). A state LR-DEA(Γ) has an SLR(1) conflict if there exists two different reduce items with LA([A α.]) LA([B β.]) or two items [A α.] and [B α.aβ] with a LA([A a]). Γ is SLR(1) if there is no SLR(1) conflict. Ina Schaefer Context-Free Analysis 92

35 SLR Grammars (2) Implementation of Parsers Example: Γ 6 is an SLR(1) grammar S E# E T + E T T ID N() N ID Consider the conflicts between [E T.] and [E T. + E] and between [T ID.] and [N ID.] FOLLOW 1 (E) {+} = {#} { +} = FOLLOW 1 (T ) FOLLOW 1 (N) ={#, +} { (} = Ina Schaefer Context-Free Analysis 93

36 SLR Grammars (3) Implementation of Parsers Example: Γ 7 (simplifed C expressions) is not an SLR(1) grammar S E# E L = R R L R ID R L Ina Schaefer Context-Free Analysis 94

37 SLR Grammars (4) Implementation of Parsers LR-DFA for Γ 7 [E R.] [S E.# ] # [S E#. ] R [S.E# ] [E.L=R] [E.R] [L.*R] [L.ID] [R.L] E [L *.R] R [R.L] * [L.*R] [L.ID] * ID L ID [L ID.] [R L.] [L *R.] * L [E L.=R] [R L.] = ID [E L=.R] [R.L] [L.*R] [L.ID] L R [E L=R.] Only conflict in items [E L. = R] and [R L.] with FOLLOW 1 (R) {=} = {=, #} { =} Ina Schaefer Context-Free Analysis 95

38 Implementation of Parsers Construction of LR(1) Automata LR(1) automaton contains items [A α.β, V ] with V T where α is on top of the stack the input rest is derivable from βc with c V, i.e. V FOLLOW 1 (A). Ina Schaefer Context-Free Analysis 96

39 Implementation of Parsers Construction of LR(1) Automata (2) LR(1) automaton for Γ 7. Conflict is resolved, as {=} { #} =. S S E#. E E.# S.E# E.L=R # E.R # L.*R #,= L.ID #,= R.L # * # L *.R #,= R.L #,= L.*R #,= L.ID #,= L R ID ID L R E L.=R # = R L. # L E R. # R L. # L ID. #,= L ID. # ID R L. #,= L *R. #,= L E L=.R # R.L # L.*R # L.ID # R E L=R. # * * L *.R # R.L # L.*R # L.ID # R L *R. # * Ina Schaefer Context-Free Analysis 97

40 LALR(1) Automata Implementation of Parsers LALR(1) Automata are constructed from LR(1) automata by merging states in which items only differ in look ahead sets. Look ahead sets for equal items are conjoint. The resulting automaton has the same states as the LR-DFA. However, LALR(1) automata can be generated more efficiently. Ina Schaefer Context-Free Analysis 98

41 Implementation of Parsers LALR(1) Automata (2) LR(1) automaton for Γ 7. S E#. q3 # S E.# q0 E S.E# E.L=R # E.R # L.*R #,= L.ID #,= R.L # L R ID q8 q4 E L.=R # = E L=.R # R L. # R.L # L.*R # q5 L.ID # E R. # q9 R q1 L ID. #,= ID L E L=R. # q2 * L *.R #,= R.L #,= L.*R #,= L.ID #,= ID L R q6 R L. #,= q7 L *R. #,= * * Ina Schaefer Context-Free Analysis 99

42 Grammar Classes Implementation of Parsers unambiguous eindeutige Grammatiken grammars LL(k) LL(1) LR(k) LR(1) LALR(1) SLR(1) LL(0) LR(0) ambiguous grammars mehrdeutige Grammatiken Ina Schaefer Context-Free Analysis 100

43 Implementation of Parsers Literature Recommended Reading for Bottom-Up Analysis: Wilhelm, Maurer: Chapter 8, Sections , pp Ina Schaefer Context-Free Analysis 101

44 Implementation of Parsers Parser Generators Educational Objectives Usage of Parser Generators Characteristics of Parser Generators Ina Schaefer Context-Free Analysis 102

45 Implementation of Parsers JavaCUP Parser Generator CUP - Constructor of Useful Parsers Java-based Generator for LALR-Parsers JFlex can be used to generate according scanner. Running JavaCUP: java -jar java-cup-11a.jar options inputfile Ina Schaefer Context-Free Analysis 103

46 Implementation of Parsers Structure of JavaCUP Specification package JavaPackageName; import java_cup.runtime.*; /* User supplied code for scanner, actions,... */ /* Terminals (tokens returned by the scanner). */ terminal TerminalDecls; /* Non-terminals */ non terminal NonTerminalDecls; /* Precedences */ precedence [left right nonassoc ] TerminalList; /* Grammar */ start with non-terminalname; non_terminalname :: = prod_1... prod_n ; Ina Schaefer Context-Free Analysis 104

47 Implementation of Parsers Example: JavaCUP Specification for Γ 7 import java_cup.runtime.*; /* Terminals (tokens returned by the scanner). */ terminal ID, EQ, MULT; /* Non terminals */ non terminal S, E, L, R; /* The grammar */ start with S; S ::= E; E ::= L EQ R R; L ::= MULT R ID; R ::= L; Ina Schaefer Context-Free Analysis 105

48 Implementation of Parsers Structure of Generated Parser Code Output Files parser.java and sym.java Tables for LALR Automaton Production table: provides the symbol number of the left hand side non-terminal, along with the length of the right hand side, for each production in the grammar, Action table: indicates what action (shift, reduce, or error) is to be taken on each lookahead symbol when encountered in each state Reduce-goto table: indicates which state to shift to after reduce Ina Schaefer Context-Free Analysis 106

49 Implementation of Parsers Usage of Generated Parser Parser calls scanner with scan() method when a new terminal is needed Initialising Parser with new Scanner parser parser_obj = new parser(new my_scanner()); Usage of Parser: Symbol parse_tree = parser_obj.parse(); Ina Schaefer Context-Free Analysis 107

50 Error Handling Error Handling Educational Objectives: Problems and Principles of Error Handling Techniques of Error Handling for Context-Free Analysis Ina Schaefer Context-Free Analysis 108

51 Error Handling Principles of Error Handling Error handling is required in all analysis phases and at runtime. One distinguishes lexical errors parse errors (in context-free analysis) errors in name and type analysis runtime errors (cannot be avoided in most cases) logical errors (behavioural errors) First 2 (3) kinds of errors are syntactic errors. We only consider error handling in context-free analysis. Specification of error handling results basically from language specification. Ina Schaefer Context-Free Analysis 109

52 Error Handling Requirements for error handling Errors should be localized as exactly as possible. (Problem: Error is not detected at error position.) As many errors at possible should be detected at once, but only real errors and no errors as consequences. Errors are not always unique, i.e. it is not clear in general how to correct an error: class int { Int a;... } or int a = 1-; Error handling should not slow down analysis of correct programs. Therefore, error handling is non-trivial and depends on the source language to be analysed. Ina Schaefer Context-Free Analysis 110

53 Error Handling Error Handling in Context-Free Analysis 1. Panic Error Handling Mark synchronizing terminal symbols, e.g. end or ; If parser reaches error state, all symbols up to next synchronizing symbol are skipped and the stack is corrected as if the production with the synchronizing symbol was read correctly. Pros: easy to implement, termination guaranteed Cons: large parts of the program can be skipped or misinterpreted Example: Incorrect Input a : = b *** c; Read until ; correct stack and reuse as if statement has been accepted Ina Schaefer Context-Free Analysis 111

54 Error Handling Error Handling in Context-Free Analysis (2) 2. Error Productions Extend grammar with productions describing typical error situations, so called error productions. Error messages can be directly associated with error productions. Pros: easy to implement, termination guaranteed Cons: extended grammar can belong to more general grammar class, knowledge of typical error situations is necessary Example: Typical error in PASCAL if... then A := E; else... Error Production: Stmt if Expr then Stmt ; else Stmt Ina Schaefer Context-Free Analysis 112

55 Error Handling Error Handling in Context-Free Analysis (3) 3. Production-Local Error Correction Goal is local correction of input such that analysis can be resumed. Local means that it is tried to correct the input for the current production. Pros: flexible and powerful technique Cons: problematic if errors occur earlier than they can be detected, operations for corrections can lead to nonterminating analysis Ina Schaefer Context-Free Analysis 113

56 Error Handling Error Handling in Context-Free Analysis (4) 4. Global Error Correction Attempt to get a correction that is as good as possible by altering the read input or the look ahead input. Idea: Define distance or quality measure on inputs. For each incorrect input, look for a syntactically correct input that is best according to the used measure. Pros: very powerful technique Cons: analysis effort can be rather high, implementation is complex and poses risk of non-termination. Ina Schaefer Context-Free Analysis 114

57 Error Handling Error Handling in Context-Free Analysis (5) 5. Interactive Error Correction In modern programming languages, syntactic analysis is often already supported by editors. In this case, editor marks error positions. Pros: quick feedback, possible error positions are shown directly, interaction with programmer possible Cons: editing can be disturbed, analysis must be able to handle incomplete programs The presented techniques can also be combined. For selection of technique, programming language syntax is important. Error handling also depends on grammar class and implementation techniques used for parser. Ina Schaefer Context-Free Analysis 115

58 Error Handling Burke-Fischer Error Handling Example of global error correction technique Procedure: Use correction window of n symbols before symbol at which error was detected. Check all possible variations of symbol sequence in correction window that can be obtained by insertion, exchange or modification of a symbol at any position. Quality Measure: Choose variation that allows longest continuation of parsing procedure Implementation: Work with two stack automata, one represents the configuration at the beginning of the correction window, the other one the configuration at the end of the correction window. In an error case, the automaton running behind can be used to resume at the old position and to test the computed variations. Ina Schaefer Context-Free Analysis 116

59 Literature Error Handling Recommended Reading: Wilhelm, Maurer: Chapter 8, Sections and (general understanding sufficient) Ina Schaefer Context-Free Analysis 117

60 Concrete and Abstract Syntax Concrete and Abstract Syntax Educational Objectives Connection of parsing to other phases of program processing and translation Differences between abstract and concrete syntax Language concepts for describing syntax trees Syntax tree construction Ina Schaefer Context-Free Analysis 118

61 Concrete and Abstract Syntax Connection of Parsers to other Phases 1. Parser directly controls following phases 2. Concrete Syntax Tree as Interface 3. Abstract Syntax Tree as Interface Ina Schaefer Context-Free Analysis 119

62 Concrete and Abstract Syntax Direct Control by Parser Example: Recursive Descent: Parser calls other actions after each derivation/reduction step Pros: simple (if realisable) flexible efficient (especially memory efficient) Cons: non-modular, no clear interfaces not suitable for global aspects of translation following phases depend on parsing cannot be used with every parser generator Ina Schaefer Context-Free Analysis 120

63 Concrete and Abstract Syntax Abstract Syntax vs. Concrete Syntax Definition (Concrete Syntax) The concrete syntax of a programming languages determines the actual text representation of the programs (incl. key words, separators). If Γ is the CFG used for parsing a program P in a certain language, the syntax tree of P according to Γ is the concrete syntax tree of P. Definition (Abstract Syntax) The abstract syntax of a programming language describes the tree structure of programs in a form that is sufficient and suitable for further processing. A tree for representing a program P according to the abstract syntax of a language is called abstract syntax tree of P. Ina Schaefer Context-Free Analysis 121

64 Abstract Syntax Concrete and Abstract Syntax abstraction from keywords and separators operator precedences are represented in tree structure (different non-terminals are not necessary) better incorporation of symbol information simplifying transformations Remarks: The abstract syntax of a language is often not specified in the language report. The abstract syntax usually also comprises information about source code positions. Ina Schaefer Context-Free Analysis 122

65 Concrete and Abstract Syntax Example: Concrete vs. Abstract Syntax Concrete Syntax: Γ 2 S E# E T + E T T F T F F (E) ID Abstract Syntax Exp = Add Mult Ident Add (Exp left, Exp right) Mult (Exp left, Exp right) Ina Schaefer Context-Free Analysis 123

66 Concrete and Abstract Syntax Example: Concrete vs. Abstract Syntax (2) Text: (a + b) c Concrete Syntax Tree Abstract Syntax Tree S E # Mult T T F Add c F E a b E T T F F ( ID + ID ) * ID a b c Ina Schaefer Context-Free Analysis 124

67 Concrete and Abstract Syntax Concrete Syntax Tree as Interface Token Stream Parser (with Tree Construction) Concrete Syntax Tree Further Language Processing Counters disadvantages of direct control by parser Advantages over Abstract Syntax No additional specification of abstract syntax required Tree construction does not have to be described. Tree construction can be done automatically by parser generators. Ina Schaefer Context-Free Analysis 125

68 Concrete and Abstract Syntax Abstract Syntax Tree as Interface Token Stream Parser (with Transforming Tree Construction) Abstract Syntax Tree Further Language Processing Advantages over Concrete Syntax Simpler, more compact tree representation Simplifies later phases Often implemented by programming or specification language as mutable data structure Ina Schaefer Context-Free Analysis 126

69 Concrete and Abstract Syntax Abstract Syntax: Specification and Tree Construction For representing abstract syntax trees, we use order-sorted terms. The sets and types of these terms are described by type declarations. Ina Schaefer Context-Free Analysis 127

70 Concrete and Abstract Syntax Order-sorted Data Types Definition Oder-sorted Data Types are specified by declarations of the following form: Variant Type Declarations V = V 0 V 1... V m Tuple Type Declaration T (T 1 sel 1,..., T n sel n ) List Type Declarations L S Example: Exp = Add Mult Ident Add (Exp left, Exp right) Mult (Exp left, Exp right) where Ident is a predefined type. Ina Schaefer Context-Free Analysis 128

71 Concrete and Abstract Syntax Order-sorted Data Types (2) Definition (Order-sorted Types - contd.) Order-sorted Terms are recursively defined as If t is a term of type V i, then it is also of type V. If t i is a term of type T i for each i, then T (t 1,..., t n ) is of type T, T is also the constructor. If s 1,..., s k are terms of type S, then L(s 1,..., s n ) is of type L, L is also the list constructor. Additional Operators the selectors sel k : T T k returns the k-th subterm of a tuple the usual list operations (rest, append, conc,...) Ina Schaefer Context-Free Analysis 129

72 Concrete and Abstract Syntax Order-sorted Data Types (3) Remarks: Order-sorted Data Types generalise data types of functional languages by subtyping, a term can belong to serveral types are used in specification languages, e.g. OBJ3, MAX,... are a very compact form for type declaration can be implemented by OO languages Ina Schaefer Context-Free Analysis 130

73 Concrete and Abstract Syntax Example: Order-sorted Data Types and OO Types Declaration of order-sorted data types: Exp = Add Mult Neg Ident Add (Exp left, Exp right) Mult (Exp left, Exp right) Neg (Exp val) Ina Schaefer Context-Free Analysis 131

74 Concrete and Abstract Syntax Implementation in Java interface Exp { Exp left() throws IllegalSelectException; Exp right() throws IllegalSelectException; Exp val() throws IllegalSelectException; } class Add implements Exp { private Exp left; private Exp right; } Add( Exp l, Exp r ) { left = l; right = r; } Exp left() { return left; } Exp right(){ return right; } Exp val() throws IllegalSelectException { throw new IllegalSelectException(); } Ina Schaefer Context-Free Analysis 132

75 Concrete and Abstract Syntax Implementation in Java (2) class Mult implements Exp { // analog zu Add } class Neg implements Exp { private Exp val; Neg( Exp v ) { val = v; } Exp left() throws IllegalSelectException { throw new IllegalSelectException(); } Exp right() throws IllegalSelectException { throw new IllegalSelectException(); } } Exp val() { return val; } Ina Schaefer Context-Free Analysis 133

76 Concrete and Abstract Syntax Implementation in Java (3) class Ident implements Exp extends PredefIdent { Exp left() throws IllegalSelectException { throw new IllegalSelectException(); } Exp right() throws IllegalSelectException { throw new IllegalSelectException();} } Exp val() throws IllegalSelectException { throw new IllegalSelectException(); } Ina Schaefer Context-Free Analysis 134

77 Concrete and Abstract Syntax Transformation of Concrete to Abstract Syntax S E # T Mult(_,_) T F F E Add(_,_) E T T F F ( ID + ID ) * ID a b c Ina Schaefer Context-Free Analysis 135

78 Concrete and Abstract Syntax Transformation to Abstract Syntax with JavaCUP S ::= E:e # {: RESULT = e; :} ; E ::= E:e + T:t {: RESULT = ADD(e,t); :} T:t {: RESULT = t; :} ; T ::= T:t * F:f {: RESULT = MULT(t,f); :} F:f {: RESULT = f; :} ; F ::= ( E:e ) {: RESULT = e ; :} ID:i {: RESULT = i; :} ; Ina Schaefer Context-Free Analysis 136

79 Concrete and Abstract Syntax Recommended Reading Wilhelm, Maurer: Section 9.1, pp Appel: Chapter 4, pp Ina Schaefer Context-Free Analysis 137

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised: EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)

More information

shift-reduce parsing

shift-reduce parsing Parsing #2 Bottom-up Parsing Rightmost derivations; use of rules from right to left Uses a stack to push symbols the concatenation of the stack symbols with the rest of the input forms a valid bottom-up

More information

Syntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 4. Y.N. Srikant

Syntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 4. Y.N. Srikant Syntax Analysis: Context-free Grammars, Pushdown Automata and Part - 4 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler

More information

Lecture 8: Deterministic Bottom-Up Parsing

Lecture 8: Deterministic Bottom-Up Parsing Lecture 8: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Fri Feb 12 13:02:57 2010 CS164: Lecture #8 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

Lecture 7: Deterministic Bottom-Up Parsing

Lecture 7: Deterministic Bottom-Up Parsing Lecture 7: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Tue Sep 20 12:50:42 2011 CS164: Lecture #7 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

Parsing Wrapup. Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing. This lecture LR(1) parsing

Parsing Wrapup. Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing. This lecture LR(1) parsing Parsing Wrapup Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing LR(1) items Computing closure Computing goto LR(1) canonical collection This lecture LR(1) parsing Building ACTION

More information

LR Parsing, Part 2. Constructing Parse Tables. An NFA Recognizing Viable Prefixes. Computing the Closure. GOTO Function and DFA States

LR Parsing, Part 2. Constructing Parse Tables. An NFA Recognizing Viable Prefixes. Computing the Closure. GOTO Function and DFA States TDDD16 Compilers and Interpreters TDDB44 Compiler Construction LR Parsing, Part 2 Constructing Parse Tables Parse table construction Grammar conflict handling Categories of LR Grammars and Parsers An NFA

More information

Simple LR (SLR) LR(0) Drawbacks LR(1) SLR Parse. LR(1) Start State and Reduce. LR(1) Items 10/3/2012

Simple LR (SLR) LR(0) Drawbacks LR(1) SLR Parse. LR(1) Start State and Reduce. LR(1) Items 10/3/2012 LR(0) Drawbacks Consider the unambiguous augmented grammar: 0.) S E $ 1.) E T + E 2.) E T 3.) T x If we build the LR(0) DFA table, we find that there is a shift-reduce conflict. This arises because the

More information

Lecture 14: Parser Conflicts, Using Ambiguity, Error Recovery. Last modified: Mon Feb 23 10:05: CS164: Lecture #14 1

Lecture 14: Parser Conflicts, Using Ambiguity, Error Recovery. Last modified: Mon Feb 23 10:05: CS164: Lecture #14 1 Lecture 14: Parser Conflicts, Using Ambiguity, Error Recovery Last modified: Mon Feb 23 10:05:56 2015 CS164: Lecture #14 1 Shift/Reduce Conflicts If a DFA state contains both [X: α aβ, b] and [Y: γ, a],

More information

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing Roadmap > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing The role of the parser > performs context-free syntax analysis > guides

More information

3. Parsing. Oscar Nierstrasz

3. Parsing. Oscar Nierstrasz 3. Parsing Oscar Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes. http://www.cs.ucla.edu/~palsberg/ http://www.cs.purdue.edu/homes/hosking/

More information

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F).

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F). CS 2210 Sample Midterm 1. Determine if each of the following claims is true (T) or false (F). F A language consists of a set of strings, its grammar structure, and a set of operations. (Note: a language

More information

Bottom-up parsing. Bottom-Up Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form

Bottom-up parsing. Bottom-Up Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form Bottom-up parsing Bottom-up parsing Recall Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form If α V t,thenα is called a sentence in L(G) Otherwise it is just

More information

3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino

3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino 3. Syntax Analysis Andrea Polini Formal Languages and Compilers Master in Computer Science University of Camerino (Formal Languages and Compilers) 3. Syntax Analysis CS@UNICAM 1 / 54 Syntax Analysis: the

More information

A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence.

A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence. Bottom-up parsing Recall For a grammar G, with start symbol S, any string α such that S α is a sentential form If α V t, then α is a sentence in L(G) A left-sentential form is a sentential form that occurs

More information

Context-free grammars

Context-free grammars Context-free grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals - tokens non-terminals - represent higher-level structures of a program start symbol,

More information

Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1)

Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) TD parsing - LL(1) Parsing First and Follow sets Parse table construction BU Parsing Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) Problems with SLR Aho, Sethi, Ullman, Compilers

More information

MIT Parse Table Construction. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology

MIT Parse Table Construction. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology MIT 6.035 Parse Table Construction Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Parse Tables (Review) ACTION Goto State ( ) $ X s0 shift to s2 error error goto s1

More information

Compiler Design 1. Bottom-UP Parsing. Goutam Biswas. Lect 6

Compiler Design 1. Bottom-UP Parsing. Goutam Biswas. Lect 6 Compiler Design 1 Bottom-UP Parsing Compiler Design 2 The Process The parse tree is built starting from the leaf nodes labeled by the terminals (tokens). The parser tries to discover appropriate reductions,

More information

PART 3 - SYNTAX ANALYSIS. F. Wotawa TU Graz) Compiler Construction Summer term / 309

PART 3 - SYNTAX ANALYSIS. F. Wotawa TU Graz) Compiler Construction Summer term / 309 PART 3 - SYNTAX ANALYSIS F. Wotawa (IST @ TU Graz) Compiler Construction Summer term 2016 64 / 309 Goals Definition of the syntax of a programming language using context free grammars Methods for parsing

More information

CSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D-1

CSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D-1 CSE P 501 Compilers LR Parsing Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 D-1 Agenda LR Parsing Table-driven Parsers Parser States Shift-Reduce and Reduce-Reduce conflicts UW CSE P 501 Spring 2018

More information

Section A. A grammar that produces more than one parse tree for some sentences is said to be ambiguous.

Section A. A grammar that produces more than one parse tree for some sentences is said to be ambiguous. Section A 1. What do you meant by parser and its types? A parser for grammar G is a program that takes as input a string w and produces as output either a parse tree for w, if w is a sentence of G, or

More information

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient

More information

Compilers. Bottom-up Parsing. (original slides by Sam

Compilers. Bottom-up Parsing. (original slides by Sam Compilers Bottom-up Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Bottom-Up Parsing More general than top-down parsing And just as efficient Builds

More information

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468 Parsers Xiaokang Qiu Purdue University ECE 468 August 31, 2018 What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure

More information

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 2/20/08 Prof. Hilfinger CS164 Lecture 11 1 Administrivia Test I during class on 10 March. 2/20/08 Prof. Hilfinger CS164 Lecture 11

More information

LR Parsing LALR Parser Generators

LR Parsing LALR Parser Generators LR Parsing LALR Parser Generators Outline Review of bottom-up parsing Computing the parsing DFA Using parser generators 2 Bottom-up Parsing (Review) A bottom-up parser rewrites the input string to the

More information

In One Slide. Outline. LR Parsing. Table Construction

In One Slide. Outline. LR Parsing. Table Construction LR Parsing Table Construction #1 In One Slide An LR(1) parsing table can be constructed automatically from a CFG. An LR(1) item is a pair made up of a production and a lookahead token; it represents a

More information

Compiler Construction: Parsing

Compiler Construction: Parsing Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Context-free grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax

More information

Wednesday, September 9, 15. Parsers

Wednesday, September 9, 15. Parsers Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs: What is a parser Parsers A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

Compiler Construction 2016/2017 Syntax Analysis

Compiler Construction 2016/2017 Syntax Analysis Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive top-down parsing Nonrecursive top-down parsing Bottom-up parsing Syntax Analysis tokens

More information

Conflicts in LR Parsing and More LR Parsing Types

Conflicts in LR Parsing and More LR Parsing Types Conflicts in LR Parsing and More LR Parsing Types Lecture 10 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 2 Due Friday, Apr. 24, 11:55pm The usual lecture time is being replaced by a discussion

More information

CS453 : JavaCUP and error recovery. CS453 Shift-reduce Parsing 1

CS453 : JavaCUP and error recovery. CS453 Shift-reduce Parsing 1 CS453 : JavaCUP and error recovery CS453 Shift-reduce Parsing 1 Shift-reduce parsing in an LR parser LR(k) parser Left-to-right parse Right-most derivation K-token look ahead LR parsing algorithm using

More information

S Y N T A X A N A L Y S I S LR

S Y N T A X A N A L Y S I S LR LR parsing There are three commonly used algorithms to build tables for an LR parser: 1. SLR(1) = LR(0) plus use of FOLLOW set to select between actions smallest class of grammars smallest tables (number

More information

Bottom up parsing. The sentential forms happen to be a right most derivation in the reverse order. S a A B e a A d e. a A d e a A B e S.

Bottom up parsing. The sentential forms happen to be a right most derivation in the reverse order. S a A B e a A d e. a A d e a A B e S. Bottom up parsing Construct a parse tree for an input string beginning at leaves and going towards root OR Reduce a string w of input to start symbol of grammar Consider a grammar S aabe A Abc b B d And

More information

Principle of Compilers Lecture IV Part 4: Syntactic Analysis. Alessandro Artale

Principle of Compilers Lecture IV Part 4: Syntactic Analysis. Alessandro Artale Free University of Bolzano Principles of Compilers Lecture IV Part 4, 2003/2004 AArtale (1) Principle of Compilers Lecture IV Part 4: Syntactic Analysis Alessandro Artale Faculty of Computer Science Free

More information

Formal Languages and Compilers Lecture VII Part 4: Syntactic A

Formal Languages and Compilers Lecture VII Part 4: Syntactic A Formal Languages and Compilers Lecture VII Part 4: Syntactic Analysis Free University of Bozen-Bolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/

More information

Part III : Parsing. From Regular to Context-Free Grammars. Deriving a Parser from a Context-Free Grammar. Scanners and Parsers.

Part III : Parsing. From Regular to Context-Free Grammars. Deriving a Parser from a Context-Free Grammar. Scanners and Parsers. Part III : Parsing From Regular to Context-Free Grammars Deriving a Parser from a Context-Free Grammar Scanners and Parsers A Parser for EBNF Left-Parsable Grammars Martin Odersky, LAMP/DI 1 From Regular

More information

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

COP4020 Programming Languages. Syntax Prof. Robert van Engelen COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and context-free grammars n Grammar derivations n More about parse trees n Top-down and

More information

Let us construct the LR(1) items for the grammar given below to construct the LALR parsing table.

Let us construct the LR(1) items for the grammar given below to construct the LALR parsing table. MODULE 18 LALR parsing After understanding the most powerful CALR parser, in this module we will learn to construct the LALR parser. The CALR parser has a large set of items and hence the LALR parser is

More information

Lecture Notes on Bottom-Up LR Parsing

Lecture Notes on Bottom-Up LR Parsing Lecture Notes on Bottom-Up LR Parsing 15-411: Compiler Design Frank Pfenning Lecture 9 September 23, 2009 1 Introduction In this lecture we discuss a second parsing algorithm that traverses the input string

More information

Bottom-Up Parsing II. Lecture 8

Bottom-Up Parsing II. Lecture 8 Bottom-Up Parsing II Lecture 8 1 Review: Shift-Reduce Parsing Bottom-up parsing uses two actions: Shift ABC xyz ABCx yz Reduce Cbxy ijk CbA ijk 2 Recall: he Stack Left string can be implemented by a stack

More information

Monday, September 13, Parsers

Monday, September 13, Parsers Parsers Agenda Terminology LL(1) Parsers Overview of LR Parsing Terminology Grammar G = (Vt, Vn, S, P) Vt is the set of terminals Vn is the set of non-terminals S is the start symbol P is the set of productions

More information

LR Parsing LALR Parser Generators

LR Parsing LALR Parser Generators Outline LR Parsing LALR Parser Generators Review of bottom-up parsing Computing the parsing DFA Using parser generators 2 Bottom-up Parsing (Review) A bottom-up parser rewrites the input string to the

More information

CS 4120 Introduction to Compilers

CS 4120 Introduction to Compilers CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 6: Bottom-Up Parsing 9/9/09 Bottom-up parsing A more powerful parsing technology LR grammars -- more expressive than LL can handle

More information

Lecture Notes on Bottom-Up LR Parsing

Lecture Notes on Bottom-Up LR Parsing Lecture Notes on Bottom-Up LR Parsing 15-411: Compiler Design Frank Pfenning Lecture 9 1 Introduction In this lecture we discuss a second parsing algorithm that traverses the input string from left to

More information

Lexical and Syntax Analysis. Bottom-Up Parsing

Lexical and Syntax Analysis. Bottom-Up Parsing Lexical and Syntax Analysis Bottom-Up Parsing Parsing There are two ways to construct derivation of a grammar. Top-Down: begin with start symbol; repeatedly replace an instance of a production s LHS with

More information

MODULE 14 SLR PARSER LR(0) ITEMS

MODULE 14 SLR PARSER LR(0) ITEMS MODULE 14 SLR PARSER LR(0) ITEMS In this module we shall discuss one of the LR type parser namely SLR parser. The various steps involved in the SLR parser will be discussed with a focus on the construction

More information

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay Syntax Analysis (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay September 2007 College of Engineering, Pune Syntax Analysis: 2/124 Syntax

More information

Formal Languages and Compilers Lecture VII Part 3: Syntactic A

Formal Languages and Compilers Lecture VII Part 3: Syntactic A Formal Languages and Compilers Lecture VII Part 3: Syntactic Analysis Free University of Bozen-Bolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 8! Bo;om- Up Parsing Shi?- Reduce LR(0) automata and

More information

Wednesday, August 31, Parsers

Wednesday, August 31, Parsers Parsers How do we combine tokens? Combine tokens ( words in a language) to form programs ( sentences in a language) Not all combinations of tokens are correct programs (not all sentences are grammatically

More information

Parsing. source code. while (k<=n) {sum = sum+k; k=k+1;}

Parsing. source code. while (k<=n) {sum = sum+k; k=k+1;} Compiler Construction Grammars Parsing source code scanner tokens regular expressions lexical analysis Lennart Andersson parser context free grammar Revision 2012 01 23 2012 parse tree AST builder (implicit)

More information

Downloaded from Page 1. LR Parsing

Downloaded from  Page 1. LR Parsing Downloaded from http://himadri.cmsdu.org Page 1 LR Parsing We first understand Context Free Grammars. Consider the input string: x+2*y When scanned by a scanner, it produces the following stream of tokens:

More information

Syntax Analysis Part I

Syntax Analysis Part I Syntax Analysis Part I Chapter 4: Context-Free Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,

More information

LR Parsing Techniques

LR Parsing Techniques LR Parsing Techniques Introduction Bottom-Up Parsing LR Parsing as Handle Pruning Shift-Reduce Parser LR(k) Parsing Model Parsing Table Construction: SLR, LR, LALR 1 Bottom-UP Parsing A bottom-up parser

More information

Review: Shift-Reduce Parsing. Bottom-up parsing uses two actions: Bottom-Up Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk

Review: Shift-Reduce Parsing. Bottom-up parsing uses two actions: Bottom-Up Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk Review: Shift-Reduce Parsing Bottom-up parsing uses two actions: Bottom-Up Parsing II Lecture 8 Shift ABC xyz ABCx yz Reduce Cbxy ijk CbA ijk Prof. Aiken CS 13 Lecture 8 1 Prof. Aiken CS 13 Lecture 8 2

More information

Fall Compiler Principles Lecture 4: Parsing part 3. Roman Manevich Ben-Gurion University of the Negev

Fall Compiler Principles Lecture 4: Parsing part 3. Roman Manevich Ben-Gurion University of the Negev Fall 2016-2017 Compiler Principles Lecture 4: Parsing part 3 Roman Manevich Ben-Gurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning

More information

4. Lexical and Syntax Analysis

4. Lexical and Syntax Analysis 4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal

More information

Fall Compiler Principles Lecture 5: Parsing part 4. Roman Manevich Ben-Gurion University

Fall Compiler Principles Lecture 5: Parsing part 4. Roman Manevich Ben-Gurion University Fall 2014-2015 Compiler Principles Lecture 5: Parsing part 4 Roman Manevich Ben-Gurion University Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Lowering

More information

SYNTAX ANALYSIS 1. Define parser. Hierarchical analysis is one in which the tokens are grouped hierarchically into nested collections with collective meaning. Also termed as Parsing. 2. Mention the basic

More information

LR Parsing. Table Construction

LR Parsing. Table Construction #1 LR Parsing Table Construction #2 Outline Review of bottom-up parsing Computing the parsing DFA Closures, LR(1) Items, States Transitions Using parser generators Handling Conflicts #3 In One Slide An

More information

Compilation 2012 Context-Free Languages Parsers and Scanners. Jan Midtgaard Michael I. Schwartzbach Aarhus University

Compilation 2012 Context-Free Languages Parsers and Scanners. Jan Midtgaard Michael I. Schwartzbach Aarhus University Compilation 2012 Parsers and Scanners Jan Midtgaard Michael I. Schwartzbach Aarhus University Context-Free Grammars Example: sentence subject verb object subject person person John Joe Zacharias verb asked

More information

4. Lexical and Syntax Analysis

4. Lexical and Syntax Analysis 4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal

More information

Bottom-Up Parsing II (Different types of Shift-Reduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh.

Bottom-Up Parsing II (Different types of Shift-Reduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh. Bottom-Up Parsing II Different types of Shift-Reduce Conflicts) Lecture 10 Ganesh. Lecture 10) 1 Review: Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient Doesn

More information

Review main idea syntax-directed evaluation and translation. Recall syntax-directed interpretation in recursive descent parsers

Review main idea syntax-directed evaluation and translation. Recall syntax-directed interpretation in recursive descent parsers Plan for Today Review main idea syntax-directed evaluation and translation Recall syntax-directed interpretation in recursive descent parsers Syntax-directed evaluation and translation in shift-reduce

More information

How do LL(1) Parsers Build Syntax Trees?

How do LL(1) Parsers Build Syntax Trees? How do LL(1) Parsers Build Syntax Trees? So far our LL(1) parser has acted like a recognizer. It verifies that input token are syntactically correct, but it produces no output. Building complete (concrete)

More information

LR(0) Parsing Summary. LR(0) Parsing Table. LR(0) Limitations. A Non-LR(0) Grammar. LR(0) Parsing Table CS412/CS413

LR(0) Parsing Summary. LR(0) Parsing Table. LR(0) Limitations. A Non-LR(0) Grammar. LR(0) Parsing Table CS412/CS413 LR(0) Parsing ummary C412/C41 Introduction to Compilers Tim Teitelbaum Lecture 10: LR Parsing February 12, 2007 LR(0) item = a production with a dot in RH LR(0) state = set of LR(0) items valid for viable

More information

UNIT III & IV. Bottom up parsing

UNIT III & IV. Bottom up parsing UNIT III & IV Bottom up parsing 5.0 Introduction Given a grammar and a sentence belonging to that grammar, if we have to show that the given sentence belongs to the given grammar, there are two methods.

More information

CS606- compiler instruction Solved MCQS From Midterm Papers

CS606- compiler instruction Solved MCQS From Midterm Papers CS606- compiler instruction Solved MCQS From Midterm Papers March 06,2014 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 Final Term MCQ s and Quizzes CS606- compiler instruction If X is a

More information

CS5363 Final Review. cs5363 1

CS5363 Final Review. cs5363 1 CS5363 Final Review cs5363 1 Programming language implementation Programming languages Tools for describing data and algorithms Instructing machines what to do Communicate between computers and programmers

More information

CSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Winter /15/ Hal Perkins & UW CSE C-1

CSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Winter /15/ Hal Perkins & UW CSE C-1 CSE P 501 Compilers Parsing & Context-Free Grammars Hal Perkins Winter 2008 1/15/2008 2002-08 Hal Perkins & UW CSE C-1 Agenda for Today Parsing overview Context free grammars Ambiguous grammars Reading:

More information

Grammars and Parsing. Paul Klint. Grammars and Parsing

Grammars and Parsing. Paul Klint. Grammars and Parsing Paul Klint Grammars and Languages are one of the most established areas of Natural Language Processing and Computer Science 2 N. Chomsky, Aspects of the theory of syntax, 1965 3 A Language...... is a (possibly

More information

WWW.STUDENTSFOCUS.COM UNIT -3 SYNTAX ANALYSIS 3.1 ROLE OF THE PARSER Parser obtains a string of tokens from the lexical analyzer and verifies that it can be generated by the language for the source program.

More information

Compiler Construction

Compiler Construction Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ws-1819/cc/ Recap: LR(1) Parsing Outline of Lecture 11 Recap: LR(1)

More information

Compilers and Language Processing Tools

Compilers and Language Processing Tools Compilers and Language Processing Tools Summer Term 2011 Prof. Dr. Arnd Poetzsch-Heffter Software Technology Group TU Kaiserslautern c Prof. Dr. Arnd Poetzsch-Heffter 1 Parser Generators c Prof. Dr. Arnd

More information

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Parsing III (Top-down parsing: recursive descent & LL(1) ) (Bottom-up parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,

More information

Properties of Regular Expressions and Finite Automata

Properties of Regular Expressions and Finite Automata Properties of Regular Expressions and Finite Automata Some token patterns can t be defined as regular expressions or finite automata. Consider the set of balanced brackets of the form [[[ ]]]. This set

More information

Compilers Course Lecture 4: Context Free Grammars

Compilers Course Lecture 4: Context Free Grammars Compilers Course Lecture 4: Context Free Grammars Example: attempt to define simple arithmetic expressions using named regular expressions: num = [0-9]+ sum = expr "+" expr expr = "(" sum ")" num Appears

More information

Parsing Algorithms. Parsing: continued. Top Down Parsing. Predictive Parser. David Notkin Autumn 2008

Parsing Algorithms. Parsing: continued. Top Down Parsing. Predictive Parser. David Notkin Autumn 2008 Parsing: continued David Notkin Autumn 2008 Parsing Algorithms Earley s algorithm (1970) works for all CFGs O(N 3 ) worst case performance O(N 2 ) for unambiguous grammars Based on dynamic programming,

More information

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Subject Name: CS2352 Principles of Compiler Design Year/Sem : III/VI

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Subject Name: CS2352 Principles of Compiler Design Year/Sem : III/VI DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Subject Name: CS2352 Principles of Compiler Design Year/Sem : III/VI UNIT I - LEXICAL ANALYSIS 1. What is the role of Lexical Analyzer? [NOV 2014] 2. Write

More information

G53CMP: Lecture 4. Syntactic Analysis: Parser Generators. Henrik Nilsson. University of Nottingham, UK. G53CMP: Lecture 4 p.1/32

G53CMP: Lecture 4. Syntactic Analysis: Parser Generators. Henrik Nilsson. University of Nottingham, UK. G53CMP: Lecture 4 p.1/32 G53CMP: Lecture 4 Syntactic Analysis: Parser Generators Henrik Nilsson University of Nottingham, UK G53CMP: Lecture 4 p.1/32 This Lecture Parser generators ( compiler compilers ) The parser generator Happy

More information

VIVA QUESTIONS WITH ANSWERS

VIVA QUESTIONS WITH ANSWERS VIVA QUESTIONS WITH ANSWERS 1. What is a compiler? A compiler is a program that reads a program written in one language the source language and translates it into an equivalent program in another language-the

More information

LR Parsing. Leftmost and Rightmost Derivations. Compiler Design CSE 504. Derivations for id + id: T id = id+id. 1 Shift-Reduce Parsing.

LR Parsing. Leftmost and Rightmost Derivations. Compiler Design CSE 504. Derivations for id + id: T id = id+id. 1 Shift-Reduce Parsing. LR Parsing Compiler Design CSE 504 1 Shift-Reduce Parsing 2 LR Parsers 3 SLR and LR(1) Parsers Last modifled: Fri Mar 06 2015 at 13:50:06 EST Version: 1.7 16:58:46 2016/01/29 Compiled at 12:57 on 2016/02/26

More information

Chapter 3: Lexing and Parsing

Chapter 3: Lexing and Parsing Chapter 3: Lexing and Parsing Aarne Ranta Slides for the book Implementing Programming Languages. An Introduction to Compilers and Interpreters, College Publications, 2012. Lexing and Parsing* Deeper understanding

More information

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

COP4020 Programming Languages. Syntax Prof. Robert van Engelen COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview Tokens and regular expressions Syntax and context-free grammars Grammar derivations More about parse trees Top-down and bottom-up

More information

LALR Parsing. What Yacc and most compilers employ.

LALR Parsing. What Yacc and most compilers employ. LALR Parsing Canonical sets of LR(1) items Number of states much larger than in the SLR construction LR(1) = Order of thousands for a standard prog. Lang. SLR(1) = order of hundreds for a standard prog.

More information

Compiler phases. Non-tokens

Compiler phases. Non-tokens Compiler phases Compiler Construction Scanning Lexical Analysis source code scanner tokens regular expressions lexical analysis Lennart Andersson parser context free grammar Revision 2011 01 21 parse tree

More information

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram CS6660 COMPILER DESIGN Question Bank UNIT I-INTRODUCTION TO COMPILERS 1. Define compiler. 2. Differentiate compiler and interpreter. 3. What is a language processing system? 4. List four software tools

More information

Action Table for CSX-Lite. LALR Parser Driver. Example of LALR(1) Parsing. GoTo Table for CSX-Lite

Action Table for CSX-Lite. LALR Parser Driver. Example of LALR(1) Parsing. GoTo Table for CSX-Lite LALR r Driver Action Table for CSX-Lite Given the GoTo and parser action tables, a Shift/Reduce (LALR) parser is fairly simple: { S 5 9 5 9 void LALRDriver(){ Push(S ); } R S R R R R5 if S S R S R5 while(true){

More information

Parser Generation. Bottom-Up Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottom-up --- from leaves to the root

Parser Generation. Bottom-Up Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottom-up --- from leaves to the root Parser Generation Main Problem: given a grammar G, how to build a top-down parser or a bottom-up parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence ----

More information

CSE 401 Compilers. LR Parsing Hal Perkins Autumn /10/ Hal Perkins & UW CSE D-1

CSE 401 Compilers. LR Parsing Hal Perkins Autumn /10/ Hal Perkins & UW CSE D-1 CSE 401 Compilers LR Parsing Hal Perkins Autumn 2011 10/10/2011 2002-11 Hal Perkins & UW CSE D-1 Agenda LR Parsing Table-driven Parsers Parser States Shift-Reduce and Reduce-Reduce conflicts 10/10/2011

More information

PSD3A Principles of Compiler Design Unit : I-V. PSD3A- Principles of Compiler Design

PSD3A Principles of Compiler Design Unit : I-V. PSD3A- Principles of Compiler Design PSD3A Principles of Compiler Design Unit : I-V 1 UNIT I - SYLLABUS Compiler Assembler Language Processing System Phases of Compiler Lexical Analyser Finite Automata NFA DFA Compiler Tools 2 Compiler -

More information

Syntactic Analysis. Syntactic analysis, or parsing, is the second phase of compilation: The token file is converted to an abstract syntax tree.

Syntactic Analysis. Syntactic analysis, or parsing, is the second phase of compilation: The token file is converted to an abstract syntax tree. Syntactic Analysis Syntactic analysis, or parsing, is the second phase of compilation: The token file is converted to an abstract syntax tree. Compiler Passes Analysis of input program (front-end) character

More information

UNIT-III BOTTOM-UP PARSING

UNIT-III BOTTOM-UP PARSING UNIT-III BOTTOM-UP PARSING Constructing a parse tree for an input string beginning at the leaves and going towards the root is called bottom-up parsing. A general type of bottom-up parser is a shift-reduce

More information

More Bottom-Up Parsing

More Bottom-Up Parsing More Bottom-Up Parsing Lecture 7 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 1 Back By Wednesday (ish) savior lexer in ~cs142/s09/bin Project 2 Due Friday, Apr. 24, 11:55pm My office hours 3pm

More information

COMPILER (CSE 4120) (Lecture 6: Parsing 4 Bottom-up Parsing )

COMPILER (CSE 4120) (Lecture 6: Parsing 4 Bottom-up Parsing ) COMPILR (CS 4120) (Lecture 6: Parsing 4 Bottom-up Parsing ) Sungwon Jung Mobile Computing & Data ngineering Lab Dept. of Computer Science and ngineering Sogang University Seoul, Korea Tel: +82-2-705-8930

More information

Compiler Passes. Syntactic Analysis. Context-free Grammars. Syntactic Analysis / Parsing. EBNF Syntax of initial MiniJava.

Compiler Passes. Syntactic Analysis. Context-free Grammars. Syntactic Analysis / Parsing. EBNF Syntax of initial MiniJava. Syntactic Analysis Syntactic analysis, or parsing, is the second phase of compilation: The token file is converted to an abstract syntax tree. Compiler Passes Analysis of input program (front-end) character

More information

CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution

CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution Exam Facts Format Wednesday, July 20 th from 11:00 a.m. 1:00 p.m. in Gates B01 The exam is designed to take roughly 90

More information