|
| 1 | +//> using options -experimental |
| 2 | + |
| 3 | +import scala.quoted.* |
| 4 | +import scala.annotation.StaticAnnotation |
| 5 | + |
| 6 | +class ScalaAnnotation(value: String) extends StaticAnnotation |
| 7 | + |
| 8 | +inline def makeClass(inline name: String): Any = ${ makeClassExpr('name) } |
| 9 | +private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Any] = { |
| 10 | + import quotes.reflect.* |
| 11 | + |
| 12 | + val name = nameExpr.valueOrAbort |
| 13 | + def decls(cls: Symbol): List[Symbol] = Nil |
| 14 | + val conMethodType = (classType: TypeRepr) => MethodType(Nil)((_: MethodType) => Nil, (_: MethodType) => classType) |
| 15 | + |
| 16 | + val javaAnnotSym = TypeRepr.of[JavaAnnot].typeSymbol |
| 17 | + val scalaAnnotSym = TypeRepr.of[ScalaAnnotation].typeSymbol |
| 18 | + |
| 19 | + val javaAnnotationDef = Apply(Select(New(TypeIdent(javaAnnotSym)), javaAnnotSym.primaryConstructor), List(Literal(StringConstant("string in a java annotation")))) |
| 20 | + val scalaAnnotationDef = Apply(Select(New(TypeIdent(scalaAnnotSym)), scalaAnnotSym.primaryConstructor), List(Literal(StringConstant("string in a scala annotation")))) |
| 21 | + |
| 22 | + val cls = Symbol.newClass( |
| 23 | + Symbol.spliceOwner, |
| 24 | + name, |
| 25 | + parents = _ => List(TypeRepr.of[Object]), |
| 26 | + decls, |
| 27 | + selfType = None, |
| 28 | + clsFlags = Flags.EmptyFlags, |
| 29 | + clsPrivateWithin = Symbol.noSymbol, |
| 30 | + clsAnnotations = List(javaAnnotationDef, scalaAnnotationDef), |
| 31 | + conMethodType, |
| 32 | + conFlags = Flags.EmptyFlags, |
| 33 | + conPrivateWithin = Symbol.noSymbol, |
| 34 | + conParamFlags = List(List()) |
| 35 | + ) |
| 36 | + |
| 37 | + val clsDef = ClassDef(cls, List(TypeTree.of[Object]), body = Nil) |
| 38 | + val newCls = |
| 39 | + Typed( |
| 40 | + Apply( |
| 41 | + Select(New(TypeIdent(cls)), cls.primaryConstructor), |
| 42 | + Nil |
| 43 | + ), |
| 44 | + TypeTree.of[Any] |
| 45 | + ) |
| 46 | + |
| 47 | + val res = Block(List(clsDef), newCls).asExpr |
| 48 | + |
| 49 | + Expr.ofTuple(res, Expr(res.show)) |
| 50 | + |
| 51 | + // { |
| 52 | + // @JavaAnnot("string in a java annotation") @ScalaAnnotation("string in a scala annotation") class name() extends java.lang.Object |
| 53 | + // (new name(): scala.Any) |
| 54 | + // } |
| 55 | +} |
0 commit comments