Compile Time Parameter for Macro Expansion
Asked Answered
D

1

1

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.

Defense answered 23/3, 2017 at 7:28 Comment(0)
D
1

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.

Defant answered 14/4, 2017 at 22:40 Comment(3)
I updated the answer to mention that scalacOptions += "-Dfoobar=yyy" may not work, contrary to a note in my original answerFinicky
Have you guys tried javaOptions += "-Dfoobar=yyy"?Winegar
See github.com/scalameta/scalameta/issues/… for related discussions and an alternative workaround to use sys.propsFinicky

© 2022 - 2024 — McMap. All rights reserved.