CS345 Project Presentation

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

Chapter 2 Syntax A language that is simple to parse for the compiler is also simple to parse for the human programmer. N. Wirth.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
1 Compiler Construction Intermediate Code Generation.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Restricting and sorting data 16 May May May Created By Pantharee Sawasdimongkol.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 2 Syntax A language that is simple to parse.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 10 Function Implementation In theory, there.
Environments and Evaluation
Logical Operators Operator AND OR NOT Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns.
INF5110: Mandatory Exercise 2 Eyvind W. Axelsen @eyvindwa Slides are partly based on.
Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree -
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
The Java Programming Language
Dr. Philip Cannata 1 Programming Languages Prolog Part 3 SQL & Prolog.
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.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Relational Databases &
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Dr. Philip Cannata 1 Functions and Recursion. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython.
Dr. Philip Cannata 1 Lexical and Syntactic Analysis Chomsky Grammar Hierarchy Lexical Analysis – Tokenizing Syntactic Analysis – Parsing Hmm Concrete Syntax.
ECE122 Feb. 22, Any question on Vehicle sample code?
1 Objects and types Typed languages = define a set of types in the language and assign a type to each expression in the program Type checking = how can.
Semantics. Semantics is a precise definition of the meaning of a syntactically and type-wise correct program. Ideas of meaning: –Operational Semantics.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
CS 153: Concepts of Compiler Design October 7 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 345 Project Presentation OOH A More Object-Oriented Hmm++ Alysha Behn Jesse Vera.
Syntax (2).
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CS345 Project Presentation Language: H-- Mikhail Iakhiaev.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Dr. Philip Cannata 1 Programming Languages Haskell.
2-1 Limiting Rows Using a Selection “…retrieve all employees in department 10” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
Visitor-Based HMM Israel Perez, Fayz Rahman, Chinedu Egboh.
BY: JAKE TENBERG & CHELSEA SHIPP PROJECT REVIEW: JGIBBERISH.
CS412/413 Introduction to Compilers Radu Rugina Lecture 11: Symbol Tables 13 Feb 02.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Compiler Design Lecture 10 Semantic Analysis. int aintegers int a[2][3]array(2, array(3, integer)) int f(int, float, char) int x float x char  int Int.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
CS314 – Section 5 Recitation 9
Topic: Classes and Objects
Principles of programming languages 12: Functional programming
Some Eclipse shortcuts
Java Primer 1: Types, Classes and Operators
Semantic Analysis with Emphasis on Name Analysis
Programming Language Concepts (CIS 635)
CS 536 / Fall 2017 Introduction to programming languages and compilers
Continuing Chapter 11 Inheritance and Polymorphism
CS 302 Week 11 Jim Williams, PhD.
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
understanding memory usage by a c++ program
Programming Languages 2nd edition Tucker and Noonan
Chapter 6 Intermediate-Code Generation
Classes & Objects: Examples
Dynamic Scoping Lazy Evaluation
Procedures – Building the Syntax Tree
PZ09A - Activation records
6.001 SICP Further Variations on a Scheme
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Restricting and Sorting Data
Review for Midterm 3.
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Presentation transcript:

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 Function}Constructor {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 Call: selectDept20, stackOffset=3 Variable: emp, LOCAL addr=1 Call: getSelector, stackOffset=3 Function = getSelector; Return type = (object, bool) 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 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 = Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createEmp; Return type = list params = Variable: return#createEmp, LOCAL addr=0 ListTupleExpression: List 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 Call: selectDept20, stackOffset=3 Variable: emp, LOCAL addr=1 FuncArg: getSelector int y Function = getSelector; Return type = bool 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 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 = Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createEmp; Return type = list params = Variable: return#createEmp, LOCAL addr=0 ListTupleExpression: List 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 Function}Constructor {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 Creating an instance of a 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() | 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 {…}

Classes:AST Block: Program (abstract syntax): Function = main; Return type = int params = Block: int x = Call: foo, stackOffset=2 args = Call: println, stackOffset=0 StringValue: It worked! Function = foo; Return type = int int temp = IntValue: 10 Object = oneObj; Object type = Test IntValue: 20 IntValue: 4 Assignment: Variable: temp, LOCAL addr=1 Object Function = oneObj; Function Name = fun Return: Variable: return#foo, LOCAL addr=0 Class: Test int myX int myY Function = fun; Return type = int int match Block: Call: println, stackOffset=0 args = StringValue: The result from method fun is: 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 Constructor = Test params = int x int y Assignment: Variable: x, LOCAL addr=4 Variable: y, LOCAL addr=5

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; 29

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. 30

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; 31

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); 32

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); 33

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; 34

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(); } 35

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) } } 36

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; 37

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 } 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(); 38

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; 39

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); } 40

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(); 41

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()); 42

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(); 43

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; } 44

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; 45

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()); 46

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 47

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"); 48

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()); 49

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 50

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; 51

Questions 52