Starting from Scala 3.3.0-RC2, there appeared macro annotations (implemented by Nicolas Stucki).
Macro annotation (part 1) https://github.com/lampepfl/dotty/pull/16392
Macro annotations class modifications (part 2) https://github.com/lampepfl/dotty/pull/16454
Enable returning classes from MacroAnnotations (part 3) https://github.com/lampepfl/dotty/pull/16534
New definitions are not visible from outside the macro expansion.
The macro annotation adding auxiliary constructor should be the following:
build.sbt
scalaVersion := "3.3.0-RC3"
import scala.annotation.{MacroAnnotation, experimental}
import scala.quoted.*
object Macros:
@experimental
class entity extends MacroAnnotation:
def transform(using Quotes)(tree: quotes.reflect.Definition): List[quotes.reflect.Definition] =
import quotes.reflect.*
tree match
case ClassDef(name, constr, parents, selfOpt, body) =>
val constrSym = Symbol.newMethod(tree.symbol, "<init>", MethodType(Nil)(_ => Nil, _ => TypeRepr.of[Unit]))
val constrDef = DefDef(constrSym, _ => Some(
Apply(Select.unique(New(Inferred(tree.symbol.typeRef)), "<init>"), List('{0}.asTerm, '{null}.asTerm))
))
val res = List(ClassDef.copy(tree)(name, constr, parents, selfOpt, body :+ constrDef))
println(res.map(_.show))
res
case _ => report.errorAndAbort("@entity can annotate only classes")
import Macros.entity
import scala.annotation.experimental
object App:
@entity @experimental
class Student(val id: Long, val name: String)
//scalac: List(@scala.annotation.experimental @Macros.entity class Student(val id: scala.Long, val name: scala.Predef.String) {
// def this() = new App.Student(0, null)
//})
Macro Annotations in Scala 3
How to generate a class in Dotty with macro?
Scala 3 macro to create enum