1

I would like to generate scala classes based on some files. Placement of the files doesn't matter (it can be resources folder or files can be placed just near my scala source files).

How can I read them when scala macro is executed? (I use StaticAnnotation's inline def apply(defn: Any): Any method)

When I try to use resources, they can't be found (I suppose those resources can't be found because it's compile time and project is not compiled yet) I would like to read files placed right near my scala sources, but how can I get source file path when macro is executed?

Eugene Nacu
  • 1,613
  • 2
  • 14
  • 22
  • 1
    What have you already tried? Why not rather using source generator (SBT)? – cchantep Jan 18 '18 at 11:59
  • @cchantep I'm designing a library. So code generation better be available for sbt and maven. If i got it right, enabling macro generator in maven is straightforward - just enable paradise plugin. I'm considering different options currently - trying to figure out what's better – Eugene Nacu Jan 19 '18 at 08:47
  • Macro is a language feature, code generation is a developer tool, none is better, it depends on the case (there I won't use macro) – cchantep Jan 19 '18 at 10:16
  • yes, I see the difference ) Trying to figure out what will be better for my case. Currently it seems macro won't work good (paradise plugin is experimental and seems to be abandoned and won't be available in future versions of scala) according to this discussion: https://contributors.scala-lang.org/t/annotation-macros/1211/34 – Eugene Nacu Jan 20 '18 at 12:17
  • What did you find was best in the end? I'm considering something similar right now and have looked at code generation and macros and not sure what to do yet. – Luke Eller Mar 16 '20 at 03:12
  • 1
    @LukeEller I ended up with code generation – Eugene Nacu Mar 17 '20 at 16:38

1 Answers1

0

your project dir

val projectDir = System.getProperty("user.dir")

now you can access source file

val file = new File(s"$projectDir/src/resources/<SOURCES FILE>")

余杰水
  • 1,404
  • 1
  • 11
  • 14
  • That's not what I asked. For example, I have root sbt project with some sub-projects. Macro annotated classes are in sub-project, but "user.dir" will give me path of the root sbt project in this case. so, s"$projectDir/src/resources/" won't find resource needed – Eugene Nacu Jan 19 '18 at 08:49
  • maybe you can use `c.enclosingPosition.source.path`; it will return current file path :) – 余杰水 Jan 19 '18 at 09:22