Expressive and safe static reflection with MorphJ

Shan Shan Huang, Yannis Smaragdakis. Expressive and safe static reflection with MorphJ. In Rajiv Gupta, Saman P. Amarasinghe, editors, Proceedings of the ACM SIGPLAN 2008 Conference on Programming Language Design and Implementation, Tucson, AZ, USA, June 7-13, 2008. pages 79-89, ACM, 2008. [doi]

Abstract

Recently, language extensions have been proposed for Java and C# to support pattern-based reflective declaration. These extensions introduce a disciplined form of meta-programming and aspect-oriented programming to mainstream languages: They allow members of a class (i.e., fields and methods) to be declared by statically iterating over and pattern-matching on members of other classes. Such techniques, however, have been unable to safely express simple, but common, idioms such as declaring getter and setter methods for fields.

In this paper, we present a mechanism that addresses the lack of expressiveness in past work without sacrificing safety. Our technique is based on the idea of nested patterns that elaborate the outer-most pattern with blocking or enabling conditions. We implemented this mechanism in a language, MorphJ. We demonstrate the expressiveness of MorphJ with real-world applications. In particular, the MorphJ reimplementation of DSTM2, a software transactional memory library, reduces 1,107 lines of Java reflection and bytecode engineering library calls to just 374 lines of MorphJ code. At the same time, the MorphJ solution is both high level and safer, as MorphJ can separately type check generic classes and catch errors early. We present and formalize the MorphJ type system, and offer a type-checking algorithm.