You are on page 1of 13

CS143 Summer2012

DecafSpecification

Handout03 June27,2012

WrittenbyJulieZelenskiandupdatedbyJerryCainandKeithSchwarz.

Inthiscourse,wewillwriteacompilerforasimpleobjectorientedprogramming languagecalledDecaf.Decafisastronglytyped,objectorientedlanguagewithsupport forinheritanceandencapsulation.Bydesign,ithasmanysimilaritieswithC/C++/Java, soyoushouldfinditfairlyeasytopickup.Keepinminditisnotanexactmatchtoany ofthoselanguages.Thefeaturesethasbeentrimmeddownandsimplifiedtokeepthe programmingprojectsmanageable.Evenso,you'llstillfindthelanguageexpressive enoughtobuildallsortsofniftyobjectorientedprograms. Thisdocumentisdesignedtogivethespecificationforthelanguagesyntaxand semantics,whichyouwillneedtorefertowhenimplementingthecourseprojects. LexicalConsiderations Thefollowingarekeywords.Theyareallreserved,whichmeanstheycannotbeusedas identifiersorredefined.
void int double bool string class interface null this extends implements for while if else return break new NewArray Print ReadInteger ReadLine

Anidentifierisasequenceofletters,digits,andunderscores,startingwithaletter. Decafiscasesensitive,e.g.,ifisakeyword,butIFisanidentifier;binkyandBinkyare twodistinctidentifiers.Identifierscanbeatmost31characterslong. Whitespace(i.e.spaces,tabs,andcarriagereturns)servestoseparatetokens,butis otherwiseignored.Keywordsandidentifiersmustbeseparatedbywhitespaceora tokenthatisneitherakeywordnoranidentifier.Thatis,ifintthisisasingleidentifier ratherthanthreekeywords,butif(23thisscansasfourtokens. ABooleanconstantiseithertrueorfalse.Likekeywords,thesewordsarereserved. Anintegerconstantcaneitherbespecifiedindecimal(base10)orhexadecimal(base16). Adecimalintegerisasequenceofdecimaldigits.Ahexadecimalintegermustbegin with0Xor0x(thatisazero,nottheletteroh)andisfollowedbyasequenceof hexadecimaldigits.Hexadecimaldigitsincludethedecimaldigitsandtheletters a throughf(eitherupperorlowercase).Forexample,thefollowingarevalidintegers:
8,012,0x0, 0X12aE.

Adoubleconstantisasequenceofdecimaldigits,aperiod,followedbyanysequenceof digits(maybenone).Thus,.12isnotvalid,butboth0.12and12.are.Adoublecan alsohaveanoptionalexponent,e.g.,12.2E+2.Foradoubleinthissortofscientific notation,thedecimalpointisrequired,thesignoftheexponentisoptional(ifnot specified,+isassumed),andtheEcanbeloweroruppercase.Asabove,.12E+2is invalid,but12.E+2isvalid.Leadingzerosonthemantissaandexponentareallowed. Astringconstantisasequenceofcharactersenclosedindoublequotes.Stringscan containanycharacterexceptanewlineordoublequote.Astringmuststartandendon asingleline;itcannotbesplitovermultiplelines:


"this string is missing its close quote this is not a part of the string above

Operatorsandpunctuationcharactersusedbythelanguageincludes:
+ - * / % < <= > >= = == != && || ! ; , . [] [ ] ( ) { }

Asinglelinecommentisstartedby//andextendstotheendoftheline.Cstyle commentsstartwith/*andendwiththefirstsubsequent*/.Anysymbolisallowedin acommentexceptthesequence*/whichendsthecurrentcomment.Cstylecomments donotnest. DecafGrammar ThereferencegrammarisgiveninavariantofextendedBNF.Themetanotationused:


x

(incourierfont)meansthatxisaterminali.e.,atoken.Terminalnamesarealso alllowercaseexceptforthosefewkeywordsthatusecapitals. x (initalic)meansyisanonterminal.Allnonterminalnamesarecapitalized. x meanszerooroneoccurrenceofx,i.e.,xisoptional x * meanszeroormoreoccurrencesofx x + meansoneormoreoccurrencesofx x +, acommaseparatedlistofoneormorex's(commasappearonlybetweenx's) | separatesproductionalternatives indicatesepsilon,theabsenceoftokens Forreadability,werepresentoperatorsbythelexemethatdenotesthem,suchas + or!=asopposedtothetoken(T_NotEqual,etc.)returnedbythescanner.

3 Program Decl VariableDecl Variable Type FunctionDecl Formals ClassDecl Field InterfaceDecl Prototype StmtBlock Stmt IfStmt ForStmt ReturnStmt BreakStmt PrintStmt Expr ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= ::= Decl+ VariableDecl|FunctionDecl|ClassDecl|InterfaceDecl Variable; Typeident int|double|bool|string|ident|Type [] Typeident (Formals )StmtBlock| voidident (Formals )StmtBlock Variable+,| + classidentextendsidentimplementsident ,{Field*} VariableDecl|FunctionDecl interfaceident { Prototype* } Typeident(Formals) ; |voidident(Formals) ; {VariableDecl*Stmt*} Expr;|IfStmt|WhileStmt|ForStmt| BreakStmt|ReturnStmt|PrintStmt|StmtBlock
if (Expr)StmtelseStmt while(Expr)Stmt for (

WhileStmt ::=

Expr; Expr ; Expr)Stmt

returnExpr; break ; Print (Expr+,) ;

LValue Call Actuals Constant

::= ::= ::= ::=

LValue=Expr|Constant|LValue|this|Call|(Expr)| Expr+Expr|Expr -Expr|Expr *Expr|Expr/Expr| Expr%Expr|-Expr|Expr<Expr|Expr<=Expr| Expr >Expr|Expr>=Expr|Expr==Expr|Expr!=Expr| Expr&&Expr|Expr||Expr|!Expr|ReadInteger ( )| ReadLine () |new ident|NewArray(Expr ,Type) ident|Expr.ident|Expr[Expr ] ident(Actuals ) | Expr.ident(Actuals ) Expr+,|
intConstant|doubleConstant|boolConstant| stringConstant|null

4 ProgramStructure ADecafprogramisasequenceofdeclarations,whereeachdeclarationestablishesa variable,function,class,orinterface.Thetermdeclarationusuallyreferstoastatement thatestablishesanidentitywhereasdefinitionmeansthefulldescriptionwithactual body.Forourpurposes,thedeclarationandthedefinitionareoneandthesame.A programmusthaveaglobalfunctionnamedmainthattakesnoargumentsandreturns anint.Thisfunctionservesastheentrypointforprogramexecution. Scope Decafsupportsseverallevelsofscoping.Adeclarationatthetoplevelisplacedinthe globalscope.Eachclassdeclarationhasitsownclassscope.Eachfunctionhasalocal scopeforitsparameterlistandanotherlocalscopeforitsbody.Asetofcurlybraces withinalocalscopeestablishesanestedlocalscope.Innerscopesshadowouterscopes; forexample,avariabledefinedinafunction'sscopemasksanothervariablewiththe samenameintheglobalscope.Similarly,functionsdefinedinclassscopeshadow globalfunctionsofthesamename. Thefollowingrulesgovernscopingrulesforidentifiers: Whenenteringascope,alldeclarationsinthatscopeareimmediatelyvisible(see notebelow) Identifierswithinascopemustbeunique(i.e.therecannotbetwofunctionsof samename,aglobalvariableandfunctionofthesamename,aglobalvariable andaclassofthesamename,etc.) Identifiersredeclaredwithanestedscopeshadowtheversionintheouterscope (i.e.itislegaltohavealocalvariablewiththesamenameasaglobalvariable,a functionwithinaclasscanhavethesamenameasaglobalfunction,andsoon.) Declarationsintheglobalscopeareaccessibleanywhereintheprogram(unless theyareshadowedbyanotheruseoftheidentifier) Declarationsinclosedscopesareinaccessible. Allidentifiersmustbedeclared.

Noteaboutvisibilityandtherelationshiptolexicalstructure:AsinJava,ourcompiler operatesinmorethanonepass.Thefirstpassgathersinformationandsetsuptheparse tree;onlyafterthatiscompletedoweperformsemanticanalysis.Abenefitofatwo passcompileristhatdeclarationsareavailableatthesamescopelevelevenbeforethe lexicalpointatwhichtheyaredeclared.Forexample,methodsofaclasscanreferto instancevariablesdeclaredlateratthebottomoftheclassdeclaration,classesand subclassesandvariablesofthoseclassescanbeplacedinthefileinanyorder,andsoon. Whenascopeisentered,alldeclarationsmadeinthatscopeareimmediatelyvisible,no matterhowmuchfurtherdownthefilethedeclarationeventuallyappears.Thisrule appliesuniformlytoalldeclarations(variables,classes,interfaces,functions)inall scopes.

5 Types Thebuiltinbasetypesareint,double,bool,string,andvoid.Decafallowsfornamed types,whichareobjectsofclassorinterfacetypes.Arrayscanbeconstructedofany nonvoidelementtype,andDecafsupportsarraysofarrays. Variables Variablescanbedeclaredofnonvoidbasetype,arraytype,ornamedtype.Variables declaredoutsideanyfunctionhaveglobalscope.Variablesdeclaredwithinaclass declarationyetoutsideafunctionhaveclassscope.Variablesdeclaredintheformal parameterlistorfunctionbodyhavelocalscope. Arrays Decafarraysarehomogeneous,linearlyindexedcollections.Arraysareimplementedas references(automaticallydereferencedpointers).Arraysaredeclaredwithoutsize information,andallarraysaredynamicallyallocatedintheheaptotheneededsize usingthebuiltinNewArrayoperator. Arrayscanbedeclaredofanynonvoidbasetype,namedtype,orarraytype (includingarrayofarrays). NewArray(N, type)allocatesanewarrayofthespecifiedtypeandnumberof elements,whereNmustbeaninteger.Nmustbestrictlypositive;aruntimeerror israisedonanattempttoallocateanegativeorzerolengtharray. Thenumberofelementsinanarrayissetwhenallocatedandcannotbechanged onceallocated. Arrayssupportthespecialsyntaxarr.length()toretrievethenumberof elementsinanarray. Arrayindexingcanonlybeappliedtoavariableofanarraytype. Arrayelementsareindexedfrom0tolength 1. Theindexusedinanarrayselectionexpressionmustbeofintegertype Aruntimeerrorisreportedwhenindexingalocationthatisoutsidethebounds forthearray. Arraysmaybepassedasparametersandreturnedfromfunctions.Thearray itselfispassedbyvalue,butitisareferenceandthuschangestoarrayelements areseeninthecallingfunction. Arrayassignmentisshallow(i.e.assigningonearraytoanothercopiesjustthe reference). Arraycomparison(==and!=)onlycomparesthereferencesforequality.

6 Strings StringsupportissomewhatsparseinDecaf.Programscanincludestringconstants,read stringsfromtheuserwiththeReadLinelibraryfunction,comparestrings,andprint strings,butthat'saboutit.Thereisnosupportforprogrammaticallycreatingand manipulatingstrings,convertingbetweenstringsandothertypes,andsoon.(Consider itanopportunityforextension!)Stringsareimplementedasreferences.


ReadLinereadsasequenceofcharsenteredbytheuser,uptobutnotincluding

thenewline. Stringassignmentisshallow(i.e.assigningonestringtoanothercopiesjustthe reference). Stringsmaybepassedasparametersandreturnedfromfunctions. Stringcomparison(==and!=)comparesthesequenceofcharactersinthetwo stringsinacasesensitivemanner(behindthesceneswewilluseaninternal libraryroutinetodothework).Notethatthisdiffersfromhowstringsare handledinbothJavaandC.

Functions Afunctiondeclarationincludesthenameofthefunctionanditsassociatedtypesignature, whichincludesthereturntypeaswellasnumberandtypesofformalparameters. Functionsareeitherglobalordeclaredwithinaclassscope;functionsmaynotbe nestedwithinotherfunctions. Functionsmayhavezeroormoreformalparameters. Formalparameterscanbeofnonvoidbasetype,arraytype,ornamedtype. Identifiersusedintheformalparameterlistmustbedistinct. Formalparametersaredeclaredinaseparatescopefromthefunctionslocal variables(thus,alocalvariablecanshadowaparameter). Afunction'sreturntypecanbeanybase,array,ornamedtype.voidisusedto indicatethefunctionreturnsnovalue. Functionoverloadingisnotallowed,i.e.theuseofthesamenameforfunctions withdifferenttypesignatures.Thiswouldbeagreatplacetoaddextensions. Ifafunctionhasanonvoidreturntype,anyreturnstatementmustreturnavalue compatiblewiththattype,thoughitispermissibletofallofftheendofa function.Agreatextensionwouldbetocheckforthiscase. Ifafunctionhasavoidreturntype,itmayonlyusetheemptyreturnstatement. Recursivefunctionsareallowed. Therearenoabstractfunctions,thoughthiswouldmakeagreatextension.

7 FunctionInvocation Functioninvocationinvolvespassingargumentvaluesfromthecallertothecallee, executingthebodyofthecallee,andreturningtothecaller,possiblywitharesult.When afunctionisinvoked,theactualargumentsareevaluatedandboundtotheformal parameters.AllDecafparametersandreturnvaluesarepassedbyvalue,thoughinthe caseofobjectsthosevaluesarereferences. Thenumberofargumentspassedthroughafunctioncallmustmatchthenumber offormalparameters. Thetypeofeachactualargumentinafunctioncallmustbecompatiblewiththe formalparameter. Theactualargumentstoafunctioncallareevaluatedfromlefttoright.Thisis differentthanCorC++,wheretheevaluationorderisunspecified. Afunctioncallreturnscontroltothecalleronareturnstatementorwhenthe textualendofthecalleeisreached. Afunctioncallevaluatestothetypeofthefunction'sdeclaredreturntype.

Classes Declaringaclasscreatesanewtypenameandaclassscope.Aclassdeclarationisalist offields,whereeachfieldiseitheravariableorfunction.Thevariablesofaclassarealso sometimescalledinstancevariablesormemberdataandthefunctionsarecalledmethodsor memberfunctions. Decafenforcesobjectencapsulationthroughasimplemechanism:allvariablesare protected(theycanonlybeaccessedbytheclassanditssubclasses)andallmethodsare public(accessibleinglobalscope).Thus,theonlywaytogainaccesstoobjectstateisvia methods. Allclassdeclarationsareglobal,soclassesmaynotbedefinedinsideafunction. Itwouldbeaninterestingextensiontosupportlocalclasses. Allclassesmusthaveuniquenames. Afieldnamecanbeusedatmostoncewithinaclassscope(i.e.cannothavetwo methodsofthesamenameoravariableandmethodofthesamename). Fieldsmaybedeclaredinanyorder. Instancevariablescanbeofnonvoidbasetype,arraytype,ornamedtype. Theuseof"this."isoptionalwhenaccessingfieldswithinamethod.

8 Objects Avariableofnamedtypeiscalledanobjectoraninstanceofthatnamedtype.Objectsare implementedasreferences.Allobjectsaredynamicallyallocatedintheheapusing Decafsnewoperator. Thenameusedinanobjectvariabledeclarationmustbeadeclaredclassor interfacename. Thetypespecifiedfornewmustbeaclassname(aninterfacenameisnotallowed here).newcannotbeusedtoallocateobjectsofbasetype. The.operatorisusedtoaccessthefields(bothvariablesandmethods)ofan object. Formethodinvocationsoftheformexpr.method(),thetypeofexprmustbesome classorinterfaceT,andmethodmustnameoneofT'smethods. Forvariableaccessexpr.var,thetypeofexprmustbesomeclassT,varmust nameoneofT'svariables,andthisaccessmustappearwiththescopeofclassTor oneofitssubclasses. Insideclassscope,youcanaccesstheprivatevariablesofthereceivingobjectas wellasotherinstancesofthatclass(sometimescalledsiblingaccess),butcannot accessthevariablesofotherunrelatedclasses. Objectassignmentisshallow(i.e.assigningoneobjecttoanothercopiesjustthe reference). Objectsmaybepassedasparametersandreturnedfromfunctions.Theobject itselfispassedbyvalue,butitisareferenceandthuschangestoitsvariablesare seeninthecallingfunction.

Inheritance Decafsupportssingleinheritance,allowingaderivedclasstoextendabaseclassby addingadditionalfieldsandoverridingexistingmethodswithnewdefinitions.The semanticsofA extends BisthatAhasallthefields(bothvariablesandfunctions) definedinBinadditiontoitsownfields.Asubclasscanoverrideaninheritedmethod (replacewithredefinition)buttheinheritedversionmustmatchtheoriginalinreturn typeandparametertypes.Decafsupportsautomaticupcastingsothatanobjectofthe derivedclasscanbeprovidedwheneveranobjectofthebasetypeisexpected. AllDecafmethodsaredynamicallydispatched(inherentlyvirtualforyouC++folks). Thecompilercannotnecessarilydeterminetheexactaddressofthemethodthatshould becalledatcompiletimetoseethis,considerinvokinganoverriddenmethodonan upcastedobjectsoinsteadthedispatchishandledatruntimebyconsultingamethod tableassociatedwitheachobject.Wewilldiscussdispatchtablesinmoredetaillateron.

9 Ifspecified,theparentofaclassmustbeaproperlydeclaredclasstype.You cannotinheritfrombasetypes,arraytypes,orinterfaces. Allofthefields(bothvariablesandmethods)oftheparentclassareinheritedby thesubclass. Subclassescannotoverrideinheritedvariables. Asubclasscanoverrideaninheritedmethod(replacewithredefinition)butthe inheritedmustmatchtheoriginalinreturntypeandparametertypes. Nooverloading:aclasscannotreusethesamenameforanothermethodwitha differenttypesignature. Aninstanceofsubclasstypeiscompatiblewithitsparenttype,andcanbe substitutedforanexpressionofaparenttype(e.g.ifavariableisdeclaredoftype Animal,youcanassignitfromarighthandsideexpressionoftype CowifCowisa subclassofAnimal.Similarly,iftheBinkyfunctiontakesaparameteroftype Animal,itisacceptabletopassavariableoftypeCoworreturnaCowfroma functionthatreturnsanAnimal).Theinverseisnottrue(theparentcannotbe substitutedwherethesubclassisexpected). Thepreviousruleappliesacrossmultiplelevelsofinheritanceaswell. Thecompiletimetypeofanobjectdetermineswhichfieldsareaccessible(i.e. onceyouhaveupcastaCowtoanAnimalvariable,youcannotaccessCowspecific additionsfromthatvariable). ThereisnodowncastinginDecaf,thoughitwouldbeanexcellentextensionto supportit. Thereisnosubtypingofarraytypes:eventhoughCowextendsAnimal,anarrayof Cows(orCow[])iscompletelyincompatiblewithanarrayofAnimals(orAnimal[]).

Interfaces Decafalsosupportssubtypingbyallowingaclasstoimplementoneormoreinterfaces. Aninterfacedeclarationconsistsofalistoffunctionprototypeswithnoimplementation. Whenaclassdeclarationstatesthatitimplementsaninterface,itisrequiredtoprovide animplementationforeverymethodspecifiedbytheinterface.(UnlikeJava/C++,there arenoabstractclasses).Eachmethodmustmatchthesignatureoftheoriginal.Decaf supportsautomaticupcastingtoaninterfacetype. Eachinterfacelistedintheimplementsclausemustbeaproperlydeclared interfacetype. Allmethodsoftheinterfacemustbeimplementedifaclassstatesthatit implementtheinterface. Theclassdeclarationmustformallydeclarethatitimplementsaninterface;just implementingtherequiredmethodsdoesnotimplicitlymarkaclassasasubtype ofaninterface. Aninstanceoftheclassiscompatiblewithanyinterfacetype(s)itimplements, andcanbesubstitutedforanexpressionoftheinterfacetype(e.g.ifavariableis declaredofinterfacetypeColorable,youcanassignitfromarighthandside

10 expressionoftypeShapeiftheShapeclassimplementstheColorableinterface. Similarly,iftheBinkyfunctiontakesaparameteroftypeColorable,itis acceptabletopassavariableoftypeShapeorreturnaShapefromafunctionthat returnsaColorable).Theinverseisnottrue(theinterfacecannotbesubstituted wheretheclassisexpected). Asubclassinheritsallinterfacesofitsparent,soifRectangleinheritsfromShape whichimplementsColorable,thenRectangleisalsocompatiblewithColorable. Itisthecompiletimedeclaredtypeofanobjectthatdeterminesitstypefor checkingforfields(i.e.onceyouhaveupcastaShapetoaColorablevariable,you cannotaccessShapespecificadditionsfromthatvariable). Thereisnosubtypingofarraytypes:eventhoughCircleimplementsDrawable, anarrayofCircles(orCircle[])iscompletelyincompatiblewithanarrayof Drawables(orDrawable[]).

TypeEquivalenceandCompatibility Decafisastronglytypedlanguage:aspecifictypeisassociatedwitheachvariable,and thevariablemaycontainonlyvaluesbelongingtothattypesrangeofvalues.IftypeA isequivalenttoB,anexpressionofeithertypecanbefreelysubstitutedfortheotherin anysituation.Twobasetypesareequivalentifandonlyiftheyarethesameexacttype. Twoarraytypesareequivalentifandonlyiftheyhavethesameelementtype(which itselfmaybeanarray.)Twonamedtypesareequivalentifandonlyiftheyarethesame name(i.e.namedequivalencenotstructural). Typecompatibilityisamorelimitedunidirectionalrelationship.IfTypeAiscompatible withB,thenanexpressionoftypeAcanbesubstitutedwhereanexpressionoftypeB wasexpected.Nothingisimpliedaboutthereversedirection.Twoequivalenttypesare typecompatibleinbothdirections.Asubclassiscompatiblewithitsparenttype,butnot thereverse.Aclassiscompatiblewithanyinterfacesitimplements.The nulltype constantiscompatiblewithallnamedtypes.Operationssuchasassignmentand parameterpassingallowfornotjustequivalenttypesbutcompatibletypes. Assignment Forthebasetypes,Decafusescopybyvaluesemantics;theassignment LValue = ExprcopiesthevalueresultingfromtheevaluationofExprintothelocation indicatedbyLValue.Forarrays,objectsandstrings,Decafusesreferencecopy semantics;theassignmentLValue = ExprcausesLValuetocontainareferencetothe objectresultingfromtheevaluationofExpr(i.e.,theassignmentcopiesapointertoan objectratherthantheobject).Saidanotherway,assignmentforarrays,objects,and stringsmakesashallow,notdeep,copy.

11 AnLValuemustbeanassignablevariablelocation. Therightsidetypeofanassignmentstatementmustbecompatiblewiththeleft sidetype. nullcanonlybeassignedtoavariableofnamedtype. Itislegaltoassigntotheformalparameterswithinafunction,suchassignments affectonlythefunctionscope.

Controlstructures DecafcontrolstructuresarebasedontheC/Javaversionsandgenerallybehave somewhatsimilarly. Anelseclausealwaysjoinswiththeclosestunclosedifstatement. Theexpressioninthetestportionsoftheif,while,andforstatementsmust havebooltype.UnlikeC,C++,andJava,theremustbeatestinaforloop. Abreakstatementcanonlyappearwithinawhileorforloop. Thevalueinareturnstatementmustbecompatiblewiththereturntypeofthe enclosingfunction.

Expressions Forsimplicity,Decafdoesnotallowcominglingandconversionoftypeswithin expressions(i.e.addinganintegertoadouble,usinganintegerasaBoolean,etc.). Constantsevaluatetothemselves(true,false,null,integers,doubles,string literals). thisisboundtothereceivingobjectwithinclassscope;itisanerrorelsewhere. Thetwooperandstobinaryarithmeticoperators(+,-,*,/,and%)musteitherbe bothintorbothdouble.Theresultisofthesametypeastheoperands. Theoperandtoaunaryminusmustbeintordouble.Theresultisthesametype astheoperand. Thetwooperandstobinaryrelationaloperators(<,>,<=,>=)musteitherbothbe intorbothdouble.Theresulttypeisbool. Thetwooperandstobinaryequalityoperators(!=,==)mustbeofequivalenttype (twoints,twoarraysofdouble,etc.)Theresulttypeisbool.Seenotesaboutan exceptiontothisruleforstrings. Thetwooperandstobinaryequalityoperandscanalsobetwoobjectsoranobject andnull.Thetypesofthetwoobjectsmustbecompatibleinatleastone direction.Theresulttypeisbool. Theoperandstoallbinaryandunarylogicaloperators(&&,||,and!)mustbeof booltype.Theresulttypeisbool. Logical&&and||donotshortcircuit;bothexpressionsareevaluatedbefore determiningtheresult. Theoperandsforallexpressionsareevaluatedlefttoright.

12 Operatorprecedencefromhighesttolowest:
[ . ! * / % + < <= > >= == != && ||

(arrayindexingandfieldselection) (unaryminus,logicalnot) (multiply,divide,mod) (addition,subtraction) (relational) (equality) (logical and) (logicalor) (assignment)

Allbinaryarithmeticoperatorsandbothbinarylogicaloperatorsareleftassociative. Assignmentandtherelationalandequalityoperatorsdonotassociate(i.e.youcannot chainasequenceoftheseoperatorsthatareatthesameprecedencelevel:a < b >= c shouldnotparse,howevera < b == cisokay).Parenthesesmaybeusedtooverridethe precedenceand/orassociativity. LibraryFunctions DecafhasaverysmallsetofroutinesinitsstandardlibrarythatallowforsimpleI/O andmemoryallocation.ThelibraryfunctionsarePrint,ReadInteger,ReadLine,and NewArray. TheargumentspassedtoaPrintstatementcanonlybestring,int,orbool. ThefirstargumenttoNewArraymustbeofintegertype,thesecondanynonvoid type. ThereturntypeforNewArrayisarrayofTwhereTisthetypespecifiedasthe secondargument. ReadLinereadsasequenceofcharsenteredbytheuser,uptobutnotincluding thenewline. ReadIntegerreadsalineoftextenteredbytheuser,andconvertstoaninteger usingatoi(returning0iftheuserdidn'tenteravalidnumber).

Decaflinking GivenDecafdoesnotallowseparatemodulesordeclarationseparatefromdefinition, thereisnotmuchworkbeyondsemanticanalysistoensurewehaveallnecessarycode. Theonetaskourlinkerneedstoperformistoverifythatthattherewasadeclarationfor theglobalfunctionmain.Thiswillbedoneaspartofcodegeneration.

13 RuntimeChecks ThereareonlytworuntimechecksthataresupportedbyDecaf. Thesubscriptofanarraymustbeinbounds,i.e.inrange[0,arr.length()). ThesizepassedtoNewArraymustbestrictlypositive.

Whenaruntimeerrorsoccurs,anappropriateerrormessageisoutputtotheterminal andtheprogramterminates. WhatDecafIsNot Bydesign,Decafisasimplelanguageandalthoughithasallthefeaturesnecessaryto writeawidevarietyofobjectorientedprograms,therearevariousthingsthatC++and Javacompilersdothatitdoesnot.Hereareafewthatcometomind: Decafdoesn'tmandatewhatthevaluesforuninitializedvariablesareorwhatthe valueofvariablesorelementsinanewlyallocatedobjectorarrayare. Decafdoesn'tcheckforuseofuninitializedvariables. Decafdoesn'tdetect(eithercompileorruntime)afunctionthatisdeclaredto returnavaluebutfailstodosobeforefallingoffthetextualendofthebody. Decafdoesn'tcheckforanobjectorarrayusebeforeitwaseverallocated. Decafdoesn'tdetectcallmethodsoraccessingvariablesofanullobject. Decafdoesn'tdetectunreachablecode. Decafhasnodeallocationfunctionandnogarbagecollection,sodynamicstorage isneverreclaimed. Decafhasnosupportforobjectconstructorsordestructors.

You might also like