Skip to content

Allow macro annotation to transform companion #19676

Closed
@nicolasstucki

Description

@nicolasstucki

With the current definition of macro annotations, we can only modify the annotated definition. There exist use cases where we want to annotate a class and add/transform/check methods in the companion object, or vice-versa.

Proposed change

package scala.annotation
import scala.quoted.*

trait MacroAnnotation extends StaticAnnotation:
  /** Transforms a tree `definition` and optionally adds new definitions.
   *
   *  This method takes as an argument the `definition` that will be transformed by the macro annotation.
   *  It returns a non-empty list containing the modified version of the annotated definition.
   *  The new tree for the definition must use the original symbol.
   *  New definitions can be added to the list before or after the transformed definitions, this order
   *  will be retained. New definitions will not be visible from outside the macro expansion.
   *
+  *  For classes or objects annotated with a macro annotation, we also provide an optional `companion`
+  *  containing the class or object companion. It is `None` if the definition does not have a companion.
+  *  If `definition` represents the class, then the companion is the module class of the object; if the
+  *  `definition` is a module class, then the companion is the class itself. This companion can be
+  *  transformed in the same way as the `definition`. If transformed it should be added to the resulting
+  *  list of definitions.
   *
   *  ...
   */
  def transform(using Quotes)(
    definition: quotes.reflect.Definition
+   companion: Option[quotes.reflect.Definition]
  ): List[quotes.reflect.Definition]

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions