Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

js.scala: JavaScript as an embedded DSL in Scala

NotificationsYou must be signed in to change notification settings

js-scala/js-scala

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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.

Publications and talks

Setup

  1. Setupvirtualization-lms-core:
  • $ git clone git@github.com:TiarkRompf/virtualization-lms-core.git
  • $ cd virtualization-lms-core
  • $ sbt publish-local
  1. Clone the project and manage it using sbt:
  • $ cd ..
  • $ git clone git@github.com:js-scala/js-scala.git
  • $ cd js-scala
  • $ sbt
  1. Run the tests:
  • > test
  1. Publish it (if you want to use it in your project):
  • > publish-local
  1. Run the examples:
  • > project examples
  • > run

Use it in your project

  1. Add a dependency on js-scala 0.4-SNAPSHOT
  • libraryDependencies += "EPFL" %% "js-scala" % "0.4-SNAPSHOT"
  1. Use Scala 2.10.2-RC1 and set the Scala organization toorg.scala-lang.virtualized
  • scalaVersion := "2.10.2-RC1"
  • scalaOrganization := "org.scala-lang.virtualized"
  1. Set the-Yvirtualize compiler option
  • scalacOptions += "-Yvirtualize"

Further projects

  • 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.

Quick start

First, be sure to be familiar withLMS tutorials.

Write a program generator

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.

Generate JavaScript code

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;}

Go a bit further

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).

js-scala modules layout

The modules defined by js-scala generally stick to the following conventions:

  • language units are defined under thescala.js.language package (though some language units are already provided by LMS under thescala.virtualization.lms.common package) ;
  • implementations are defined under thescala.js.exp package. A language unitFoo is implemented by a module namedFooExp (another module defining optimizations can also be defined under the nameFooExpOpt) ;
  • code generators are defined under thescala.js.gen.js andscala.js.gen.scala packages, for JavaScript and Scala, respectively. A code generator for a language unitFoo has 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 termfun instead 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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors9


[8]ページ先頭

©2009-2025 Movatter.jp