Bubble Foundry


Towards a Scala DSL for Javascript

by Peter.

Reposting from the Lift mailing list.

For some time know I’ve been thinking about how cool it’d be to be able to essentially write Javascript but with all the Scala goodiness behind the scenes. Lift already has abstractions for more common Javascript language elements, so I have suspected that it could be used as the basic for something that looked more like plain Javascript.

This evening I was looking at PhantomJS and realized that to use it for the type of work I need I would have to control it with lots of Javascript files generated on the fly. So, I finally sat down and hacked around. This is what I’ve come up with:

As you can see, for Javascript language features I’ve basically just put j_ before what are also reserved words in Scala. So, JsFalse becomes j_false. The same is true for break, continue, and return.

As you can see with j_if and j_for, those case classes are declared such that you get a more natural syntax, one approaching Javascript’s. For instance, you can directly call a JsVar with 0 to n parameters, without writing Call("var_name", params0, ...). I guess that the experimental Dynamic trait could be added to the pimped JsVar (RichJsVar, of course) but that’s probably going a bit far! ;-)

I’ve also added a bunch of implicits, both for my pimped classes but also to convert JsCmd to JsExp. Lift already has a conversion the other way around but there isn’t one in this direction. I’m not sure if there is no implicit for a good reason. Perhaps this will break things?

Where is this wonderful code, you ask? Why, it’s a simple Gist: https://gist.github.com/1028437!

I look forward to your comments!