jeudi 6 février 2020

Possible to identify/use Scala macros using reflection or similar?

I know that Scala macros can't be referenced in code which is compiled in the same compilation run as the macro itself.

I also know from empirical testing that if one has a codebase that does that (refer to a macro in the same project), if the reference to the macro is removed, the code is compiled, the reference to the macro is re-inserted, and the code is compiled again, the second compilation will succeed, and the macro-generated code will function correctly. I assume this is because the compiler sees the .class file for the macro from the first compilation run and uses that.

Is there a way to write code (using reflection or similar) which determines if code generated by a macro exists, and if so calls it? I'm thinking of something similar to How to invoke method on companion object via reflection?, but instead of invoking a normal method, invoking macro-generated code.

My goal is to have code which does one thing when compiled the first time, and a different thing when compiled every time after the first, without any changes to the source code in-between the two compilation runs. I understand that this is not a good practice. Builds should be deterministic in most cases. My interest is in whether it's possible to create Scala code like this as a technical curiosity.





Aucun commentaire:

Enregistrer un commentaire