Syntax Analysis. Amitabha Sanyal. ( as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay


 Ashley Moody
 3 years ago
 Views:
Transcription
1 Syntax Analysis ( as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay September 2007
2 College of Engineering, Pune Syntax Analysis: 2/124 Syntax Analysis Recap A syntax analyzer or parser Ensures that the input program is wellformed by attemting to group tokens according to certain rules. This is called syntax checking.
3 College of Engineering, Pune Syntax Analysis: 2/124 Syntax Analysis Recap A syntax analyzer or parser Ensures that the input program is wellformed by attemting to group tokens according to certain rules. This is called syntax checking. May actually create the hierarchical structure that arises out of such grouping. This information is required by subsequent phases.
4 College of Engineering, Pune Syntax Analysis: 4/124 Syntax Analysis Example fundef fname params compoundstmt identifier ( ) { vdecl slist } main () { int i,sum; sum = 0; for (i=1; i<=10; i++); sum = sum + i; printf("%d\n",sum); } main type varlist ; int varlist, var var identifier identifier sum i...
5 College of Engineering, Pune Syntax Analysis: 6/124 Syntax Analysis Recap To check whether a program is wellformed requires a specification of what is a wellformed program. 1. the specification be precise. 2. the specification be complete. Must cover all the syntactic details of the language 3. the specification must be convenient to use by both language designer and the implementer A context free grammar meets these requirements. How is the hierarchical structure of the program represented? 1. Using a data structure called a parse tree.
6 College of Engineering, Pune Syntax Analysis: 8/124 Syntax Analysis How are parsers constructed? Till early seventies, parsers (in fact all of the compiler) were written manually. A better understanding of parsing algorithms has resulted in tools that can automatically generate parsers. Examples of parser generating tools: Yacc/Bison: Bottomup (LALR) parser generator Antlr: Topdown (LL) scanner cum parser generator.
7 College of Engineering, Pune Syntax Analysis: 10/124 Syntax Analysis Interface of a parser with the rest of the compiler Source Program Lexical analyser get next token token Parser Rest of the compiler
8 College of Engineering, Pune Syntax Analysis: 12/124 Specification of Syntax by Context Free Grammars Informal description of variable declarations in C: starts with integer or real as the first token. followed by one or more identifier tokens, separated by token comma followed by token semicolon Question: Can the list of identifier tokens be empty? declaration type idlist ; idlist id idlist, id type integer real Illustrates the usefulness of a formal specification.
9 College of Engineering, Pune Syntax Analysis: 14/124 Context Free Grammar A CFG G is formally defined to have four components (N, T, S, P): 1. T is a finite set of terminals. 2. N is a finite set of nonterminals. 3. S is a special nonterminal ( from N ) called the start symbol. 4. P is a finite set of production rules of the form such as A α, where A is from N and α from (N T ) start symbol nonterminals declaration type idlist ; idlist id idlist, id type integer real production terminals
10 College of Engineering, Pune Syntax Analysis: 16/124 Derivation Example : G = ({list}, {id,,}, list, {list list, id, list id}) A derivation is traced out as follows list list, id list, id, id id, id, id The transformation of a string of grammar symbols by replacing a nonterminal by the corresponding right hand side of a production is called a derivation. The set of all possible terminal strings that can be derived from the start symbol of a CFG is the language generated by the CFG. This grammar generates a list of one or more ids separated by commas.
11 College of Engineering, Pune Syntax Analysis: 18/124 Why the Term Context Free? Why the term context free? 1. The only kind of productions permitted are of the form nonterminal sequence of terminals and nonterminals 2. Rules are used to replace an occurrence of the lhs nonterminal by its rhs. The replacement is made regardless of the context (symbols surrounding the nonterminal).
12 College of Engineering, Pune Syntax Analysis: 20/124 Notational Conventions Symbol type single terminal single nonterminal single grammar symbol (symbol from {N T } ) string of terminals string of grammar symbols null string Convention letters a, b, c, operators delimiters, keywords letters A, B, C and names such as declaration, list and S is the start symbol X, Y, Z letters x, y, z α, β, γ ɛ
13 College of Engineering, Pune Syntax Analysis: 22/124 Formal Definitions Let A γ be a production rule α A β be a string of grammar symbols Replacing the nonterminal A in α A β yields α γ β. Formally, this is stated as α A β derives α γ β in one step. Symbolically α A β α γ β. α 1 α2 means α 1 derives α 2 in zero or more steps. Clearly α α is always true for any α. + α 1 α2 means α 1 derives α 2 in one or more steps.
14 College of Engineering, Pune Syntax Analysis: 24/124 FOrmal Definitions The language L(G) generated by a context free grammar G is defined as {w S = + w, w T }. Strings in L(G) are called sentences of G. A string α, α (N T ), such that S = α, is called a sentential form of G. Two grammars are equivalent,if they generate the same language.
15 College of Engineering, Pune Syntax Analysis: 26/124 Basic Concepts in Parsing For constructing a derivation, there are choices at each sentential form. choice of the nonterminal to be replaced choice of a rule corresponding to the nonterminal. Instead of choosing the nonterminal to be replaced, in an arbitrary fashion, it is possible to make an uniform choice at each step. replace the leftmost nonterminal in a sentential form replace the rightmost nonterminal in a sentential form The corresponding derivations are known as leftmost and rightmost derivations respectively. Given a sentence w of a grammar G, there are several distinct derivations for w.
16 College of Engineering, Pune Syntax Analysis: 28/124 Parse Trees A parse tree is a pictorial form of depicting a derivation. 1. root of the tree is labeled with S 2. each leaf node is labeled by a token or by ɛ 3. an internal node of the tree is labeled by a nonterminal 4. if an internal node has A as its label and the children of this node from left to right are labeled with X 1, X 2,..., X n then there must be a production A X 1 X 2... X n where X i is a grammar symbol.
17 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E Leftmost derivation: E E + T E + T E + T F T F id F id id
18 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T Leftmost derivation: E E + T E + T + T E + T F T F id F id id
19 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T Leftmost derivation: E E + T E + T + T T + T + T E + T F T F id F id id
20 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E + T F Leftmost derivation: E E + T E + T + T T + T + T F + T + T T F id F id id
21 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E + T E E + T T F F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T F id id
22 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T + T F F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T F id id
23 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T F id F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T id + id + T id
24 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T F id F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T id + id + T id + id + F id
25 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T F id F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T id + id + T id + id + F id + id + id id
26 College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E + T F T F id F id id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T id + id + T id + id + F id + id + id Rightmost derivation: E E + T E + F E + id E + T + id E + F + id E + id + id T + id + id F + id + id id + id + id
27 College of Engineering, Pune Syntax Analysis: 32/124 Derivations and Parse Trees The following summarize some interesting relations between the two concepts Parse tree filters out the choice of replacements made in the sentential forms.
28 College of Engineering, Pune Syntax Analysis: 32/124 Derivations and Parse Trees The following summarize some interesting relations between the two concepts Parse tree filters out the choice of replacements made in the sentential forms. Given a left (right) derivation for a sentence, one can construct a unique parse tree for the sentence.
29 College of Engineering, Pune Syntax Analysis: 32/124 Derivations and Parse Trees The following summarize some interesting relations between the two concepts Parse tree filters out the choice of replacements made in the sentential forms. Given a left (right) derivation for a sentence, one can construct a unique parse tree for the sentence. For every parse tree for a sentence there is a unique leftmost and a unique rightmost derivation.
30 College of Engineering, Pune Syntax Analysis: 32/124 Derivations and Parse Trees The following summarize some interesting relations between the two concepts Parse tree filters out the choice of replacements made in the sentential forms. Given a left (right) derivation for a sentence, one can construct a unique parse tree for the sentence. For every parse tree for a sentence there is a unique leftmost and a unique rightmost derivation. Can a sentence have more than one distinct parse trees, and therefore more than one left (right) derivations?
31 College of Engineering, Pune Syntax Analysis: 34/124 Ambiguous Grammars Produces more than one parse trees for some sentence of the grammar. Example: S if C then S else S S if C then S S ass First parse tree: S if C then S First rightmost derivation: S if C then S else S if C then S else S ass ass
32 College of Engineering, Pune Syntax Analysis: 34/124 Ambiguous Grammars Produces more than one parse trees for some sentence of the grammar. Example: S if C then S else S S if C then S S ass First parse tree: S First rightmost derivation: if C then S else S S if C then S else S S if C then S else ass if C then ass S ass
33 College of Engineering, Pune Syntax Analysis: 34/124 Ambiguous Grammars Produces more than one parse trees for some sentence of the grammar. Example: S if C then S else S S if C then S S ass First parse tree: S if C then S else S if C then S ass S First rightmost derivation: S if C then S else S S if C then S else ass S if C then if C then S else ass ass
34 College of Engineering, Pune Syntax Analysis: 34/124 Ambiguous Grammars Produces more than one parse trees for some sentence of the grammar. Example: S if C then S else S S if C then S S ass First parse tree: if C then S S else if C then S ass S S First rightmost derivation: S if C then S else S S if C then S else ass S if C then if C then S else ass S if C then if C then ass else ass ass
35 College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S if C then S else S ass ass
36 College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S S if C then S else if C then S else S if C then S else S S
37 College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S S if C then S else if C then S else S S if C then S else if C then S else ass if C then S else S ass
38 College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S S if C then S else if C then S else S S if C then S else if C then S else ass S if C then S else if C then ass else ass if C then S else S ass ass
39 College of Engineering, Pune Syntax Analysis: 38/124 Ambiguous Grammars Ambiguous grammars are usually not suitable for parsing: It cannot be decided by an algorithm that a given context free grammar is indeed ambiguous? A parse tree would be used subsequently for semantic analysis; more than one parse tree would imply several interpretations and there is no obvious way of preferring one over another. What can be done with such grammars in the context of parsing? 1. Rewrite the grammar such that it becomes unambiguous. 2. Use the grammar but supply disambiguating rules (as in YACC).
40 College of Engineering, Pune Syntax Analysis: 40/124 Left Recursive and Right Recursive Grammar Rules Left recursive rule: the first symbol in the rhs of the rule is the same nonterminal as that in the lhs list list, id id Right recursive rule: the last symbol in the rhs of the rule is the same nonterminal as that in the lhs list id, list id Languages denote by list in both case are the same. Important consequences on parsers generated.
41 College of Engineering, Pune Syntax Analysis: 42/124 Introduction to Parsing A parser for a context free grammar G is a program P that given an input w, either verifies that w is a sentence of G and, additionally, may also give the parse tree for w. or gives an error message stating that w is not a sentence. May provide some information to locate the error.
42 College of Engineering, Pune Syntax Analysis: 44/124 Parsing Strategies Two ways of creating a parse tree: Topdown parsers Created from the root down to leaves. Bottomup parsers Created from leaves upwards to the root. Both the parsing strategies can also be rephrased in terms of derivations.
43 College of Engineering, Pune Syntax Analysis: 46/124 Example of Bottom Up Parsing Grammar: D var list : type ; type integer real list list,id id The input string is var id,id : integer; The parse tree construction from the leaves is shown in next page. The sentential forms that were produced during the parse are var id, id : integer ; var list, id : integer ; var list : integer ; var list : type ; D The sentential forms happen to be a right most derivation in the reverse order.
44 College of Engineering, Pune Syntax Analysis: 48/124 Principles of Bottom Up Parsing The basic steps of a bottomup parser are 1. to identify a substring within a rightmost sentential form which matches the rhs of a rule 2. when this substring is replaced by the lhs of the matching rule, it must produce the previous rmsentential form. Such a substring is called a handle. Bottom up parsing is essentially the process of detecting handles and reducing them. Different bottomup parsers use different methods for handle detection.
45 College of Engineering, Pune Syntax Analysis: 50/124 Example of Handles Handles are underlined var id, id : integer ; var list, id : integer ; var list : integer ; var list : type ; D
46 College of Engineering, Pune Syntax Analysis: 52/124 Principles of Bottom Up Parsing A handle of a right sentential form γ, is a production rule A β, and a position in γ such that when β is replaced by A in γ at the given position, the resulting string is the previous right sentential form in a rightmost derivation of γ. Formally, if S = rm α A w = rm αβ w then rule A β in the position following α in γ is a handle of γ ( = αβ w). Only terminal symbols can appear to the right of a handle in a rightmost sentential form.
47 College of Engineering, Pune Syntax Analysis: 54/124 ShiftReduce Parsers A parsing method that directly uses the principle of bottom up parsing outlined. A shiftreduce parser requires the following data structures. 1. a buffer for holding the input string to be parsed. 2. a data structure for detecting handles (a stack happens to be adequate) 3. a data structure for storing and accessing the lhs and rhs of rules.
48 College of Engineering, Pune Syntax Analysis: 56/124 ShiftReduce Parsers Actions of the shiftreduce parser are: Shift: Moving symbols from the input buffer onto the stack, one symbol at a time. This move is called a shift action. Reduce: Checking whether a handle occurs in the stack; if a handle is detected then a reduction by an appropriate rule is performed ( popping off the rhs of a rule from the stack and pushing its lhs), this move is called a reduce action. Accept: If the stack contains the start symbol only and input buffer is empty, then it announces a successful parse. This move is known as accept action. Error: A situation when the parser can neither shift nor reduce nor accept, it declares an error, error action and halts.
49 College of Engineering, Pune Syntax Analysis: 58/124 Example of ShiftReduce Parsing Consider the grammar: E E + T E T T T T F T /F F F P F P P P B B (E) id stack input parser move $ id ** id / id $ shift  $ id ** id / id $ shift id $id ** id / id $ reduce by B id $B ** id / id $ reduce by P B $P ** id / id $ reduce by P P $P ** id / id $ shift **
50 College of Engineering, Pune Syntax Analysis: 60/124 Handle Detection in ShiftReduce Parsing Result: Handle in a shiftreduce parser is never buried inside the stack. Proof Outline : Consider the stack contents at some intermediate stage of parsing, say j th sentential form, and assume the handle is on (tos) as shown below. stack α B input x y z There are two possible forms for obtaining the (j 1) th sentential form. (j 1) th sentential j th sentential rule used a) αbxaz αbxyz A y b) δayz αbxyz A βbx In (i) after shifting y, the handle would be found on tos as claimed. In (ii), α = δβ and even in this situation, shifting of zero or more symbols would allow this handle to occur on tos and get detected.
51 College of Engineering, Pune Syntax Analysis: 62/124 Limitations of ShiftReduce Parser For some grammars, the shiftreduce parser may get into the following conflicting situations. Shiftreduce conflict A handle β occurs at tos; the nexttoken a is such that βaγ happens to be another handle. The parser has two options reduce the handle using A β ignore the handle β; shift a and continue parsing and eventually reduce using B βaγ. Reducereduce conflict the stack contents are αβγ and both βγ and γ are handles with A βγ and B γ as the corresponding rules. Then the parser has two reduce possibilities. To handle such conflicts, the nexttoken could be used to prefer one move over the other. choose shift (or reduce) in a shiftreduce conflict prefer one reduce (over others) in a reducereduce conflict.
52 College of Engineering, Pune Syntax Analysis: 64/124 LR Parser Model nonnexttoken input terminals terminals $ states Action goto S0 shift to state S 1 state reduce S 2 stack LR Parser error S 0 $ tos S n output parsing Initial Configuration Working of a LR Parser table tos nexttoken Action parser action S j S j a s i push a ; push S i ; continue a rj rj : A α ; α = r ; pop 2 r symbols ; tos= S k ; goto[ S k, a ] = S l ; push A ; push S l ; continue $ acc successful parse ; halt S j a error error handling
53 College of Engineering, Pune Syntax Analysis: 66/124 LR Parsers Consist of a stack which contains strings of the form s 0 X 1 s 1 X 2... X m s m, where X i is a grammar symbol and s i is a special symbol called a state. a parsing table which comprises two parts, usually named as Action and Goto. The entries in the Action part are: s i which means shift to state i r j which stands for reduce by the j th rule, accept error The Goto part contains blank entries or state symbols.
54 College of Engineering, Pune Syntax Analysis: 68/124 Configuration of a SLR Parser The SLR parser has a driver routine which initializes the stack with the start state and calls scanner to get a token (nexttoken). For any configuration, as indicated by (tos, nexttoken), it consults the parsing table and performs the action specified there. The goto part of the table is used only after a reduction. The parsing continues till either an error or accept entry is encountered.
55 College of Engineering, Pune Syntax Analysis: 70/124 SLR(1) Parser LR Parsing Table for an expression grammar Grammar : E E + T T T T * F F F (E) id Action Goto state id + * ( ) $ E T F s5 s5 s6 r2 r4 r6 r1 r3 r5 s7 r4 r6 s4 s4 r2 r4 r6 s11 acc r2 r4 r s5 s4 9 3 s5 s4 10 s6 s7 r1 r1 r3 r3 r3 r5 r5 r
56 College of Engineering, Pune Syntax Analysis: 72/124 Working of a SLR(1) Parser Parsing the Input * a = * * b using LR Parsing Table of Fig 3.17 Stack Input Action table Goto table $ 0 * a = * * b $ [ 0, *] = s4 $ 0 * 4 a = * * b $ [ 4, id ] = s5 $ 0 *4 id 5 = * * b $ [ 5, = ] = r 4 [ 4, L ] = 8 $ 0 *4 L 8 = * * b $ [ 8, = ] = r 5 [ 4, R] = 7 $ 0 *4 R 7 = * * b $ [ 7, = ] = r 3 [ 0, L ] = 2 $ 0 L 2 = * * b $ [ 2, = ] = s 6 $ 0 L 2 = 6 * * b $ [ 6, * ] = s12 $ 0 L 2 = 6 * 12 * b $ [ 12, * ] = s12 $ 0L2=6*12*12 b $ [12, id ] = s11 $ 0L2=6*12*12id 11 $ [ 11, $ ] = r 4 [12, L] = 10 $ 0L2=6*12*12L10 $ [ 10, $ ] = r 5 [12, R ] = 13 $ 0L2=6*12*12R13 $ [ 13, $ ] = r 3 [12, L ] = 10 $ 0 L 2 = 6 *12 L 10 $ [ 10, $ ] = r 5 [ 12, R ] =13 $ 0L 2 = 6 *12 R 13 $ [ 13, $ ] = r 3 [ 6, L ] = 10 $ 0 L 2 = 6 L 10 $ [ 10, $ ] = r5 [ 6, R ] = 9 $ 0 L 2 = 6 R 9 $ [ 9, $ ] = r1 [ 0, S ] = 1 $ 0 S 1 $ [ 1, $ ] = acc
57 College of Engineering, Pune Syntax Analysis: 74/124 Configuration of a LR Parser $ A configuration of a LR parser is defined by a tuple, ( stack contents, unexpended part of input). Initial configuration is (s 0, a 1 a 2... a n $), where s 0 is a designated start state and the second component is the entire sentence to be parsed. Let an intermediate configuration be given by (s 0 X 1 s 1... X i s i, a j a j+1... a n $), then resulting configuration i) after a shift action is given by (s 0 X 1 s 1... X i s i a j s k, a j+1... a n $) provided Action[s i, a j ] = s k ; both stack and nexttoken change after a shift. ii) after a reduce action is given by (s 0 X 1 s 1... X i r As, a j... a n $) where Action[s i, a j ] = r l ; rule p l : A β, β has r grammar symbols and goto(s i r, A) = s. Only the stack changes here.
58 College of Engineering, Pune Syntax Analysis: 76/124 LR(0) Items LR(0) item : An LR(0) item for a grammar G is a production rule of G with the symbol ( read as dot or bullet) inserted at some position in the rhs of the rule. Example of LR(0) items : For the rule given below decls decls decl the possible LR(0) items are : I 1 : decls decls decl I 2 : decls decls decl I 3 : decls decls decl The rule decls ɛ has only one LR(0) item, I 4 : decls
59 College of Engineering, Pune Syntax Analysis: 78/124 LR(0) Items An LR(0) item is complete if the is the last symbol in the rhs. Example : I 3 and I 4 are complete items and I 1 and I 2 are incomplete items. An LR(0) item is called a kernel item, if the dot is not at the left end. However the item S S is an exception and is defined to be a kernel item. Example : I 1, I 2, I 3 are all kernel items and I 4 is a nonkernel item.
60 College of Engineering, Pune Syntax Analysis: 80/124 Canonical Collection of LR(0) Items The construction of the SLR parsing table requires two functions closure and goto. closure: Let U be the collection of all LR(0) items of a cfg G. Then closure : U 2 U. 1. closure(i ) = {I }, for I U 2. If A α Bβ closure(i ), then the item B η is added to closure(i ). 3. Apply step (ii) above repeatedly till no more new items can be added to closure(i ). Example: Consider the grammar A A a b closure(a A a) = {A A a, A b}
61 College of Engineering, Pune Syntax Analysis: 82/124 Canonical Collection of LR(0) Items goto: goto : U X 2 U, where X is a grammar symbol. goto(a α X β, X ) = closure(a αx β). Example: goto(a Aa, A) = closure(a A a) = {A A a} closure and goto can be extended to a set S of LR(0) items by appropriate generalizations closure(s) = I S {closure(i )} goto(s, X ) = I S {goto(i, X )}
62 College of Engineering, Pune Syntax Analysis: 84/124 Algorithm for Constructing Canonical Collection of LR(0) Items. procedure items(g, C); begin i := 0; I 0 := { closure( S S )}; C := I i ; repeat for each set of items I i in C and each grammar symbol X, such that goto(i i,x ) is not empty and / C, do i := i + 1 ; I i := goto(i i,x ); C := C I i until no more sets of items can be added to C end
63 College of Engineering, Pune Syntax Analysis: 86/124 Illustration of the Algorithm For the grammar: E E + T T T T F F F (E) id I 0 is closure(e E). The items E E, E E + T and E T are added to I 0. The last one in turn causes the addition of T T F and T F. The item T F leads to the addition of F (E) and F id. No more items can be added and the collection I 0 is complete
64 College of Engineering, Pune Syntax Analysis: 88/124 Canonical Collection of LR(0) items I 0 E. E E E + T E T..... T T * F T F F (E) F id I 4 F (. E ) E E + T E T..... T T * F T F F (E) F id I 7 I 8. T T * F F. (E) F id. F ( E. ) E E + T. E E. I I F 1 E E. id. + T 5 I 9 E T E + T T.. * F I 2 I 3 E T. T T. T F. * F I 6 E T... E + T T * F T F F (E) F id I 10 I 11 T T * F F (E)..
65 College of Engineering, Pune Syntax Analysis: 90/124 LR Automaton For Expression Grammar * I 2 ( I T 0 E ( F id T I 4 F I I 3 5 ( id F E id ( I I ) I 11 * + I 1 T I9 I 7 F I 10 I 0. E E I 1 E E. E E + T I 2 E T. T T * F. I 3 T F. I 4 F ( E ). I8 F (E ) E E + T.. I I 5 6 F id. E E +. T I9 E E + T T T *F.. T I 7 T T * F. I 10 T*F. F I 11 (E). Only the kernel items of each state is shown in the above
66 College of Engineering, Pune Syntax Analysis: 92/124 Construction of SLR(1) Parsing Table The procedure is described below: 1. From the input grammar G, construct an equivalent augmented grammar G. 2. Use the algorithm for constructing FOLLOW sets to compute FOLLOW(A), A N. 3. Call procedure items(g, C) to get the desired canonical collection C = {I 0, I 1,..., I n }. 4. Choose as many state symbols as the cardinality of C. We use numbers 0 through n to represent states.
67 College of Engineering, Pune Syntax Analysis: 94/124 Construction of SLR(1) Parsing Table For each I i, 0 i n do steps given below. 1. if A α a β I i and goto(i i,a) = I j, then action[i, a] = shift j. 2. If A α I i, then action[i, a] = reduce A α for all a FOLLOW (A). 3. If I i contains the item S S, then action[i, $] = accept 4. All remaining entries of state i in the action table are marked as error. 5. For nonterminals A, such that goto(i i, A) = I j create goto[i, A] = j. The remaining entries in the goto table are marked as error. The initial state of the parser is the state corresponding to the set I 0.
68 College of Engineering, Pune Syntax Analysis: 96/124 Illustration of Algorithm State i 0 Item with GOTO. t in I i ( I i, t ) F. id F. (E) I I 5 4 Complete item none Action Table shift 5 shift 4 1 E E. + T I shift 6 6 E E. acc on $ State i Item with. A in I i GOTO (I i, A ) goto Table 0 A = E A = T A = F I 1 I2 I none
69 College of Engineering, Pune Syntax Analysis: 98/124 SLR(1) Grammar and Parser stack input $ ((id + id))$ $( (id + id))$ $(( id + id))$ $((id + id))$ $((F + id))$ $((T + id))$ $((E + id))$ $((E + id))$ $((E + id ))$ $((E + F ))$ $((E + T ))$ $((E ))$ $((E) )$ $(F )$ $(T )$ $(E )$ $(E) $ $F $ $T $ $E $
70 College of Engineering, Pune Syntax Analysis: 100/124 SLR(1) Grammar and Parser A grammar for which there is a conflict free SLR(1) parsing table is called a SLR(1) grammar and a parser which uses such a table is known as SLR(1) parser. How do conflicts manifest in a SLR(1) parser? A shift reduce conflict is detected when a state has 1. a complete item of the form A α with a FOLLOW(A), and also 2. an incomplete item of the form B β a γ A reducereduce conflict is noticed when a state has two or more complete items of the form A α and B β, and FOLLOW(A) FOLLOW(B) Φ.
71 College of Engineering, Pune Syntax Analysis: 102/124 Conceptual Issues 1. What information do the states contain? 2. Where exactly is handle detection taking place in the parser? 3. Why is FOLLOW information used to create the reduce entries in the action table? To answer these questions, we need to see the canonical collection of LR(0) items as a graph. A node labeled I i is constructed for each member of C. For every nonempty goto(i i, X ) = I j, a directed edge (I i, I j ) is added labeled with X. The graph is a deterministic finite automaton if the node labeled I 0 is treated as the start state and all other nodes are made final states. What does the automaton recognize?
72 College of Engineering, Pune Syntax Analysis: 104/124 Viable Prefix and Valid Items A viable prefix of a grammar is defined to be the prefixes of right sentential forms that do not contain any symbols to the right of a handle. 1. By adding terminal symbols to viable prefixes, rightmost sentential forms can be constructed. 2. Viable prefixes are precisely the set of symbols that can ever appear on the stack of a shiftreduce parser 3. A viable prefix either contains a handle or contains parts of one or more handles. 4. Given a viable prefix, if one could identify the set of potential handles associated with it then a recognizer for viable prefixes would also recognize handles. The significance of LR(0) item can now be understood. A complete item corresponds to a handle while an incomplete item indicates the part of a handle seen so far.
73 College of Engineering, Pune Syntax Analysis: 106/124 Viable Prefix and Valid Items A LR(0) item A β 1 β 2 is defined to be valid for a viable prefix, αβ 1, provided S = rm αa w = rm αβ 1 β 2 w 1. It is interesting to note that in above, if β 2 = Bγ and B δ, then B δ is also a valid item for this viable prefix. 2. There could be several distinct items which are valid for the same viable prefix γ. 3. A particular item may be valid for many distinct viable prefixes. 4. The parser would halt when the viable prefix S is seen, in the item sense, it indicates a move from S to S. This is the reason for augmenting the input grammar.
74 College of Engineering, Pune Syntax Analysis: 108/124 Viable Prefixes and Valid Items Example : For the LRautomaton given in Figure 3.21, these concepts and their relationships are explained in the following. Consider the path { I 0, I 4, I 8, I 6 } which has the label (E+along it. The items that are valid for the viable prefix, (E+are determined below. 1. E = rm E = T = F = (E) = (E + T ) shows that E E + T is a valid item 2. E = E = T = F = (E) = (E + T ) = (E + T F ) shows that T T F is also a valid item. 3. E = rm (E + T ) = (E + F ) shows that T F is another such item. 4. E = rm (E + T ) = (E + F ) = (E + (E)) shows that F (E) is a valid item. 5. E = rm (E + F ) = (E+id ) shows that F id is a valid item. It should be noted that are no other valid items for this viable prefix.
75 College of Engineering, Pune Syntax Analysis: 110/124 Viable Prefixes and Valid Items Given a LR(0) item, say T T F, there may be several viable prefixes for which it is valid. 1. E = rm E = T = T F shows that this item is valid for the viable prefix T. 2. E = E = T = F = (E) = (T ) = (T F ) shows that it is also valid for ( T. 3. E = E = T = T F = T (E) = T (T ) = T (T F) shows that it is valid also for T * ( T. 4. E = E = E + T = E + T F shows validity for E + T. There may be several other viable prefixes for which this item is valid.
76 College of Engineering, Pune Syntax Analysis: 112/124 Theory of LR Parsing THEOREM : Starting from I 0, if traversing the LR(0) automaton γ results in state j, then set items in I j are the only valid items for the viable prefix γ. The theorem stated without proof above is a key result in LR Parsing. It provides the basis for the correctness of the construction process we learnt earlier. An LR parser does not scan the entire stack to determine when and which handle appears on top of stack ( compare with shiftreduce parser ). The state symbol on top of stack provides all the information that is present in the stack. In a state which contains a complete item a reduction is called for. However, the lookahead symbols for which the reduction should be applied is not obvious. In SLR(1) parser the FOLLOW information is used to guide reductions.
77 College of Engineering, Pune Syntax Analysis: 114/124 Limitations of SLR(1) PARSER Using FOLLOW information for is imprecise S L = R R L R id R L The SLR automaton and the parsing table for this grammar are shown.
78 College of Engineering, Pune Syntax Analysis: 116/124 SLR Automaton for a Grammar I 1 S S.. S L = R R L L. * R L id. S L = R... R R.. * R id S S S. L = R L L L I 2 R I 3 S L = R S R R L. = R I 6 I 9 S * id L L I o. I 5 id. id * I 4 L * R. R L L. * R L id. id R I 7 L * R. FOLLOW S { $ } S { $ } L { = $ } R { = $ } R L. I 8 L *
79 College of Engineering, Pune Syntax Analysis: 118/124 SLR Parsing Table Grammar : S S S L = R R L * R id R L Action Goto state id * = $ S L R s5 s s5 s4   s6 r5 acc r5 r r4 r s5 s r3 r r5 r r
80 College of Engineering, Pune Syntax Analysis: 120/124 SLR Parsing Table Observe that {=} FOLLOW(R), and R L is an item in state 2. There is another item, S L = R in the same state Note that state 2 recognizes the viable prefix L and the shift entry is justifiable. How about the reduce entry? After seeing L, if we reduce it to R, with the expectation of = to follow, there must exist a viable prefix R =... and hence a right sentential form of the form R = z. It can be shown that such is not possible. The problem seems to be with our FOLLOW information.
81 College of Engineering, Pune Syntax Analysis: 122/124 Limitations of SLR(1) Parser What is wrong with FOLLOW? This information is not correct for state 2. The sentential forms that permit = to follow R are of the form L... and taken care of in the state 8 of the parser. The context in state 2 is different ( viable prefix is L ), and use of FOLLOW constrains the parser. Given an item and a state the need is to identify the terminal symbols that can actually follow the lhs nonterminal.
82 College of Engineering, Pune Syntax Analysis: 124/124 Limitations of SLR(1) Parser An item of the form, A α β, a where the first component is a LR(0) item and the second component is a set of terminal symbols is called a LR(1) item. The second component is known as lookahead symbol. The value 1 indicates that the length of lookahead is 1. The lookahead symbol is used in a reduce operation only. For an item of the form, A α β, a if β is not ɛ, the lookahead has no effect. But for an item, A α, a the reduction is applied only if the nexttoken is a.
Bottomup parsing. BottomUp Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form
Bottomup parsing Bottomup 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 informationFormal Languages and Compilers Lecture VII Part 3: Syntactic A
Formal Languages and Compilers Lecture VII Part 3: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationBottom 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 informationLR Parsing Techniques
LR Parsing Techniques Introduction BottomUp Parsing LR Parsing as Handle Pruning ShiftReduce Parser LR(k) Parsing Model Parsing Table Construction: SLR, LR, LALR 1 BottomUP Parsing A bottomup parser
More information3. 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 informationPART 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 informationContextfree grammars
Contextfree grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals  tokens nonterminals  represent higherlevel structures of a program start symbol,
More informationSection 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 informationCompiler Design 1. BottomUP Parsing. Goutam Biswas. Lect 6
Compiler Design 1 BottomUP 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 informationCompiler Construction: Parsing
Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Contextfree grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax
More informationUNITIII BOTTOMUP PARSING
UNITIII BOTTOMUP PARSING Constructing a parse tree for an input string beginning at the leaves and going towards the root is called bottomup parsing. A general type of bottomup parser is a shiftreduce
More informationA leftsentential form is a sentential form that occurs in the leftmost derivation of some sentence.
Bottomup 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 leftsentential form is a sentential form that occurs
More informationCompiler Construction 2016/2017 Syntax Analysis
Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive topdown parsing Nonrecursive topdown parsing Bottomup parsing Syntax Analysis tokens
More informationS 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 informationLR Parsing. Leftmost and Rightmost Derivations. Compiler Design CSE 504. Derivations for id + id: T id = id+id. 1 ShiftReduce Parsing.
LR Parsing Compiler Design CSE 504 1 ShiftReduce 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 informationPrinciples 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 informationMODULE 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 informationMIT 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 informationSYNTAX 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 informationLR Parsers. Aditi Raste, CCOEW
LR Parsers Aditi Raste, CCOEW 1 LR Parsers Most powerful shiftreduce parsers and yet efficient. LR(k) parsing L : left to right scanning of input R : constructing rightmost derivation in reverse k : number
More information4. 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 informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and contextfree grammars n Grammar derivations n More about parse trees n Topdown and
More information4. 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 informationLR 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 informationLexical and Syntax Analysis. BottomUp Parsing
Lexical and Syntax Analysis BottomUp Parsing Parsing There are two ways to construct derivation of a grammar. TopDown: begin with start symbol; repeatedly replace an instance of a production s LHS with
More informationFormal Languages and Compilers Lecture VII Part 4: Syntactic A
Formal Languages and Compilers Lecture VII Part 4: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationWWW.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 informationSyntax Analysis: Contextfree Grammars, Pushdown Automata and Parsing Part  4. Y.N. Srikant
Syntax Analysis: Contextfree 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 informationUNIT 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 informationConcepts Introduced in Chapter 4
Concepts Introduced in Chapter 4 Grammars ContextFree Grammars Derivations and Parse Trees Ambiguity, Precedence, and Associativity Top Down Parsing Recursive Descent, LL Bottom Up Parsing SLR, LR, LALR
More informationLecture BottomUp Parsing
Lecture 14+15 BottomUp Parsing CS 241: Foundations of Sequential Programs Winter 2018 Troy Vasiga et al University of Waterloo 1 Example CFG 1. S S 2. S AyB 3. A ab 4. A cd 5. B z 6. B wz 2 Stacks in
More informationCS 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 informationChapter 4. Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem RecursiveDescent Parsing BottomUp Parsing Copyright 2012 AddisonWesley. All rights reserved.
More informationBottom Up Parsing. Shift and Reduce. Sentential Form. Handle. Parse Tree. Bottom Up Parsing 9/26/2012. Also known as ShiftReduce parsing
Also known as ShiftReduce parsing More powerful than top down Don t need left factored grammars Can handle left recursion Attempt to construct parse tree from an input string eginning at leaves and working
More informationCSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Introduction  Language implementation systems must analyze source code, regardless of the specific implementation approach  Nearly all syntax analysis is based on
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 BottomUp Parsing Bottomup parsing is more general than topdown parsing And just as efficient
More informationSyntax Analysis Part I
Syntax Analysis Part I Chapter 4: ContextFree Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,
More informationMonday, 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 nonterminals S is the start symbol P is the set of productions
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (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 informationParsing. Roadmap. > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing
Roadmap > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing The role of the parser > performs contextfree syntax analysis > guides
More informationWednesday, 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 informationParsers. 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 informationLALR 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 informationParsers. 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 informationWednesday, 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 informationEDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:
EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 20170911 This lecture Regular expressions Contextfree grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)
More informationVIVA 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 languagethe
More informationLet 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 informationParsing. 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 informationCompilers. Bottomup Parsing. (original slides by Sam
Compilers Bottomup Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) BottomUp Parsing More general than topdown parsing And just as efficient Builds
More informationChapter 4: LR Parsing
Chapter 4: LR Parsing 110 Some definitions Recall For a grammar G, with start symbol S, any string α such that S called a sentential form α is If α Vt, then α is called a sentence in L G Otherwise it is
More informationLR Parsing Techniques
LR Parsing Techniques BottomUp Parsing  LR: a special form of BU Parser LR Parsing as Handle Pruning ShiftReduce Parser (LR Implementation) LR(k) Parsing Model  k lookaheads to determine next action
More informationTop down vs. bottom up parsing
Parsing A grammar describes the strings that are syntactically legal A recogniser simply accepts or rejects strings A generator produces sentences in the language described by the grammar A parser constructs
More informationParsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones
Parsing III (Topdown parsing: recursive descent & LL(1) ) (Bottomup parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,
More informationLecture 8: Deterministic BottomUp Parsing
Lecture 8: Deterministic BottomUp 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 informationCompilerconstructie. najaar Rudy van Vliet kamer 140 Snellius, tel rvvliet(at)liacs(dot)nl. college 3, vrijdag 22 september 2017
Compilerconstructie najaar 2017 http://www.liacs.leidenuniv.nl/~vlietrvan1/coco/ Rudy van Vliet kamer 140 Snellius, tel. 071527 2876 rvvliet(at)liacs(dot)nl college 3, vrijdag 22 september 2017 + werkcollege
More informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview Tokens and regular expressions Syntax and contextfree grammars Grammar derivations More about parse trees Topdown and bottomup
More informationSyntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38
Syntax Analysis Martin Sulzmann Martin Sulzmann Syntax Analysis 1 / 38 Syntax Analysis Objective Recognize individual tokens as sentences of a language (beyond regular languages). Example 1 (OK) Program
More informationLecture 7: Deterministic BottomUp Parsing
Lecture 7: Deterministic BottomUp 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 informationCSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D1
CSE P 501 Compilers LR Parsing Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 D1 Agenda LR Parsing Tabledriven Parsers Parser States ShiftReduce and ReduceReduce conflicts UW CSE P 501 Spring 2018
More informationHow 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 informationSLR parsers. LR(0) items
SLR parsers LR(0) items As we have seen, in order to make shiftreduce parsing practical, we need a reasonable way to identify viable prefixes (and so, possible handles). Up to now, it has not been clear
More informationCSE302: Compiler Design
CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University March 20, 2007 Outline Recap LR(0)
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 5: Syntax Analysis (Parsing) Zheng (Eddy) Zhang Rutgers University January 31, 2018 Class Information Homework 1 is being graded now. The sample solution
More informationSyntax Analysis Check syntax and construct abstract syntax tree
Syntax Analysis Check syntax and construct abstract syntax tree if == = ; b 0 a b Error reporting and recovery Model using context free grammars Recognize using Push down automata/table Driven Parsers
More informationTopDown Parsing and Intro to BottomUp Parsing. Lecture 7
TopDown Parsing and Intro to BottomUp Parsing Lecture 7 1 Predictive Parsers Like recursivedescent but parser can predict which production to use Predictive parsers are never wrong Always able to guess
More informationThe analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program.
COMPILER DESIGN 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 languagethe target
More informationLR Parsing  The Items
LR Parsing  The Items Lecture 10 Sections 4.5, 4.7 Robb T. Koether HampdenSydney College Fri, Feb 13, 2015 Robb T. Koether (HampdenSydney College) LR Parsing  The Items Fri, Feb 13, 2015 1 / 31 1 LR
More informationChapter 4. Lexical and Syntax Analysis. Topics. Compilation. Language Implementation. Issues in Lexical and Syntax Analysis.
Topics Chapter 4 Lexical and Syntax Analysis Introduction Lexical Analysis Syntax Analysis Recursive Descent Parsing BottomUp parsing 2 Language Implementation Compilation There are three possible approaches
More informationCOMP421 Compiler Design. Presented by Dr Ioanna Dionysiou
COMP421 Compiler Design Presented by Dr Ioanna Dionysiou Administrative! Any questions about the syllabus?! Course Material available at www.cs.unic.ac.cy/ioanna! Next time reading assignment [ALSU07]
More informationBottomup Parser. Jungsik Choi
Formal Languages and Compiler (CSE322) Bottomup Parser Jungsik Choi chjs@khu.ac.kr * Some slides taken from SKKU SWE3010 (Prof. Hwansoo Han) and TAMU CSCE434500 (Prof. Lawrence Rauchwerger) Bottomup
More informationTabledriven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and nonterminals.
Bottomup Parsing: Tabledriven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and nonterminals. Basic operation is to shift terminals from the input to the
More information3. 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 informationSyntactic Analysis. TopDown Parsing
Syntactic Analysis TopDown Parsing Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in Compilers class at University of Southern California (USC) have explicit permission to make
More informationCS 4120 Introduction to Compilers
CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 6: BottomUp Parsing 9/9/09 Bottomup parsing A more powerful parsing technology LR grammars  more expressive than LL can handle
More informationSyntax Analysis. Prof. James L. Frankel Harvard University. Version of 6:43 PM 6Feb2018 Copyright 2018, 2015 James L. Frankel. All rights reserved.
Syntax Analysis Prof. James L. Frankel Harvard University Version of 6:43 PM 6Feb2018 Copyright 2018, 2015 James L. Frankel. All rights reserved. ContextFree Grammar (CFG) terminals nonterminals start
More informationParser Generation. BottomUp Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottomup  from leaves to the root
Parser Generation Main Problem: given a grammar G, how to build a topdown parser or a bottomup parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence 
More informationBottomUp Parsing II. Lecture 8
BottomUp Parsing II Lecture 8 1 Review: ShiftReduce Parsing Bottomup 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 informationSyntax Analyzer  Parser
Syntax Analyzer  Parser ASU Textbook Chapter 4.24.9 (w/o error handling) Tsansheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 A program represented by a sequence of tokens
More informationDownloaded 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 informationBottomUp Parsing II (Different types of ShiftReduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh.
BottomUp Parsing II Different types of ShiftReduce Conflicts) Lecture 10 Ganesh. Lecture 10) 1 Review: BottomUp Parsing Bottomup parsing is more general than topdown parsing And just as efficient Doesn
More informationBottomUp Parsing LR Parsing
BottomUp Parsing LR Parsing Maryam Siahbani 2/19/2016 1 What we need for LR parsing LR0) states: Describe all possible states in which parser can be Parsing table ransition between LR0) states Actions
More informationIntroduction to Syntax Analysis
Compiler Design 1 Introduction to Syntax Analysis Compiler Design 2 Syntax Analysis The syntactic or the structural correctness of a program is checked during the syntax analysis phase of compilation.
More informationLR Parsing LALR Parser Generators
LR Parsing LALR Parser Generators Outline Review of bottomup parsing Computing the parsing DFA Using parser generators 2 Bottomup Parsing (Review) A bottomup parser rewrites the input string to the
More informationTopDown Parsing and Intro to BottomUp Parsing. Lecture 7
TopDown Parsing and Intro to BottomUp Parsing Lecture 7 1 Predictive Parsers Like recursivedescent but parser can predict which production to use Predictive parsers are never wrong Always able to guess
More informationSyntax. In Text: Chapter 3
Syntax In Text: Chapter 3 1 Outline Syntax: Recognizer vs. generator BNF EBNF Chapter 3: Syntax and Semantics 2 Basic Definitions Syntax the form or structure of the expressions, statements, and program
More information8 Parsing. Parsing. Top Down Parsing Methods. Parsing complexity. Top down vs. bottom up parsing. Top down vs. bottom up parsing
8 Parsing Parsing A grammar describes syntactically legal strings in a language A recogniser simply accepts or rejects strings A generator produces strings A parser constructs a parse tree for a string
More informationPrinciple 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 informationChapter 3. Describing Syntax and Semantics ISBN
Chapter 3 Describing Syntax and Semantics ISBN 0321493621 Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Copyright 2009 AddisonWesley. All
More informationSyn S t yn a t x a Ana x lysi y s si 1
Syntax Analysis 1 Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token, tokenval Get next token Parser and rest of frontend Intermediate representation Lexical error Syntax
More informationSimple 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 shiftreduce conflict. This arises because the
More informationProgramming Language Syntax and Analysis
Programming Language Syntax and Analysis 2017 Kwangman Ko (http://compiler.sangji.ac.kr, kkman@sangji.ac.kr) Dept. of Computer Engineering, Sangji University Introduction Syntax the form or structure of
More informationReview: ShiftReduce Parsing. Bottomup parsing uses two actions: BottomUp Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk
Review: ShiftReduce Parsing Bottomup parsing uses two actions: BottomUp 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 informationIntroduction to Syntax Analysis. The Second Phase of FrontEnd
Compiler Design IIIT Kalyani, WB 1 Introduction to Syntax Analysis The Second Phase of FrontEnd Compiler Design IIIT Kalyani, WB 2 Syntax Analysis The syntactic or the structural correctness of a program
More informationCSCI312 Principles of Programming Languages
Copyright 2006 The McGrawHill Companies, Inc. CSCI312 Principles of Programming Languages! LL Parsing!! Xu Liu Derived from Keith Cooper s COMP 412 at Rice University Recap Copyright 2006 The McGrawHill
More informationParsing  1. What is parsing? Shiftreduce parsing. Operator precedence parsing. Shiftreduce conflict Reducereduce conflict
Parsing  1 What is parsing? Shiftreduce parsing Shiftreduce conflict Reducereduce conflict Operator precedence parsing Parsing1 BGRyder Spring 99 1 Parsing Parsing is the reverse of doing a derivation
More informationLL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012
Predictive Parsers LL(k) Parsing Can we avoid backtracking? es, if for a given input symbol and given nonterminal, we can choose the alternative appropriately. his is possible if the first terminal of
More informationCS308 Compiler Principles Syntax Analyzer Li Jiang
CS308 Syntax Analyzer Li Jiang Department of Computer Science and Engineering Shanghai Jiao Tong University Syntax Analyzer Syntax Analyzer creates the syntactic structure of the given source program.
More informationCS2210: Compiler Construction Syntax Analysis Syntax Analysis
Comparison with Lexical Analysis The second phase of compilation Phase Input Output Lexer string of characters string of tokens Parser string of tokens Parse tree/ast What Parse Tree? CS2210: Compiler
More informationIntroduction to Parsing. Comp 412
COMP 412 FALL 2010 Introduction to Parsing Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit permission to make
More information