Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS345 Project Presentation

Similar presentations


Presentation on theme: "CS345 Project Presentation"— Presentation transcript:

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

2 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

3 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

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

5 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

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

7 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 ]

8 First Class Function: Changes in BNF
Old Primary : callOrLambda|IdentifierOrArrayRef| Literal |subExpressionOrTuple|ListOrListComprehension New Primary : callOrLambda|IdentifierOrArrayRef|FuncArg| Literal |subExpressionOrTuple|ListOrListComprehension FuncArg : Identifier ({Parameter})

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

10 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) ]

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

12 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

13 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

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

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

16 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

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

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

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

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

21 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() {…}

22 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() {…}

23 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]; } …

24 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

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

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

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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 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

41 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

42 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

43 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

44 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

45 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

46 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

47 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

48 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

49 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

50 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

51 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

52 Questions 52


Download ppt "CS345 Project Presentation"

Similar presentations


Ads by Google