CS345 Project Presentation

Size: px
Start display at page:

Download "CS345 Project Presentation"

Transcription

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 FunctionConstructor {rettype Identifier Function MyObject: Identifier Identifier = create Identifier callargs Constructor: Identifier ([{ Parameter ]) block Declaration : Type Identifier [ [Literal] ]{, Identifier [ [ Literal ] ] Type : int bool float list tuple object string void Statements : { Statement Statement : ; Declaration Block ForEach Assignment IfStatement WhileStatement CallStatement ReturnStatement Block : { Statements ForEach: for( Expression < Expression ) Block Assignment : Identifier [ [ Expression ] ]= Expression ; Parameter : Type Identifier IfStatement: if ( Expression ) Block [elseifstatement Block ] WhileStatement: while (Expression )Block

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 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) 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 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 FunctionConstructor {rettypeidentifier Function Constructor: Identifier ([{ Parameter ]) block BNF for creating an instance of a class MyObject: Identifier Identifier = create Identifier callargs BNF for calling the class s function ObjFunction: Identifier. Identifier. Identifier callargs

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

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

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

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

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

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 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 instanceof ObjFunction) 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 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;

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

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

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

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;

52 Questions

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

High Level Languages. Java (Object Oriented) This Course. Jython in Java. Relation. ASP RDF (Horn Clause Deduction, Semantic Web) Dr. 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 1 Dr. Philip Cannata 2 Programming Languages Lexical

More information

Programming Languages

Programming Languages Programming Languages Chapter 19 - Continuations Dr. Philip Cannata 1 Exceptions (define (f n) (let/cc esc (/ 1 (if (zero? n) (esc 1) n)))) > (f 0) 1 > (f 2) 1/2 > (f 1) 1 > Dr. Philip Cannata 2 Exceptions

More information

CS2 Current Technologies Note 1 CS2Bh

CS2 Current Technologies Note 1 CS2Bh CS2 Current Technologies Note 1 Relational Database Systems Introduction When we wish to extract information from a database, we communicate with the Database Management System (DBMS) using a query language

More information

Real-World Performance Training SQL Introduction

Real-World Performance Training SQL Introduction Real-World Performance Training SQL Introduction Real-World Performance Team Basics SQL Structured Query Language Declarative You express what you want to do, not how to do it Despite the name, provides

More information

CS2 Current Technologies Lecture 2: SQL Programming Basics

CS2 Current Technologies Lecture 2: SQL Programming Basics T E H U N I V E R S I T Y O H F R G E D I N B U CS2 Current Technologies Lecture 2: SQL Programming Basics Dr Chris Walton (cdw@dcs.ed.ac.uk) 4 February 2002 The SQL Language 1 Structured Query Language

More information

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries T E H U N I V E R S I T Y O H F R G E D I N B U CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries Chris Walton (cdw@dcs.ed.ac.uk) 11 February 2002 Multiple Tables 1 Redundancy requires excess

More information

King Fahd University of Petroleum and Minerals

King Fahd University of Petroleum and Minerals 1 King Fahd University of Petroleum and Minerals Information and Computer Science Department ICS 334: Database Systems Semester 041 Major Exam 1 18% ID: Name: Section: Grades Section Max Scored A 5 B 25

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Syntax Intro and Overview. Syntax

Syntax Intro and Overview. Syntax Syntax Intro and Overview CS331 Syntax Syntax defines what is grammatically valid in a programming language Set of grammatical rules E.g. in English, a sentence cannot begin with a period Must be formal

More information

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

Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University 1 Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University Lecture 3 Part A CIS 311 Introduction to Management Information Systems (Spring 2017)

More information

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

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) ) CS 345 Spring 2010 Midterm Exam Name EID 1. [4 Points] Circle the binding instances in the following expression: (calc (parse '+ with x + 5 5 with y - x 3 + y y z ) ) 2. [7 Points] Using the following

More information

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

Part III. Data Modelling. Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1 Part III Data Modelling Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1 Outline of this part (I) 1 Introduction to the Relational Model and SQL Relational Tables Simple Constraints

More information

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

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information

Programming Languages. Dr. Philip Cannata 1

Programming Languages. Dr. Philip Cannata 1 Programming Languages Dr. Philip Cannata 0 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata Dr. Philip Cannata

More information

Programming Languages. Dr. Philip Cannata 1

Programming Languages. Dr. Philip Cannata 1 Programming Languages Dr. Philip Cannata 0 High Level Languages This Course Jython in Java Java (Object Oriented) ACL (Propositional Induction) Relation Algorithmic Information Theory (Information Compression

More information

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

Database Management System. * First install Mysql Database or Wamp Server which contains Mysql Databse. Database Management System * First install Mysql Database or Wamp Server which contains Mysql Databse. * Installation steps are provided in pdf named Installation Steps of MySQL.pdf or WAMP Server.pdf

More information

Informatics Practices (065) Sample Question Paper 1 Section A

Informatics Practices (065) Sample Question Paper 1 Section A Informatics Practices (065) Sample Question Paper 1 Note 1. This question paper is divided into sections. Section A consists 30 marks. 3. Section B and Section C are of 0 marks each. Answer the questions

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,

More information

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

Name SOLUTIONS EID NOTICE: CHEATING ON THE MIDTERM WILL RESULT IN AN F FOR THE COURSE. CS 345 Fall TTh 2012 Midterm Exam B Name SOLUTIONS EID NOTICE: CHEATING ON THE MIDTERM WILL RESULT IN AN F FOR THE COURSE. 1. [5 Points] Give two of the following three definitions. [2 points extra credit

More information

Pivot Tables Motivation (1)

Pivot Tables Motivation (1) Pivot Tables The Pivot relational operator (available in some SQL platforms/servers) allows us to write cross-tabulation queries from tuples in tabular layout. It takes data in separate rows, aggregates

More information

Mid-Term 2 Grades

Mid-Term 2 Grades Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

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

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

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

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields

More information

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

Building lexical and syntactic analyzers. Chapter 3. Syntactic sugar causes cancer of the semicolon. A. Perlis. Chomsky Hierarchy Building lexical and syntactic analyzers Chapter 3 Syntactic sugar causes cancer of the semicolon. A. Perlis Chomsky Hierarchy Four classes of grammars, from simplest to most complex: Regular grammar What

More information

Reminder About Functions

Reminder About Functions Reminder About Functions (let ((z 17)) (let ((z 3) (a ) (x (lambda (x y) (- x (+ y z))))) (let ((z 0) (a )) (x z a)))) int h, i; void B(int w) { int j, k; i = 2*w; w = w+1; void A(int x, int y) { bool

More information

Introduction. Introduction to Oracle: SQL and PL/SQL

Introduction. Introduction to Oracle: SQL and PL/SQL Introduction Introduction to Oracle: SQL and PL/SQL 1 Objectives After completing this lesson, you should be able to do the following: Discuss the theoretical and physical aspects of a relational database

More information

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

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II) Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

More information

CS 536 Midterm Exam Spring 2013

CS 536 Midterm Exam Spring 2013 CS 536 Midterm Exam Spring 2013 ID: Exam Instructions: Write your student ID (not your name) in the space provided at the top of each page of the exam. Write all your answers on the exam itself. Feel free

More information

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

CSE P 501 Compilers. Static Semantics Hal Perkins Winter /22/ Hal Perkins & UW CSE I-1 CSE P 501 Compilers Static Semantics Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Attribute grammars Representing types Symbol tables Note: this covers

More information

Notes on Chapter Three

Notes on Chapter Three Notes on Chapter Three Methods 1. A Method is a named block of code that can be executed by using the method name. When the code in the method has completed it will return to the place it was called in

More information

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

CS Reading Packet: Views, and Simple Reports - Part 1 CS 325 - Reading Packet: "Views, and Simple Reports - Part 1" p. 1 Sources: CS 325 - Reading Packet: "Views, and Simple Reports - Part 1" * Oracle9i Programming: A Primer, Rajshekhar Sunderraman, Addison

More information

CS Programming I: Arrays

CS Programming I: Arrays CS 200 - Programming I: Arrays Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Array Basics

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

CS Reading Packet: "Writing relational operations using SQL"

CS Reading Packet: Writing relational operations using SQL CS 325 - Reading Packet: "Writing relational operations using SQL" p. 1 CS 325 - Reading Packet: "Writing relational operations using SQL" Sources: Oracle9i Programming: A Primer, Rajshekhar Sunderraman,

More information

Midterm Exam CS 251, Intermediate Programming March 6, 2015

Midterm Exam CS 251, Intermediate Programming March 6, 2015 Midterm Exam CS 251, Intermediate Programming March 6, 2015 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Compilers CS S-10 Object Oriented Extensions

Compilers CS S-10 Object Oriented Extensions Compilers CS414-2003S-10 Object Oriented Extensions David Galles Department of Computer Science University of San Francisco 10-0: Classes simplejava classes are equivalent to C structs class myclass {

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Midterm Exam CS 251, Intermediate Programming October 8, 2014

Midterm Exam CS 251, Intermediate Programming October 8, 2014 Midterm Exam CS 251, Intermediate Programming October 8, 2014 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

CSE 340 Fall 2014 Project 4

CSE 340 Fall 2014 Project 4 CSE 340 Fall 2014 Project 4 Due on Dec. 5, 2014 by 11:59 pm Abstract The goal of this project is to give you some hands-on experience with implementing a compiler. You will write a compiler for a simple

More information

The role of semantic analysis in a compiler

The role of semantic analysis in a compiler Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Lecture 20 Sections Wed, Apr 1, 2009

Lecture 20 Sections Wed, Apr 1, 2009 s Return End Call s Lecture 20 Sections 7.1-7.5 Hampden-Sydney College Wed, Apr 1, 2009 Outline s Return 1 s Return End End Call s 2 Call s 3 s Return End Call s To write the assembly code for the beginning

More information

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

RDBMS Using Oracle. BIT-4 Lecture Week 3. Lecture Overview RDBMS Using Oracle BIT-4 Lecture Week 3 Lecture Overview Creating Tables, Valid and Invalid table names Copying data between tables Character and Varchar2 DataType Size Define Variables in SQL NVL and

More information

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

Parsing Scheme (+ (* 2 3) 1) * 1 Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

More information

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

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages

More information

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

Relation Overriding. Syntax and Semantics. Simple Semantic Domains. Operational Semantics SE3E03, 2006 1.59 61 Syntax and Semantics Syntax Shape of PL constructs What are the tokens of the language? Lexical syntax, word level How are programs built from tokens? Mostly use Context-Free Grammars

More information

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

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

Last Time. What do we want? When do we want it? An AST. Now! Java CUP 1 Last Time What do we want? An AST When do we want it? Now! 2 This Time A little review of ASTs The philosophy and use of a Parser Generator 3 Translating Lists CFG IdList -> id IdList comma

More information

Compilers CS S-05 Semantic Analysis

Compilers CS S-05 Semantic Analysis Compilers CS414-2003S-05 Semantic Analysis David Galles Department of Computer Science University of San Francisco 05-0: Syntax Errors/Semantic Errors A program has syntax errors if it cannot be generated

More information

Functions and Recursion. Dr. Philip Cannata 1

Functions and Recursion. Dr. Philip Cannata 1 Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

SMURF Language Reference Manual Serial MUsic Represented as Functions

SMURF Language Reference Manual Serial MUsic Represented as Functions SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu

More information

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Lecture 9. February 7, 2018 Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

More information

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

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

C++ 8. Constructors and Destructors

C++ 8. Constructors and Destructors 8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

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

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

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

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object Review: Diagrams for Inheritance - String makemodel - int mileage + (String, int) Class #3: Inheritance & Polymorphism Software Design II (CS 220): M. Allen, 25 Jan. 18 + (String, int) + void

More information

Intermediate Representations

Intermediate Representations Intermediate Representations A variety of intermediate representations are used in compilers Most common intermediate representations are: Abstract Syntax Tree Directed Acyclic Graph (DAG) Three-Address

More information

JAVA WRAPPER CLASSES

JAVA WRAPPER CLASSES JAVA WRAPPER CLASSES Description Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

CS 415 Midterm Exam Spring 2002

CS 415 Midterm Exam Spring 2002 CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming

More information

Project 1: Scheme Pretty-Printer

Project 1: Scheme Pretty-Printer Project 1: Scheme Pretty-Printer CSC 4101, Fall 2017 Due: 7 October 2017 For this programming assignment, you will implement a pretty-printer for a subset of Scheme in either C++ or Java. The code should

More information

FUNCTIONAL AND LOGIC PROGRAMS

FUNCTIONAL AND LOGIC PROGRAMS FUNCTIONAL AND LOGIC PROGRAMS Contents Language Specific Compilation Context Handling Identification Scope Overloading Imported Scope Type Checking Type table Type equivalence Coercions Casts and conversions

More information

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

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating 1 ecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating records for arrays o Short-circuiting Or o If statement

More information

CSE 401 Midterm Exam Sample Solution 11/4/11

CSE 401 Midterm Exam Sample Solution 11/4/11 Question 1. (12 points, 2 each) The front end of a compiler consists of three parts: scanner, parser, and (static) semantics. Collectively these need to analyze the input program and decide if it is correctly

More information

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

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation? Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated

More information

CA4003 Compiler Construction Assignment Language Definition

CA4003 Compiler Construction Assignment Language Definition CA4003 Compiler Construction Assignment Language Definition David Sinclair 2017-2018 1 Overview The language is not case sensitive. A nonterminal, X, is represented by enclosing it in angle brackets, e.g.

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

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

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException VERSION A CSC 1351: Final Name: 1 Interfaces, Classes and Inheritance 2 Basic Data Types (arrays, lists, stacks, queues, trees,...) 2.1 Does the following code compile? If it does not, how can it be fixed?

More information

GOLD Language Reference Manual

GOLD Language Reference Manual GOLD Language Reference Manual Language Guru: Timothy E. Chung (tec2123) System Architect: Aidan Rivera (ar3441) Manager: Zeke Reyna (eer2138) Tester: Dennis Guzman (drg2156) October 16th, 2017 1 Introduction

More information

CS453 CLASSES, VARIABLES, ASSIGNMENTS

CS453 CLASSES, VARIABLES, ASSIGNMENTS CS453 CLASSES, VARIABLES, ASSIGNMENTS CS453 Lecture Code Generation for Classes 1 PA6 new in MeggyJava member / instance variables local variables assignments let s go check out the new MeggyJava grammar

More information

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

C:\Temp\Templates. Download This PDF From The Web Site 11 2 2 2 3 3 3 C:\Temp\Templates Download This PDF From The Web Site 4 5 Use This Main Program Copy-Paste Code From The Next Slide? Compile Program 6 Copy/Paste Main # include "Utilities.hpp" # include

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

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

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang Object Oriented Programming and Design in Java Session 2 Instructor: Bert Huang Announcements TA: Yipeng Huang, yh2315, Mon 4-6 OH on MICE clarification Next Monday's class canceled for Distinguished Lecture:

More information

CIT 3136 Lecture 7. Top-Down Parsing

CIT 3136 Lecture 7. Top-Down Parsing CIT 3136 Lecture 7 Top-Down Parsing Chapter 4: Top-down Parsing A top-down parsing algorithm parses an input string of tokens by tracing out the steps in a leftmost derivation. Such an algorithm is called

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must

More information

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

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

More information

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

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

More information

Special Member Functions

Special Member Functions CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) U Waterloo CS247 (Spring 2017)

More information

Compiler II: Code Generation Human Thought

Compiler II: Code Generation Human Thought Course map Compiler II: Code Generation Human Thought Abstract design Chapters 9, 12 abstract interface H.L. Language & Operating Sys. Compiler Chapters 1-11 abstract interface Virtual Machine Software

More information

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

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false Test 1 Multiple Choice. Write your answer to the LEFT of each problem. 4 points each 1. Which celebrity has not received an ACM Turing Award? A. Alan Kay B. John McCarthy C. Dennis Ritchie D. Bjarne Stroustrup

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

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

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134) GaE Graphs Ain t Easy Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134) Introduction Graphs Complex data structure Ubiquitous and fundamental Goal: We want to provide the end user a streamlined

More information

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

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions Special Member Functions CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) C++

More information