0

I have a ClassSymbol and want to generate a zero-argument method throwing ???. Here are my attempts:

Assume that object Test is the type we have ClassSymbol of.

I.

val sym = //the ClassSymbol
val tpe = tq"$sym.type"
q"def foo(): $tpe = ???"

Result:

[error]  stable identifier required, but Test.type found.

II.

val sym = //the ClassSymbol
val tpe = tq"${sym.name}.type"
q"def foo(): $tpe = ???"

Result:

[error]  found   : c.universe.TypeName
[error]  required: c.universe.TermName
[error]         val tpe = tq"${sym.name}.type"

III.

val sym = //the ClassSymbol
val tpe = tq"${TermName(sym.name.toString)}.type"
q"def foo(): $tpe = ???"

Result:

Compiles successfully

So I ended up using the method III which looks pretty scary.

Is there a "native" way to use ClassSymbol in a quasiquote?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Some Name
  • 8,555
  • 5
  • 27
  • 77

1 Answers1

2

We can save your approach II

val tpe = tq"${sym.name.toTermName}.type"

This is similar to III but without manual handling strings.

Also don't forget that besides quasiquotes you can always build trees with manual parsing

val tree = tb.parse(s"def foo(): ${sym.name}.type = ???") // for macros c.parse instead of tb.parse 

Regarding the "native" way, now it's better to use a ModuleSymbol

val sym = rm.moduleSymbol(Test.getClass)

or

val sym = typeOf[Test.type].termSymbol.asModule 

rather than ClassSymbol

val sym0 = rm.classSymbol(Test.getClass)

or

val sym0 = typeOf[Test.type].typeSymbol.asClass 

Testing:

val tpe = tq"$sym.type"
val tree = q"def foo(): $tpe = ???"
tb.typecheck(tree) // no exception

I used runtime reflection but for macros it's similar.

If you already have a ClassSymbol it can be converted to a ModuleSymbol

val sym = sym0.companionSymbol // not sym0.companion but .companionSymbol is deprecated

or

val sym = sym0.asInstanceOf[scala.reflect.internal.Symbols#ClassSymbol].sourceModule.asInstanceOf[ModuleSymbol]

or

val sym = sym0.owner.info.decl(sym0.name.toTermName)

Get the module symbol, given I have the module class, scala macro

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • 1
    Thanks. I guess that when using an arbitrary class type it should be tested for being a `Module` (`isModule`) before insterting the `.type` suffix. – Some Name Nov 01 '20 at 00:53