My question might be contrived, and I would like to consider it more than a proof of feasibility than something recommended. To give you some context, I would try to have in an embedded DSL a different syntax than
val myVal = "someContent"
I would like to be able to do something like that:
assign("SomeContent","someVariable") => converted to
someVariable = "SomeContent"
and then later in the code, the variable is available. Typically we could have something like in the REPL:
assign("John","name")
println("Hello " + name)
I have been thinking that macros (or ScalaCompiler plugin but I think that here it is even more complicated) in order to do the trick. First I don't know if this is feasible being new to macros.
I have started with something simplistic considering that I would only manipulate String and I started with something like
def assign(content: String, targetVal: String):Unit = macro assignMacro
def assignMacro(c:Context)(content: c.Expr[String],
targetVal: c.Expr[String]):c.expr[Unit] = {
import c.universe._
c.Expr[Unit](ValDef(Modifiers(), TermName(targetVal.value),
TypeTree(), Literal(Constant(content.value)))
}
Unfortunately it seems to fail due to several mistakes
- First it complains when I try to create a new term name suggesting if I am sure then I should call eval of my expression. Unfortunately I am not sure ;) and if I try, it fails ;)
- If I replace this targetVal and content with constants like myVal and myContent, I get a second error message like compiler found and required Unit
I am a bit stuck. First is this possible ? I would guess yes ;) And how could I achieve this ?
Thanks for the help
Best Regards