CASLondonCPDDay February16 LittleManComputer AdditionalNotesonCompilerandInterpreters 1 UnderstandingCompilersandInterpreters 1.1 WhatweLearnfromAssemblyCode Learningaboutassemblycode,remindusthat: 1. Variablescorrespondtomemorylocations. 2. Thememoryofacomputercontainsbothdataandcode. 3. IfstatementsandloopsarecreatedbychangingtheProgramCounter. 1.2 Compilers Acompilerisatranslatorfromahighlevellanguagetotheassemblycodeofaparticular CPU.Acompiledprogramworkson • • theparticularCPUand OperatingSystem thatitwascompiledfor.Internally,thecompilerhasseveralstages: 1. Aparserchecksthatthesourcecodefollowsthesyntaxofthelanguage.Atreeis constructedrepresentingtheprogramcode.Atthisstage,syntaxerrorsare generated. 2. Thetypecheckerchecksthattheexpressionsintheprogramarecorrectlytyped andhowmuchspaceisneedforeachvariable.Atthisstage,theerrorsgenerated concernvariables(andothernames)thatarenotdeclaredandcodethatis incorrectlytypes. 3. Thecodegeneratorthentranslatestheprogramtoassemblycode.Compilers usuallyincludeanassemblersotheoutputisusuallyinbinary(callobjectcode) ratherthanassemblycode.Thetwomaintasksarei)decidingwhichregisterto use(as,unlikeLMC,modernCPUshavemanyregisters)andii)choosetheCPU instructions. Thefirsttwostepsaredeterminedbythelanguagebeingcompiled;thefinalstepis determinedbytheprocessorbeingtargeted.Moderncompilershaveamodular structure,whichfront-endsfordifferentsourcelanguagesandback-endsfordifferent CPUs.Inaddition,moderncompilersincludeoptimisersthatmakethegeneratedcode fasterwithoutchangingitsmeaning.Theseoptimiserstypicallyoperateonan intermediatelanguage,whichisusedforallsourcelanguagesandallCPUs. 1.3 Interpreter Aninterpreterissimplerthanacompiler.Itincludestheparserbutinsteadofthecode generator,theinterpretergoesthroughtheinternalrepresentationofthesourcecode (suchasanabstractsyntaxtree)and‘executes’thecodedirectly. Althoughinprincipleanylanguagecanbecompiledorinterpreted,languagesthatare usuallycompiledtendtobedynamicallytypedandscoped,whilecompiledlanguages arestaticallytypedandlexicallyscoped. Dynamicvstatictyping:indynamictyping,thetypeofavariabledependsonits useandmaychangeatdifferentpointsintheprogram.Sincethetypeisnotknow Page 1 of 4 CASLondonCPDDay February16 inadvance,theoperation(e.g.integerversusfloatingpointarithmetic)cannotbe determinedeither,whichisinconvenientforacompiler. Dynamicsscoping:scopingisaboutmatchingnamestovariables(ormemory locations).Inalexicallyscopedlanguage,suchasC,thecompilermatchesnames tovariables.InamoredynamiclanguagelikePython,namesare‘resolved’atrun timeandtheprocessdependsonthevariablesthatexistwhenareferencetoa nameisexecuted.Manylanguagesincludeaspectsofbothapproaches. 2 WritinganLMCInterpreter OnewaytounderstandhowaninterpreterworksistowriteonefortheLMC.(Note:an interpreterforaCPUisoftencalledanemulatororasimulator).Below,weoutlinehow anLMCinterpretercanbewritten.Hereisanexampleofapossiblesolutionbeingused. Load (L) Run(R) Stop(S) > R MAR = 0 MDR = 0 ACC = 0 PC = Program halted Load (L) Run(R) Stop(S) > L Location = 0 Enter value (or Location = 1 Enter value (or Location = 2 Enter value (or Location = 3 Enter value (or Location = 4 Enter value (or Location = 5 Enter value (or Location = 6 Enter value (or Load (L) Run(R) Stop(S) > R MAR = 0 MDR = 0 ACC = 0 PC = Press enter to continue MAR = 4 MDR = 11 ACC = 11 PC Press enter to continue MAR = 5 MDR = 17 ACC = 28 PC Press enter to continue MAR = 6 MDR = 28 ACC = 28 PC Program halted Load (L) Run(R) Stop(S) > 0 '.') '.') '.') '.') '.') '.') '.') 504 105 306 0 11 17 . 0 = 1 = 2 = 3 2.1 DesignSuggestions Herearesomefragmentsofsuchaprogramtoillustratetheidea: Representthestateofthesystem.TheLMCstateisitsregistersandmemory. acc = 0 mdr = 0 mar = 0 pc = 0 memory = [504,105,306, 0, 11, 17,...] Updatethestate:thismeansfollowingtherulesoftheCPU.IntheLMC,thewaythe datamovesbetweenregistersdependsontheopcode: def execute(memory, opcode, arg): global acc, mar, mdr, pc if opcode == ADD: mar = arg readMem(memory) acc = acc + mdr elif opcode == SUB: mar = arg readMem(memory) Page 2 of 4 CASLondonCPDDay February16 acc = acc - mdr elif opcode == STO: mar = arg mdr = acc writeMem(memory) elif opcode == LDA: mar = arg readMem(memory) acc = mdr elif opcode == BR: pc = opcode elif ... Someoftheadditionalfunctionsneededtocompletetheinterpreterareshownbelow: def readMem(memory): global mdr mdr = memory[mar] def writeMem(memory): memory[mar] = mdr def fetch(memory): global pc, mar mar = pc pc = pc + 1 readMem(memory) 2.2 JavaandVirtualMachine Manysystemscombineaspectsofbothcompilersandinterpreters.Anotableexampleis JavaandthesimilarapproachtakenbytheMicrosoft.netlanguagefamily. JavaisacompiledlanguagebutitisnotcompiledforrealCPUs.Instead,thecompiled codeisforaJavaVirtualMachine(JVM).AstherearenorealJVMCPUs,theyare emulated.Thisapproachhasmanyadvantages:forexample,onlyonecompiledversion ofaprogramisneededanditcanberunonanymachinewithanemulator,butitis muchfasterthanapureinterpreter. 3 Appendix1:LMCVersions LittleManComputerisawidelyusedsimulatorofa(verysimple)computer.Therearea numberofimplementations. 1. Anexcellentversioninjavascript: a. Availablefromhttp://peterhigginson.co.uk/LMC/ b. Ithasadequatedocumentationat http://peterhigginson.co.uk/LMC/help.html c. TheMDRisnotvisible. 2. AMSWindowsversion,requiring.NETandfunctionallythesameas1.Excellent ifyoucanrunit. a. Availablefromhttp://www.gcsecomputing.org.uk/lmc/lmc.html 3. Awebapplet,usingJava,withinstructionsandexamples(seehomepage)from YorkUniversityinCanada. a. Homepage:http://www.yorku.ca/sychen/research/LMC/ Page 3 of 4 CASLondonCPDDay February16 b. Webapplet:http://www.yorku.ca/sychen/research/LMC/LittleMan.html c. Theappletisgoodifitwillruninyourbrowser;Ifindthatonlyonedigit ofthememoryisdisplayed.Theword‘compile’isusedinsteadof assemble.Increasingincompatiblewithmodernbrowsers. 4. 5. 6. 7. AnotherJavaversionfromtheUniversityofMinnesota;alsoavailableasaweb applet: a. Seefromhttp://www.d.umn.edu/~gshute/cs3011/LMC.html b. Aminorissue:thisversiondoesnoshowtheMARandMDRregistersand doesnotsimulatetheseparatestagesofthefetch-executecycle. AversionfromDurhamUniversityforMacorWindows a. Seehttp://www.dur.ac.uk/m.j.r.bordewich/LMC.html b. Thisversioncallsthe‘assembler’a‘compiler’whichisunfortunate,butit isotherwisegood. Aspreadsheetversion a. http://www.ictcool.com/2011/12/16/download-lmc-simulation-v-1-5-2requires-microsoft-excel/ b. Thisversiondoesnotincludeanassembler:youcanenterthe3-digit codesinstead. Aflashversion a. AvailableasaCASresourcefrom http://community.computingatschool.org.uk/resources/1383 b. Thisversionismainlyusedfordemonstrationratherthanprogramming; thereisnoassembler.Thewebpageisuseful. ThereisalsoaninformativeWikipediapage http://en.wikipedia.org/wiki/Little_man_computer Appletversion Javaversion Enter program here Enter program here Importantnote:theappletusesthemnemonic'STA'whereastheJavaversionuses 'STO'forstoreaccumulator. Page 4 of 4