






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!







CS143 Handout 21 Autumn 2007 October 31, 2007
The Goal In the third programming project, your job is to implement a semantic analyzer for your compiler. We're now at the penultimate phase of the front-end. If we confirm the source program is free from compile-time errors, we're ready to generate code! Your semantic analyzer will traverse your parse tree (as many times as you like, incidentally) and validate that the semantic rules of the language are being respected, printing appropriate error messages for violations. What kind of rules are being verified? Lots of type checking, for one. Arithmetic operations require numbers. The actual parameters in a call must be compatible with the formal parameters. Variables must be declared and can only be used in ways that are acceptable for the declared type. The test expression used in an if statement must evaluate to a Boolean value. In addition to type checking, there are other rules: new declarations don't conflict with earlier ones, access control on class fields, break statements only appear in loops, and so on. One of the more interesting and worthwhile parts of the assignment is thinking through what is the best way to report various errors, so as to most help the programmer fix the mistake and move on. Scope Checkpoint: Thursday, November 8th^ at 11:59 p.m. Everything: Thursday, November 15th^ at 11:59 p.m. This assignment has a bit more room for design decisions than the previous assignments. Your program will be considered correct if it verifies the semantic rules and reports appropriate errors, but there are various ways to go about accomplishing this and ultimately how you structure things is up to you. There is no definitive way, but there are good and bad choices. Part of your job is brainstorming your options, making thoughtful decisions, and documenting your reasons. Your finished submission will have a working semantic analyzer that reports all varieties of errors. Given that semantic analysis is a bigger job than the scanner or parser, we have plotted a "checkpoint" along the way. At the checkpoint, your analyzer needs to show it can handle errors related to scoping and declarations, because these form the foundation for the later work. We’ll try to identify any issues and/or bad design decisions right away so you don’t find yourself trapped after a huge time investment. Past students speak of the semantic analyzer project in hushed and reverent tones. For many, PP3 makes the first two programming projects seem like elementary school math tests. Although an expert procrastinator can build a scanner or a parser the night
before, a one night shot at PP3 is not recommended. Give yourself plenty of time to work through the issues, ask questions, and thoroughly test your project. In particular, you need to build a solid and robust foundation for your checkpoint to ensure you will be able to complete all the tasks of semantic analysis by the final due date. Decaf’s Semantic Rules Before you embark on your semantic analysis journey, you should know the rules! Review the typing rules, scoping rules, and other restrictions as outlined in the specification handout. Your compiler is responsible for reporting any and all transgressions. For each requirement given in the spec, you may want to consider what information you will need to gather to be able to check that requirement and when and where that checking is handled. Reporting Errors Running a semantically correct program through your compiler should not produce any output at this stage. However, when a rule is violated, you are responsible for printing an appropriate message for each error. Your compiler should not stop after the first error, but instead continue checking the rest of the parse tree. You should use our provided error-reporting facility for printing error messages. ReportError will identify the line number and print the source text, underlining the particular section in error. The line that follows is a message describing the problem. *** Error on line 9 here is the offennddnig line with the troubling section underlined ^^^^^^^^^^^ Misspelled words are not allowed in Decaf programs! If you remember back to PP1, each token's location was placed in yylloc by the scanner. yacc then tracked the location of each symbol on the parse stack using @1 , @2 , etc. As part of PP2, you were storing locations with the parse tree nodes, but at the time you may not have realized the eventual purpose was for semantic analysis. Those locations are used to provide the context for the error and precisely point out where the trouble is. Devising clear wording for all the various error situations is actually trickier than it sounds. (Think of all the confusing messages you've seen: g++ error messages, for instance. Oy!) The best compilers have a plethora of specialized error messages, each used in a very particular situation. However, in the interest of keeping things manageable, we will adopt a small set of fairly generic error messages and use each in a variety of contexts.
Used for a class that claims to implement an interface but fails to implement one or more of the required methods. *** 'this' is only valid within class scope Used to report use of this outside class scope. *** Incompatible operands: double * string *** Incompatible operand:! int[] Used to report expressions with operands of inappropriate type. Assignment, arithmetic, relational, equality, and logical operators all use the same messages. The first is for binary operators, the second for unary. *** [] can only be applied to arrays *** Array subscript must be an integer *** Size for NewArray must be an integer Used to report incorrectly formed array subscript expressions or improper use of the NewArray built-in. *** Function 'Winky' expects 4 arguments but 3 given *** Incompatible argument 2 : string given, string[] expected *** Incompatible argument 3 : double given, int/bool/string expected Used to report mismatches between actual and formal parameters in a function call. The last one is a special-case message used for incorrect argument types to the Print built-in function. *** Cow has no such field 'trunk' *** Cow field 'spots' only accessible within class scope Used to report problems with the dot operator. Field means either variable or method. The first message reports to an attempt to apply dot to a non-class type or access a non-existent field from a class. The last is used when the field exists but is not accessible in this context. *** Test expression must have boolean type *** break is only allowed inside a loop *** Incompatible return: int given, void expected Used to report improper statements. We have deliberately tried to provide blanket error messages rather than enumerate distinct messages for all the errors. For example, the "incompatible operands" message is used when the % operator is applied to two string s or when assigning null to a double variable. This will help reduce the number of different errors you need to emit.
Error Recovery You will need to determine the appropriate action for your compiler to take after an error. The goal is to report each error once and recover in such a way that few or no further errors will result from the same root cause. For example, if a variable is declared of an undeclared named type, after reporting the error, you might be flexible in the rest of the compilation in allowing that variable to be used. Assume that once the declaration is fixed, it is likely the later uses of it will be correct as well. There is some guesswork about how to proceed. If you encounter a second declaration that conflicts with the first, do you keep the first and discard the second? Replace the first with the second? Is one strategy more likely to cause fewer cascading errors later? What about if you see a declaration with a mangled type or a completely undeclared variable? Should you try to guess the intended type from the surrounding context? Should you mark the variable as having an error type and use that status to suppress additional errors? How will you constrain errors from tainting the rest of the context, such as adding five operands where the first is a string? Ideally, you want to continue checking everything else that you can, while suppressing any cascading errors that result from the first error, i.e. those errors that would most likely be fixed if the original error were fixed. A few examples might help. Consider b[4] where b is undeclared. You report about b , but should you also report that you can’t apply brackets to a non-array type? If you assume that if b was supposed to have been declared of the needed array type, the second would also be fixed. What about b[4] + 5? Again, if you assume the missing declaration was an int array, this should be fine, so it is another cascading error that should be ignored. What about b[4.5] = 10? b is still undeclared, but the array subscript is also not right. Fixing the declaration of b won't fix the array subscript problem, so there are two errors to report. Now consider b[4.5] = 1 + 4.0. The error on the right side is yet another distinct error (co-mingled int and double ) and fixing the left hand side will not fix that error, so there are three errors to report. The idea is that each distinct error that requires an independent action to correct gets its own error message, but those errors due to the same root cause are not re-reported. It will come down to judgment calls on the fringe cases. It will be up to you to make decisions and document your reasoning. Think about it carefully, try experimenting with some C++/Java compilers (competitive analysis!), decide what you think is right, and explain your strategy in your README.
come in handy for managing symbol tables and scoping information. Read the .h file to learn more about its facilities Implementation Hints For the checkpoint, you need to implement store declarations, manage scopes, and report declaration errors. Here is a quick sketch of the tasks that need to be performed for the milestone:
behaved. If you have any questions about the specification of Decaf, be sure to ask!
The README Your README file is expected to briefly explain your design decisions. Sketch how your code is structured, and explain why you believe the design is a good one (i.e. why it leads to a correct and robust semantic analyzer). You should also document the decisions you made regarding semantic error handling and anything we should know about your submission in order to properly test it. Grading The checkpoint is worth 25 points. We will use this milestone to check your progress, by running your submission through a set of tests, diff'ing your output to our solution. We will report any discrepancies back to you as feedback so you can address these issues before the final submission. The checkpoint deadline is firm—in order to get quick turnaround, we cannot accept any late submissions for the checkpoint. We will grade the checkpoint on a strictly pass/marginal pass/fail basis: a submission that works correctly on all or most of our tests will receive full credit (25 points), one that succeeds on at least half our tests will receive about half credit, otherwise it is a zero. Not hitting the checkpoint is a sad (and totally avoidable) situation—you will have to do that work for the final submission anyway, and you will be bummed if you've lost your chance to earn 25 free points. Don't let this happen to you! The final PP3 submission is worth 100 points. Most of the points are allocated for correctness, but we will also evaluate your design decisions (as described in your README ) and the cleanliness and efficacy of your implementation. We will diff your output against our solution as a first pass, expecting that we will likely have made similar choices for most situations, but we will also be examining your output manually. The chief criteria we will use is whether your output makes sense from the point of view of a programmer using your compiler. Extension Ideas As always, there are lots of ways in which you could extend the project. Here are a few ideas to get you started. If you’re in doubt about how much extra credit a given project would be worth, you could ask us for an estimate.