Skip to content

Commit d0bb8b6

Browse files
committed
Add reflect ClassDef.apply and Symbol.newClass
1 parent 84fc139 commit d0bb8b6

File tree

20 files changed

+391
-11
lines changed

20 files changed

+391
-11
lines changed

compiler/src/dotty/tools/dotc/core/Symbols.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,7 @@ object Symbols {
575575
def complete(denot: SymDenotation)(using Context): Unit = {
576576
val cls = denot.asClass.classSymbol
577577
val decls = newScope
578-
denot.info = ClassInfo(owner.thisType, cls, parentTypes.map(_.dealias), decls)
578+
denot.info = ClassInfo(owner.thisType, cls, parentTypes.map(_.dealias), decls, selfInfo)
579579
}
580580
}
581581
newClassSymbol(owner, name, flags, completer, privateWithin, coord, assocFile)

compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,11 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
230230
end ClassDefTypeTest
231231

232232
object ClassDef extends ClassDefModule:
233+
def apply(cls: Symbol, parents: List[Tree], body: List[Statement]): ClassDef =
234+
val untpdCtr = untpd.DefDef(nme.CONSTRUCTOR, Nil, tpd.TypeTree(dotc.core.Symbols.defn.UnitClass.typeRef), tpd.EmptyTree)
235+
val ctr = ctx.typeAssigner.assignType(untpdCtr, cls.primaryConstructor)
236+
tpd.ClassDefWithParents(cls.asClass, ctr, parents, body)
237+
233238
def copy(original: Tree)(name: String, constr: DefDef, parents: List[Tree], selfOpt: Option[ValDef], body: List[Statement]): ClassDef = {
234239
val dotc.ast.Trees.TypeDef(_, originalImpl: tpd.Template) = original
235240
tpd.cpy.TypeDef(original)(name.toTypeName, tpd.cpy.Template(originalImpl)(constr, parents, derived = Nil, selfOpt.getOrElse(tpd.EmptyValDef), body))
@@ -262,6 +267,7 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
262267

263268
object DefDef extends DefDefModule:
264269
def apply(symbol: Symbol, rhsFn: List[List[Tree]] => Option[Term]): DefDef =
270+
assert(symbol.isTerm, s"expected a term symbol but received $symbol")
265271
withDefaultPos(tpd.DefDef(symbol.asTerm, prefss =>
266272
xCheckMacroedOwners(xCheckMacroValidExpr(rhsFn(prefss)), symbol).getOrElse(tpd.EmptyTree)
267273
))
@@ -1806,7 +1812,7 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
18061812
(x.prefix, x.name.toString)
18071813
end TermRef
18081814

1809-
type TypeRef = dotc.core.Types.NamedType
1815+
type TypeRef = dotc.core.Types.TypeRef
18101816

18111817
object TypeRefTypeTest extends TypeTest[TypeRepr, TypeRef]:
18121818
def unapply(x: TypeRepr): Option[TypeRef & x.type] = x match
@@ -2456,6 +2462,20 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
24562462
def requiredModule(path: String): Symbol = dotc.core.Symbols.requiredModule(path)
24572463
def requiredMethod(path: String): Symbol = dotc.core.Symbols.requiredMethod(path)
24582464
def classSymbol(fullName: String): Symbol = dotc.core.Symbols.requiredClass(fullName)
2465+
2466+
def newClass(owner: Symbol, name: String, parents: List[TypeRepr], decls: Symbol => List[Symbol], selfType: Option[TypeRepr]): Symbol =
2467+
assert(parents.nonEmpty && !parents.head.typeSymbol.is(dotc.core.Flags.Trait), "First parent must be a class")
2468+
val cls = dotc.core.Symbols.newNormalizedClassSymbol(
2469+
owner,
2470+
name.toTypeName,
2471+
dotc.core.Flags.EmptyFlags,
2472+
parents,
2473+
selfType.getOrElse(Types.NoType),
2474+
dotc.core.Symbols.NoSymbol)
2475+
cls.enter(dotc.core.Symbols.newConstructor(cls, dotc.core.Flags.Synthetic, Nil, Nil))
2476+
for sym <- decls(cls) do cls.enter(sym)
2477+
cls
2478+
24592479
def newMethod(owner: Symbol, name: String, tpe: TypeRepr): Symbol =
24602480
newMethod(owner, name, tpe, Flags.EmptyFlags, noSymbol)
24612481
def newMethod(owner: Symbol, name: String, tpe: TypeRepr, flags: Flags, privateWithin: Symbol): Symbol =
@@ -2624,6 +2644,8 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
26242644
def companionClass: Symbol = self.denot.companionClass
26252645
def companionModule: Symbol = self.denot.companionModule
26262646
def children: List[Symbol] = self.denot.children
2647+
def typeRef: TypeRef = self.denot.typeRef
2648+
def termRef: TermRef = self.denot.termRef
26272649

26282650
def show(using printer: Printer[Symbol]): String = printer.show(self)
26292651

library/src/scala/quoted/Quotes.scala

Lines changed: 98 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,15 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
464464

465465
/** Methods of the module object `val ClassDef` */
466466
trait ClassDefModule { this: ClassDef.type =>
467+
/** Create a class definition tree
468+
*
469+
* @param cls The class symbol. A new class symbol can be created using `Symbol.newClass`.
470+
* @param parents The parents trees class. The trees must align with the parent types of `cls`.
471+
* Parents can be `TypeTree`s if they don't have term parameter,
472+
* otherwise the can be `Term` containing the `New` applied to the parameters of the extended class.
473+
* @param body List of members of the class. The members must align with the members of `cls`.
474+
*/
475+
@experimental def apply(cls: Symbol, parents: List[Tree /* Term | TypeTree */], body: List[Statement]): ClassDef
467476
def copy(original: Tree)(name: String, constr: DefDef, parents: List[Tree /* Term | TypeTree */], selfOpt: Option[ValDef], body: List[Statement]): ClassDef
468477
def unapply(cdef: ClassDef): (String, DefDef, List[Tree /* Term | TypeTree */], Option[ValDef], List[Statement])
469478
}
@@ -2534,6 +2543,11 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
25342543
def typeSymbol: Symbol
25352544
def termSymbol: Symbol
25362545
def isSingleton: Boolean
2546+
2547+
/** This type seen as if it were the type of a member of prefix type `self` declared in class `member.owner`.
2548+
*
2549+
* Also see `typeRef` and `termRef`
2550+
*/
25372551
def memberType(member: Symbol): TypeRepr
25382552

25392553
/** The base classes of this type with the class itself as first element. */
@@ -3543,19 +3557,73 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
35433557
/** The class Symbol of a global class definition */
35443558
def classSymbol(fullName: String): Symbol
35453559

3560+
/** Generates a new class symbol for a class with a parameterless constructor.
3561+
*
3562+
* Example usage:
3563+
* ```
3564+
* val name: String = "myClass"
3565+
* val parents = List(TypeTree.of[Object], TypeTree.of[Foo])
3566+
* def decls(cls: Symbol): List[Symbol] =
3567+
* List(Symbol.newMethod(cls, "foo", MethodType(Nil)(_ => Nil, _ => TypeRepr.of[Unit])))
3568+
*
3569+
* val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfInfo = None)
3570+
* val fooSym = cls.declaredMethod("foo").head
3571+
*
3572+
* val fooDef = DefDef(fooSym, argss => Some('{println(s"Calling foo")}.asTerm))
3573+
* val clsDef = ClassDef(cls, parents, body = List(fooDef))
3574+
* val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Foo])
3575+
*
3576+
* Block(List(clsDef), newCls).asExprOf[Foo]
3577+
* ```
3578+
* constructs the equivalent to
3579+
* ```
3580+
* '{
3581+
* class myClass() extends Object with Foo {
3582+
* def foo(): Unit = println("Calling foo")
3583+
* }
3584+
* new myClass(): Foo
3585+
* }
3586+
* ```
3587+
*
3588+
* @param parent The owner of the class
3589+
* @param name The name of the class
3590+
* @param parents The parent classes of the class. The first parent must not be a trait.
3591+
* @param decls The member declarations of the class provided the symbol of this class
3592+
* @param selfType The self type of the class if it has one
3593+
*
3594+
* This symbol starts without an accompanying definition.
3595+
* It is the meta-programmer's responsibility to provide exactly one corresponding definition by passing
3596+
* this symbol to the ClassDef constructor.
3597+
*
3598+
* @note As a macro can only splice code into the point at which it is expanded, all generated symbols must be
3599+
* direct or indirect children of the reflection context's owner.
3600+
*/
3601+
@experimental def newClass(parent: Symbol, name: String, parents: List[TypeRepr], decls: Symbol => List[Symbol], selfType: Option[TypeRepr]): Symbol
3602+
35463603
/** Generates a new method symbol with the given parent, name and type.
3547-
*
3548-
* This symbol starts without an accompanying definition.
3549-
* It is the meta-programmer's responsibility to provide exactly one corresponding definition by passing
3550-
* this symbol to the DefDef constructor.
3551-
*
3552-
* @note As a macro can only splice code into the point at which it is expanded, all generated symbols must be
3553-
* direct or indirect children of the reflection context's owner.
3554-
*/
3604+
*
3605+
* To define a member method of a class, use the `newMethod` within the `decls` function of `newClass`.
3606+
*
3607+
* @param parent The owner of the method
3608+
* @param name The name of the method
3609+
* @param tpe The type of the method (MethodType, PolyType, ByNameType)
3610+
*
3611+
* This symbol starts without an accompanying definition.
3612+
* It is the meta-programmer's responsibility to provide exactly one corresponding definition by passing
3613+
* this symbol to the DefDef constructor.
3614+
*
3615+
* @note As a macro can only splice code into the point at which it is expanded, all generated symbols must be
3616+
* direct or indirect children of the reflection context's owner.
3617+
*/
35553618
def newMethod(parent: Symbol, name: String, tpe: TypeRepr): Symbol
35563619

35573620
/** Works as the other newMethod, but with additional parameters.
35583621
*
3622+
* To define a member method of a class, use the `newMethod` within the `decls` function of `newClass`.
3623+
*
3624+
* @param parent The owner of the method
3625+
* @param name The name of the method
3626+
* @param tpe The type of the method (MethodType, PolyType, ByNameType)
35593627
* @param flags extra flags to with which the symbol should be constructed
35603628
* @param privateWithin the symbol within which this new method symbol should be private. May be noSymbol.
35613629
*/
@@ -3569,6 +3637,9 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
35693637
*
35703638
* Note: Also see reflect.let
35713639
*
3640+
* @param parent The owner of the /var/lazy val
3641+
* @param name The name of the val/var/lazy val
3642+
* @param tpe The type of the val/var/lazy val
35723643
* @param flags extra flags to with which the symbol should be constructed
35733644
* @param privateWithin the symbol within which this new method symbol should be private. May be noSymbol.
35743645
* @note As a macro can only splice code into the point at which it is expanded, all generated symbols must be
@@ -3582,7 +3653,10 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
35823653
* It is the meta-programmer's responsibility to provide exactly one corresponding definition by passing
35833654
* this symbol to the BindDef constructor.
35843655
*
3656+
* @param parent The owner of the binding
3657+
* @param name The name of the binding
35853658
* @param flags extra flags to with which the symbol should be constructed
3659+
* @param tpe The type of the binding
35863660
* @note As a macro can only splice code into the point at which it is expanded, all generated symbols must be
35873661
* direct or indirect children of the reflection context's owner.
35883662
*/
@@ -3644,9 +3718,11 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
36443718
*
36453719
* symbol.tree.tpe
36463720
*
3647-
* It should be replaced by the following code:
3721+
* It should be replaced by one of the following:
36483722
*
36493723
* tp.memberType(symbol)
3724+
* symbol.typeRef
3725+
* symbol.termRef
36503726
*
36513727
*/
36523728
def tree: Tree
@@ -3817,6 +3893,19 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
38173893

38183894
/** Case class or case object children of a sealed trait or cases of an `enum`. */
38193895
def children: List[Symbol]
3896+
3897+
/** Type reference to the symbol usable in the scope of its owner.
3898+
*
3899+
* To get a reference to a symbol from a specific prefix `tp`, use `tp.memberType(symbol)` instead.
3900+
*
3901+
* @pre symbol.isType returns true
3902+
*/
3903+
@experimental
3904+
def typeRef: TypeRef
3905+
3906+
/** Term reference to the symbol usable in the scope of its owner. */
3907+
@experimental
3908+
def termRef: TermRef
38203909
end extension
38213910
}
38223911

project/MiMaFilters.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ object MiMaFilters {
1919
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#CompilationInfoModule.XmacroSettings"),
2020
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.deriving.Mirror.fromProductTyped"),
2121
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.deriving.Mirror.fromTuple"),
22+
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
23+
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#ClassDefModule.apply"),
24+
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),
25+
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolModule.newClass"),
26+
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.typeRef"),
27+
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.typeRef"),
28+
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.termRef"),
29+
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.termRef"),
2230

2331
// Private to the compiler - needed for forward binary compatibility
2432
ProblemFilters.exclude[MissingClassProblem]("scala.annotation.since")
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import scala.quoted.*
2+
3+
inline def makeClass(inline name: String): Any = ${ makeClassExpr('name) }
4+
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Any] = {
5+
import quotes.reflect.*
6+
7+
val name = nameExpr.valueOrAbort
8+
val parents = List.empty[Tree] // BUG: first parent is not a class
9+
def decls(cls: Symbol): List[Symbol] = Nil
10+
11+
val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = Nil, decls, selfType = None)
12+
val clsDef = ClassDef(cls, parents, body = List())
13+
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Object])
14+
15+
Block(List(clsDef), newCls).asExpr
16+
17+
// '{
18+
// class `name`() {
19+
// def foo(): Unit = println("Calling `name`.foo")
20+
// }
21+
// new `name`()
22+
// }
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
def test: Any = makeClass("foo") // error
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import scala.quoted.*
2+
3+
inline def makeClass(inline name: String): Foo = ${ makeClassExpr('name) }
4+
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Foo] = {
5+
import quotes.reflect.*
6+
7+
val name = nameExpr.valueOrAbort
8+
val parents = List(TypeTree.of[Foo]) // BUG: first parent is not a class
9+
def decls(cls: Symbol): List[Symbol] =
10+
List(Symbol.newMethod(cls, "foo", MethodType(Nil)(_ => Nil, _ => TypeRepr.of[Unit])))
11+
12+
val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfType = None)
13+
val fooSym = cls.declaredMethod("foo").head
14+
15+
val fooDef = DefDef(fooSym, argss => Some('{println(s"Calling ${$nameExpr}.foo")}.asTerm))
16+
val clsDef = ClassDef(cls, parents, body = List(fooDef))
17+
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Foo])
18+
19+
Block(List(clsDef), newCls).asExprOf[Foo]
20+
21+
// '{
22+
// class `name`() extends Foo {
23+
// def foo(): Unit = println("Calling `name`.foo")
24+
// }
25+
// new `name`()
26+
// }
27+
}
28+
29+
trait Foo {
30+
def foo(): Unit
31+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
def test: Foo = makeClass("foo") // error

tests/run-macros/newClass.check

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Constructing foo
2+
class Test_2$package$foo$1
3+
Constructing bar
4+
class Test_2$package$bar$1
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import scala.quoted.*
2+
3+
inline def makeClass(inline name: String): Any = ${ makeClassExpr('name) }
4+
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Any] = {
5+
import quotes.reflect.*
6+
7+
val name = nameExpr.valueOrAbort
8+
val parents = List(TypeTree.of[Object])
9+
def decls(cls: Symbol): List[Symbol] = Nil
10+
11+
val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfType = None)
12+
13+
val clsDef = ClassDef(cls, parents, body = List('{println(s"Constructing ${$nameExpr}")}.asTerm))
14+
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Object])
15+
16+
Block(List(clsDef), newCls).asExpr
17+
// '{
18+
// class `name`() { println("Constructing `name`") }
19+
// new `name`()
20+
// }
21+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@main def Test: Unit = {
2+
val foo = makeClass("foo")
3+
println(foo.getClass)
4+
val bar = makeClass("bar")
5+
println(bar.getClass)
6+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Calling foo.foo
2+
class Test_2$package$foo$1
3+
Calling bar.foo
4+
class Test_2$package$bar$1
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import scala.quoted.*
2+
3+
inline def makeClass(inline name: String): Foo = ${ makeClassExpr('name) }
4+
private def makeClassExpr(nameExpr: Expr[String])(using Quotes): Expr[Foo] = {
5+
import quotes.reflect.*
6+
7+
val name = nameExpr.valueOrAbort
8+
val parents = List(TypeTree.of[Object], TypeTree.of[Foo])
9+
def decls(cls: Symbol): List[Symbol] =
10+
List(Symbol.newMethod(cls, "foo", MethodType(Nil)(_ => Nil, _ => TypeRepr.of[Unit])))
11+
12+
val cls = Symbol.newClass(Symbol.spliceOwner, name, parents = parents.map(_.tpe), decls, selfType = None)
13+
val fooSym = cls.declaredMethod("foo").head
14+
15+
val fooDef = DefDef(fooSym, argss => Some('{println(s"Calling ${$nameExpr}.foo")}.asTerm))
16+
val clsDef = ClassDef(cls, parents, body = List(fooDef))
17+
val newCls = Typed(Apply(Select(New(TypeIdent(cls)), cls.primaryConstructor), Nil), TypeTree.of[Foo])
18+
19+
Block(List(clsDef), newCls).asExprOf[Foo]
20+
21+
// '{
22+
// class `name`() extends Object, Foo {
23+
// def foo(): Unit = println("Calling `name`.foo")
24+
// }
25+
// new `name`()
26+
// }
27+
}
28+
29+
trait Foo {
30+
def foo(): Unit
31+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
@main def Test: Unit = {
2+
val foo: Foo = makeClass("foo")
3+
foo.foo()
4+
println(foo.getClass)
5+
val bar: Foo = makeClass("bar")
6+
bar.foo()
7+
println(bar.getClass)
8+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Calling Foo.foo with i = 1
2+
class Test_2$package$foo$1
3+
Calling Foo.foo with i = 1
4+
class Test_2$package$bar$1

0 commit comments

Comments
 (0)