Skip to content

Commit

Permalink
Add reflect ClassDef.apply
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasstucki committed Feb 18, 2022
1 parent d466f9f commit 1fbda34
Show file tree
Hide file tree
Showing 9 changed files with 101 additions and 1 deletion.
21 changes: 20 additions & 1 deletion compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala
Expand Up @@ -228,6 +228,10 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
end ClassDefTypeTest

object ClassDef extends ClassDefModule:
def apply(cls: Symbol, parents: List[Tree], body: List[Statement]): ClassDef =
val constr = ctx.typeAssigner.assignType(untpd.DefDef(nme.CONSTRUCTOR, Nil, tpd.TypeTree(dotc.core.Symbols.defn.UnitClass.typeRef), untpd.EmptyTree), cls.primaryConstructor)
tpd.ClassDefWithParents(cls.asClass, constr, parents, body)

def copy(original: Tree)(name: String, constr: DefDef, parents: List[Tree], selfOpt: Option[ValDef], body: List[Statement]): ClassDef = {
val dotc.ast.Trees.TypeDef(_, originalImpl: tpd.Template) = original
tpd.cpy.TypeDef(original)(name.toTypeName, tpd.cpy.Template(originalImpl)(constr, parents, derived = Nil, selfOpt.getOrElse(tpd.EmptyValDef), body))
Expand Down Expand Up @@ -260,6 +264,7 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler

object DefDef extends DefDefModule:
def apply(symbol: Symbol, rhsFn: List[List[Tree]] => Option[Term]): DefDef =
assert(symbol.isTerm, s"expected a term symbol but received $symbol")
withDefaultPos(tpd.DefDef(symbol.asTerm, prefss =>
xCheckMacroedOwners(xCheckMacroValidExpr(rhsFn(prefss)), symbol).getOrElse(tpd.EmptyTree)
))
Expand Down Expand Up @@ -1804,7 +1809,7 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
(x.prefix, x.name.toString)
end TermRef

type TypeRef = dotc.core.Types.NamedType
type TypeRef = dotc.core.Types.TypeRef

object TypeRefTypeTest extends TypeTest[TypeRepr, TypeRef]:
def unapply(x: TypeRepr): Option[TypeRef & x.type] = x match
Expand Down Expand Up @@ -2454,6 +2459,20 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
def requiredModule(path: String): Symbol = dotc.core.Symbols.requiredModule(path)
def requiredMethod(path: String): Symbol = dotc.core.Symbols.requiredMethod(path)
def classSymbol(fullName: String): Symbol = dotc.core.Symbols.requiredClass(fullName)

def newClass(owner: Symbol, name: String, parents: List[TypeRepr], decls: Symbol => List[Symbol], selfInfo: Option[TypeRepr]): Symbol =
val cls = dotc.core.Symbols.newNormalizedClassSymbol(
owner,
name.toTypeName,
Flags.EmptyFlags,
parents,
dotc.core.Scopes.newScope, // TODO remove from parameters of newNormalizedClassSymbol
selfInfo.getOrElse(Types.NoType),
dotc.core.Symbols.NoSymbol)
cls.enter(dotc.core.Symbols.newConstructor(cls, dotc.core.Flags.Synthetic, Nil, Nil))
for sym <- decls(cls) do cls.enter(sym)
cls

def newMethod(owner: Symbol, name: String, tpe: TypeRepr): Symbol =
newMethod(owner, name, tpe, Flags.EmptyFlags, noSymbol)
def newMethod(owner: Symbol, name: String, tpe: TypeRepr, flags: Flags, privateWithin: Symbol): Symbol =
Expand Down
3 changes: 3 additions & 0 deletions library/src/scala/quoted/Quotes.scala
Expand Up @@ -464,6 +464,7 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>

/** Methods of the module object `val ClassDef` */
trait ClassDefModule { this: ClassDef.type =>
@experimental def apply(cls: Symbol, parents: List[Tree /* Term | TypeTree */], body: List[Statement]): ClassDef
def copy(original: Tree)(name: String, constr: DefDef, parents: List[Tree /* Term | TypeTree */], selfOpt: Option[ValDef], body: List[Statement]): ClassDef
def unapply(cdef: ClassDef): (String, DefDef, List[Tree /* Term | TypeTree */], Option[ValDef], List[Statement])
}
Expand Down Expand Up @@ -3533,6 +3534,8 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
/** The class Symbol of a global class definition */
def classSymbol(fullName: String): Symbol

@experimental def newClass(owner: Symbol, name: String, parents: List[TypeRepr], decls: Symbol => List[Symbol], selfInfo: Option[TypeRepr]): Symbol

/** Generates a new method symbol with the given parent, name and type.
*
* This symbol starts without an accompanying definition.
Expand Down
4 changes: 4 additions & 0 deletions project/MiMaFilters.scala
Expand Up @@ -17,6 +17,10 @@ object MiMaFilters {
ProblemFilters.exclude[MissingClassProblem]("scala.compiletime.ops.long$"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#CompilationInfoModule.XmacroSettings"),
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#CompilationInfoModule.XmacroSettings"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),

// Private to the compiler - needed for forward binary compatibility
ProblemFilters.exclude[MissingClassProblem]("scala.annotation.since")
Expand Down
4 changes: 4 additions & 0 deletions tests/run-macros/newClass.check
@@ -0,0 +1,4 @@
Constructing foo
class Test_2$package$foo$1
Constructing bar
class Test_2$package$bar$1
21 changes: 21 additions & 0 deletions tests/run-macros/newClass/Macro_1.scala
@@ -0,0 +1,21 @@
import scala.quoted.*

inline def makeClass(inline name: String): Any = ${ makeClassExpr('name) }
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Any] = {
import quotes.reflect.*

val name = nameExpr.valueOrAbort
val parents = List(TypeTree.of[Object])
def decls(cls: Symbol): List[Symbol] = Nil

val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfInfo = None)

val clsDef = ClassDef(cls, parents, body = List('{println(s"Constructing ${$nameExpr}")}.asTerm))
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Object])

Block(List(clsDef), newCls).asExpr
// '{
// class `name`() { println("Constructing `name`") }
// new `name`()
// }
}
6 changes: 6 additions & 0 deletions tests/run-macros/newClass/Test_2.scala
@@ -0,0 +1,6 @@
@main def Test: Unit = {
val foo = makeClass("foo")
println(foo.getClass)
val bar = makeClass("bar")
println(bar.getClass)
}
4 changes: 4 additions & 0 deletions tests/run-macros/newClassExtends.check
@@ -0,0 +1,4 @@
Calling foo.foo
class Test_2$package$foo$1
Calling bar.foo
class Test_2$package$bar$1
31 changes: 31 additions & 0 deletions tests/run-macros/newClassExtends/Macro_1.scala
@@ -0,0 +1,31 @@
import scala.quoted.*

inline def makeClass(inline name: String): Foo = ${ makeClassExpr('name) }
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Foo] = {
import quotes.reflect.*

val name = nameExpr.valueOrAbort
val parents = List(TypeTree.of[Object], TypeTree.of[Foo])
def decls(cls: Symbol): List[Symbol] =
List(Symbol.newMethod(cls, "foo", MethodType(Nil)(_ => Nil, _ => TypeRepr.of[Unit])))

val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfInfo = None)
val fooSym = cls.declaredMethod("foo").head

val fooDef = DefDef(fooSym, argss => Some('{println(s"Calling ${$nameExpr}.foo")}.asTerm))
val clsDef = ClassDef(cls, parents, body = List(fooDef))
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Foo])

Block(List(clsDef), newCls).asExprOf[Foo]

// '{
// class `name`() extends Foo {
// def foo(): Unit = println("Calling `name`.foo")
// }
// new `name`()
// }
}

trait Foo {
def foo(): Unit
}
8 changes: 8 additions & 0 deletions tests/run-macros/newClassExtends/Test_2.scala
@@ -0,0 +1,8 @@
@main def Test: Unit = {
val foo: Foo = makeClass("foo")
foo.foo()
println(foo.getClass)
val bar: Foo = makeClass("bar")
bar.foo()
println(bar.getClass)
}

0 comments on commit 1fbda34

Please sign in to comment.