Skip to content

Commit b8c61a5

Browse files
committed
New utility method tpd.AnonymousClass
As the name implies, this creates an anonymous class.
1 parent b4dc2d6 commit b8c61a5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/dotty/tools/dotc/ast/tpd.scala

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,34 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo {
244244
ta.assignType(untpd.TypeDef(cls.name, impl), cls)
245245
}
246246

247+
/** An anonymous class
248+
*
249+
* new parent { forwarders }
250+
*
251+
* where `forwarders` contains forwarders for all functions in `fns`.
252+
* `fns` must be non-empty. The class has the same owner as the first function in `fns`.
253+
* Its position is the union of all functions in `fns`.
254+
*/
255+
def AnonClass(parent: Type, fns: List[TermSymbol], methNames: List[TermName])(implicit ctx: Context): Block = {
256+
def methName(fnName: TermName): TermName = if (fnName == nme.ANON_FUN) nme.apply else fnName
257+
val owner = fns.head.owner
258+
val parents =
259+
if (parent.classSymbol.is(Trait)) defn.ObjectClass.typeRef :: parent :: Nil
260+
else parent :: Nil
261+
val cls = ctx.newNormalizedClassSymbol(owner, tpnme.ANON_FUN, Synthetic, parents,
262+
coord = fns.map(_.pos).reduceLeft(_ union _))
263+
println(i"creating anon class with parent $parent -> ${cls.info.parents}%, %")
264+
println(cls.classInfo.classParents)
265+
val constr = ctx.newConstructor(cls, Synthetic, Nil, Nil).entered
266+
def forwarder(fn: TermSymbol, name: TermName) = {
267+
val fwdMeth = fn.copy(cls, name, Synthetic | Method).entered.asTerm
268+
DefDef(fwdMeth, prefss => ref(fn).appliedToArgss(prefss))
269+
}
270+
val forwarders = (fns, methNames).zipped.map(forwarder)
271+
val cdef = ClassDef(cls, DefDef(constr), forwarders)
272+
Block(cdef :: Nil, New(cls.typeRef, Nil))
273+
}
274+
247275
def Import(expr: Tree, selectors: List[untpd.Tree])(implicit ctx: Context): Import =
248276
ta.assignType(untpd.Import(expr, selectors), ctx.newImportSymbol(ctx.owner, expr))
249277

0 commit comments

Comments
 (0)