[JSR308] A simple proposal for recursive annotations

Christian Haack chaack at cs.ru.nl
Sun Jun 14 04:13:42 EDT 2009


Jonathan Aldrich wrote:
> 
> As I think I've written to this list before, adding recursive 
> annotations--ideally in the simplest possible way--would be an enormous 
> gain in the power of the annotation system, which right now is 
> relatively hobbled.
> 

If the goal is minimizing the necessary extensions to the JLS and javac, 
I would propose to simply allow the type 'Annotation' as a return type 
for annotation methods. This would allow annotations of unbounded depth, 
even if the number of annotation types in a given program is fixed.

Consider, for instance, a program with two user-defined annotation types:

@interface Nil { }

@interface Cons {
   Annotation value();
}

With these two annotation types, we can represent all cons-lists as 
well-typed annotations (of type 'Annotation'):

@Nil, @Cons(@Nil), @Cons(@Cons(@Nil)), ...

Of course, the type 'Annotation' also has some junk members. For instance:

@Cons(@Override), @Cons(@Cons(@Retention))

Fortunately, such junk members are easily recognized by an annotation 
processor. The semantic checking of annotations would need to be partly 
handled by annotation processors, instead of completely by javac.

The advantage of this solution is that the extension to the JLS and 
javac would be extremely small. All that would be needed is allowing the 
type 'Annotation' as a return type for annotation methods, plus a 
restriction that prevents well-foundedness problems caused by the 
combination of recursive types and user-defined default values (see 
Section D.3.2 of the JSR-308 specification). To prevent this 
well-foundedness problem, I would suggest to simply forbid user-defined 
default values for annotation methods whose return type is 'Annotation'.

As an experiment, I have created a patch for the latest version of the 
JSR-308 compiler. Only 7 lines needed to be patched. In case you are 
interested, I have uploaded the patch to the URL below, which also 
contains some very simple tests, one of which is a variant of James 
Hunt's example from several days ago.

http://www.cs.ru.nl/~chaack/recursive-annotation-types

Christian



More information about the JSR308 mailing list