cs345 project presentation

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

Upload: watson

Post on 09-Jan-2016

32 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS345  Project  Presentation

CS345 Project Presentation

TanmayaGodbole, Melissa Olson,

Sriratana Sutasirisap

Language: Hmm++

Page 2: CS345  Project  Presentation

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

Page 3: CS345  Project  Presentation

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

Page 4: CS345  Project  Presentation

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: - | !

Page 5: CS345  Project  Presentation

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

Page 6: CS345  Project  Presentation

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: ” {~[“] }”

Page 7: CS345  Project  Presentation

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 ]

Page 8: CS345  Project  Presentation

First Class Function: Changes in BNF

Old• Primary : callOrLambda|IdentifierOrArrayRef| Literal |

subExpressionOrTuple|ListOrListComprehensionNew• Primary : callOrLambda|IdentifierOrArrayRef|FuncArg| Literal |

subExpressionOrTuple|ListOrListComprehension• FuncArg : Identifier ({Parameter})

Page 9: CS345  Project  Presentation

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

First Class Function: OldImplementation

Page 10: CS345  Project  Presentation

Program (abstract syntax): Function = main; Return type = intparams = Block: list emp = Call: createEmp, stackOffset=2args =int x =IntValue: 6000 Call: println, stackOffset=0args = Call: selectDept20, stackOffset=3args = Variable: emp, LOCAL addr=1 Call: getSelector, stackOffset=3args = 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 = listparams = list emp (object, bool) selector

Block:int x =IntValue: 20 Return: Variable: return#selectDept20, LOCAL addr=0ListComprehension:ListTupleExpression: Tuple of: Variable: name, LOCAL addr=4 Variable: sal, LOCAL addr=5TupleGenerator: (null, name, null, null, null, sal, dept) Variable: emp, LOCAL addr=1 Call: selector, stackOffset=0args = Variable: sal, LOCAL addr=5 Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createEmp; Return type = listparams = Block: Return: Variable: return#createEmp, LOCAL addr=0ListTupleExpression: List of:ListTupleExpression: Tuple of:IntValue: 7839StringValue: KINGStringValue: PRESIDENTIntValue: 0StringValue: 17-NOV-81IntValue: 5000IntValue: 10

ListTupleExpression: Tuple of:IntValue: 7369StringValue: SMITHStringValue: CLERKIntValue: 7902StringValue: 17-DEC-80IntValue: 800IntValue: 20

[ (SMITH, 800)]

Page 11: CS345  Project  Presentation

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: New Implementation

Page 12: CS345  Project  Presentation

Program (abstract syntax): Function = main; Return type = intparams = Block: list emp = Call: createEmp, stackOffset=2args =int x =IntValue: 6000 Call: println, stackOffset=0args = Call: selectDept20, stackOffset=3args = Variable: emp, LOCAL addr=1FuncArg: getSelectorargs =int y Function = getSelector; Return type = boolparams =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 = listparams = list emp (int ->bool) selector

Block:int x =IntValue: 20 Return: Variable: return#selectDept20, LOCAL addr=0ListComprehension:ListTupleExpression: Tuple of: Variable: name, LOCAL addr=4 Variable: sal, LOCAL addr=5TupleGenerator: (null, name, null, null, null, sal, dept) Variable: emp, LOCAL addr=1 Call: selector, stackOffset=0args = Variable: sal, LOCAL addr=5 Binary: Operator: == Variable: dept, LOCAL addr=6 Variable: x, LOCAL addr=3 Function = createEmp; Return type = listparams = Block: Return: Variable: return#createEmp, LOCAL addr=0ListTupleExpression: List of:ListTupleExpression: Tuple of:IntValue: 7839StringValue: KINGStringValue: PRESIDENTIntValue: 0StringValue: 17-NOV-81IntValue: 5000IntValue: 10

ListTupleExpression: Tuple of:IntValue: 7369StringValue: SMITHStringValue: CLERKIntValue: 7902StringValue: 17-DEC-80IntValue: 800IntValue: 20

Page 13: CS345  Project  Presentation

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 ASTChanges to AbstractSyntax.java• FuncArg class

- stores information about parameters

Page 14: CS345  Project  Presentation

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: Parser.jj

Page 15: CS345  Project  Presentation

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

First Class Function: AbstractSyntax.java

Page 16: CS345  Project  Presentation

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

Page 17: CS345  Project  Presentation

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: New Implementation

Page 18: CS345  Project  Presentation

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

Page 19: CS345  Project  Presentation

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

Page 20: CS345  Project  Presentation

First Class Function: Demo Databaselist 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) ];}

Page 21: CS345  Project  Presentation

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_test1.c

Page 22: CS345  Project  Presentation

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_test2.c

Page 23: CS345  Project  Presentation

First Class Function: Demo fcf_test3.cint 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];} …

Page 24: CS345  Project  Presentation

Classes: Modifications to BNF• Program: {[ Declaration ]|retType Identifier Function | MyClass | MyObject}• Primary: callOrLambda|IdentifierOrArrayRef| Literal |subExpressionOrTuple|

ListOrListComprehension| ObjFunction• BNF for creating a new classMyClass: Class Idenitifier { {retType Identifier Function}Constructor {retTypeIdentifier

Function } }Constructor: Identifier ([{ Parameter } ]) block • BNF for creating an instance of a classMyObject: Identifier Identifier = create Identifier callArgs• BNF for calling the class’s functionObjFunction: Identifier . Identifier . Identifier callArgs

Page 25: CS345  Project  Presentation

Classes: ExampleClass Test{intmyX;intmyY; Test(intx, inty){myX= x;myY = y; }intfun (intmatch){ println(myX +myY + match); return myX + myY + match; }}

temp = Test.oneObj.fun(4);

• Creating a new class

• Creating an instance of a class Test oneObj = create Test(9, 78);

• Calling the class’s function

Page 26: CS345  Project  Presentation

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

Page 27: CS345  Project  Presentation

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 {…}

Page 28: CS345  Project  Presentation

Classes:ASTProgram (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

Page 29: CS345  Project  Presentation

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

Page 30: CS345  Project  Presentation

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.

Page 31: CS345  Project  Presentation

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

Page 32: CS345  Project  Presentation

Classes: Symbol Tablepublic 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); }

Page 33: CS345  Project  Presentation

Classes: Static Type Checkvoid 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);

}

Page 34: CS345  Project  Presentation

Classes: Static Type Checkpublic 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; }

Page 35: CS345  Project  Presentation

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

Page 36: CS345  Project  Presentation

Classes: Static Type Checkif (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; }}

Page 37: CS345  Project  Presentation

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

Page 38: CS345  Project  Presentation

Classes: Symbol Tablepublic 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(); }

Page 39: CS345  Project  Presentation

Classes: Symbol TableThe 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; }

Page 40: CS345  Project  Presentation

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

Page 41: CS345  Project  Presentation

Classes: Symbol Tableprivate 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();

Page 42: CS345  Project  Presentation

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

Page 43: CS345  Project  Presentation

Classes: ProcessOOFunctionelse { 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(); }

Page 44: CS345  Project  Presentation

Classes: InterpreterRun 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; }

Page 45: CS345  Project  Presentation

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

Page 46: CS345  Project  Presentation

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

Page 47: CS345  Project  Presentation

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

Page 48: CS345  Project  Presentation

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

Page 49: CS345  Project  Presentation

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

Page 50: CS345  Project  Presentation

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 }

Page 51: CS345  Project  Presentation

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

Page 52: CS345  Project  Presentation

Questions