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

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

Agenda. Previously. Tentative syllabus. Fall Compiler Principles Lecture 5: Parsing part 4 12/2/2015. Roman Manevich Ben-Gurion University

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

Last Time. What do we want? When do we want it? An AST. Now!

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

Compilers and Language Processing Tools

COMP 181. Prelude. Prelude. Summary of parsing. A Hierarchy of Grammar Classes. More power? Syntax-directed translation. Analysis

Abstract Syntax. Mooly Sagiv. html://

Context-free grammars

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

Using JFlex. "Linux Gazette...making Linux just a little more fun!" by Christopher Lopes, student at Eastern Washington University April 26, 1999

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

CUP. Lecture 18 CUP User s Manual (online) Robb T. Koether. Hampden-Sydney College. Fri, Feb 27, 2015

Compiler Construction: Parsing

Conflicts in LR Parsing and More LR Parsing Types

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

Compilation 2013 Parser Generators, Conflict Management, and ML-Yacc

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

For example, we might have productions such as:

Lecture Bottom-Up Parsing

Lecture 8: Deterministic Bottom-Up Parsing

In One Slide. Outline. LR Parsing. Table Construction

Lecture 7: Deterministic Bottom-Up Parsing

JavaCUP. There are also many parser generators written in Java

LR Parsing - The Items

Bottom-Up Parsing. Lecture 11-12

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

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS

A clarification on terminology: Recognizer: accepts or rejects strings in a language. Parser: recognizes and generates parse trees (imminent topic)

Bottom-Up Parsing. Lecture 11-12

JavaCC Parser. The Compilation Task. Automated? JavaCC Parser

LR Parsing LALR Parser Generators

Monday, September 13, Parsers

Syntax-Directed Translation. Lecture 14

LR Parsing LALR Parser Generators

Wednesday, September 9, 15. Parsers

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

EDAN65: Compilers, Lecture 04 Grammar transformations: Eliminating ambiguities, adapting to LL parsing. Görel Hedin Revised:

How do LL(1) Parsers Build Syntax Trees?

CS606- compiler instruction Solved MCQS From Midterm Papers

CSE 401 Midterm Exam Sample Solution 11/4/11

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

Wednesday, August 31, Parsers

Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich Ben-Gurion University of the Negev

Topic 3: Syntax Analysis I

SLR parsers. LR(0) items

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

CS 11 Ocaml track: lecture 6

shift-reduce parsing

Lexical and Syntax Analysis. Bottom-Up Parsing

Topic 5: Syntax Analysis III

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

Review of CFGs and Parsing II Bottom-up Parsers. Lecture 5. Review slides 1

LR Parsing. Table Construction

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

Formal Languages and Compilers Lecture VII Part 4: Syntactic A

Downloaded from Page 1. LR Parsing

Example CFG. Lectures 16 & 17 Bottom-Up Parsing. LL(1) Predictor Table Review. Stacks in LR Parsing 1. Sʹ " S. 2. S " AyB. 3. A " ab. 4.

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

Lexical Analysis. Textbook:Modern Compiler Design Chapter 2.1

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

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

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

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

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

Syntax-Directed Translation

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

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

Fall Compiler Principles Lecture 3: Parsing part 2. Roman Manevich Ben-Gurion University

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

CSE 401 Midterm Exam 11/5/10

10/4/18. Lexical and Syntactic Analysis. Lexical and Syntax Analysis. Tokenizing Source. Scanner. Reasons to Separate Lexical and Syntactic Analysis

LR Parsing Techniques

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


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

Formal Languages and Compilers Lecture VII Part 3: Syntactic A

CSE302: Compiler Design

CS 4120 Introduction to Compilers

Compiler Construction

CSE 401/M501 18au Midterm Exam 11/2/18. Name ID #

Concepts Introduced in Chapter 4

Principles of Programming Languages

Table-driven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and non-terminals.

Defining syntax using CFGs

Compiler Construction

LR Parsers. Aditi Raste, CCOEW

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

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

10/5/17. Lexical and Syntactic Analysis. Lexical and Syntax Analysis. Tokenizing Source. Scanner. Reasons to Separate Lexical and Syntax Analysis

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

FROWN An LALR(k) Parser Generator

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

Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation

3. Parsing. Oscar Nierstrasz

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

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

Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich Ben-Gurion University of the Negev

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

Properties of Regular Expressions and Finite Automata

Transcription:

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 Local Optimizations Register Allocation Top-down Parsing (LL) Dataflow Analysis Instruction Selection Bottom-up Parsing (LR) Loop Optimizations Attribute Grammars mid-term exam 2

Previously LR(0) parsing Running the parser Constructing transition diagram Constructing parser table Detecting conflicts SLR(0) Eliminating SHIFT-REDUCE via FOLLOW sets 3

SLR parsing 4

SLR parsing A handle should not be reduced to a nonterminal N if the lookahead is a token that cannot follow N A reduce item N α is applicable only when the lookahead is in FOLLOW(N) If b is not in FOLLOW(N) we just proved there is no terminating derivation S =>* βnb and thus it is safe to remove the reduce item from the conflicted state Differs from LR(0) only on the ACTION table Now a row in the parsing table may contain both shift actions and reduce actions and we need to consult the current token to decide which one to take 5

SLR action table Lookahead token from the input State id + ( ) [ ] $ state action 0 shift shift q0 shift 1 shift shift q1 shift 2 accept q2 3 shift shift q3 shift 4 E E+T E E+T E E+T q4 E E+T 5 T id T id r5, s6 T id vs. q5 T id 6 E T E T E T q6 E T 7 shift shift q7 shift 8 shift shift q8 shift 9 T (E) T (E) T (E) q9 T E as before T id T id[e] SLR use 1 token look-ahead [ is not in FOLLOW(T) LR(0) no look-ahead 6

Agenda LR(1) LALR(1) Dealing with ambiguity CUP parser generator 7

Going beyond SLR(0) Some common language constructs introduce conflicts even for SLR (0) S S (1) S L = R (2) S R (3) L * R (4) L id (5) R L 8

q0 S S S L = R S R L * R L id R L R S L q3 q1 q2 S R S S S L = R R L = q9 S L = R q6 R * * q4 id id q5 L id id S L = R R L L * R L id L * R R L L * R L id * L q8 L R L R L * R q7 9

shift/reduce conflict (0) S S (1) S L = R (2) S R (3) L * R (4) L id (5) R L q2 S L = R R L = q6 S L = R vs. R L FOLLOW(R) contains = S L = R * R = R SLR cannot resolve conflict S L = R R L L * R L id 10

Inputs requiring shift/reduce (0) S S (1) S L = R (2) S R (3) L * R (4) L id (5) R L q2 S L = R R L = q6 S L = R R L L * R L id For the input id the rightmost derivation S => S => R => L => id requires reducing in q2 For the input id = id S => S => L = R => L = L => L = id => id = id requires shifting 11

LR(1) grammars In SLR: a reduce item N α is applicable only when the lookahead is in FOLLOW(N) But FOLLOW(N) merges lookahead for all alternatives for N Insensitive to the context of a given production LR(1) keeps lookahead with each LR item Idea: a more refined notion of FOLLOW computed per item 12

LR(1) item Already matched To be matched Input N α β, t Hypothesis about αβ being a possible handle, so far we ve matched α, expecting to see β and after reducing N we expect to see the token t 13

LR(1) items LR(1) item is a pair LR(0) item Lookahead token Meaning We matched the part left of the dot, looking to match the part on the right of the dot, followed by the lookahead token Example The production L id yields the following LR(1) items LR(1) items (0) S S (1) S L = R (2) S R (3) L * R (4) L id (5) R L LR(0) items [L id] [L id ] [L id, *] [L id, =] [L id, id] [L id, $] [L id, *] [L id, =] [L id, id] [L id, $] 14

Computing Closure for LR(1) For every [A α Bβ, c] in S for every production B δ and every token b in the grammar such that b FIRST(βc) Add [B δ, b] to S 15

* q0 (S S, $) (S L = R, $) (S R, $) (L * R, = ) (L id, = ) (R L, $ ) (L id, $ ) (L * R, $ ) q4 * (L * R, =) (R L, =) (L * R, =) (L id, =) (L * R, $) (R L, $) (L * R, $) (L id, $) id R id q5 R L S q3 (S R, $) q1 (S S, $) q2 (S L = R, $) (R L, $) (L id, $) (L id, =) q7 L (L * R, =) (L * R, $) q6 q9 (S L = R, $) = R (S L = R, $) (R L, $) (L * R, $) (L id, $) q8 (R L, =) (R L, $) L * q11 (L id, $) id q12 (R L, $) q13 q10 (L * R, $) (R L, $) (L * R, $) (L id, $) R (L * R, $) id 16

Back to the conflict q2 (S L = R, $) (R L, $) = q6 (S L = R, $) (R L, $) (L * R, $) (L id, $) Is there a conflict now? 17

LALR(1) LR(1) tables have huge number of entries Often don t need such refined observation (and cost) Idea: find states with the same LR(0) component and merge their lookaheads component as long as there are no conflicts LALR(1) not as powerful as LR(1) in theory but works quite well in practice Merging may not introduce new shift-reduce conflicts, only reduce-reduce, which is unlikely in practice 18

* q0 (S S, $) (S L = R, $) (S R, $) (L * R, = ) (L id, = ) (R L, $ ) (L id, $ ) (L * R, $ ) q4 * (L * R, =) (R L, =) (L * R, =) (L id, =) (L * R, $) (R L, $) (L * R, $) (L id, $) id R id q5 R L S q3 (S R, $) q1 (S S, $) q2 (S L = R, $) (R L, $) (L id, $) (L id, =) q7 L (L * R, =) (L * R, $) q6 q9 (S L = R, $) = R (S L = R, $) (R L, $) (L * R, $) (L id, $) q8 (R L, =) (R L, $) L * q11 (L id, $) id q12 (R L, $) q13 q10 (L * R, $) (R L, $) (L * R, $) (L id, $) R (L * R, $) id 19

* q0 (S S, $) (S L = R, $) (S R, $) (L * R, = ) (L id, = ) (R L, $ ) (L id, $ ) (L * R, $ ) q4 * (L * R, =) (R L, =) (L * R, =) (L id, =) (L * R, $) (R L, $) (L * R, $) (L id, $) id R id q5 R L S q3 (S R, $) q1 (S S, $) q2 (S L = R, $) (R L, $) (L id, $) (L id, =) q7 L (L * R, =) (L * R, $) q6 q9 (S L = R, $) = R (S L = R, $) (R L, $) (L * R, $) (L id, $) q8 (R L, =) (R L, $) L * q11 (L id, $) id q12 (R L, $) q13 q10 (L * R, $) (R L, $) (L * R, $) (L id, $) R (L * R, $) id 20

* q0 (S S, $) (S L = R, $) (S R, $) (L * R, = ) (L id, = ) (R L, $ ) (L id, $ ) (L * R, $ ) q4 * (L * R, =) (R L, =) (L * R, =) (L id, =) (L * R, $) (R L, $) (L * R, $) (L id, $) id R id q5 R L S q3 (S R, $) q1 (S S, $) q2 (S L = R, $) (R L, $) (L id, $) (L id, =) q7 L id (L * R, =) (L * R, $) q6 q9 (S L = R, $) = R (S L = R, $) (R L, $) (L * R, $) (L id, $) q8 (R L, =) (R L, $) L * q12 (R L, $) q10 (L * R, $) (R L, $) (L * R, $) (L id, $) R id 21

Left/Right- recursion At home: create a simple grammar with leftrecursion and one with right-recursion Construct corresponding LR(0) parser Any conflicts? Run on simple input and observe behavior Attempt to generalize observation for long inputs 22

Automated Parser Generation (via CUP) 23

High-level structure text Lexer spec JFlex.java javac Lexical analyzer ADTL.lex Lexer.java tokens (Token.java) Parser spec CUP.java javac Parser ADTL.cup sym.java Parser.java AST 24

Expression calculator expr expr + expr expr - expr expr * expr expr / expr - expr ( expr ) number Goals of expression calculator parser: Is 2+3+4+5 a valid expression? What is the meaning (value) of this expression? 25

Syntax analysis with CUP CUP parser generator Generates an LALR(1) Parser Input: spec file Output: a syntax analyzer tokens Parser spec CUP.java javac Parser AST 26

CUP spec file Package and import specifications User code components Symbol (terminal and non-terminal) lists Terminals go to sym.java Types of AST nodes Precedence declarations The grammar Semantic actions to construct AST 27

Expression Calculator 1 st Attempt terminal Integer NUMBER; terminal PLUS, MINUS, MULT, DIV; terminal LPAREN, RPAREN; non terminal Integer expr; Symbol type explained later expr ::= expr PLUS expr expr MINUS expr expr MULT expr expr DIV expr MINUS expr LPAREN expr RPAREN NUMBER ; 28

Ambiguities + * * a b c + a + b * c + a b c + + a b c a + b + c + a b c 29

Ambiguities as conflicts for LR(1) + * + * a b c a + b * c + a b c + + a b c a + b + c + a b c 30

terminal Integer NUMBER; terminal PLUS,MINUS,MULT,DIV; terminal LPAREN, RPAREN; terminal UMINUS; non terminal Integer expr; Expression Calculator 2 nd Attempt precedence left PLUS, MINUS; precedence left DIV, MULT; precedence left UMINUS; Increasing precedence expr ::= expr PLUS expr expr MINUS expr expr MULT expr expr DIV expr MINUS expr %prec UMINUS LPAREN expr RPAREN NUMBER ; Contextual precedence 31

Parsing ambiguous grammars using precedence declarations Each terminal assigned with precedence By default all terminals have lowest precedence User can assign his own precedence CUP assigns each production a precedence Precedence of rightmost terminal in production or user-specified contextual precedence On shift/reduce conflict resolve ambiguity by comparing precedence of terminal and production and decides whether to shift or reduce In case of equal precedences left/right help resolve conflicts left means reduce right means shift More information on precedence declarations in CUP s manual 32

Resolving ambiguity precedence left PLUS + + + a b c + a b c a + b + c 33

Resolving ambiguity precedence left PLUS precedence left MULT * + + a b c * a b c a * b + c 34

Resolving ambiguity precedence left MULT MINUS expr %prec UMINUS * - - a b a * b - a * b 35

Resolving ambiguity terminal Integer NUMBER; terminal PLUS,MINUS,MULT,DIV; terminal LPAREN, RPAREN; terminal UMINUS; UMINUS never returned by scanner (used only to define precedence) precedence left PLUS, MINUS; precedence left DIV, MULT; precedence left UMINUS; expr ::= expr PLUS expr expr MINUS expr expr MULT expr expr DIV expr MINUS expr %prec UMINUS LPAREN expr RPAREN NUMBER ; Rule has precedence of UMINUS 36

More CUP directives precedence nonassoc NEQ Non-associative operators: < > ==!= etc. 1<2<3 identified as an error (semantic error?) start non-terminal Specifies start non-terminal other than first non-terminal Can change to test parts of grammar Getting internal representation Command line options: -dump_grammar -dump_states -dump_tables -dump 37

Scanner integration import java_cup.runtime.*; %% %cup Generated from token %eofval{ declarations in.cup file return new Symbol(sym.EOF); %eofval} NUMBER=[0-9]+ %% <YYINITIAL> + { return new Symbol(sym.PLUS); } <YYINITIAL> - { return new Symbol(sym.MINUS); } <YYINITIAL> * { return new Symbol(sym.MULT); } <YYINITIAL> / { return new Symbol(sym.DIV); } <YYINITIAL> ( { return new Symbol(sym.LPAREN); } <YYINITIAL> ) { return new Symbol(sym.RPAREN); } <YYINITIAL>{NUMBER} { return new Symbol(sym.NUMBER, new Integer(yytext())); } <YYINITIAL>\n { } <YYINITIAL>. { } Parser gets terminals from the scanner 38

Recap Package and import specifications and user code components Symbol (terminal and non-terminal) lists Define building-blocks of the grammar Precedence declarations May help resolve conflicts The grammar May introduce conflicts that have to be resolved 39

Assigning meaning expr ::= expr PLUS expr expr MINUS expr expr MULT expr expr DIV expr MINUS expr %prec UMINUS LPAREN expr RPAREN NUMBER ; So far, only validation Add Java code implementing semantic actions 40

Assigning meaning expr ::= expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue() + e2.intvalue()); :} expr:e1 MINUS expr:e2 {: RESULT = new Integer(e1.intValue() - e2.intvalue()); :} expr:e1 MULT expr:e2 {: RESULT = new Integer(e1.intValue() * e2.intvalue()); :} expr:e1 DIV expr:e2 {: RESULT = new Integer(e1.intValue() / e2.intvalue()); :} MINUS expr:e1 {: RESULT = new Integer(0 - e1.intvalue(); :} %prec UMINUS LPAREN expr:e1 RPAREN {: RESULT = e1; :} NUMBER:n {: RESULT = n; :} ; Symbol labels used to name variables RESULT names the left-hand side symbol 41

Building an AST More useful representation of syntax tree Less clutter Actual level of detail depends on your design Basis for semantic analysis Later annotated with various information Type information Computed values Technically a class hierarchy of abstract syntax tree nodes 42

Parse tree vs. AST expr + expr + expr expr expr 1 + ( 2 ) + ( 3 ) 1 2 3 43

AST hierarchy example expr int_const plus minus times divide 44

AST construction AST Nodes constructed during parsing Stored in push-down stack Bottom-up parser Grammar rules annotated with actions for AST construction When node is constructed all children available (already constructed) Node (RESULT) pushed on stack Top-down parser More complicated 45

AST construction 1 + (2) + (3) expr + (2) + (3) expr + (expr) + (3) expr + (3) expr + (expr) expr expr expr ::= expr:e1 PLUS expr:e2 {: RESULT = new plus(e1,e2); :} LPAREN expr:e RPAREN {: RESULT = e; :} INT_CONST:i {: RESULT = new int_const(, i); :} plus e1 e2 expr plus e1 e2 expr expr expr 1 + ( 2 ) + ( 3 ) int_const val = 1 int_const val = 2 int_const val = 3 46

Example of lists terminal Integer NUMBER; terminal PLUS,MINUS,MULT,DIV,LPAREN,RPAREN,SEMI; terminal UMINUS; non terminal Integer expr; non terminal expr_list, expr_part; precedence left PLUS, MINUS; precedence left DIV, MULT; precedence left UMINUS; expr_list ::= expr_list expr_part expr_part ; expr_part ::= expr:e {: System.out.println("= " + e); :} SEMI ; expr ::= expr PLUS expr expr MINUS expr expr MULT expr expr DIV expr MINUS expr %prec UMINUS LPAREN expr RPAREN NUMBER ; 47

Next lecture: Intermediate Representation