” 写作Compiler编程、 写作JavaCompiler – Based on a similar lab work in Caen UniversityAntlr, Calculator and MVaP languageThe objectives of the lab work (on machine) :1. to be familiar with a lexical and syntactic analyser tool. We have choosen the ANTLRtool,which uses Java language.Your friend is the ANTLRdocumentation : httpss ://github.com/antlr/antlr4/blob/master/doc/index.md2. In a second part, you will have to design a programming language dealing with variables,conditional structures and loops. Apart From conditional structures, assignements tovariables and loops, the language is intented to manipulate aritmetical and booleanexpressions. You will use antlr for the lexical, syntactic and code generation. The targetlanguage for the code generation will be the MVaP language, the language of the MVaPstack machine. The descriptions of the instructions are given in the MVaP-Cheat-Sheetpdf.1 Quick start of AntlrQuestion. Download the install file install.txt and follow the instructions to installANTLR. The installation instructions are for a Gnu/Linux or similar operating systems (Unix,Mac OS X). I recommend then to read httpss ://github.com/antlr/antlr4/blob/master/doc/index.md.The following is an attribute grammar for arithmetical expressions using sum and product.The first axiom is always start, et every non-terminal should start with a lower case letter.Tokens always are in upper-case. We end the start axiom with the system token EOF, whichis automatically produced by the lexical analyser after reading the input.grammar Calculator;// grammar rulesstart: expr EOF;expr: expr * expr| expr + expr| INT;//lexical rules. When something is unmatched, we skip it.NEWLINE : \r? \n – skip;WS : ( |\t)+ – skip;INT : (0…9)+;UNMATCH : . – skip;Question. Explain why this grammar is ambigous.Question. Put this grammar in a file (say Calculator.g4) and compile (follow the instructionsin the install.txt file).Question. Use the grun tool to Visualise the syntactic tree (see install.txt file for the correspondingcommand line). A use case with grun :grun Calculator start -guiAnalyse the results with the following expressions :4224+ 24- 65*8+2* 15+2 * 8+ 36 *4 / 5+38Question. We use attribute grammars to evaluate such arithmetical expressions, by associatingeach rule with an attribute. We can do the following for the addition rule for instance.expr returns [int val]: a=expr + b=expr {$val=$a.val +$b.val;}Complete so that the result of the evaluation of the arithmetical expression is printed.To obtain the text of a token, use the tokens text attribute, and the tokens attribute int toget the integer value held by the token if the text is a valid numeric string. See httpss ://github.com/antlr/antlr4/blob/master/doc/actions.mdfor the set of tokens and rules attributes,given by ANTLR and also the syntax for adding your own attributes and retreiving their values.Question. Analyse the output of the syntactic tree (with grun) and of the result of theevaluation of the expression 5 + 2 8 + 3. Permute now in expr the order in which the rules forthe sum and product are given, and do the same as above with the expression 5 + 2 8 + 3.Do we have same outputs ? Why ?2 CalculatorThe objective is to enrich our calculator language to manipulate complex arithmeticalexpressions with variables and types, loops, printing and reading, and conditional structures.We recommend to use standard techniques to deal with ambiguity. For instance, forarithmetical expressions, division and product have high priorities on sum and substractions,with same priorities we evaluate from left to right. We recommend to read again httpss ://github.com/antlr/antlr4/blob/master/doc/left-recursion.md to know which rules areused by default by ANTLR to resolve ambiguity.We will add more and more rules to our grammar Calculator.g4.2Question. Enrich the grammar to include divisions, substractions and parenthesized expressions.Test with the following expressions (they all evaluate to the same value). We supposefrom now that every expression is Ended by a line break, but you can enrich by adding forinstance the possibility to end them also with semi-colons (you encapsulate them in a tokenEndOfInstruction).4224+24-65*8+2*16*4/5+3842+1+2+-35*8+2*-1/-1(5*6*7*11 + 2)/11*5-1008(5*6*7*11 + 2)/(11*5)(5*6*7*11 + 2)/11/5(5*6*7*11 + 2)/(11/5)-1114Question. We have seen in exercises lecture rules for manipulating boolean expressionswith comparisons between arithmetical expressions. Complete these rules to add comparisonsbetween boolean expressions and add the rules to the Calculator grammar. We recall thatthe comparisons operations are == (equality), (difference), (less than), (greaterthan), = (less or equal than) et = (greater or equal than), and the operators for booleanexpressions are and, or and not. The rule should also accept parenthesized boolean expressions.Test with the following expressions.true and false or true and not truetrue or false and falsetrue or (false or false)false or (true and not false)(not true and false) or (true and not false)false or not true or true and not 42 == 42false or 42 = 40false or (5*6*7*11 + 2)/11*5-1008 = 5*8+2*-1/-150 5142+1+2+-3 5*8+2*-1/-1(5*6*7*11 + 2)/11/5 (5*6*7*11 + 2)/(11/5)-1114(5*6*7*11 + 2)/11/5 = (5*6*7*11 + 2)/(11/5)-11145*8+2*1 6*4/5+385*8+2*1 = 6*4/5+3842 == (5*6*7*11 + 2)/11/53 Code GenerationThe goal is to use the MVaP machine to execute the programs written in our language,and then we need to generate a machine code instead of evaluating directly the expressions.The target language for the Code generation will be the MVaP language.3Reminder. If you did not yet install MVaP, please follow the instructions in install.txt.Read also the MVaP-Cheat-Sheet.pdf file for the set of instructions of the MVaP machine.Until now, we have associated an integer attribute with each rule to store the result of theevaluation. For the code generation with target language MVaP, we will instead use a stringaccumulator to store the MVaP code.Question. Modify the grammar so that it generates, for each rule, the associated MVaPcode, instead of evaluating its value.Tests. Test your parser to check that you really generate the right MVaP, you can use theexpressions above. Run the MVaP generated code to check that the results are correct (seeinstall.txt on how to run MVaP machine). The tool grun can be quickly too heavy fortesting. Instead, you can use the following to automate the tests :import java.io.*;import org.antlr.v4.runtime.*;public class MainCalculator {public static void main(String args[]) throws Exception {CalculatorLexer lex;if (args.length == 0)lex = new CalculatorLexer(new ANTLRInputStream(System.in));elselex = new CalculatorLexer(new ANTLRFileStream(args[0]));CommonTokenStream tokens = new CommonTokenStream(lex);CalculatorParser parser = new CalculatorParser(tokens);try {parser.start(); // start the first axiom of the grammar} catch (RecognitionException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}4 Global VariablesWe would like to be able to Manipulate global variables and types. We will manipulateonly int, float and bool types. Values by default for variables is 0. In our language, any variableshould be declared before first use. One should be able to assign to variables constants, e.g.,,x = 4, as well expressions, e.g.,, x = 6 y (in this latter we are expecting that the value of yis computed and multiplied with 6 before assigning it to x).We will follow the C language structure as follows : a program in our language starts withdeclarations of variables first and then can do computations. See below, a proposition for thestructure of the file Calculator and a beginning of the rules.4grammar Calculator;@parser::members {private int _label = 0;/** generator of label names */private int nextLabel() { return _label++; }}start : calcul EOF;calcul returns [ String code ]@init{ $code = new String(); } // we initialise $code, to use it as accumulator@after{ System.out.println($code); } // we print the MVaP code produced by the parser: (decl { $code += $decl.code; })*NEWLINE*(instruction { $code += $instruction.code; })*{ $code += HALT\n; };EndInstruction: (NEWLINE | ;)+;decl returns [ String code ] // declarations of variables: TYPE IDENTIFIER EndInstruction{// to be completed}| TYPE IDENTIFIER = expression EndInstruction{// to be completed};instruction returns [ String code ] // an Instruction other than declaration: expression EndInstruction // boolean or arithmetical expressions{//to be completed}| assignment EndInstruction // assigning values to variables{// to be completed}| EndInstruction{$code=;};assignment returns [ String code ] // Assign an expression5: IDENTIFIER = expression{//to be completed};// lexerTYPE : int | float | bool; // three typesIDENTIFIER : ; //to be completed, any sequence of [a-zA-Z0-9_], starting always with [a-zA-Z] or _Question. To deal with variables, you will probably need symbol tables to be able to decidewhether an identifier has been already used, and also to be able to recover the value of a variablewhenever it is used, in particular know its address in the stack (recall that the declarations aredone at the beginning, and then if you declare variables first in your MVaP code, you are ableto compute their addresses in the stack). To keep track of the tuples (id-variable,type-variable,adress-in-stack), you can use for instance an HashMap, declared and initialised in the header@parser : :members.Modify now the Calculator grammar to generate MVaP code for all the rules we havewritten so far (arithmetical and boolean expressions), and for declarations and assignments ofglobal variables.Use the test collection to test your grammar. Each of the wanted behaviour has a test filewith a collection of expressions to be tested. From now on, it is better to use the test set tocheck whether your proposal corresponds to the wanted behaviour.Adding Input and Output operations. To ease the tests and the use of our language,it might interesting to include a mechanism for reading from the system input and writingon the system output. We recall that the MVaP machine has two dedicated instructions READand WRITE. The following rules allow to deal with input and output operations. Add the iorule to the grammar file and modify also the instruction rule so that one can readln andprintln in our language.io returns [ String code ]: READ ( IDENTIFIER ){int at = // to be completed, adress of the variable $IDENTIFIER.text;$code= READ ;$code+=\n; // new line after READ$code+= STOREG + + at + \n;}| WRITE ( expression ){$code = $expression.code+ WRITE + \n+ POP + \n;};WRITE : println;6READ : readln;5 BlocksIn order to deal with conditional structures and loops with several instructions, we needto be able to encapsulate a set of instructions in a block, so that we make a difference betweenthe instructions to execute inside the Conditional structure, and the others outside.Question. Add to the grammar the possibility to manipulate a block of instructions, encapsulatedbetween { and }. The beginning of the rule can be the following :block returns [ String code ]@init{ $code = new String ()}: // to be completed6 While LoopsLets enrich our language with while loops. The wanted syntax is the following, with conda boolean expression :while (cond)instructionsQuestion. Add the necessary rules to our grammar file. We are expecting that you allowthe two following forms.while (cond)// 1 single instruction.// or a block of instructionswhile (cond) {//several instructions}7 Conditional StructuresLets now add jumps to our language with the if . . . then else . . . construction. The intendedsyntax is the following (cond still a boolean expression) :if (cond)instructionthenelse instructionelseThe else is not mandatory. Also, as with the while instruction, the set of instructionsinstructionthen and instructionelse might be a single or a block of instructions.Question. Add the necessary rules for manipulating the if . . . then else . . . instruction.请加QQ:99515681 或邮箱:99515681@qq.com WX:codehelp
“
添加老师微信回复‘’官网 辅导‘’获取专业老师帮助,或点击联系老师1对1在线指导。