liva · 2016. 7. 25. · the liva programming language supports two kinds of types: primitive types...

20
LIVA A Lite Version of Java Shanqi Lu Jiafei Song Zihan Jiao Yanan Zhang sl4017 js4984 zj2203 yz3054

Upload: others

Post on 05-Feb-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

  • LIVAALiteVersionofJava

    ShanqiLu JiafeiSong ZihanJiao YananZhangsl4017 js4984 zj2203 yz3054

  • 1

    Table of Contents

    CHAPTER1INTRODUCTION....................................................................................................3

    CHAPTER2LEXICALCONVENTIONS........................................................................................32.1WhiteSpace...............................................................................................................................32.2Comments..................................................................................................................................42.3Identifiers...................................................................................................................................42.4Keyword.....................................................................................................................................42.5Literals.......................................................................................................................................4

    2.5.1BooleanLiterals..........................................................................................................................42.5.2IntegerLiterals............................................................................................................................52.5.3FloatingPointLiterals.................................................................................................................52.5.4CharacterLiterals........................................................................................................................52.5.5StringLiterals..............................................................................................................................52.5.6EscapeSequencesforCharacterandStringLiterals...................................................................52.5.7TheNullLiteral............................................................................................................................6

    2.6Separators..................................................................................................................................62.7Operators...................................................................................................................................6

    CHAPTER3Types....................................................................................................................63.1PrimitiveTypes...........................................................................................................................6

    3.1.1IntegralTypes.............................................................................................................................63.1.2Floating-PointTypes...................................................................................................................73.1.3TheBooleanType.......................................................................................................................7

    3.2ReferenceTypes.........................................................................................................................73.2.1Objects........................................................................................................................................73.2.2TheClassString...........................................................................................................................73.2.3Arrays..........................................................................................................................................8

    CHAPTER4Classes.................................................................................................................84.1ClassDeclarations.......................................................................................................................84.2ClassMembers...........................................................................................................................94.3FieldDeclarations.......................................................................................................................94.4MethodDeclarations..................................................................................................................94.5ConstructorDeclarations............................................................................................................94.5Inheritance...............................................................................................................................10

    CHAPTER5Statements..........................................................................................................105.1ExpressionStatements.............................................................................................................105.2DeclarationStatements............................................................................................................115.3ControlFlowStatements..........................................................................................................11

    5.3.1If-thenandIf-then-else.............................................................................................................115.3.2Looping:for...............................................................................................................................125.3.3Looping:while...........................................................................................................................12

  • 2

    5.4MethodCreationandMethodCall............................................................................................135.5PrinttoConsole........................................................................................................................145.6EmptyStatement......................................................................................................................15

    CHAPTER6Expressions.........................................................................................................156.1Evaluation,Denotation,andResult...........................................................................................156.2TypeofanExpression...............................................................................................................166.3EvaluationOrder......................................................................................................................16

    6.3.1Left-HandOperandFirst...........................................................................................................166.3.2EvaluateOperandsbeforeOperation.......................................................................................166.3.3EvaluationRespectsParenthesesandPrecedence..................................................................16

    6.4LexicalLiterals..........................................................................................................................166.5TheArithmeticOperations.......................................................................................................176.6TheRelationalOperations........................................................................................................176.7TheBitwiseandConditionalOperations:..................................................................................186.8MethodInvocationExpressions................................................................................................186.9ArrayAccessExpressions..........................................................................................................186.10Assignment.............................................................................................................................19

  • 3

    CHAPTER 1 INTRODUCTION LivaisageneralpurposeprogramminglanguageandaliteversionofJava.Itisdesignedtoletprogrammers who are familiar with class-based languages feel comfortable with developingcommonalgorithmslikeGCD.ItisliteinthesensethatitmaintainssomebutnotallfeaturesinJava. It has the similar syntax and abstract data types in Java and supports object-orientedparadigmandinheritance.However,genericsandnestedclassesarebeyondthescopeofthisproject,hencetheyarenottobeimplemented.The Liva programming language is strongly typed. The compiler checks whether argumentspassedtoafunctionmatchexpectedtypesandreturnanerrorifnot.ItisaportablelanguageandcompileddowntoLLVM.Thislanguagereferencemanualisorganizedasfollows:

    • Chapter2describesthelexicalconventionsoftheLivaprogramminglanguage.• Chapter 3 describes types. Types are divided into two categories: primitive types and

    referencetypes.• Chapter4describesclassesincludingclassdeclarationsandinheritance.• Chapter5describesstatements.• Chapter6describesexpressions.

    CHAPTER 2 LEXICAL CONVENTIONS ThischapterspecifiesthelexicalconventionsofLivaprogramminglanguage.Acompilertakesaprogramwhichconsistsofasequenceofcharactersandreduceittoasequenceofelements,which are tokens,white space and comments. The tokens are identifiers, keywords, literals,separators,andoperators.

    Element:WhiteSpace|Comment|Token

    Token:Identifier|Keyword|Literal|Separator|Operator

    2.1WhiteSpace

  • 4

    White space in Liva is defined as space character, tab character, form feed character(page-breaking)andlineterminatorcharacter.Whitespacecharactersareignoredbyacompilerexceptastheyservetoseparatetokens.2.2CommentsThereisonekindofcomments:

    • /*text*/Allcharactersfrom“/*”to“*/”areignored.2.3IdentifiersAnidentifierisasequenceofletters,digitsandunderscore‘_’.Itcanonlybeginwithaletter.Identifiersarethenamesofvariables,methodsandclasses.Theyarecase-sensitive.2.4KeywordKeywordsarereservedandcannotbeusedasidentifiers.

    • Keyword:

    2.5LiteralsLiteralsaresyntacticrepresentationsofnumeric,character,booleanorstringdata.Theyareusedforrepresentingvaluesinprograms.2.5.1BooleanLiteralsTherearetwobooleanliterals:

    • true representsatrueBooleanvalue• false representsafalseBooleanvalue

    for new if boolean this break

    double implements else import return extendsint char interface void class float

    while

  • 5

    2.5.2IntegerLiteralsInteger numbers in Liva are in decimal format. Negative decimal numbers such as -10 areactuallyexpressionsconsistingoftheoperator‘-’andintegerliteral.Theprimitivetypeofintegerliteralisint.2.5.3FloatingPointLiteralsFloatingpointnumbersareexpressedasdecimalfractionsandconsistof:

    • anoptional‘+’or‘-’sign;ifomitted,thevalueispositive,• oneofthefollowingformats

    Format Example

    integerdigits 9integerdigits . 7.integerdigits . integerdigits 17.31 . integerdigits .56

    2.5.4CharacterLiteralsCharacterliteralsareexpressedasasinglequote:'a', '#', 'π'2.5.5StringLiteralsStringliteralsbeginwithadoublequotecharacter",followedbyzeroormorecharactersandaterminatingdoublequote"Withinstringliterals,therecanbeescapesequencesbutnotunescapednewline.2.5.6EscapeSequencesforCharacterandStringLiteralsAnescapesequenceisusedtorepresentaspecialcharacter.Itbeginswithabackslashcharacter(\),whichindicatesthatthefollowingcharactersshouldbetreatedspecially.Escapesequencesarelistedinthetablebelow.Name CharacterTAB \tnewline \ndoublequote \”singlequote \’backslash \\

  • 6

    2.5.7TheNullLiteralNullisaspecialliteralwhichrepresentsanullvaluewhichdoesnotrefertoanyobject.Thenullliteralisformedas:null2.6SeparatorsSeparatorsaretokensusedforseparatingtokens.

    2.7OperatorsTheexpressionsectionofthismanualwillexplainbehaviorsoftheseoperators.Herelistsalltheoperators.

    CHAPTER 3 Types TheLivaprogramminglanguagesupportstwokindsoftypes:primitivetypesandreferencetypes.Therearealsotwokindsofdatavalues:primitivevaluesandreferencevaluesaccordingly.Thereisalsoaspecialnulltype.Primitivetypesarebooleantypesandnumerictypes.Referencetypesareclasstypesandarraytypes3.1PrimitiveTypesPrimitivetypesareredefinedandtheirnamesarereservedkeywords.3.1.1IntegralTypes

    = > < ! == >=

  • 7

    Theintegraltypesareintandchar.Theintegerdatatypeisa32-bitsequenceofdigits,whichhasaminimumvalueof-2^31andamaximumvalueof 2^31-1.An integer literal is a sequenceof digits precededby anoptionalnegativesign.Asinglezerocannotbeprecededbyanegativesign.

    Thechardatatypebelongstointegraltypeswhosevaluesare16-bitunsignedintegers.

    3.1.2Floating-PointTypesThefloating-pointdatatypeisasigned-precision32-bitformatvalues.

    3.1.3TheBooleanTypeThebooleandata type has twopossible values:trueandfalse. A boolean is its own type andcannotbecomparedtoanon-booleanvariable.Therefore,expression“true==1”wouldleadtoanerror.

    3.2ReferenceTypesTherearetwokindsofreferencetypes:classtypesandarraytypes.3.2.1ObjectsAnobjectcanbeaclassinstanceoranarray.3.2.2TheClassString

    int x = 10; int y = -50; int z = 0;

    char x = 'a';

    float x = 1.5; float y = -5.1; float z = 2.0;

    boolean x = true; boolean y = false;

  • 8

    AninstanceofclassStringisasequenceofcharacters.TheclassStringsupportsthefollowingbuilt-inmethods:

    • charAt(intindex)ThismethodreturnsthecharacterlocatedattheString'sspecifiedindexbutreturnsanerroriftheindexisoutofrange.Indexesstartfromzero.• length()Thismethodreturnsthelengthofastring.

    3.2.3ArraysArrayscanbeseenasaspecialtype.Anarrayobjectcontainsanumberofvariables.Allelementsinanarraysmusthavethesametype.

    CHAPTER 4 Classes Aclassdeclarationdefinesanewreferencetypeandhowitisimplemented.Classescontainfieldsandmethods. Field declarations describe class variables whilemethod declarations describeprogramsthatmaybeinvokedbyotherprograms4.1ClassDeclarationsClasses are defined in the following way. The optional extends clause in a class declarationspecifiesthesuperclassofthecurrentclass.

    classMyClassextendsSuperClass{//field,constructor//methoddeclarations

    }

    String w = "Liva"; String x = new String("Liva"); int y = x.length(); char z = x.charAt(1);

    int[] ai; char ac[] = { 'a', 'b', 'c', ' ' };

  • 9

    4.2ClassMembersMembersofaclassconsistof:

    • Membersinheritedfromitssuperclass• Membersdeclaredintheclassdeclaration

    4.3FieldDeclarationsFieldDeclarationsspecifyvariablesofaclasstype.4.4MethodDeclarationsMethoddeclarationsspecifyexecutablecodethatmightbeinvoked.

    4.5ConstructorDeclarationsIftheconstructorisnotdefined,thecompilergeneratesadefaultone.

    /* Field declarations and method declarations */ class Calculation{ int z; void addition(int x, int y){ z = x+y; } void Subtraction(int x,int y){ z = x-y; } }

  • 10

    4.5InheritanceInheritanceisthatasubclassacquiresallthebehaviorsandpropertiesofasuperclass.

    CHAPTER 5 Statements Statements include: if, else, for, break, continue, return, as well all expressions which areexplainedinthefollowing.Exceptasindicated,statementsareexecutedinsequence5.1ExpressionStatementsAnexpressionstatementconsistsofanexpressionfollowedbyasemicolon.

    /* User defined constructor*/ class Calculation{ int z; constructor (int z){ this.z = z; } void addition(int x, int y){ z = x+y; } void Subtraction(int x,int y){ z = x-y; } }

    expression;

    class My_Calculation extends Calculation { void multiplication(int x, int y) { z = x * y; } }

  • 11

    Usuallyexpressionstatementsareassignmentsorfunctioncalls.

    5.2DeclarationStatements Adeclarationstatementdeclaresavariablebyspecifyingitsdatatypeandname.Italsocouldinitializethevariableduringthedeclaring.

    5.3ControlFlowStatements 5.3.1If-thenandIf-then-elseTherearetwoformsofconditionalstatements.For the first case, the conditional expression that is evaluated is enclosed in balancedparentheses. The sectionof code that is conditionally executed is specified as a sequenceofstatementsenclosedinbalancedbraces.Iftheconditionalexpressionevaluatestofalse,controljumpstotheendoftheif-thenstatement.

    /* declare a variable with data type and name */ char a; int b =10; float c; int array1[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; String name= "class"; boolean isMatch = false;

    /* Object creation expressions */ Student e1 = new Student (); /* Object creation expressions */ c = 8933.234;

    if (expression) { statement

    }

  • 12

    Inthesecondcasethesecondsub-statementisexecutediftheexpressionisfalse.Asusualthe‘else’ambiguityisresolvedbyconnectinganelsewiththelastencounteredelselessif.

    5.3.2Looping:for The‘for’conditionwillalsoruninaloopsolongastheconditionspecifiedinthe‘for’statementistrue.The‘for’statementhasthefollowingformat:

    Thefirstexpressionspecifiesinitializationfortheloopanditisexecutedonceatthebeginningofthe'for'statement;thesecondspecifiesatest,madebeforeeachiteration,suchthattheloopisterminated when the expression becomes false; the third expression typically specifies anincrementordecreasewhichisperformedaftereachiteration.Thefollowingexampleusesa‘for’statementtoprintthenumbersfrom0to10:

    5.3.3Looping:whileThe‘while’statementhastheform:

    The‘while’statementwillbeexecutedinaloopaslongasthespecifiedconditioninthewhilestatementistrue.Theexpressionmusthavetypeboolean,oracompile-timeerroroccurs.

    if (expression) { statement1

    } else { Statement2

    }

    for (expression1; expression2; expression 3) { statement

    }

    for (int num=0; num < 11; num ++) { print(num); }

    while(expression) { statement

    }

  • 13

    • Ifthevalueforexpressionistrue,thenthecontainedstatementisexecuted

    • Ifexecutionofthestatementcompletesnormally,thentheentire‘while’statementisexecutedagain,beginningbyre-evaluatingtheexpression.

    • Ifthevalueoftheexpressionisfalse,nofurtheractionistakenandthe‘while’statementcompletesnormally.

    5.3.4Branching:break,continue,andreturn Thebreakstatementcausesterminationofthesmallestenclosingforstatement;controlpassestothestatementfollowingtheterminatedstatement.Theexpressionfor ‘break’statement isshownbelow:

    Thecontinuestatementcausescontroltopasstotheloop-continuationportionofthesmallestenclosingforstatement;thatistotheendoftheloop.Theexpressionfor‘continue’statementisshowbelow:

    Afunctionreturnstoitscallerbymeansofthe‘return’statement,whichhasoneoftheforms:

    Inthefirstcasenovalueisreturnedwhenamethodisdeclaredvoid.Forthefirstcase,theuserscouldspecifynoreturnstatementforsimplification.Inthesecondcase,simplyputthevalue(oran expression that calculates the value) after the return Keyword, then the value of theexpressionisreturnedtothecallerofthefunction. 5.4MethodCreationandMethodCall Theusercouldwritetheuser-definedmethods.

    break;

    continue;

    return; return(expression);

    returnType nameOfMethod (Parameter List) { // method body }

  • 14

    • returnType: Methodmayreturnavalue. • nameOfMethod: Thisisthemethodname.Themethodsignatureconsistsofthemethod

    nameandtheparameterlist. • Parameter List: The list of parameters, it is the type, order, and number of

    parametersofamethod.Theseareoptional,methodmaycontainzeroparameters. • method body: Themethodbodydefineswhatthemethoddoeswithstatements.

    Forusingamethod, it shouldbe called. Thereare twoways inwhichamethod is called i.e.methodreturnsavalueorreturningnothing(noreturnvalue).Following is the example to demonstrate how to define amethod and how to call itwith areturnedvalue:

    5.5PrinttoConsole Theprint()functiontakesoneormoreparametersandprintsthemonebyonetostandardoutput.Theparametertypemaybestring,number,orobject.Itisinthefollowingform:

    Hereisanexampletoacceptanintandprinttheinttotheconsole.

    Anotherexampletoacceptastringandprintthestringtotheconsole:

    void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); prin("Minimum Value = " + c); } int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }

    print (parameters);

    print (1);

    print (“CS4115 is fun!”)

  • 15

    5.6EmptyStatement Anemptystatementdoesnothingandhasthefollowingform:

    CHAPTER 6 Expressions Much of the work in a program is done by evaluatingexpressions, such as assignments tovariables,orfortheirvalues,whichcanbeusedasargumentsoroperandsinlargerexpressions,ortoaffecttheexecutionsequenceinstatements,orboth.

    Thischapterspecifiesthemeaningsofexpressionsandtherulesfortheirevaluation.

    6.1Evaluation,Denotation,andResultLivaevaluatesalargerexpressionbyevaluatingsmallerpartsofit.Sotheresultofanexpressionisimportant.Whenanexpressioninaprogramisevaluated(executed),theresultdenotesoneofthreethings:

    • Avariable• Avalue• Nothing(forvoidfunctionsandmethods)

    Anexpressiondenotesnothingifandonlyifitisamethodinvocationthatinvokesamethodthatdoesnotreturnavalue,thatis,amethoddeclaredvoid.Suchanexpressioncanbeusedonlyasan expression statement (in statement chapter), because every other context in which anexpressioncanappearrequirestheexpressiontodenotesomething.

    Ifanexpressiondenotesavariable,andavalueisrequiredforuseinfurtherevaluation,thenthevalueofthatvariableisused.Inthiscontext,iftheexpressiondenotesavariableoravalue,wemayspeaksimplyofthevalueoftheexpression.Inthisway,wemaysayeachexpressiondenotesavalueinacertaintype.

    ;

  • 16

    6.2TypeofanExpressionForanexpressionthatdenotestoavariable,thevaluestoredinavariableisalwayscompatiblewiththetypeofthevariable.Inotherwords,thevalueofanexpressionwhosetypeisTisalwayssuitableforassignmenttoavariableoftypeT.

    The rules for determining the type of an expression that denotes to a value are explainedseparatelybelowforeachkindofexpression.Includingarithmeticoperations,relationoperations,bitwise/conditionaloperations,assignment.

    6.3EvaluationOrder

    Livaguaranteesthattheoperandsofoperatorsappeartobeevaluatedinaspecificevaluationorder,namely,fromlefttoright.

    6.3.1Left-HandOperandFirst

    Theleft-handoperandofabinaryoperatorappearstobefullyevaluatedbeforeanypartoftheright-handoperandisevaluated.

    6.3.2EvaluateOperandsbeforeOperation

    Liva guarantees that every operand of an operator (except the conditional operators&,|)appearstobefullyevaluatedbeforeanypartoftheoperationitselfisperformed.

    Forexample,inanassignmentexpression,theassignmentwillnotbeevaluateduntiltherighthandoperands(ifitisanotherexpression)isevaluated.

    6.3.3EvaluationRespectsParenthesesandPrecedence

    Liva respects the order of evaluation indicated explicitly by parentheses and implicitly byoperatorprecedence.

    6.4LexicalLiterals

    Aliteraldenotesafixed,unchangingvalue.Thiskindofexpressioncouldbeevaluatedwithoutbeingbrokenintosmallexpressions.

    Thetypeofaliteralisdeterminedasfollows:

  • 17

    • Thetypeofanintegerliteralisint.• Thetypeofafloating-pointisfloat.• Thetypeofabooleanliteralisboolean.• Thetypeofacharacterliteralischar.• ThetypeofastringliteralisString.• Thetypeofthenullliteralnullisthenulltype;itsvalueisthenullreference.Evaluationofalexicalliteralalwayscompletesnormally.

    6.5TheArithmeticOperationsThevalueofanequalityexpression isnumeric(intordouble,dependsontheoperands).Theoperators+,-,*,/,and%arecalledthearithmeticoperators.Theyhavethesameprecedenceand are syntactically left-associative (they group left-to-right). The type of the arithmeticexpressionisthepromotedtypeofitsoperands.

    Thetypeofeachoftheoperandsofarithmeticoperatorsmustbeatypethatisconvertibletoaprimitivenumerictype,oracompile-timeerroroccurs.Forexample:“+”twoobjectsofauser-definedclassisprohibited.

    + Adds values on either side of the operator

    - Subtracts right hand operand from left hand operand

    * Multiplies values on either side of the operator

    / Divides left hand operand by right hand operand

    % Divides left hand operand by right hand operand and returns remainder

    6.6TheRelationalOperationsThevalueofanequalityexpressionisalwaysboolean.Theequalityoperatorsmaybeusedtocomparetwooperandsthatareconvertibletonumericinttype,ortwooperandsoftypeboolean.Allothercasesresultinacompile-timeerror.

    == ( Addition) Adds values on either side of the operator

    != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

  • 18

    6.7TheBitwiseandConditionalOperations:UnlikeJava,Livauses&,|,^,~forbothbitwiseandconditionaloperations.Thatdependsontheoperands.TheoperandsofaBitwise/ConditionalOperationshouldbothbeintorboolean.

    & Binary AND if both operands are int type / Logic AND if both operands are boolean type

    | Binary OR if both operands are int type / Logic OR if both operands are boolean type

    ^ Binary XOR if both operands are int type / Logic XOR if both operands are boolean type

    ~ Binary Complement if both operands are int type / Logic INVERT if both operands are boolean type

    6.8MethodInvocationExpressionsAmethod/function invocation expression is used to invoke an instancemethod (declared inpreviouschapters).Theresulttypeofthechosenmethodisdeterminedasfollows:Ifthechosenmethod/functionisdeclaredwithareturntypeofvoid,thentheresultisvoid.Otherwise,theresulttypeisthemethod/function'sdeclaredreturntype.

    6.9ArrayAccessExpressionsAnarrayaccessexpressioncontainstwosubexpressions,thearrayreferenceexpression(beforetheleftbracket)andtheindexexpression(withinthebrackets).

    Notethatthearrayreferenceexpressionmaybeanameoranyprimaryexpressionthatisnotan

    > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

    < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

    >= Checks if the value of left operand is greater than or equal to (no less than) the value of right operand, if yes then condition becomes true.

  • 19

    arraycreationexpression.Thetypeofthearrayreferenceexpressionmustbeanarraytype.Fortheindexexpression,thepromotedtypemustbeint,oracompile-timeerroroccurs.

    TheresultofanarrayaccessexpressionisavariableoftypeT,namelythevariablewithinthearrayselectedbythevalueoftheindexexpression.

    6.10AssignmentInLiva,theonlyassignmentoperatoris“=”.

    Theresultofthefirstoperandofanassignmentoperatormustbeavariable.Thisoperandmaybeanamedvariable,suchasalocalvariableorafieldofthecurrentobjectorclass,oritmaybeacomputedvariable,ascanresultfromafieldaccessoranarrayaccess(definedpreviously).