cs 360 programming languages interpretersinterpreter vs compiler vs combinations is about a...

73
CS 360 Programming Languages Interpreters

Upload: others

Post on 01-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

CS360ProgrammingLanguages

Interpreters

Page 2: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

ImplementingPLsMostofthecourseislearningfundamentalconceptsforusing andunderstanding PLs.

– Syntaxvs.semanticsvs.idioms.– Powerfulconstructslikeclosures,first-classobjects,iterators(streams),multithreading,…

Aneducatedcomputerscientistshouldalsoknowsomethingsaboutimplementing PLs.

– Implementingsomethingrequiresfullyunderstandingitssemantics.

– Thingslikeclosuresandobjectsarenot“magic.”– ManyprogrammingtasksarelikeimplementingsmallPLs.

• Example:"connect-the-dotsprogramminglanguage"from141.

Page 3: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

WaystoimplementalanguageTwofundamentalwaystoimplementaprogramminglanguageX.

• Writeaninterpreter inanotherlanguageY.– Betternames:evaluator,executor.– Immediatelyexecutestheinputprogramasit'sread.

• Writeacompiler inanotherlanguageY thatcompilestoathirdlanguageZ.– Bettername:translator– TakesaprograminX andproduceanequivalentprograminZ.

Page 4: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Firstprogramminglanguage?

Page 5: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Firstprogramminglanguage?

Page 6: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Interpretersvs compilers

• Interpreters– Takesone"statement"ofcodeatatimeandexecutesitinthelanguageoftheinterpreter.

– Likehavingahumaninterpreterwithyouinaforeigncountry.

• Compilers– TranslatecodeinlanguageXintocodeinlanguageZandsaveitforlater.(Typicallytoafileondisk.)

– Likehavingapersontranslateadocumentintoaforeignlanguageforyou.

Page 7: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Realityismorecomplicated

Evaluation(interpreter)andtranslation(compiler)areyouroptions.

– Butinmodernpracticewecanhavemultiplelayersofboth.

AexamplewithJava:– Javawasdesignedtobeplatformindependent.

• AnyprogramwritteninJavashouldbeabletorunonanycomputer.

– Achievedwiththe"JavaVirtualMachine."• Anidealizedcomputerforwhichpeoplehavewritteninterpretersthatrunon"real"computers.

Page 8: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Example:Java

• Javaprogramsarecompiledtoan"intermediaterepresentation"calledbytecode.– Thinkofbytecode asaninstructionsetfortheJVM.

• Bytecode istheninterpretedbya(software)interpreterinmachine-code.

• Complication:Bytecodeinterpretercancompilefrequently-usedfunctionstomachinecodeifitdesires (just-in-timecompilation).

• CPUitselfisaninterpreterformachinecode.

Page 9: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

SermonInterpretervscompilervscombinationsisaboutaparticularlanguageimplementation,notthelanguagedefinition.

Sothereisnosuchthingasa“compiledlanguage”oran“interpretedlanguage.”

– Programscannot“see”howtheimplementationworks.

Unfortunately,youhearthesephrasesallthetime:– “Cisfasterbecauseit’scompiledandLISPisinterpreted.”– IcanwriteaCinterpreteroraLISPcompiler,regardlessofwhatmostimplementationshappentodo.

Page 10: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

OnecomplicationInatraditionalimplementationviacompiler,youdonotneedthelanguageimplementation(thecompiler)toruntheprogram.

– Onlytocompileit.– Toletotherpeoplerunyourprogram,yougivethemthecompiledbinarycode.

ButRacket,Scheme,LISP,Javascript,Ruby,…haveeval– Allowsaprogram,whileitisrunning,tocreateastring(orinRacket,alist)witharbitrarycodeandexecuteit.

– Sincewedon’tknowaheadoftimewhatthecodewillbe,weneedalanguageimplementationatrun-timetosupporteval

– Usuallyyouseethisinlanguagesthataretraditionallyinterpreted,becausethenimplementingeval iseasy:theinterpreterisalreadyavailable.

Page 11: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

eval /apply• ThesefunctionsarebuiltintoRacket,andareatraditionalpartofLISP/Schemeimplementations.

• eval:takesalistargumentandtreatsitlikeprogramcode,executingitandreturningtheresult.

• apply:takesafunctionandalist,andcallsthefunctionontheargumentsinthelist.

Page 12: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

quote• Alsobuilt-in,butwedon'tnoticeitbecauseit'scalledautomaticallywheneverweuseasinglequote.

• (quote …) or'(…) isaspecialformthatmakes“everythingunderneath”intoplainsymbolsandlists,insteadofinterpretingthemasvariablesorfunctioncalls.

• eval andquote areinverses:– quote stopsevaluationofsomething.– eval forcesevaluationofsomething.

Page 13: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Backtoimplementingalanguage"(cons 1 '(2 3))"

ParsingCall

Function Integer

Constant

1

cons

Staticchecking(whatischeckeddependsonPL)

PossibleErrors/warnings

Restofimplementation

PossibleErrors/warnings

List

Constant Constant

2 3

Page 14: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

SkippingthosestepsLISP/Scheme-likelanguageshaveaninterestingproperty:

– Theformatinwhichwewriteatheprogramcode(alist)isidenticaltothemaindatastructurethelanguageitselfusestorepresentdata(alist).

– Becausetheselistsarealwaysfullyparenthesized,wegetparsingessentiallyforfree!

– NotsoinPython,C++,Java,etc.

Wecanalso,forsimplicity,skipstaticchecking.– Assumesubexpressionshavecorrecttypes.

• Wewillnotworryabout(add #f "hi").– Interpreterwilljustcrash.

Page 15: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Write(Mini-)RacketinRacket

Page 16: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-Racket

• Onlyonedatatype:numbers.– Nobooleans,lists,etc.

• Mini-Racketwillusenames forallfunctionsratherthansymbols.– add,sub,mul,etc.

• Simplifiedmechanismsforconditionals,functiondefinitions,andfunctioncalls.

Page 17: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Heartoftheinterpreter

• mini-eval:Evaluatesanexpressionandreturnsavalue(willcallmini-apply tohandlefunctions)

• mini-apply:Takesafunctionandargumentvaluesandevaluateitsbody(callsmini-eval).

Page 18: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(define (mini-eval expr env)is this a ______ expression?if so, then call our special handler

for that type of expression.)What kind of expressions will we have?• numbers• variables (symbols)• math function calls• others as we need them

Page 19: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

• Howdoweevaluatea(literal)number?– Thatis,whentheinterpreterseesanumber,whatvalueshoulditreturn?

• Justreturnit!

• Psuedocode forfirstlineofmini-eval:– Ifthisexpressionisanumber,thenreturnit.

Page 20: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

• Howdowehandle(add 3 4)?

• Needtwofunctions:– Onetodetectthatanexpressionisanadditionexpression.

– Onetoevaluatetheexpression.

Page 21: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(add 3 4)

• Isthisanexpressionanadditionexpression?(equal? 'add (car expr))

• Evaluateanadditionexpression:(+ (cadr expr) (caddr expr))

Page 22: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Youtry(lab,part1)

• Addsubtraction(e.g.,sub)• Addmultiplication(mul)• Adddivision(div)• Addexponentiation(exp)• Optional:

– Addotherprimitives,likesqrt,abs,etc.– Makesubworkwithsinglearguments(returnsthenegation).

Page 23: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(add3(add45))

• Whydoesn'tthiswork?

Page 24: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(add3(add45))

• Howshould ourlanguageevaluatethissortofexpression?

• Wecouldforbidthiskindofexpression.– Insistthingstobeaddedalwaysbenumbers.

• Or,wecouldallowthethingstobeaddedtobeexpressionsthemselves.– Needarecursivecalltomini-eval insideeval-add.

Page 25: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Youtry(lab,part2)

• Fixyourmathcommandssothattheywillrecursivelyevaluatetheirarguments.

Page 26: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

AddingVariables

Page 27: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingvariables

• Representaframe asahashtable.• Racket'shashtables:(define ht (make-hash))(hash-set! ht key value)(hash-has-key? ht key)(hash-ref ht key)

Page 28: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingvariables

• Representanenvironmentasalistofframes.

globalx 2y 3

f .

x 7y 1

hashtablex: 7y: 1

hashtablex: 2y: 3

Page 29: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingvariables

• Twothingswecandowithavariableinourprogramminglanguage:– Defineavariable– Getthevalueofavariable

• PrettymuchthesametwothingswecandowithavariableinregularRacket(exceptforset!)

Page 30: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Gettingthevalueofavariable

• Newtypeofexpression:asymbol.• Whenevermini-eval seesasymbol,itshouldlookupthevalueofthevariablecorrespondingtothatsymbol.

Page 31: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

GettingthevalueofavariableFollowtherulesoflexicalscoping:

(define (lookup-variable-value var env); Pseudocode:; If our current frame has a value for the; variable, then get its value and return it.; Otherwise, if our current frame has a frame; pointer, then follow it and try the lookup; there.; Otherwise, (if we are out of frames), throw an; error.

Page 32: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

GettingthevalueofavariableFollowtherulesoflexicalscoping:

(define (lookup-variable-value var env)(cond ((hash-has-key? (car env) var)

(hash-ref (car env) var))((not (null? env))

(lookup-variable-value var (cdr env)))((null? env)

(error "unbound variable" var))))

Page 33: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Definingavariable(lab,part3)

• mini-eval needstohandleexpressionsthatlooklike(define variable expr)– expr cancontainsub-expressions.

• Addtwofunctionstotheevaluator:– definition?:testsifanexpressionfitstheformofadefinition.

– eval-definition:extractthevariable,recursivelyevaluatetheexpressionthatholdsthevalue,andaddabindingtothecurrentframe.

Page 34: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingconditionals

• WewillhaveoneconditionalinMini-Racket:ifzero

• Syntax:(ifzero expr1 expr2 expr3)• Semantics:

– Evaluateexpr1,testifit'sequaltozero.– Ifyes,evaluateandreturnexpr2.– Ifno,evaluateandreturnexpr3.

Page 35: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingconditionals(lab,part4)

• Addfunctionsifzero? andeval-ifzero.

• Iftime,trychallengesonthebackofthelab.

Page 36: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

• Designingourinterpreteraroundmini-eval.

• (define (mini-eval expr env) …• Determineswhattypeofexpressionexpr is• Dispatchtheevaluationoftheexpressiontotheappropriatefunction– number? ->evaluateinplace– symbol? ->lookup-variable-value– add?/subtract?/multiply? ->appropriatemathfunc

– definition? ->eval-define– ifzero? ->eval-ifzero

Page 37: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Today

• Twomorepiecestoadd:– Closures(lambda? /eval-lambda)– Functioncalls(call? /eval-call)

Page 38: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-RacketwillhavesomesimplificationsfromnormalRacket.

• Allfunctionswillhaveexactlyoneargument.• Removestheneedforlambdaexpressionstohaveparentheses.

• NormalRacket:(lambda (x) (+ x 1))

• Mini-Racket:(lambda x (add x 1))

Page 39: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-RacketwillhavesomesimplificationsfromnormalRacket.

• NormalRackethastwoversionsofdefine,oneforvariablesandoneforfunctions:(define x 3)(define (add1 x) (+ x 1)).

• The2nd versionisjustashortcutfor(define add1 (lambda (x) (+ x 1))

Page 40: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-RacketwillhavesomesimplificationsfromnormalRacket.

• Mini-Racketwillnothavethe"shortcut"define;wemustuseanexplicitlambda.

• NormalRacket:(define (add1 x) (+ x 1)) (define add1 (lambda (x) (+ x 1)))

• Mini-Racket:(define add1 (lambda x (add x 1))

Page 41: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-RacketwillhavesomesimplificationsfromnormalRacket.

• NormalRacketrecognizesafunctioncallasanylistthatstartswithafunctionname(oranythingthatevaluatestoaclosure).

• Mini-Racketwillrecognizefunctioncallsasliststhatstartswiththesymbolcall.– ThismakestheMini-Racketsyntaxmorecomplicated,butsimplifiestheinterpretercode.

Page 42: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-RacketwillhavesomesimplificationsfromnormalRacket.

• NormalRacket:(add1 5)

• Mini-Racket:(call add1 5)

Page 43: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Implementingclosures

• InMini-Racket,all(user-defined)functionsandclosureswillhaveasingleargument.

• Syntax:(lambda var expr)– Notethedifferentsyntaxfrom"real"Racket.

• Semantics:Createsanewclosure(anonymousfunction)ofthesingleargumentvar,whosebodyisexpr.

Page 44: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(lambda var expr)

• Needanewdatastructuretorepresentaclosure.

• Whycan'twejustrepresentthemasthelist(lambdavar closure)above?– Hint:Whatismissing?Thinkofenvironmentdiagrams.

Page 45: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(lambda var expr)

• WewillrepresentclosuresinternallyinMini-Racketusingalistoffourcomponents:– Thesymbol'closure– Theargumentvariable(var)– Thebody(expr)– Theenvironmentinwhichthisclosurewasdefined.

Page 46: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Evaluateattoplevel:(lambda x (add x 1))

Ourevaluatorshouldreturn'(closure x (add x 1) (#hash(…)))

Arg:xCode:(addx1)

global

Page 47: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Writelambda? andeval-lambda

• lambda? iseasy.• eval-lambda should:

– Extractthevariablenameandthebody,butdon’tevaluatethebody (notuntilwecallthefunction)

– Returnalistofthesymbol'closure,thevariable,thebody,andthecurrentenvironment.

Page 48: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

(define (eval-lambda expr env) (list 'closure

(cadr expr) ; the variable(caddr expr) ; the bodyenv))

Page 49: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Functioncalls

• Firstweneedtheotherhalfoftheeval/apply paradigm.

Page 50: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

• Rememberfromenvironmentdiagrams:

• Toevaluateafunctioncall,makeanewframewiththefunction'sargumentsboundtotheirvalues,thenrunthebodyofthefunctionusingthenewenvironmentforvariablelookups.

Page 51: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-Apply

(define (mini-apply closure argval)

Pseudocode:• Makeanewframemappingtheclosure'sargument(i.e.,

thevariablename)toargval.• Makeanewenvironmentconsistingofthenewframe

pointingtotheclosure'senvironment.• Evaluatetheclosure'sbodyinthenewenvironment(and

returntheresult).

Page 52: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-Apply

(define (mini-apply closure argval)(let ((new-frame (make-hash)))(hash-set! new-frame <arg-name> argval)(let ((new-env

<construct new environment>))<eval body of closure in new-env>

)))

Page 53: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Mini-Apply

(define (mini-apply closure argval)(let ((new-frame (make-hash)))(hash-set! new-frame (cadr closure) argval)(let ((new-env

(cons new-frame (cadddr closure))))(mini-eval (caddr closure) new-env))))

Page 54: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Functioncalls

• Syntax:(call expr1 expr2)• Semantics:

– Evaluateexpr1 (mustevaluatetoaclosure)– Evaluateexpr2 toavalue(theargumentvalue)– Applyclosuretovalue(andreturnresult)

Page 55: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Youtryit

• Writecall? (easy)• Writeeval-call (alittleharder)

– Evaluateexpr1 (mustevaluatetoaclosure)– Evaluateexpr2 toavalue(theargumentvalue)– Applyclosuretovalue(andreturnresult)

• Whendone,younowhaveaTuring-completelanguage!

Page 56: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

; expr looks like; (call expr1 expr2)(define (eval-call expr env)

(mini-apply <eval the function><eval the argument>)

Page 57: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

; expr looks like; (call expr1 expr2)(define (eval-call expr env)

(mini-apply (mini-eval (cadr expr) env)(mini-eval (caddr expr) env)))

Page 58: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Magicinhigher-orderfunctionsThe“magic”:Howisthe“rightenvironment”aroundforlexicalscopewhenfunctionsmayreturnotherfunctions,storethemindatastructures,etc.?

Lackofmagic:Theinterpreterusesaclosuredatastructuretokeeptheenvironmentitwillneedtouselater

Page 59: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Isthisexpensive?

• Time tobuildaclosureistiny:makealistwithfouritems.

• Space tostoreclosuresmight belargeifenvironmentislarge.

Page 60: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Interpretersteps

• Parser– Takescodeandproducesanintermediaterepresentation(IR),e.g.,abstractsyntaxtree.

• Staticchecking– Typicallyincludessyntacticalanalysisandtypechecking.

• InterpreterdirectlyrunscodeintheIR.

Page 61: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Compilersteps

• Parser• Staticchecking• Codeoptimizer

– TakeASTandalterittomakethecodeexecutefaster.

• Codegenerator– Producecodeinoutputlanguage(andsaveit,asopposedtorunningit).

Page 62: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Codeoptimization

// Test if n is primeboolean isPrime(int n) {for (int x = 2; x < sqrt(n); x++) {if (n % x == 0) return false;

}return true;}

Page 63: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Codeoptimization

// Test if n is primeboolean isPrime(int n) {double temp = sqrt(n);for (int x = 2; x < temp; x++) {if (n % x == 0) return false;

}return true;}

Page 64: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Commoncodeoptimizations

• Replacingconstantexpressionswiththeirevaluations.

• Ex:Gamethatdisplaysan8by8grid.Eachcellwillbe50pixelsby50pixelsonthescreen.– int CELL_WIDTH = 50;– int BOARD_WIDTH = 8 * CELL_WIDTH;

Page 65: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Commoncodeoptimizations

• Replacingconstantexpressionswiththeirevaluations.

• Ex:Gamethatdisplaysan8by8grid.Eachcellwillbe50pixelsby50pixelsonthescreen.– int CELL_WIDTH = 50;– int BOARD_WIDTH = 400;

• Referencestothesevariableswouldprobablyreplacedwithconstantsaswell.

Page 66: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Commoncodeoptimizations

• Reorderingcodetoimprovecacheperformance.for (int x = 0; x < HUGE_NUMBER; x++) {huge_array[x] = f(x)another_huge_array[x] = g(x)

}

Page 67: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Commoncodeoptimizations

• Reorderingcodetoimprovecacheperformance.for (int x = 0; x < HUGE_NUMBER; x++) {huge_array[x] = f(x)

}for (int x = 0; x < HUGE_NUMBER; x++) {another_huge_array[x] = g(x)

}

Page 68: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Commoncodeoptimizations

• Loops:unrolling,combining/distribution,changenesting

• Findingcommonsubexpressions andreplacingwithareferencetoatemporaryvariable.– (a + b)/4 + (a + b)/3

• Recursion:replacewithiterationifpossible.– That'swhattail-recursionoptimizationdoes!

Page 69: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

• Whydon'tinterpretersdotheseoptimizations?

• Usually,there'snotenoughtime.– WeneedthecodetorunNOW!– Sometimes,canoptimizealittle(e.g.,tail-recursion).

Page 70: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Codegeneration

• Lastphaseofcompilation.• Choosewhatoperationstouseintheoutputlanguageandwhatordertoputthemin(instructionselection,instructionscheduling).

• Ifoutputinalow-levellanguage:– Pickwhatvariablesarestoredinwhichregisters(registerallocation).

– Includedebuggingcode?(store"true"function/variablenamesandlinenumbers?)

Page 71: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Java

• Usesbothinterpretationandcompilation!• Step1:CompileJavasourcetobytecode.

– Bytecode is"machinecode"foramade-upcomputer,theJavaVirtualMachine(JVM).

• Step2:Aninterpreterinterpretsthebytecode.

• Historically,thebytecode interpretermadeJavacodeexecuteveryslowly(1990s).

Page 72: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

Just-in-timecompilation

• Bytecode interpretershistoricallywouldtranslateeachbytecode commandintomachinecodeandimmediatelyexecuteit.

• Ajust-in-timecompilerhastwooptimizations:– Cachesbytecode ->machinecodetranslationssoitcanre-usethemlater.

– Dynamicallycompilessectionsofbytecode intomachinecode"whenitthinksitshould."

Page 73: CS 360 Programming Languages InterpretersInterpreter vs compiler vs combinations is about a particular language implementation, not the language definition. So there is no such thing

JIT:aclassictrade-off

• Startupisslightlyslower– Needtimetodosomeinitialdynamiccompilation.

• Oncetheprogramstarts,itrunsfasterthanaregularinterpreter.– Becausesomesectionsarenowcompiled.