- Notifications
You must be signed in to change notification settings - Fork15
js-scala/js-scala
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
js-scala is a Scala library providing composable JavaScript code generators as embedded DSLs. Generate (optimized) JavaScript code from Scala-like code:
importscala.js.language.JStraitJavaScriptGreetextendsJS {defgreet(name:Rep[String]):Rep[Unit]= { println("Hello,"+ name+"!") }}
greet is a JavaScript program generator producing a program that prints a message in the console:
functiongreet(x0){varx1="Hello, "+x0;varx2=x1+"!";varx3=console.log(x2);}
Note: some language units also support server-side code generation (see theQuick start section below), allowing code sharing between client and server sides.
- ECOOP 2012 paper (PDF) and slides (PDF)
- Scala Days 2012 talk
- mloc-js'13 talk (slides)
- GPCE'13 paper (PDF) andslides
- Setupvirtualization-lms-core:
$ git clone git@github.com:TiarkRompf/virtualization-lms-core.git$ cd virtualization-lms-core$ sbt publish-local
- Clone the project and manage it using sbt:
$ cd ..$ git clone git@github.com:js-scala/js-scala.git$ cd js-scala$ sbt
- Run the tests:
> test
- Publish it (if you want to use it in your project):
> publish-local
- Run the examples:
> project examples> run
- Add a dependency on js-scala 0.4-SNAPSHOT
libraryDependencies += "EPFL" %% "js-scala" % "0.4-SNAPSHOT"
- Use Scala 2.10.2-RC1 and set the Scala organization to
org.scala-lang.virtualized
scalaVersion := "2.10.2-RC1"scalaOrganization := "org.scala-lang.virtualized"
- Set the
-Yvirtualizecompiler option
scalacOptions += "-Yvirtualize"
play-js-validation uses this DSL to enable form validation code in Play 2.0 to be written once and checked on both client and server sides.
forest uses this DSL to enable HTML templates to be written once and shared between client and server sides, both for initial rendering and automatic updating.
First, be sure to be familiar withLMS tutorials.
Write your program generator in a trait extending the language units you want to use:
importscala.js.language.JS// JavaScript-like language unitimportscala.js.language.dom.Dom// DOM APItraitProgramextendsJSwithDom {defprintClicks()= {for (target<- document.find("#target")) { target.on(Click) { click=> println("click at ("+ click.offsetX+","+ click.offsetY+")") } } }}
TheProgram trait contains a methodprintClicks that describes a JavaScript program searching for an element with id “target”, attaching it a “click” event listener and printing the mouse coordinates on each click.
To generate a JavaScript program from the above program description, write a Scala application instantiating your program generator and creating a code generator with the corresponding language unit implementations:
importscala.js.exp.JSExp// JS language unit implementationimportscala.js.exp.dom.DomExp// Dom language unit implementationimportscala.js.gen.js.GenJS// JS JavaScript code generatorimportscala.js.gen.js.dom.GenDom// Dom JavaScript code generatorobjectGeneratorextendsApp {// instantiate the program generator with language unit implementationsvalprogram=newProgramwithJSExpwithDomExp// create a code generator for these language units and pass it the program as a parametervalgen=newGenJSwithGenDom {valIR: program.type= program }// emit the code of the program described by the printClicks method gen.emitExecution(program.printClicks(),new java.io.PrintWriter("printclicks.js"))}
The above code generator will print the following JavaScript program in fileprintclicks.js:
(function(){varx0=document.querySelector("#target");if(x0!==null){varx1=x0;x1.addEventListener('click',function(x2){varx3=x2.offsetX;varx4="click at ("+x3;varx5=x4+", ";varx6=x2.offsetY;varx7=x5+x6;varx8=x7+")";varx9=console.log(x8);},false);}varx13=undefined;}
Some language unit implementations also have a trait defining optimizations. When such a trait exists it is named like the language unit implementation trait with the additional suffixOpt. For instance, there is aDomExpOpt trait for theDom language unit. If you use it in the above example instead ofDomExp, it will generatedocument.getElementById("target") instead ofdocument.querySelector("#target").
Some language units also have Scala code generators, allowing code using them to be shared by the client-side and the server-side (see next section for more details on this).
The browser API is not exactly the same as the native API. It tries to be as most type safe as possible and sometimes uses shorter names (e.g.on instead ofaddEventListener).
The modules defined by js-scala generally stick to the following conventions:
- language units are defined under the
scala.js.languagepackage (though some language units are already provided by LMS under thescala.virtualization.lms.commonpackage) ; - implementations are defined under the
scala.js.exppackage. A language unitFoois implemented by a module namedFooExp(another module defining optimizations can also be defined under the nameFooExpOpt) ; - code generators are defined under the
scala.js.gen.jsandscala.js.gen.scalapackages, for JavaScript and Scala, respectively. A code generator for a language unitFoohas nameGenFoo.
A language unit is a trait usually named according to a concept (e.g.Arrays,Adts, etc.) or to a type suffixed by “Ops” (e.g.OptionOps,ListOps, etc.). Mix such traits in your code to import theirvocabulary. This vocabulary can consist of top-level functions (e.g.fun, provided by theFunctions language unit, orarray, provided byArrays), or methods implicitly added toRep[X] values where “X” is (generally) the name of the language unit without the trailingOps (e.g. theElementOps trait implicitly adds methods onRep[Element] values, theBooleanOps trait implicitly adds methods onRep[Boolean] values).
TheJsScala language unit defines a core language supporting the following concepts or types:
if,while,==,var, tuples (using Scala syntax) ;- “primitive types” (
Int,Long,Double,Float,Boolean),String,List; - functions (using the term
funinstead of Scala’sdef) ; println.
This trait has code generators for both Scala and JavaScript, meaning that you can generate Scala and JavaScript programs from the same code.
TheJS trait extendsJsScala with JavaScript specific language units: arrays, dynamic typing, regexps.
TheDom trait provides Web browsers APIs (e.g. thewindow anddocument objects, a selector API, etc.).
About
js.scala: JavaScript as an embedded DSL in Scala
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors9
Uh oh!
There was an error while loading.Please reload this page.