Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any trick to use macros in the same file they are defined?

I have the following code:

object Macros {

  import scala.language.experimental.macros
  import scala.reflect.macros.blackbox

  def hello(): Unit = macro hello_impl

  def hello_impl(c: blackbox.Context)(): c.Expr[Unit] = {
    import c.universe._
    reify {
      println("Hello World!")
    }
  }
}


object Main {

  def main(args: Array[String]): Unit = {
    Macros.hello()
  }

}

It throws the following compilation error:

Error:(21, 17) macro implementation not found: hello
(the most common reason for that is that you cannot use macro implementations in the same compilation run that defines them)
    Macros.hello()
                ^

My question is: is there a way to "fool" the compiler in order to use macro expansions in the same file they are defined? My motivation is the following: I like to code in Scala, and lately I was submitting some problems in online judge Codeforces and some Scala constructions turned out to be very slow. So, I want to create some macro expansions in order to execute those constructions fast. But I cannot submit more than one file.

Thanks!

like image 544
ale64bit Avatar asked Jan 13 '15 10:01

ale64bit


1 Answers

At the moment, this is not possible in production releases of Scala 2.10 and 2.11. We might be able to achieve this with scala.meta, but that's well in the future.

like image 181
Eugene Burmako Avatar answered Nov 15 '22 22:11

Eugene Burmako