1 / 52

CS345 Project Presentation

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

watson
Download Presentation

CS345 Project Presentation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

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

  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: NewImplementation int main() { list emp = createEmp(); int x = 6000; println( selectDept20(emp, getSelector(int y)) ); } boolgetSelector(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 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() (curTopLevelType = retType() curTopLevelToken = <IDENTIFIER> ( decList = restOfGlobalDec() {globals.addAll(decList); } | 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. 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

  29. Classes: Demo Class Test{ intmyX; intmyY; 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; }

  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.

  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 instanceofMyObject) { MyObjectobj = (MyObject) s; if( !symbolTable.classExistence(obj.getType())){ logger.error(obj.getLineNum(), UNDEFINED_CLASS, obj.getType()); } symbolTable.createObj(obj); checkClass(obj, obj.getType()); return; }

  32. Classes: Symbol Table public void createObj(MyObjectobj) { Scope lastScope = scopes.get(scopes.size() - 1); intcurCount = 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); }

  33. Classes: Static Type Check void checkClass(MyObjectobj, 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(MyObjectobj, Constructor cons) { symbolTable.startConstructor(cons); checkOOStatement(obj, cons.getBody()); symbolTable.endConstructor(cons); }

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

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

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

  37. Classes: Static Type Check Checksbinary, and theneachterm in the binary. SincemyX, myY are variables, itprocesses the Variables – whichfinds the instance variables, and assignsthem an address on the stackwhichisrecorded by the symbol table. private Type processOOVariableUse(MyObjectobj, Variable var) { Type type = symbolTable.assignOOAddress(obj, var); if (type == null) { logger.error(var.getLineNum(), VAR_UNDEFINED, var.getName()); return null; } return type; }

  38. Classes: Symbol Table public Type assignOOAddress(MyObjectobj, 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(); }

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

  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 instanceofObjFunction) { ObjFunction of = (ObjFunction) exp; return processOOFunction(of); }

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

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

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

  44. Classes: Interpreter Run Statement – if (s instanceofMyObject) { MyObjectobj = (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; }

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

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

  47. Classes: Object Function if (exp instanceofObjFunction) { 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

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

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

  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 }

More Related