Search code examples
scalameta

Compile Time Parameter for Macro Expansion


I would like to write an annotation macro that adds an extends <sometype> to traits where <sometype> can be specified at compile time.

How can a compile time parameter be passed to a macro expansion? Ideally I would like to specify a command line argument at the compiler call.


Solution

  • Macro annotations don't have access to the command-line flags passed to scalac. However, one possible way to achieve this might be to use system properties.

    For example, in the macro annotation implementation

    // MyMacro.scala
    val someType = sys.props.getOrElse("myapp.sometype", ???)
    

    Then pass the type as a command line option

    // command-line
    scalac -Dmyapp.sometype=foobar Code.scala
    

    Similarly, it's possible to run sbt -Dsometype=foobar compile. However, note that the JVM process needs to start with the system property flag, so setting scalacOptions += "-Dsometype=foobar" may not work.