samedi 24 octobre 2020

How to recognize an anonymous class in a Scala macro?

I have a macro which enumerates class members. I would like to extend the macro so that it works recursively by enumerating inside into any class members in a form:

    object obj {
      var name = "value"
      var nested = new {
        var x = 0
      }
    }

In a runtime reflection I have used before transitioning to macros the corresponding test which works well for me is symbol.info.widen =:= typeOf[AnyRef], however this cannot work with macro, as in this can the type is not AnyRef, but its subclass (refinement).

When I print the type to the console, I get e.g.:

AnyRef{def x: Int; def x_=(x$1: Int): Unit}

When I list all base classes, I get:

List(, class Object, class Any)

I cannot use a test >:> typeOf[AnyRef], as almost anything would pass such test.

How can I test for this?

Here is the reflection version of the function, working fine:

  def listMembersNested_A(m: Any): Seq[(String, Any)] = {
    import scala.reflect.runtime.currentMirror
    import scala.reflect.runtime.universe._

    val anyMirror = currentMirror.reflect(m)
    val members = currentMirror.classSymbol(m.getClass).toType.members
    val items = for {
      symbol <- members
      if symbol.isTerm && !symbol.isMethod && !symbol.isModule
    } yield {
      val field = anyMirror.reflectField(symbol.asTerm)
      symbol.name.decodedName.toString.trim -> (if (symbol.info.widen =:= typeOf[AnyRef]) {
        listMembersNested_A(field.get)
      } else {
        field.get
      })
    }
    items.toSeq
  }

Its macro counterpart (it is a materialization macro):

    def impl[O: c.WeakTypeTag](c: blackbox.Context): c.Expr[ListMembersNested[O]] = {
      import c.universe._

      val O = weakTypeOf[O]

      val dive = O.members.sorted.collect {
        case f if f.isMethod && f.asMethod.paramLists.isEmpty && f.asMethod.isGetter =>
          val fName = f.name.decodedName.toString
          if (f.info.widen =:= typeOf[AnyRef]) { /// <<<<<< this does not work
            q"$fName -> listMembersNested(t.$f)"
          } else {
            q"$fName -> t.$f"
          }
      }
      val r = q" Seq(..$dive)"
      val membersExpr = c.Expr[Seq[(String, Any)]](r)

      reify {
        new ListMembersNested[O] {
          def listMembers(t: O) = membersExpr.splice
        }
      }
    }




Aucun commentaire:

Enregistrer un commentaire