









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










CS164 Programming Languages and Compilers Spring 2019
Assigned: Nov 3, 2020 Checkpoint: Nov 25, 2020 at 11:59pm Due: Dec 4, 2020 at 11:59pm
The three programming assignments in this course will direct you to develop a compiler for ChocoPy, a statically typed dialect of Python. The assignments will cover (1) lexing and pars- ing of ChocoPy into an abstract syntax tree (AST), (2) semantic analysis of the AST, and (3) code generation. For this assignment, you are to implement a RISC-V code generator for ChocoPy. This phase of the compiler takes as input the type-annotated AST of a semantically valid and well-typed ChocoPy program, and produces as output RISC-V assembly code. Section 5 describes the version of RISC-V that we will be using, as well as the execution environment used for grading. This assignment is also accompanied by the ChocoPy RISC-V implementation guide, which is a document that describes in detail the design decisions taken by the reference compiler. Unlike previous assignments, the starter code provided for this assignment is quite extensive. We encourage you to make full use of this code, since it will save you about half the development effort of building a code generator. Reading the accompanying implementation guide is essential to understanding the provided starter code. This assignment can get a bit tedious, so start early. However, implementing a code generator can be a very rewarding task, since you will (finally) be able to execute ChocoPy programs and observe their behavior.
The setup this is essentially the same as last time. You can use the same team repository and working directory as you did for Project 2.
$ cd team-repo $ git fetch shared $ git merge shared/proj3 -m "Start project 3 from skeleton" $ git push
(Again, only one member should do this, or all kinds of conflicts will result). Other team members will now be able to pull this to their own machines with
$ cd team-repo $ git pull
After these steps, the code for the project will be in the proj3 subdirectory of your local working directory. Run any of the commands referred to below in that subdirectory.
java -cp "chocopy-ref.jar:target/assignment.jar" chocopy.ChocoPy --pass=..s
--run --dir src/test/data/pa3/sample --test
Windows users should replace the colon between the JAR names in the classpath with a semicolon: java -cp "chocopy-ref.jar;target/assignment.jar" .... This applies to all java commands listed in this document.
The assignment repository contains a number of files that provide a skeleton for the project. Some of these files should not be modified, as they are essential for the assignment to compile correctly. Other files must be modified in order to complete the assignment. You may also have to create some new files in this directory structure. The list below summarizes each file or directory in the provided skeleton. They are all under the proj3 subdirectory.
string concatenation). Just put such routines in a directory src/main/asm/chocopy/pa and look to see how CodeGenBase uses the emitStdFunc routines.
The target architecture for this code generation assignment is RV32IM, which is the 32-bit version of RISC-V that supports basic integer arithmetic plus the multiplication (and division) extensions. In order to execute RISC-V code in a platform-independent manner, we will be using a version of the Venus simulator, which was originally developed by Keyhan Vakil. Venus dictates the execution environment, which includes the initial values of registers, the addresses of the various memory segments, and the set of supported system calls. Section 3 points to some documentation for Venus.
To support the goals of this project, our version of Venus has been modified—we refer to this variant as Venus 164. The modifications mainly try to make the assembly language conform to the one supported by the official GNU-based RISC-V toolchain.
The simulator is distributed both as a JAR in our instructional maven repo (for use with the auto-grader) and in web form to enable interactive debugging. The web version of Venus 164 is hosted at the following URL:
https://chocopy.org/venus.html
You can enter RISC-V assembly code in the editor and then switch to the simulator tab to run the program. You can add break-points and step through instructions one at a time to observe changes to the registers and to the memory. The CS164 staff cannot provide support on using the web UI.
The objective of this assignment is to build a code generator for ChocoPy that takes as input a typed AST corresponding to a ChocoPy program in JSON format, and produces as output a RISC-V assembly program that can execute in the Venus 164 execution environment.
Finally, the command
java -cp "chocopy-ref.jar:target/assignment.jar" chocopy.ChocoPy
--pass=rrr --run <chocopy_input_file>
will run the combined command with the reference implementation. In any command, you can omit the --out
The interface to your code generation assignment will be the static method StudentCodeGen.process(). The input to this method is a typed AST in JSON format, corresponding to a semantically valid and well-typed ChocoPy program. The typed AST will be in the same format that was used as the output format for the previous assignment. The field inferredType will be non-null for every expression in the AST that evaluates to a value. The output is expected to be a RISC-V assembly program, which is executed in the Venus 164 environment. The assembly program that your compiler generates need not match the program generated by the reference compiler. The reference compiler performs several optimizations, which you are not expected to match. Your goal is to independently produce an assembly program that implements the operational semantics given in the ChocoPy reference manual.
Testing is performed by executing the generated RISC-V program in Venus 164 and comparing the contents of the output stream with that produced by the reference-implementation-generated program. The program is expected to behave as per the operational semantics defined in the ChocoPy language manual: chocopy language reference.pdf. The output should contain a sequence of lines, where the ith line corresponds to the string representation of the str, int, or bool object provided as argument to the ith dynamic invocation of the predefined print function.
In this assignment, all compiled ChocoPy programs will have 32MB of memory to work with. The register gp will point to the beginning of the heap before the first top-level statement is executed. Garbage collection (GC) has not yet been implemented in the reference implementation; therefore, newly allocated objects block space for the entire remaining duration of the program. You are not expected to implement GC in this assignment, though the heap and object layouts have been designed in such a way that GC can be easily integrated. The tests used by the auto-grader require far less than 32MB of memory to execute.
In case of run-time errors, your program is expected to print an appropriate error message and exit with an appropriate exit code. The error messages and exit codes used by the reference implementation are described in chocopy implementation guide.pdf. Fortunately, you do not have to hand-code the error messages or corresponding exit codes. The errors corresponding to
invalid arguments to predefined functions and out-of-memory are generated by the code that has already been provided to you. For errors corresponding to operations on None, division by zero, and index out-of-bounds, we have provided you built-in routines that are emitted in the method CodeGenImpl.emitCustomCode(). Your generated programs can simply jump to one of these labels when the appropriate condition is met and the error message will be printed for you before aborting the program with an appropriate exit code. You do need to jump to these error handlers exactly when the appropriate condition is met. A run-time error is raised when one of the pre-conditions in the operational semantics fails to be true. For example, in the operational rule [dispatch], if the object on which a method is dispatched turns out to be the value None, then the second line fails to be true; therefore, the run-time error is reported after evaluating the object expression but before evaluating any of the arguments of the method call. These rules have been designed to conform to the error-reporting logic used by Python. You will not be tested on program executions that lead to arithmetic integer overflow or out- of-memory.
Before submitting your completed assignment, you must edit the README.md and provide the following information: (1) names of the team members who completed the assignment, (2) acknowl- edgements for any collaboration or outside help received, and (3) how many late hours have been consumed (refer to the course website for grading policy).
In this assignment, you are provided a significant amount of skeleton code. You are not strictly required to use this code; however, we strongly recommend that you do, since it performs about half of the work required to implement a code generator for ChocoPy. This section describes the design of the skeleton code. The code itself is also heavily documented using Javadoc-style comments. Although the entry point for this assignment is the static StudentCodeGen.process() method, this method does little more than handle input/output. Most of the heavy lifting is done within the CodeGenImpl class in the chocopy.pa3 package, which itself is a sub-class of CodeGenBase from the chocopy.common package. The CodeGenImpl class contains skeletons for emitting RISC-V code corresponding to top level statements and function bodies. You are expected to edit this skeleton and emit code corresponding to all types of program statements and expressions. In doing so, you will most likely want to use inherited fields and methods from the base class, CodeGenBase, which you cannot modify (but can override if needed).
The following tasks have already been performed by CodeGenBase:
in its analysis (you likely do not need to add to this hierarchy):
The class RiscVBackend contains a large number of methods for emitting RISC-V assembly instruc- tions to an output stream. The field backend defined within CodeGenBase references the backend whose output stream will be returned by the static method StudentCodeGen.process() as the as- sembly program produced by your ChocoPy compiler. The methods within RiscVBackend usually take the form of emitXYZ, where XYZ is a RISC-V instruction in uppercase. These methods are strongly typed: the arguments to these methods are expected to be objects of type Register (an enum defined within RiscVBackend), type Label (for addresses), or type Integer (for immediates). Each such method also expects a comment string as the last argument. For example, to generate the RISC-V instruction lw a0, 4(fp), you might execute the following Java code in CodeGenImpl:
backend.emitLW(A0, FP, 4, "Load something");
Similarly, to invoke a function whose descriptor is available in a variable say funcInfo, you might execute the following Java code in CodeGenImpl:
backend.emitJAL(funcInfo.getCodeLabel(), "Invoke function");
The class Label is heavily used throughout the provided code framework to represent labels in the generated assembly. A Label object simply encapsulates the name of a label as a string. Several instruction-emitting methods of the RiscVBackend expect a Label as an argument. Labels can be created in two ways: either by directly instantiating a new Label object with a specific string provided as an argument to its constructor, or by invoking the utility method generateLocalLabel() defined in CodeGenBase. The utility method generates a fresh label named label
This section answers some common questions that we anticipate may arise when working with the skeleton code.
Where can I find the label corresponding to entity X? Labels for built-in routines are present in fields of CodeGenBase. For example, the field allocLabel points to the label for the built- in routine alloc. Labels for class prototypes and dispatch tables are contained in the corresponding ClassInfo objects. Labels for function entry are contained in the corresponding FuncInfo objects. Labels for global variables are contained in the corresponding GlobalInfo objects.
How do I get a ClassInfo/FuncInfo object corresponding to X? The CodeGenBase has fields that reference ClassInfo objects corresponding to predefined classes. For example, the field objectClass references the class descriptor for class object, the field intClass references the descriptor for int, and so on. Similar fields are present for predefined functions, such as printFunc and lenFunc. In general, you can query the current symbol table to retrieve the descriptor for a class or a function that is currently in scope. One exception is the ClassInfo object for lists. The field listClass in CodeGenBase references a pseudo-class descriptor for lists, which is useful for getting a label that points to the prototype empty list object. There is no real list class in ChocoPy, and therefore there is no entry in any symbol table that references this descriptor.
errors inline with the code itself. It is intended to serve as a debugging aid while you develop your compiler, as an alternative to inspecting your JSON output manually. To run the web-based IDE: open a terminal, cd to the web directory of the assignment package, and run the following command: python -m WebCompiler 8000
Make sure that python corresponds to Python 3+. On some installations, you may have to specify the command python3 instead. This command starts a local web server at port 8000. Leave this process running while you use your Web IDE. Now, go to a Web browser and navigate to http://localhost:8000 (replace 8000 if you used a different port). You should see a web page with a code editor, and options to select your own compiler stages (i.e., the student’s version) or the reference compiler’s stages. Enter a ChocoPy program and click the button to compile to RISC-V. If the program is valid, then a new window will open up with the compiled RISC-V code pre-filled within the Venus Web-based simulator. In case of static errors, this window will close and you will be taken back to the code editor; hover your mouse over the red cross in the left margin to read the corresponding error message. The source locations associated with compiler errors in the JSON are used to highlight the errornous fragments of code in the editor. For the Web IDE to work, you must have the web server up and running, and you must have built the JARs using mvn clean package. The PA3 starter code does not bundle the student’s parser or semantic analysis. If you wish to use your own implementation for the first two stages instead of the reference implementation from your PA1 and PA2 repositories into the appropriate directories corresponding to packages pa1 and pa2 respectively.
Support The Web IDE is an experimental feature provided on a best-effort basis. While the in- structors appreciate bug reports for the IDE on Piazza, it is not an integral part of your assignment and as such we cannot guarantee that issues with the IDE (if any) will be addressed by the assign- ment submission deadline. It is provided only with the hope that it may be useful in avoiding some of the tedious aspects of inspecting the JSON manually. Additionally, you are welcome to send us feature requests or to share improvements to the UI on Piazza (you can edit web/index.html).
Part way through the assignment, on November 25, 2020, we will have a checkpoint to evalu- ate your progress. At that time, we want your code generation to work correctly on a small set of ChocoPy language features. In particular, we want your code to work on programs with only functions, variable access (global + local + nonlocal), integer and boolean operations, and simple control-structures: if-else and while. For the checkpoint, you are not required to have imple- mented object instantiation, attribute access, method dispatch, or operations on lists and strings. Appendix A lists the tests that you are expected to pass by the checkpoint. The same tests will also be included as part of the final submission, where you are expected to generate code for the full ChocoPy language. The checkpoint accounts for a substantial part of your overall grade for this assignment, so do not take it lightly. Section 9.1 describes how to submit your checkpoint. Section 10.1 describes the grading rubric. For the checkpoint, you do not need to create custom tests in the student contributed directory and do not need to write anything in the README apart from your names. There are no slip hours available for the checkpoint.
Submitting your checkpoint requires the following steps:
Submitting your final assignment requires the following steps:
The project as a whole is worth 30 points. Of these, 8 points will come from the checkpoint, 18 from the final submission, and 4 from a team assessment. The checkpoint and final submission apply to the entire team, and the team assessment is individual.
We count the number of successful simple tests from the file src/test/pa3/data/samples and bench- marks from the src/test/pa3/data/benchmarks directory, which exercise only the features re- quired for checkpoints. Each benchmark program tests a combination of a subset of ChocoPy fea- tures to perform a non-trivial task. No hidden tests will be used for the checkpoint. Appendix A lists the tests that we will run. The checkpoint scores up to 8 points, based on the proportion of tests passed.
We will publish only the scores for the top-5 teams in the leaderboard for each of these rankings. If you prefer to opt out of this listing, please let us know.
At the checkpoint, your code generator will be evaluated on the following 23 tests in src/test/data/pa3:
sample/literal_bool.py sample/op_cmp_int.py sample/literal_int.py sample/op_div_mod.py sample/literal_str.py sample/op_logical.py sample/id_global.py sample/op_mul.py sample/id_local.py sample/op_negate.py sample/var_assign.py sample/op_sub.py sample/call.py sample/stmt_if.py sample/call_with_args.py sample/stmt_while.py sample/nested.py sample/stmt_return_early.py sample/nested2.py benchmarks/exp.py sample/op_add.py benchmarks/prime.py sample/op_cmp_bool.py