Question

I am trying to change a compiler plugin some other person wrote which runs directly after the typer and I want to generate code that throws an Exception.

The Exception class looks like this:

case class MyException(message: String) extends Exception(message)

In the actual code, this is an inner class, though.

I looked how he got the symbols of a fixed class and did it similarly, I don't know if there is a better way but here is how he did it:

val exceptionClass = MyException.getClass.getName
val exceptionName = if (exceptionClass.last == '$') exceptionClass.dropRight(1) else exceptionClass
val symbol = rootMirror.getModuleByName(newTermName(exceptionName))

To throw the exception, I did this:

import CODE._
THROW(symbol, Literal(Constant("My message")))

I think, the following are also equivalent (and yield equivalent behaviour)

Throw(symbol.tpe, Literal(Constant("My Message")))
Throw(NEW(symbol, Literal(Constant("My message"))))
Throw(New(symbol.tpe, Literal(Constant("My message"))))

But I got an exception:

== Enclosing template or block ==

Apply( // val <error>: <error> in class <error>
  new MyException.type."<init>" // val <error>: <error> in class <error>, tree.tpe=<error>
  Nil
)

== Expanded type of tree ==

TypeRef(TypeSymbol(class MyException extends ))

uncaught exception during compilation: scala.reflect.internal.Types$TypeError
error: scala.reflect.internal.Types$TypeError: MyException.type does not have a constructor
...

I suppose I somehow have to use "new" differently, does anyone know how this is done correctly?

Was it helpful?

Solution

Someone of the Scala mailing list told me the solution:

I should get the symbol differently, I need the symbol of the class, not of the module, the latter is used if it is an object to call methods on it etc, but we need the class here, so instead of

val symbol = rootMirror.getModuleByName(newTermName(exceptionName))

I write

val symbol = rootMirror.getClassByName(newTermName(exceptionName))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top