scalacode-generationtemplate-haskelltreehugger

Code generation with Scala


When using the SBT toolchain in Scala, is it possible to write a task that will read a special part of the project's source to generate scala-code at compile time.

Any ideas or even articles/tutorials on this? I am looking for something rather similar to Template Haskell.


Solution

  • treehugger.scala is a library designed for code generation.

    import treehugger.forest._
    import definitions._
    import treehuggerDSL._
    
    val tree: Tree = Predef_println APPLY LIT("Hello, world!")
    
    println(tree)
    println(treeToString(tree))
    

    The above code prints two lines:

    Apply(Ident(println),List(Literal(Constant(Hello, world!))))
    println("Hello, world!")
    

    treehugger does generate an AST, but non-compliant to scalac's AST.