Download PIMPL Organizing Files
Transcript
6.3. Contextual Analysis 6.3.1 Aalborg University Choice of visitor pattern for the compiler A way of traversing an AST must be chosen in order to decide if a given AST, which represents a program, conforms to the contextual rules of PIMPL. There are different ways to traverse an AST and some of them are described in this section. Lastly one of these are chosen to be the method used for the contextual analysis part of the compiler and later for the code generation part of the compiler. The object oriented approach dictates that a new method must be added to each node class for every type of traversal the AST must support. This approach is very intuitive if the developer has experience with object-oriented programming languages. Each new traversal will be placed in many different class files. This results in scattered code. The procedural method uses switch statements for traversing the AST. The code for each traversal in this approach is, unlike the object oriented approach, kept in one place. Depending on the AST this might cause the programmer to write more code than with other approaches. A Visitor approach makes it easy to evoke different methods on the nodes in the AST. A visitor pattern allows methods to be encapsulated in a visitor class, instead of having each node class implement its own methods. The project group decided that a visitor approach would be the best solution. Many different types of visitors exists, but the project group decided to use a variation of the Visitor pattern which exploits static overloading, because the chosen parser generator tool, JavaCC, provides a Java interface that follows this static overloading visitor approach. The PIMPL compiler uses three different visitors, one for AST transformation, one for contextual analysis, and one for code generation. The AST transformation visitor is a dynamic dispatch visitor variation which uses a single method to the apply its transformation, to the AST, to a Select group of Nodes. 6.3.2 Type checking Type checking is done in order to enforce the rules of the type system of the programming language. The type rules are in turn designed to prevent runtime errors. Type rules check the expected types of arguments, for both subprograms and operators, and specify what the resulting type should be. This check is done by utilizing a visitor, that traverses the trees nodes. An example of a visit method in the contextual analysis visitor of the PIMPL compiler is shown in listing 6.9. When the visitor reaches an IntConst node during the traversal of the AST, it will evoke a method that tries to parse an Int from the string in value in the node, and report an error if parseInt throws an exception. 77