What are the annotees of a scala macro annotation?

2019-09-02 02:20发布

问题:

After spending quite sometime searching through scala documentations I have not found this particular bit of information. Or at least not phrased in a way I could easily understand or get any certainty out of.

I have this annotation:

class MyAnnotation extends StaticAnnotation {

  def macroTransform(annotees: Any*) = macro myImpl

}

And I have used it on two or more classes like this:

@MyAnnotation
class One {}

@MyAnnotation
class Two {}

I would like to know if the annotees will contain both the classes or if the macro will be executed twice (one for each instance of the annotation). Will I have?

annotess.map(_tree).toList == List(oneClassDef /*classdef of One*/, twoClassDef /*classdef of Two*/)
> true

Is it possible to make it so that the annotation trigger only one application of the macro with all the annotated classes in the annotees at once?

回答1:

Annottees only include the directly annotated member + an enclosing definition (class/trait) for a value/type parameter + a companion for the annotated member (or for the enclosing definition for a value/type parameter).

Unfortunately, it's virtually impossible to implement your request in the current namer/typer architecture of scalac (and, to the best of knowledge, in dotc as well), so I'd suggest a workaround - annotating a definition that encloses all the classes that you want to process.