Macros: knownDirectSubclasses broken into nested type?

I have a macro that lists the direct subtypes of a sealed tag:

import scala.reflect.macros.Context
import language.experimental.macros

object Checker {
  def apply[A]: Unit = macro applyImpl[A]

  def applyImpl[A: c.WeakTypeTag](c: Context): c.Expr[Unit] = {
    val tpe = c.weakTypeOf[A].typeSymbol.asClass
    require (tpe.isSealed)
    tpe.typeSignature // SI-7046
    require (tpe.knownDirectSubclasses.nonEmpty)

    import c.universe._
    c.Expr[Unit](reify {} .tree)
  }
}

Then it works:

sealed trait A
case class A1(i: Int) extends A

object NotNested {
  val nada = Checker[A]
}

But this fails:

object Nested {
  sealed trait A
  case class A1(i: Int) extends A

  val nada = Checker[A]
}

[error] java.lang.IllegalArgumentException: requirement failed: 
        Did not find sub classes

I thought I ran into SI-7046 , so I added a call tpe.typeSignature, but that doesn't help.

I need to work for this using Scala 2.10.2. Somehow I have to activate some additional type trees that will be initialized, I think?

+2
source share
1 answer

A possible workaround is as follows (do you think @EugeneBurmako).

val cls: ClassSymbol = sub.asClass

println(s"knownDirectSubclasses = ${cls.knownDirectSubclasses}")
// print "knownDirectSubclasses = Set()"

val subsub = cls.owner.typeSignature.decls.filter {
  case c: ClassSymbol =>
    cls != c && c.selfType.baseClasses.contains(cls)

  case _ => false
}

println(s"subsub = $subsub")
// print the actual sub classes
0
source

Source: https://habr.com/ru/post/1618471/


All Articles