Package Templates: A Definition by Semantics-Preserving Source-to-Source Transformations to Efficient Java Code

Eyvind W. Axelsen and Stein Krogdahl

Package Templates (PT) is a mechanism designed for writing reusable modules, called templates, each consisting of a set of classes that can be adapted to their use in a program through compile-time specialization. A template must be instantiated in a program before its classes can be used. The mechanism supports type-safe renaming, merging, type parameterization and refinement in the form of static additions and overrides that are orthogonal to the corresponding concepts of ordinary inheritance.

In this paper, we consider PT as an extension to Java, and a PT program will then consist of a number of Java packages and templates, where templates are instantiated in packages or other templates. Our aim and main contribution is to define the meaning of such a program, and to show that this definition is consistent. We first show this for a core subset of PT, C-PT, and define a set of source-to-source transformations for converting C-PT programs to plain Java programs using semantics we have described informally in previous papers. We can then define the meaning of a C-PT program in terms of the resulting Java program. Thus, we have to verify that the transformations will always convert a legal C-PT program to a legal Java program. Finally, we briefly discuss how this approach can be extended to full PT.

A main challenge is to preserve externally visible names (for classes, methods and fields), and at the same time prevent unwanted subsequent rebindings caused e.g. by overload resolution in the Java compiler. Names that are bound to declarations in a template should not be rebound to different declarations by subsequent compositions or adaptions.

In addition to defining the runtime semantics of PT constructs in terms of their translation to Java, the transformation rules can also be seen as a high-level approach to how a compiler for this language might be implemented.