Language Translators - Lee McCluskey LANGUAGE TRANSLATORS: WEEK 21 LECTURE: Using JavaCup to create simple interpreters

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Abstract Syntax Mooly Sagiv html:// 1.
1 JavaCUP JavaCUP (Construct Useful Parser) is a parser generator Produce a parser written in java, itself is also written in Java; There are many parser.
Exercise: Balanced Parentheses
Compilers and Language Translation
Lexical and Syntactic Analysis Here, we look at two of the tasks involved in the compilation process –Given source code, we need to first break it into.
Honors Compilers An Introduction to Grammars Feb 12th 2002.
9/27/2006Prof. Hilfinger, Lecture 141 Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik)
Cse321, Programming Languages and Compilers 1 6/12/2015 Lecture #10, Feb. 14, 2007 Modified sets of item construction Rules for building LR parse tables.
FACS Week 14 Grammars and their properties; Introduction to Parsing Lee McCluskey, room 2/07
Environments and Evaluation
CS 280 Data Structures Professor John Peterson. Lexer Project Questions? Must be in by Friday – solutions will be posted after class The next project.
28-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
Chapter 2 A Simple Compiler
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
Syntax Directed Translation. Syntax directed translation Yacc can do a simple kind of syntax directed translation from an input sentence to C code We.
1 Abstract Syntax Tree--motivation The parse tree –contains too much detail e.g. unnecessary terminals such as parentheses –depends heavily on the structure.
CPSC 388 – Compiler Design and Construction Parsers – Context Free Grammars.
Syntax and Semantics Structure of programming languages.
1 Chapter 2 A Simple Compiler. 2 Outlines 2.1 The Structure of a Micro Compiler 2.2 A Micro Scanner 2.3 The Syntax of Micro 2.4 Recursive Descent Parsing.
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
LANGUAGE TRANSLATORS: WEEK 24 TRANSLATION TO ‘INTERMEDIATE’ CODE (overview) Labs this week: Tutorial Exercises on Code Generation.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
LANGUAGE TRANSLATORS: WEEK 3 LECTURE: Grammar Theory Introduction to Parsing Parser - Generators TUTORIAL: Questions on grammar theory WEEKLY WORK: Read.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 2.
CS 461 – Oct. 7 Applications of CFLs: Compiling Scanning vs. parsing Expression grammars –Associativity –Precedence Programming language (handout)
CS Describing Syntax CS 3360 Spring 2012 Sec Adapted from Addison Wesley’s lecture notes (Copyright © 2004 Pearson Addison Wesley)
Profs. Necula CS 164 Lecture Top-Down Parsing ICOM 4036 Lecture 5.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
LANGUAGE TRANSLATORS: WEEK 17 scom.hud.ac.uk/scomtlm/cis2380/ See Appel’s book chapter 3 for support reading Last Week: Top-down, Table driven parsers.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Syntax and Semantics Structure of programming languages.
CS 153: Concepts of Compiler Design September 16 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Chapter 2. Design of a Simple Compiler J. H. Wang Sep. 21, 2015.
CPS 506 Comparative Programming Languages Syntax Specification.
Abstract Syntax Trees Compiler Baojian Hua
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
1 Using Yacc. 2 Introduction Grammar –CFG –Recursive Rules Shift/Reduce Parsing –See Figure 3-2. –LALR(1) –What Yacc Cannot Parse It cannot deal with.
Compiler Principles Fall Compiler Principles Lecture 6: Parsing part 5 Roman Manevich Ben-Gurion University.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Compiler Construction By: Muhammad Nadeem Edited By: M. Bilal Qureshi.
Chapter 3 Context-Free Grammars and Parsing. The Parsing Process sequence of tokens syntax tree parser Duties of parser: Determine correct syntax Build.
Parser Generation Using SLK and Flex++ Copyright © 2015 Curt Hill.
C H A P T E R T W O Linking Syntax And Semantics Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
LECTURE 3 Compiler Phases. COMPILER PHASES Compilation of a program proceeds through a fixed series of phases.  Each phase uses an (intermediate) form.
Overview of Compilation Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Programming Language Principles Lecture 2.
CMSC 330: Organization of Programming Languages Pushdown Automata Parsing.
CS 404Ahmed Ezzat 1 CS 404 Introduction to Compiler Design Lecture Ahmed Ezzat.
Chapter 3 – Describing Syntax CSCE 343. Syntax vs. Semantics Syntax: The form or structure of the expressions, statements, and program units. Semantics:
Chapter 3 – Describing Syntax
CS 153: Concepts of Compiler Design September 14 Class Meeting
CUP: An LALR Parser Generator for Java
A Simple Syntax-Directed Translator
CS510 Compiler Lecture 4.
Core Core: Simple prog. language for which you will write an interpreter as your project. First define the Core grammar Next look at the details of how.
PROGRAMMING LANGUAGES
CPSC 388 – Compiler Design and Construction
CPSC 388 – Compiler Design and Construction
Mini Language Interpreter Programming Languages (CS 550)
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Lecture 7: Introduction to Parsing (Syntax Analysis)
R.Rajkumar Asst.Professor CSE
Syntax-Directed Translation
Chap 7. Advanced Control Statements in Java
COMPILER CONSTRUCTION
Presentation transcript:

Language Translators - Lee McCluskey LANGUAGE TRANSLATORS: WEEK 21 LECTURE: Using JavaCup to create simple interpreters Tutorial / Practical 1. Run JavaCup on Linux / Ouranos following the “self study” file in the website 2. Continue to do paper based exercises creating SR parsers

Language Translators - Lee McCluskey JavaCup Grammar in “parser.cup” PLUS action code JavaCup Parsing Table in “parser.java” and “sym.java” PLUS action code Scanner in “scanner.java” javac Library Classes for Interpreting Parsing Table Interpreter

Language Translators - Lee McCluskey An Interpreter for an expression evaluator stm ::= ID:id ASSIGNS expr:e {: put(id,e.intValue()); :} SEMI | PRINT expr:e {: System.out.println("= " + e); :} SEMI ; expr ::= expr:e1 SQUARED {: RESULT = new Integer(e1.intValue() * e1.intValue());:} | ID:id {:RESULT = new Integer(get(id));:} | expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue() + e2.intValue());:} The left hand side of each production is always implicitly labelled as RESULT.

Language Translators - Lee McCluskey Problem with evaluation during parsing: Imagine trying to implement Java’s “DO WHILE ” “IF ( ) ” using option 2 (evaluating code while parsing). These are examples of compound statements The problem is that repetition or branching cannot be easily dealt with when interpreting the program at the same time as parsing it. We can execute an assignment statement after we parse it … but not so easy with parts of compound statements.

Language Translators - Lee McCluskey A better option.. RECALL Option 3 from previous week: - Use JavaCup to build up a Parse Tree; Attach ACTION CODE to production rules to do this. - Once parsing has finished, pass this Parse Tree to the next part of the interpreter/ compiler/ translator eg to a Java interpreter or Compiler.

Language Translators - Lee McCluskey LPL (See code in Q3parser directory for definition). Using Javacup + interpreter code we can easily create an interpreter for code such as the following example x = 23; repeat x = x-1; y = x*x; print(x,y) until x; print(x)

Language Translators - Lee McCluskey Part of LPL’s parser.cup file stm::= ID:id ASSIGNS exp:e {: RESULT = new AssignStm(id,e); :} | REPEAT stm:s1 UNTIL exp:e {: RESULT = new RepeatStm(s1,e); :} | exp ::= INT:n {: RESULT = new NumExp(n.intValue()); :} | ID:id {:RESULT = new IdExp(id);:} | exp:e1 PLUS exp:e2 {: RESULT = new OpExp(e1,OpExp.Plus,e2); :}

Language Translators - Lee McCluskey LPL – build up of syntax tree stm(new AssignStm(new IdExp(“x”), new NumExp(9))) PARSING expr(new IdExp(“x”)) expr(new NumExp(9)) ID,"x" ASSIGNS INT,9 SEMI SCANNING x = 9; TOKEN STREAM Prog(interpStm(, new NumExp(9 Table("",0,null)); REST OF TREE

Language Translators - Lee McCluskey Example from lecture 3... Eg might be something like this … new CompoundStm( new AssignStm("b",new NumExp(5)), new CompoundStm( new AssignStm("a", new OpExp(new NumExp(5), OpExp.Times, new IdExp("b"))), new PrintStm(new ExpList(new OpExp(new IdExp("b"), OpExp.Times, new IdExp("a")))) ) );

Language Translators - Lee McCluskey LPL – how the interpreter works Once the input program is parsed successfully, the program’s parse tree is passed to the interpreter to be interpreted! The interpreter code is situated at the beginning of parser.cup and is copied to parser.java verbatim. Sequence: 1. When executed with an input program P, the Parser creates a Syntax (or ‘parse’) Tree representing P. 2. The Syntax Tree together with an empty Table is passed to the interpreter in the action code. 3. The entries in the Table correspond to variable’s current values as P is interpreted (the Table is called the ‘Store’) 4. Commands in P change the Store

Language Translators - Lee McCluskey LPL - the Store Table represents the STORE of the program class Table { String id; int value; Table tail; Table(String i, int v, Table t) {id =i; value=v; tail=t;} etc - it is a RECURSIVE type

Language Translators - Lee McCluskey LPL - INTERPRETER interpStm applies a statement s to a store t (t is represented as a Table) interpStm is called initially with an empty store … prog ::= stm: s {: RESULT = interpStm(s,new Table("",0,null)); :} ; interpStm’s input is the parse tree in Java Constructor form. This could be processed in many ways e.g. a SYMBOL TABLE can be extracted from it and used to track variable DECLARATIONS.

Language Translators - Lee McCluskey interpStm - compound If s is a compound statement then we want to apply the first statement to the current store t getting store t’, then apply the second statement to t’. That is what this piece of code does: else if (s instanceof CompoundStm) return interpStm(s.get2(), interpStm(s.get1(),t)); Here t’ = interpStm(s.get1(),t)

Language Translators - Lee McCluskey interpStm - assignment ASSIGNMENT: else if (s instanceof AssignStm) return update(t,s.getLHS(),interpExp(s.getRHS(), t)); If s is an assignment then it has a LHS (the variable) and a RHS (the expression). update takes the current store t, the LHS, the VALUE of the RHS in the current store, and returns a NEW store. Table update(Table t,String str, int i) { return (new Table(str, i, t));}

Language Translators - Lee McCluskey interpStm - repeat Apply the inside of the loop to obtain a new store. If the repeat expression is 0 in this new store then end, otherwise recursively call InterpStm with the new store. else if (s instanceof RepeatStm) { Table table_temp = interpStm(s.getRepStm(),t); int int_temp = interpExp(s.getRepExp(),table_temp); if (int_temp == 0) return table_temp; else return interpStm(s, table_temp); }

Language Translators - Lee McCluskey InterExp InterExp is a recursive method for evaluating Expressions in the context of a certain store. InterpExp takes expression e and store t and returns a VALUE. Note a VALUE in LPL is always ‘int’ - we don’t allow booleans, strings etc

Language Translators - Lee McCluskey Conclusions... The definition of LPL in parser.cup contains the syntax specification and the Java Code implementing LPL’s interpreter

Language Translators - Lee McCluskey APPENDIX: Steps to Updating/improving the JavaCup-generated Interpreter Each time you make an addition to the language go through the following steps. n As an example, we will use the WHILE COMMAND

Language Translators - Lee McCluskey STEP 1 n Work out what concrete syntax you want for your new command or other extension. Write down its semantics. WHILE DO Evaluate. If it is zero skip and goto the next statement after WHILE in the program. Otherwise execute, then execute WHILE DO again.

Language Translators - Lee McCluskey STEP 2 n Put the new syntax in scanner.java Eg add the following to scanner.java: case ’W': advance(); advance(); advance(); advance(); advance(); return new Symbol(sym.WHILE); case ’D': advance(); advance(); return new Symbol(sym.DO);

Language Translators - Lee McCluskey Step 3: n Add abstract syntax to parser.cup - the non-terminals/terminals, the production rule, and the attached action code terminal REPEAT, UNTIL, SEMI, PLUS, WHILE, DO... Stm ::= WHILE exp:e DO stm:s {: RESULT = new WhileStm(s,e); :}

Language Translators - Lee McCluskey Step 4: n Add the new Syntax Class for the While Statement to the action code class WhileStm extends Stm { Stm s; Exp exp; WhileStm(Stm a, Exp e) {s=a; exp=e;} public Stm getWhileStm() {return s;} public Exp getWhileExp() {return exp;} }

Language Translators - Lee McCluskey Step 5: n Add to the action code statements that interpret the WHILE Stm Table interpStm(Stm s, Table t) {... else if (s instanceof WhileStm) int temp = interpExp(s.getWhileExp(),t); if (temp == 0) return t; else return interpStm(s, interpStm(s.getWhileStm(),t))...

Language Translators - Lee McCluskey Step 6: Follow the steps to create the interpreter in the READ - ME file as usual.