Using Scalate to generate Scala code (like Visual Studio T4)

89 views
Skip to first unread message

Lorenzo

unread,
Feb 26, 2013, 10:56:04 AM2/26/13
to Scalate
Hello,

I need to generate some scala code as a pre-compilation phase (i.e.
something that takes input text files, and generate code files
_before_ the compile phase, much like lexers and parser generators -
think antlr and similar-)
In the Microsoft world, this is done using T4, which is basically
something really similar to the good old asp (text + tags which
contain code, whose result will be substituted after running the
code).
http://msdn.microsoft.com/en-us/library/vstudio/bb126445.aspx (looks
familiar? :) )

I came across scalate and while I understand this is not its main
purpose, I would like to use ssp in the same way as T4.
Something like this:

From hello.ssp
-------------
def printHello {
val greeting = <%= List("Hello", ", ", "world").mkString %>
println(greeting)
-------------
To hello.scala

def printHello {
val greeting = "Hello, world"
println(greeting)

I have tried this approach using a very simple command line program
(two lines, TemplateEngine and layout) and it works, but obviously I
would like it to be automated and turn it into a maven plugin, so I do
not need to remember to run the program before building the project.
Question #1: has anyone used scalate in this way? Is it a bad idea?
Question #2: I looked at the maven-scalate-plugin; the "precompile"
Mojo uses scalate types only through reflection. Why is it so? If I
want to introduce my new "transform" Mojo, should I follow the same
pattern? Programming using reflection is a pain I would avoid, if not
necessary.

Thank you,
Lorenzo Dematte'

Lorenzo Dematté

unread,
Feb 28, 2013, 2:52:37 AM2/28/13
to Scalate
More questions: what should I do with generated scala files?
In particular, where should I put them?
I see three ways of handling it:
1) generate the .scala files in the same directory of the .ssp files, keep them (maybe with a nice disclaimer at the beginning of the file, the classical "this code was generated, do not edit it, edit the .ssp instead, etc.)
2) generate the .scala files in a temp directory, add the dir to the maven sources path, destroy scala files after compilation
3) go all the way down: generate scala files in memory (string buffer), compile them with scala-compiler, place the class files in the target directory (where maven will pick them up)

I have tried the three approaches, and they all work, but I especially like #1 for two reasons: it is more similar to what T4 does, and you get IDE support! (code completion of classes in generated files, debugging, etc.)

What do you think? Which approach should I follow?

Lorenzo

Reply all
Reply to author
Forward
0 new messages