CS345 Project Presentation

Similar documents
High Level Languages. Java (Object Oriented) This Course. Jython in Java. Relation. ASP RDF (Horn Clause Deduction, Semantic Web) Dr.

Programming Languages

CS2 Current Technologies Note 1 CS2Bh

Real-World Performance Training SQL Introduction

CS2 Current Technologies Lecture 2: SQL Programming Basics

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

King Fahd University of Petroleum and Minerals

Introduction to Programming Using Java (98-388)

Syntax Intro and Overview. Syntax

Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )

Part III. Data Modelling. Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Programming Languages. Dr. Philip Cannata 1

Programming Languages. Dr. Philip Cannata 1

Database Management System. * First install Mysql Database or Wamp Server which contains Mysql Databse.

Informatics Practices (065) Sample Question Paper 1 Section A

Principles of Programming Languages

Name SOLUTIONS EID NOTICE: CHEATING ON THE MIDTERM WILL RESULT IN AN F FOR THE COURSE.

Pivot Tables Motivation (1)

Mid-Term 2 Grades

Java Bytecode (binary file)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CLASS DESIGN. Objectives MODULE 4

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Building lexical and syntactic analyzers. Chapter 3. Syntactic sugar causes cancer of the semicolon. A. Perlis. Chomsky Hierarchy

Reminder About Functions

Introduction. Introduction to Oracle: SQL and PL/SQL

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

CS 536 Midterm Exam Spring 2013

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1

Notes on Chapter Three

CS Reading Packet: "Views, and Simple Reports - Part 1"

CS Programming I: Arrays

Advanced Systems Programming

CS260 Intro to Java & Android 03.Java Language Basics

CSC Java Programming, Fall Java Data Types and Control Constructs

Language Reference Manual simplicity

CS Reading Packet: "Writing relational operations using SQL"

Midterm Exam CS 251, Intermediate Programming March 6, 2015

Compilers CS S-10 Object Oriented Extensions

Pace University. Fundamental Concepts of CS121 1

Rules and syntax for inheritance. The boring stuff

Midterm Exam CS 251, Intermediate Programming October 8, 2014

Sprite an animation manipulation language Language Reference Manual

CSE 340 Fall 2014 Project 4

The role of semantic analysis in a compiler

Computational Expression

Lecture 20 Sections Wed, Apr 1, 2009

RDBMS Using Oracle. BIT-4 Lecture Week 3. Lecture Overview

Parsing Scheme (+ (* 2 3) 1) * 1

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

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

Compilers CS S-05 Semantic Analysis

Functions and Recursion. Dr. Philip Cannata 1

.Net Technologies. Components of.net Framework

Class, Variable, Constructor, Object, Method Questions

Index COPYRIGHTED MATERIAL

The SPL Programming Language Reference Manual

SMURF Language Reference Manual Serial MUsic Represented as Functions

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

1 Lexical Considerations

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

C++ 8. Constructors and Destructors

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Intermediate Representations

JAVA WRAPPER CLASSES

The PCAT Programming Language Reference Manual

Scala : an LLVM-targeted Scala compiler

CS 360 Programming Languages Interpreters

CS 415 Midterm Exam Spring 2002

Project 1: Scheme Pretty-Printer

FUNCTIONAL AND LOGIC PROGRAMS

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating

CSE 401 Midterm Exam Sample Solution 11/4/11

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

CA4003 Compiler Construction Assignment Language Definition

Super-Classes and sub-classes

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

GOLD Language Reference Manual

CS453 CLASSES, VARIABLES, ASSIGNMENTS

C:\Temp\Templates. Download This PDF From The Web Site

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CIT 3136 Lecture 7. Top-Down Parsing

CS558 Programming Languages

CA Compiler Construction

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Special Member Functions

Compiler II: Code Generation Human Thought

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false

CS558 Programming Languages

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134)

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Transcription:

CS345 Project Presentation Language: Hmm++ TanmayaGodbole, Melissa Olson, Sriratana Sutasirisap

Project Overview: Hmm++ Revise and correct existing BNF Implement First Class Function Add an object oriented feature: Classes Modified BNF to recognize syntax for classes and object instantiation Interpreter

BNF: What exists in Hmm Program : {[ Declaration ] rettype Identifier Function MyClass MyObject Function : ( ) Block MyClass: Class Idenitifier { {rettype Identifier FunctionConstructor {rettype Identifier Function MyObject: Identifier Identifier = create Identifier callargs Constructor: Identifier ([{ Parameter ]) block Declaration : Type Identifier [ [Literal] ]{, Identifier [ [ Literal ] ] Type : int bool float list tuple object string void Statements : { Statement Statement : ; Declaration Block ForEach Assignment IfStatement WhileStatement CallStatement ReturnStatement Block : { Statements ForEach: for( Expression < Expression ) Block Assignment : Identifier [ [ Expression ] ]= Expression ; Parameter : Type Identifier IfStatement: if ( Expression ) Block [elseifstatement Block ] WhileStatement: while (Expression )Block

BNF: What exists in Hmm Expression : Conjunction { Conjunction Conjunction : Equality {&&Equality Equality : Relation [EquOp Relation ] EquOp: ==!= Relation : Addition [RelOp Addition ] RelOp: < <= > >= Addition : Term {AddOp Term AddOp: + Term : Factor {MulOp Factor MulOp: * / % Factor : [UnaryOp]Primary UnaryOp:!

BNF: What exists in Hmm Primary : callorlambda IdentifierOrArrayRef Literal subexpressionortuple ListOrListComprehension ObjFunction callorlambda : Identifier callargs LambdaDef callargs : ([Expression passfunc {,Expression passfunc] ) passfunc : Identifier (Type Identifier { Type Identifier ) LambdaDef : (\\ Identifier {,Identifier > Expression) IdentifierOrArrayRef : Identifier [ [Expression] ] subexpressionortuple : ([ Expression [,[ Expression {, Expression ] ] ] ) ListOrListComprehension: [ Expression {, Expression ] Expression[< Expression ] {, Expression[< Expression ] ] ObjFunction: Identifier. Identifier. Identifier callargs

BNF: What actually exists in Hmm Identifier : (a b z A B Z){ (a b z A B Z ) (0 1 9) Literal : Integer True False ClFloat ClString Integer : Digit { Digit ClFloat: 0 1 9 {0 1 9.{0 1 9 ClString: {~[ ]

BNF: Revised and Corrected Update the concrete syntax, it matches the existing code. Change ClFloat, after the dot, should be a ()+ not a ()* old: ClFloat: (0 1 9) {0 1 9.{0 1 9 new: ClFloat: (0 1 9) {0 1 9. (0 1 9) {0 1 9) In ifstatement : (in the else for ifstatement) old: IfStatement: if (Expression)Block [elseifstatement Block ] new: IfStatement: if (Expression)Block [ Block ]

First Class Function: Changes in BNF Old Primary : callorlambda IdentifierOrArrayRef Literal subexpressionortuple ListOrListComprehension New Primary : callorlambda IdentifierOrArrayRef FuncArg Literal subexpressionortuple ListOrListComprehension FuncArg : Identifier ({Parameter)

First Class Function: OldImplementation int main() { list emp = createemp(); int x = 6000; println( selectdept20(emp, getselector()) ); (object, bool) getselector(){ int x = 1000; return (\ y > y < x); list selectdept20(list emp,(object, bool) selector) { int x = 20; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x]; list createemp() { return [ (7839, "KING", "PRESIDENT", 0, "17 NOV 81", 5000, 10), (7369, "SMITH", "CLERK", 7902, "17 DEC 80", 800, 20)];

Program (abstract syntax): Function = main; Return type = int params = Block: list emp = Call: createemp, stackoffset=2 args = int x = IntValue: 6000 Call: println, stackoffset=0 args = Call: selectdept20, stackoffset=3 args = Variable: emp, LOCAL addr=1 Call: getselector, stackoffset=3 args = Function = getselector; Return type = (object, bool) params = Block: int x = IntValue: 1000 Return: Variable: return#getselector, LOCAL addr=0 Lambda: [y] Binary: Operator: < Variable: y, LAMBDA addr=0 Variable: x, LAMBDA addr=1 Function = selectdept20; Return type = list params = list emp (object, bool) selector Block: int x = IntValue: 20 Return: Variable: return#selectdept20, LOCAL addr=0 ListComprehension: ListTupleExpression: Tuple of: Variable: name, LOCAL addr=4 Variable: sal, LOCAL addr=5 TupleGenerator: (null, name, null, null, null, sal, dept) Variable: emp, LOCAL addr=1 Call: selector, stackoffset=0 args = Variable: sal, LOCAL addr=5 Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createemp; Return type = list params = Block: Return: Variable: return#createemp, LOCAL addr=0 ListTupleExpression: List of: ListTupleExpression: Tuple of: IntValue: 7839 StringValue: KING StringValue: PRESIDENT IntValue: 0 StringValue: 17 NOV 81 IntValue: 5000 IntValue: 10 ListTupleExpression: Tuple of: IntValue: 7369 StringValue: SMITH StringValue: CLERK IntValue: 7902 StringValue: 17 DEC 80 IntValue: 800 IntValue: 20 [ ] (SMITH, 800)

First Class Function: New Implementation int main() { list emp = createemp(); int x = 6000; println( selectdept20(emp, getselector(int y)) ); bool getselector(int y) { int x = 1000; return y < x; list selectdept20(list emp, (int >bool) selector) { int x = 20; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x]; list createemp() { return [ (7839, "KING", "PRESIDENT", 0, "17 NOV 81", 5000, 10), (7369, "SMITH", "CLERK", 7902, "17 DEC 80", 800, 20)];

Program (abstract syntax): Function = main; Return type = int params = Block: list emp = Call: createemp, stackoffset=2 args = int x = IntValue: 6000 Call: println, stackoffset=0 args = Call: selectdept20, stackoffset=3 args = Variable: emp, LOCAL addr=1 FuncArg: getselector args = int y Function = getselector; Return type = bool params = int y Block: int x = IntValue: 1000 Return: Variable: return#getselector, LOCAL addr=0 Binary: Operator: INT< Variable: y, LOCAL addr=1 Variable: x, LOCAL addr=2 Function = selectdept20; Return type = list params = list emp (int >bool) selector Block: int x = IntValue: 20 Return: Variable: return#selectdept20, LOCAL addr=0 ListComprehension: ListTupleExpression: Tuple of: Variable: name, LOCAL addr=4 Variable: sal, LOCAL addr=5 TupleGenerator: (null, name, null, null, null, sal, dept) Variable: emp, LOCAL addr=1 Call: selector, stackoffset=0 args = Variable: sal, LOCAL addr=5 Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createemp; Return type = list params = Block: Return: Variable: return#createemp, LOCAL addr=0 ListTupleExpression: List of: ListTupleExpression: Tuple of: IntValue: 7839 StringValue: KING StringValue: PRESIDENT IntValue: 0 StringValue: 17 NOV 81 IntValue: 5000 IntValue: 10 ListTupleExpression: Tuple of: IntValue: 7369 StringValue: SMITH StringValue: CLERK IntValue: 7902 StringValue: 17 DEC 80 IntValue: 800 IntValue: 20

First Class Function: Changes to the Code Changes to Parser.jj Changed Primary to also include funcarg funcarg method identifies the arguments of the first class function that is passed as a parameter. It creates a FuncArg object which is added to the AST Changes to AbstractSyntax.java FuncArg class stores information about parameters

First Class Function: Parser.jj public static class FuncArg extends Expression implements LValue{ private String name; private List<Declaration>args; private intlinenum; public FuncArg(Token t, List<Declaration> a) { name = t.image; linenum = t.beginline; args = a; public void display(int level){ super.display(level); Indenter indent = new Indenter(level); System.out.print(name); indent.display(" args = "); for( Declaration d: args){ d.display(level + 1); public String getname(){ return name; @Override public intgetlinenum(){ return linenum;

First Class Function: AbstractSyntax.java Expression primary() : { Expression e; Token t; { LOOKAHEAD(3) e = callorlambda() { return e; LOOKAHEAD(3) e = funcarg() { return e; //added later LOOKAHEAD(2) e = identifierorarrayref() { return e; e = literal() { return e; LOOKAHEAD(2) t = <LBRACE><RBRACE> { return ListTupleExpression.emptyList(t.beginLine); e = subexpressionortuple() { return e; e = listorlistcomprehension() { return e; /* TODO: Figure out the cast: type() <LPAREN> e = expression() <RPAREN> { return e; */ //function added later Expression funcarg() : {Token id; Declaration dec = null; List<Declaration>args= new ArrayList<Declaration>(); { id = <IDENTIFIER><LPAREN> (dec = parameter() {args.add(dec);)* <RPAREN> {return new FuncArg(id, args);

Interpreter: Overview main files are Interpreter.java, StaticTypeCheck.java, and SymbolTable.java StaticTypeCheck.java is where compile time error checking occurs. This includes: processing occurs by traveling down the parse tree simulating the program, even parts that are never called making sure arguments and parameters match type checking variables and associated declarations are stored on symbol table SymbolTable.java controls scoping (static) maintains a system of global and local scopes contains 2 hash maps one for global variables and one for local variables Interpreter.java where runtime errors occur processing occurs by actual running of the program (call history) starts in main and travels to any function calls, etc. retrieves variable values according to their address, retrieved from symbol table and corresponds to location on runtime stack

First Class Function: New Implementation int main() { list emp = createemp(); int x = 6000; println( selectdept20(emp, getselector(int y)) ); bool getselector(int y) { int x = 1000; return y < x; list selectdept20(list emp, (int > bool) selector) { int x = 20; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x]; list createemp() { return [ (7839, "KING", "PRESIDENT", 0, "17 NOV 81", 5000, 10), (7369, "SMITH", "CLERK", 7902, "17 DEC 80", 800, 20)];

First Class Function: Interpreter a function call evaluates its arguments and passes the resulting values to the corresponding parameters println( selectdept20(emp, getselector(int c)) ); When the program execution sees a FuncArg, then a FuncArgValue is returned which is equivalent to the FuncArg expressions must return values because they are used in assignments, if statements, etc. FuncArgValue allows a function to be stored in a variable and returned if(exp instanceof FuncArg){ FuncArg funcarg = (FuncArg) exp; FuncArgValue val = new FuncArgValue(funcArg.getName(), funcarg.getargs()); return val;

First Class Function: Interpreter The parameters of a method call are stored on the symbol table so that they can be used in the method body for (int i = 0, size = args.size(); i < size; i++) { setvarvalue(params.get(i).getvariable(), args.get(i)); Sees call to selector function to call has not been set in StaticTypeCheck, we must set it now if(exp instanceof Call) { Value val = getvarvalue(call.getvar()); if(val instanceof FuncArgValue){ FuncArgValue newval = (FuncArgValue)val; Function methodtocall = Util.findFunction(prog.getFunctions(), newval.getmethodname()); call.setfunctwithoutoffset(methodtocall); return callrealfunction(call, args);

First Class Function: Demo Database list createemp() { return [ (7839, "KING", "PRESIDENT", 0, "17 NOV 81", 5000, 10), (7698, "BLAKE", "MANAGER", 7839, "01 MAY 81", 2850, 30), (7782, "CLARK", "MANAGER", 7839, "09 JUN 81", 2450, 10), (7566, "JONES", "MANAGER", 7839, "02 APR 81", 2975, 20), (7788, "SCOTT", "ANALYST", 7566, "09 DEC 82", 3000, 20), (7902, "FORD", "ANALYST", 7566, "03 DEC 81", 3000, 20), (7369, "SMITH", "CLERK", 7902, "17 DEC 80", 800, 20), (7499, "ALLEN", "SALESMAN", 7698, "20 FEB 81", 1600, 30), (7521, "WARD", "SALESMAN", 7698, "22 FEB 81", 1250, 30), (7654, "MARTIN", "SALESMAN", 7698, "28 SEP 81", 1250, 30), (7844, "TURNER", "SALESMAN", 7698, "08 SEP 81", 1500, 30), (7876, "ADAMS", "CLERK", 7788, "12 JAN 83", 1100, 20), (7900, "JAMES", "CLERK", 7698, "03 DEC 81", 950, 30), (7934, "MILLER", "CLERK", 7782, "23 JAN 82", 1300, 10) ];

First Class Function: Demo fcf_test1.c int main() { list emp = createemp(); int x = 6000; println( selectdept20(emp, getselector(int c)) ); //don't need to use variable y bool getselector(int y) { int x = 1000; return y < x; list selectdept20(list emp, (object > bool) selector) { //type of selector must be (object > bool) because we do not know that sal is an int int x = 20; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x]; list createemp() {

First Class Function: Demo fcf_test2.c int main() { list emp = createemp(); int x = 6000; (object > bool) selector = getselector(int y); //storing in a variable println( selectdept20(emp, selector )); bool getselector(int y) { int x = 2000; return y < x; list selectdept20(list emp, (object > bool) selector) { //type of selector must be (object > bool) because we do not know that sal is an int int x = 20; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x]; list createemp() {

First Class Function: Demo fcf_test3.c int main() { list emp = createemp(); int x = 6000; (object > bool) selector = returnfunct(); println( selectdept20(emp, selector )); bool getselector(int y) { int x = 1000; return y < x; (object > bool) returnfunct(){ return getselector(int y); list selectdept20(list emp, (object > bool) selector) { //type of selector must be (object > bool) because we do not know that sal is an int int x = 30; return [ (name, sal) (_, name, _, _, _, sal, dept) < emp, selector(sal), dept == x];

Classes: Modifications to BNF Program: {[ Declaration ] rettype Identifier Function MyClass MyObject Primary: callorlambda IdentifierOrArrayRef Literal subexpressionortuple ListOrListComprehension ObjFunction BNF for creating a new class MyClass: Class Idenitifier { {rettype Identifier FunctionConstructor {rettypeidentifier Function Constructor: Identifier ([{ Parameter ]) block BNF for creating an instance of a class MyObject: Identifier Identifier = create Identifier callargs BNF for calling the class s function ObjFunction: Identifier. Identifier. Identifier callargs

Classes: Example Creating a new class Class Test{ intmyx; intmyy; Test(intx, inty){ myx= x; myy = y; intfun (intmatch){ println(myx +myy + match); return myx + myy + match; Creating an instance of a class Test oneobj = create Test(9, 78); Calling the class s function temp = Test.oneObj.fun(4);

Classes:Changes to Parser.jj Modified Program() to recognize class and object c= myclass() {classlist.add(c); o= obj() {objlist.add(o); Added ObjFunction to be a part of Primary() LOOKAHEAD(3) e = objfunc() { return e; Added MyClassmyClass(), Constructor constructor(), MyObjectobj(), ObjFunctionobjFunc() MyClassmyClass() : { Constructor cons; List<Declaration> globals= new ArrayList<Declaration>(); List<Declaration>decList List<Function>funcList = new ArrayList<Function>(); Token classname; Function f;{ <MYCLASS>className = <IDENTIFIER><LCURLY> (curtopleveltype = rettype() curtopleveltoken = <IDENTIFIER> ( declist = restofglobaldec() {globals.addall(declist); f = restoffunction() { funclist.add(f); ))* cons = constructor() (curtopleveltype = rettype() curtopleveltoken = <IDENTIFIER> ( declist = restofglobaldec() {globals.addall(declist); f = restoffunction() { funclist.add(f); ))* <RCURLY> { return new MyClass(className, globals, funclist, cons);

Classes:Changes to AbstractSyntax.java Modified the class Program{ public Program(List<Declaration>globals, List<Function> functions, List<MyClass> classes, List<MyObject> objects) { this.globals = globals; this.functions = functions; this.classes = classes; this.objects= objects; Added these classes: MyClass{ Constructor{ MyObject extends Statement{ ObjFunction extends Expression {

Program (abstract syntax): Function = main; Return type = int params = Block: int x = Call: foo, stackoffset=2 args = Call: println, stackoffset=0 args = StringValue: It worked! Function = foo; Return type = int params = Block: int temp = IntValue: 10 Object = oneobj; Object type = Test args = IntValue: 20 IntValue: 4 Assignment: Variable: temp, LOCAL addr=1 Object Function = oneobj; Function Name = fun args = Variable: temp, LOCAL addr=1 Return: Variable: return#foo, LOCAL addr=0 Variable: temp, LOCAL addr=1 Class: Test int myx int myy Function = fun; Return type = int params = int match Block: Call: println, stackoffset=0 args = StringValue: The result from method fun is: Call: println, stackoffset=0 args = Binary: Operator: INT+ Binary: Operator: INT+ Variable: myx, INSTANCE addr=2 Variable: myy, INSTANCE addr=3 Variable: match, LOCAL addr=5 Return: Variable: return#fun, LOCAL addr=4 Binary: Operator: INT+ Binary: Operator: INT+ Variable: myx, INSTANCE addr=2 Variable: myy, INSTANCE addr=3 Variable: match, LOCAL addr=5 Constructor = Test params = int x int y Block: Assignment: Variable: myx, INSTANCE addr=2 Variable: x, LOCAL addr=4 Assignment: Variable: myy, INSTANCE addr=3 Variable: y, LOCAL addr=5 Classes:AST

Classes: Demo Class Test{ int myx; int myy; Test(int x, int y){ myx = x; myy = y; int fun (int match){ println (myx +myy + match); return myx + myy + match; int main() { int x = foo(); println( "It worked!" ); int foo(){ int temp = 10; Test oneobj = create Test(20, 4); temp = Test.oneObj.fun(temp); println(temp); return temp;

Classes: Checking the class syntax The class goes through Static Type Check and is then added to the Symbol Table (stored in an ArrayList) The object and a list of its instance variables are stored in the symbol table in a HashMap the object as the key, and a list of the Instance Variables as the values Each object of a class is given its own copies of the global variables of a class.

Classes: Objects An outline of the steps required to actually create the object, assign the instance variables an address in the symbol table, and call the constructor An object can be created in main, or any other function checkstatement in StaticTypeCheck, checks if the statement in the body of the function is if(s instanceof MyObject) { MyObject obj = (MyObject) s; if(!symboltable.classexistence(obj.gettype())){ logger.error(obj.getlinenum(), UNDEFINED_CLASS, obj.gettype()); symboltable.createobj(obj); checkclass(obj, obj.gettype()); return;

Classes: Symbol Table public void createobj(myobject obj) { Scope lastscope = scopes.get(scopes.size() 1); int curcount = lastscope.getcurcount(); MyClass c = globalclasses.get(obj.gettype()); List<Declaration> objvars = c.getglobals(); for(declaration decl: objvars){ Variable current = decl.getvariable(); current.setexecutiondata(vartype.instance, instancecount + curcount, null); instancecount++; instancevariables.put(obj, objvars);

Classes: Static Type Check void checkclass(myobject obj, String classname) { //added later MyClass c = symboltable.getclass(classname); Constructor cons = c.getconstructor(); checkconstructor(obj, cons); for(function funct : c.getfunctions()) { checkoofunction(obj, funct); void checkconstructor(myobject obj, Constructor cons) { symboltable.startconstructor(cons); checkoostatement(obj, cons.getbody()); symboltable.endconstructor(cons);

Classes: Static Type Check public void startconstructor(constructor cons){ curconstructor = cons; scopes.add(new Scope(getCurCount(), cons.getnumscopevariables())); addlocaldeclarations(cons.getparams()); public void endconstructor(constructor cons { scopes.get(scopes.size() 1).closeScope(curConstructor.getNumScopeVariables()); scopes.remove(scopes.size() 1); curconstructor = null;

Classes: Static Type Check startconstructor opens a new scope within the scope of the object endconstructor closes the scope of the constructor void checkoofunction(myobject obj, Function f) { symboltable.startfunction(f); checkoostatement(obj, f.getbody()); symboltable.endfunction();

Classes: Static Type Check if (s instanceof Return) { Return ret = (Return) s; Type funtype = symboltable.getcurfunctiontype(); // Make sure the 'void' type is actually consistent with a return expression. if (funtype == BaseType.VOID && ret.getresult()!= null) { logger.error(ret.getlinenum(), VOID_CAN_NOT_RETURN); return; if (funtype!= BaseType.VOID && ret.getresult() == null) { logger.error(ret.getlinenum(), NON_VOID_MUST_RETURN); return; // We also need to process the "variable" that serves as a return value: checkooexpression(ret.gettarget()); if (ret.getresult()!= null) { Type exptype = checkooexpression(ret.getresult()); testassignment(exptype, funtype, ret.getlinenum(), 1) return;

Classes: Static Type Check Checks binary, and then each term in the binary. Since myx, myy are variables, it processes the Variables which finds the instance variables, and assigns them an address on the stack which is recorded by the symbol table. private Type processoovariableuse(myobject obj, Variable var) { Type type = symboltable.assignooaddress(obj, var); if (type == null) { logger.error(var.getlinenum(), VAR_UNDEFINED, var.getname()); return null; return type;

Classes: Symbol Table public Type assignooaddress(myobject obj, Variable var){ if (lambdacontexts.size() == 0) { Declaration decl = findnormaloodeclaration(obj, var); //myx, myy go into this if (decl == null) { decl = findnormaldeclaration(var); // x goes into this if (decl == null) { return null; // We have established the declaration: copy the variable type and address: var.setexecutiondata(decl.getvariable()); // Make sure the type is defined: myassert(decl.gettype()!= null, "The type in the declaration is null"); return decl.gettype();

Classes: Symbol Table The FindNormalOODeclaration method finds the instance variable in the symbol table private Declaration findnormaloodeclaration(myobject obj, Variable var) { List<Declaration> declist = instancevariables.get(obj); Declaration result = null; for(declaration decl : declist){ String curname = decl.getvariable().getname(); if(curname.equals(var.getname())) result = decl; return result;

Classes: Object Function The steps involved in calling a function of an object temp = Test.oneObj.fun(temp); goes to checkstatement. Since it is an instance of Expression, it goes into checkexpression { if (exp instanceof ObjFunction) ObjFunction of = (ObjFunction) exp; return processoofunction(of);

Classes: Symbol Table private Type processoofunction (ObjFunction of) { List<Expression> args = of.getargs(); String funcname = of.getfuncname(); MyObject obj = symboltable.getobject(of.getobjname()); MyClass c = symboltable.getclass(obj.gettype()); Function funct = null; List<Function> flist = c.getfunctions(); for(function func : flist){ if(func.getname().equals(of.getfuncname())) funct = func; // Just in case the call has been already processed, don't try to do it again! FunctionType prototype; String name = funct.getname();

Classes: ProcessOOFunction if (funct == null) { logger.error(of.getlinenum(), UNDEF_FUNCTION, name); return null; // Update the 'function' reference in the call: of.setoofunction(funct, symboltable.getcurcount()); int linenum = of.getlinenum(); List<Type> paramtypes = prototype.getparamtypes(); // Checking the Prototype: if (of.getargs().size()!= paramtypes.size()) { logger.error(linenum, INV_NUM_ARGS, name, paramtypes.size(), of.getargs().size());

Classes: ProcessOOFunction else { for (int i = 0, size = args.size(); i < size; i++) { Type argtype = checkexpression(args.get(i)); if (argtype == null) { continue; // check if arg type matches param type testassignment(argtype, paramtypes.get(i), linenum, i); return prototype.getresulttype();

Classes: Interpreter Run Statement if (s instanceof MyObject) { MyObject obj = (MyObject)s; MyClass c = Util.findClass(prog.getClasses(), obj.gettype()); Constructor cons = c.getconstructor(); List<Value> args = evaluateexplist(obj.getargs()); callconstructor(cons, args); return false;

Classes: Interpreter private List<Value> evaluateexplist(list<expression> members) throws InterpreterRuntimeError { List<Value> result = new ArrayList<Value>(members.size()); for (Expression exp : members) { result.add(runexpression(exp)); return result;

Classes: Constructor public void callconstructor(constructor c, List<Value> args) throws InterpreterRuntimeError { List<Declaration> params = c.getparams(); if (args.size()!= params.size()) { throw new InterpreterRuntimeError(c.getLineNum(), INV_NUM_ARGS, "constructor", params.size(), args.size()); for (int i = 0, size = args.size(); i < size; i++) { setvarvalue(params.get(i).getvariable(), args.get(i)); //need to worry about this! runstatement(c.getbody());

Classes: Object Function if (exp instanceof ObjFunction) { ObjFunction of = (ObjFunction)exp; List<Expression> unevaluated = of.getargs(); List<Value> args = evaluateexplist(unevaluated); return calloofunction(of, args); calloofunction returns the result of the function which is defined in the body of the class

Classes: Interpreter public Value calloofunction(objfunction objfunc, List<Value> args) throws InterpreterRuntimeError { MyClass c = Util.findClass(prog.getClasses(), objfunc.getclassname()); Function f = null; List<Function> flist = c.getfunctions(); for(function func : flist){ if(func.getname().equals(objfunc.getfuncname())) f = func; Value result = null; baseptr += objfunc.getstackoffset(); if(f == null) throw new InterpreterRuntimeError(objFunc.getLineNum(), UNDEF_FUNCTION, "object function");

Classes: calloofunction List<Declaration> params = f.getparams(); if (args.size()!= params.size()) { throw new InterpreterRuntimeError(objFunc.getLineNum(), INV_NUM_ARGS, f.getname(), params.size(), args.size()); for (int i = 0, size = args.size(); i < size; i++) { setvarvalue(params.get(i).getvariable(), args.get(i)); //need to worry about this! // Now, execute the actual Function body: runstatement(f.getbody());

Classes: calloofunction // NOTE: By convention, the return value shall be assigned the FIRST address: if (f.isvoid() == false) { Declaration returndec = f.getreturndecl(); Variable v = returndec.getvariable(); int address = v.getaddress(); result = stack[baseptr + address]; if (result == null) { throw new InterpreterRuntimeError(objFunc.getLineNum(), FUNCTION_DID_NOT_RETURN_VALUE, f.getname()); baseptr = objfunc.getstackoffset(); return result; //this result corresponds to the result of the actualy function you're calling

Classes: Demo classtest.c Class Test{ int myx; int myy; Test(int x, int y){ myx = x; myy = y; int fun (int match){ println(myx +myy + match); return myx + myy + match; int main() { int x = foo(); println( "It worked!" ); int foo(){ int temp = 10; Test oneobj = create Test(20, 4); temp = Test.oneObj.fun(temp); println(temp); return temp;

Questions