1 What is Moby?
2 Running Moby from Dr Scheme
3 API
3.1 World
js-big-bang
on-draw
3.2 World Examples
stop-when
on-redraw
3.2.1 Types
js-div
js-p
js-button
js-button*
js-text
js-input
js-bidirectional-input
get-input-value
js-img
3.2.2 Stimulus Handlers
on-tick
on-tick*
on-shake
on-shake*
on-location-change
on-location-change*
on-tilt
on-tilt*
on-acceleration
on-acceleration*
3.2.3 Effects
make-effect: none
make-effect: beep
make-effect: play-sound
make-effect: stop-sound
make-effect: pause-sound
make-effect: set-sound-volume
make-effect: raise-sound-volume
make-effect: lower-sound-volume
make-effect: play-dtmf-tone
make-effect: set-wake-lock
make-effect: release-wake-lock
make-effect: send-sms
make-effect: pick-playlist
3.3 API Extensions
get-url
location-distance
xml->s-exp
define-struct
4 Developer details
4.1 Dependencies
4.2 Installing from Developer Sources
4.3 Running Moby from the command line
4.4 Compiler
4.4.1 An example
4.5 Runtime
4.6 Ugly Hacks
5 Appendix
5.1 Bindings from ASL
5.2 Unimplemented forms
Version: 4.2.2

Moby: the Moby Scheme Compiler

1 What is Moby?

Moby is a project from the PLT Scheme team. The Moby compiler consumes Advanced Student Language (ASL) programs that use World primitives, and produces applications for mobile platforms. The current prototype supports desktop browsers and smartphones. Our long-term goal is to make Scheme the premiere reactive scripting language for mobile phones.

Shriram Krishnamurthi presented the ideas behind Moby at ILC 2009 in his talk The Moby Scheme Compiler for Smartphones.

2 Running Moby from DrScheme

To use Moby from DrScheme, create a file in the Module language, and at the top of your program, include the following language line:

  #lang planet dyoo/moby:1

followed by the program. For example, running the program:

  #lang planet dyoo/moby:1
  (define initial-world 0)
  (js-big-bang initial-world (on-tick 1 add1))

will invoke a web browser, which should show the running program on a web page. The page should also provide links to download packages of the compiled program.

3 API

3.1 World

The Moby language supports reactive World-style programming; the reactive libraries allow one to write interactive web sites that work with the DOM as well as CSS stylesheets.

As an example,
  (js-big-bang 0
               (on-tick 1 add1))
uses 0 as an initial world, and establishes an on-tick handler that increments the world after every second.

(js-big-bang a-world handlers ...)  void
  a-world : world
  handlers : handler?
A Moby program may start a reactive computation with js-big-bang. The rest of the arguments hook into the reactive computation. One instance of a handler is on-tick, which registers a function to update the world on a clock tick.

In the absence of an on-draw or on-redraw handler, js-big-bang will show the current state of the world; on transitions, the world is re-drawn to screen.

(on-draw to-dom to-css)  scene
  to-dom : (world -> (DOM-sexp))
  to-css : (world -> (CSS-sexp))
One of the main handlers to js-big-bang is on-draw, which controls how the world is rendered on screen. The first argument computes a rendering of the world as a DOM tree, and the second argument computes that tree’s styling.

3.2 World Examples

Example 1:

The following will render the world as a paragraph of text, styled with a font-size of 30. Whenever the world is changed due to a stimulus, on-draw is called to re-draw the world.

  (js-big-bang 0 ; initial world
  
                ; the dom tree renderer
                (on-draw
                (lambda (w)
                  (list (js-p '(("id" "myPara")))
                        (list (js-text "hello world"))))
  
                ; the css renderer
                (lambda (w)
                  '(("myPara" ("font-size" "30"))))))

Example 2:

The following will show a logo and an input text field. Whenever the number in the text is changed, the world will reflect that change.

  (define (form-value w)
    (format "~a" w))
  
  (define (update-form-value w v)
    (string->number v))
  
  (define elt
    (js-bidirectional-input "text" form-value update-form-value))
  
  (define (draw w)
    (list (js-div)
          (list (js-img "http://plt-scheme.org/logo.png"))
          (list elt)
          (list (js-p '(("id" "aPara")))
                (list (js-text (format "~a" w))))))
  
  (define (draw-css)
    '(("aPara" ("font-size" "50px"))))
  
  (js-big-bang 0
               (on-draw draw draw-css))

(stop-when stop?)  handler?
  stop? : (world -> boolean)
When the world should be stopped – when stop? applied to the world produces true – then the js-big-bang terminates.

(on-redraw hook)  handler?
  hook : (world -> scene)
For simple applications, on-redraw is sufficient to draw something graphical.

Example:

The following program shows a ball falling down a scene.

  ; Simple falling ball example.  A red ball falls down the screen
  ; until hitting the bottom.
  
  ; The dimensions of the screen:
  (define WIDTH 320)
  (define HEIGHT 480)
  
  ; The radius of the red circle.
  (define RADIUS 15)
  
  ; The world is the distance from the top of the screen.
  (define INITIAL-WORLD 0)
  
  ; tick: world -> world
  ; Moves the ball down.
  (define (tick w)
    (+ w 5))
  
  ; hits-floor?: world -> boolean
  ; Returns true when the distance reaches the screen height.
  (define (hits-floor? w)
    (>= w HEIGHT))
  
  ; We have some simple test cases.
  (check-expect (hits-floor? 0) false)
  (check-expect (hits-floor? HEIGHT) true)
  
  ; render: world -> scene
  ; Produces a scene with the circle at a height described by the world.
  (define (render w)
    (place-image (circle RADIUS "solid" "red") (/ WIDTH 2) w
                 (empty-scene WIDTH HEIGHT)))
  
  ; Start up a big bang, 15 frames a second.
  (js-big-bang INITIAL-WORLD
               (on-tick 1/15 tick)
               (on-redraw render)
               (stop-when hits-floor?))

3.2.1 Types

A dom-sexp describes the structure of a web page:

  dom-sexp = (list dom-element dom-sexp ...)

a css-sexp describes the structure of a page’s styling:

  css-sexp = 
(listof (cons (or dom-element string)
              (listof (list string string))))

An attrib is a:
  attrib = (list string string)

Each of the dom-elements can take in an optional attribute list to assign to the new dom element; the common useful attribute is a key-value binding for an "id", which can be used to identify an element in the css-drawing function.

Here are examples of a dom-expr and a css-sexp.
  (define a-dom-sexp (list (js-div '(("id" "main-div")))
                           (list (js-text "Hello world"))))
  
  (define a-css-sexp (list (list "main-div"
                                 (list "background" "white")
                                 (list "font-size" "40px"))))

Here are the dom-element constructors.

(js-div [attribs])  dom-element?
  attribs : (listof attrib?) = '()
Constructs a div element.

(js-p [attribs])  dom-element?
  attribs : (listof attrib?) = '()
Constructs a paragraph element.

(js-button world-update-f [attribs])  dom-element
  world-update-f : (world -> world)
  attribs : (listof attrib) = '()
Constructs a button. When the button is pressed, the world is updated through world-update-f.

(js-button* world-update-f effect-f [attribs])  dom-element
  world-update-f : (world -> world)
  effect-f : (world -> effect)
  attribs : (listof attrib) = '()
Constructs a button. When the button is pressed, the original world is updated, and the original world is used to construct an effect.

(js-text text)  dom-element
  text : string?
Constructs regular text.

(js-input type [attribs])  dom-element
  type : string
  attribs : (listof attrib) = '()
Creates an input form element.

(js-bidirectional-input type    
  val-f    
  world-update-f    
  [attribs])  dom-element
  type : string
  val-f : (world -> string)
  world-update-f : (world string -> world)
  attribs : (listof attrib) = '()
Creates an input form element that synchronizes with the world. val-f defines what the value of the form element should be when the world changes, and world-update-f defines what the value of the world should be updated to when the form element changes.

(get-input-value elt)  string
  elt : (or input-dom-element string)
Get the value attribute of an input node. If a string is provided, looks for the node with the given string id. Meant to be used with the dom-element constructed by js-input.

(js-img url [attribs])  dom-element
  url : string
  attribs : (listof attrib) = '()
Creates an image element.

Here is an example of a user interface.
  (define input-node
    (js-input "text" '(("id" "myname"))))
  
  (define (refresh w)
    (get-input-value "myname"))
  
  (define (draw w)
    (list (js-div)
          (list (js-div) (list (js-text (format "I see: ~s~n" w))))
          (list (js-div) (list input-node))
          (list (js-div) (list (js-button refresh) (list (js-text "Update!"))))))
  
  (define (draw-css w)
    '())
  
  (js-big-bang ""
               (on-draw draw draw-css))

A single text input form element allows the user to enter some value. That value is read from the interface by the refresh function that’s associated to the button.

3.2.2 Stimulus Handlers

Stimulus handlers are provided as additional arguments to a js-big-bang.

Each stimulus has an unstarred and a starred version; the starred version allows you to provide an effect-generating function. When the given stimulus emits, the old world is used to compute both the new world and the optional effect. Afterwards, each effect in the effect group is applied.

  effect = atomic-effect
  | (listof effect)

(on-tick delay world-update-f)  handler
  delay : number
  world-update-f : (world -> world)
(on-tick* delay world-update-f effect-f)  handler
  delay : number
  world-update-f : (world -> world)
  effect-f : (world -> effect)
Delays by n seconds, and then calls the handlers.

(on-shake world-update-f)  handler
  world-update-f : (world -> world)
(on-shake* world-update-f effect-f)  handler
  world-update-f : (world -> world)
  effect-f : (world -> effect)
Calls the shake handlers when the phone is physically jerked.

(on-location-change world-update-f)  handler
  world-update-f : (world (lat number) (long number) -> world)
(on-location-change* world-update-f    
  effect-f)  handler
  world-update-f : (world (lat number) (long number) -> world)
  effect-f : (world number number -> effect)
Calls the location handlers when the latitude or longitude of the device has changed.

(on-tilt world-update-f)  handler
  world-update-f : (world number number number -> world)
(on-tilt* world-update-f effect-f)  handler
  world-update-f : (world number number number -> world)
  effect-f : (world number number number -> effect)
Calls the tile handlers when the phone has been tilted.

(on-acceleration world-update-f)  handler
  world-update-f : (world number number number -> world)
(on-acceleration* world-update-f effect-f)  handler
  world-update-f : (world number number number -> world)
  effect-f : (world number number number -> effect)
Calls the acceleration handlers when the device feels change in acceleration.

3.2.3 Effects

Effects allow world programs to apply side effects to the outside world. These are used in conjunction with the starred version of the stimulus handlers described above.

(make-effect:none)  effect
No result when interpreted.
(make-effect:beep)  effect
Audible beep when interpreted.

(make-effect:play-sound a-sound)  effect
  a-sound : sound
Plays a sound from the given sound. If the sound is already playing, then the sound continues to play.
(make-effect:stop-sound a-sound)  effect
  a-sound : sound
Stops playing a sound from the given url.
(make-effect:pause-sound a-sound)  effect
  a-sound : sound
Pauses a sound; if make-effect:play-sound for the same sound is given later, play restarts from the point where it was paused.

A sound is a:
  sound = string
  | playlist

(make-effect:set-sound-volume volume)  effect
  volume : number
Sets the sound volume; the number should be between 0 and 100.
(make-effect:raise-sound-volume)  effect
Raises the sound volume. If the volume’s already at 100, has no effect.
(make-effect:lower-sound-volume)  effect
Lowers the sound volume. If the volume’s set to 0, has no effect.

(make-effect:play-dtmf-tone tone)  effect
  tone : number
On a smartphone, plays a DTMF tone, where tone is between 0 and 15 inclusive.

(make-effect:set-wake-lock flag)  effect
  flag : number
On a smartphone, sets the wake-lock flag to prevent the phone from sleeping. Low-level call.
(make-effect:release-wake-lock)  effect
On a smartphone, releases a wake-lock to allow the phone to go to sleep again.

(make-effect:send-sms phone-number message)  effect
  phone-number : string
  message : string
Sends an SMS message.

(make-effect:pick-playlist world-update-f)  effect
  world-update-f : (world playlist -> world)
Brings up a playlist picker; when a playlist is selected, the world is updated using world-update-f with the selected playlist sound.

3.3 API Extensions

The following helper functions and forms are provided by Moby.

(get-url url)  string?
  url : string?
Does an HTTP GET to download the string content from a URL.

As an example, if get-url is called on the URL to the PLT Scheme homepage,
  (get-url "http://plt-scheme.org/")
it produces the textual content of the "index.html" on the homepage.

(location-distance lat-1 long-1 lat-2 long-2)  number?
  lat-1 : number?
  long-1 : number?
  lat-2 : number?
  long-2 : number?
Given latitude-1, longitude-1, latitude-2, longitude-2, produces the distance between the locations in terms of meters.

(xml->s-exp xml-string)  s-expression?
  xml-string : string?
Parses a string containing XML to s-expressions.

(define-struct name (id ...))
define-struct will define structure constructors, selectors, mutators, and a predicate. e.g.

  (define-struct foo (a b))
defines the following forms:
  • make-foo: X Y -> foo

  • foo-a: foo -> X

  • foo-b: foo -> Y

  • foo?: any -> boolean

  • set-foo-a!: foo X -> void

  • set-foo-b!: foo Y -> void

4 Developer details

The compiler takes a ASL program and translates it to Javascript code. Moby reimplements the ASL primitives in a Javascript runtime library that’s included with the compiled application. (See doc/moby-developer-api.txt for more details.)

To support smartphones, Moby uses a bridge library called Phonegap, which provides access to the native facilities of several cell phones. In this way, Moby should be able to support multiple platforms with a lot of code reuse. Moby handles the other libraries (tilt, location, sms, music), though with support only for the Android platforms for now.

4.1 Dependencies

Moby is mostly written in PLT Scheme, and the project sources are hosted by github.com. To develop with Moby, you will need the following:

If you wish to generate programs for the Android+Phonegap backend, you’ll also need:

4.2 Installing from Developer Sources

To install Moby from the development sources:
  1. Download the Moby source, currently hosted on github and place them in your PLT Scheme collects directory.

    For example,

    $ cd ~/.plt-scheme/4.2.1/collects

    $ git clone git://github.com/dyoo/moby-scheme.git moby

    downloads the developer sources into a PLT Scheme user collects directory.

    Also, do a setup-plt -l moby so that PLT Scheme compiles the Moby source code.

  2. 2. If you’re going to do Android development, make sure that ant and the android binary are in your path; Moby will use your PATH variable to find Apache Ant and the Android SDK.

    You can verify that android and ant can be found with the following:

    $ which android

    /usr/local/android/tools/android

     

    $ which ant

    /usr/bin/ant

    The path values you get back may differ according to your system’s configuration.

4.3 Running Moby from the command line

You can run the Moby command line utility ("moby/src/moby.ss") on a Moby program to produce a compiled version of your application. Moby supports two output backends, both which rely on Javascript:
  • js: compiles to a web page application, which can be deployed on any web server.

  • js+android-phonegap: compiles to an Android .apk application package; can also use features of the mobile platform.

By default, the command line utility will use the js backend.

Let’s run moby on the falling-ball.ss example in "moby/examples/falling-ball.ss". We can first generate a web program.

$ cd moby/examples

$ mred ../src/moby.ss falling-ball.ss

$ cd FallingBall/

$ ls

index.html  main.js  runtime  test

If you open up index.html from your web browser, you should see a red ball falling down the screen.

Furthermore, we may want to generate an Android application.

$ cd moby/examples

$ mred ../src/moby.ss -t js+android-phonegap falling-ball.ss

$ cd FallingBall

$ ls

AndroidManifest.xml  build.properties    gen               res

assets               build.xml           libs              src

bin                  default.properties  local.properties  tests

 

$ ls bin

classes  classes.dex  DroidGap.ap_  DroidGap-debug.apk

"DroidGap-debug.apk" is the compiled Android binary. The Ant "build.xml" build-script in the "FallingBall" directory can install, uninstall, and reinstall the application if the Android emulator is online.

    $ ant install

Buildfile: build.xml

 

[some output cut]

 

install:

     [echo] Installing bin/DroidGap-debug.apk onto default emulator...

     [exec] 1594 KB/s (120997 bytes in 0.074s)

03:38 I/ddms: Created: [Debugger 8610-->1641 inactive]

03:38 I/ddms: Good handshake from client, sending HELO to 1641

     [exec]     pkg: /data/local/tmp/DroidGap-debug.apk

     [exec] Success

03:39 I/ddms: Closing [Client pid: 1641]

 

BUILD SUCCESSFUL

Total time: 6 seconds

After this, you can look at the Android emulator, which should now have the "FallingBall" application installed.

4.4 Compiler

Moby consists of the following core files for the compiler:
  • "src/compiler/beginner-to-javascript.ss": translates Scheme programs to javascript programs.

  • "src/compiler/env.ss": maintains the environment structures that map identifiers to bindings.

  • "src/compiler/permission.ss": defines a list of capabilities that a function can be tagged with.

  • "src/compiler/toplevel.ss": maps the primitive toplevel names available in the base language.

  • "src/compiler/modules.ss": adds a few extensions to the toplevel language, including the reactive world primitives.

  • "src/compiler/pinfo.ss": maintains program information used to analyze a program and figure out what functions are used and what capabilities are needed.

  • "src/compiler/desugar.ss": applies syntactic transformations on programs to a core form.

  • "src/compiler/helpers.ss": auxillary helper functions.

The compiler is intentionally written in a small superset of the language ("src/compiler/lang.ss"). As a consequence, it is self hosting, and we take advantage of this to produce a running compiler on the browser. ("support/js/test/test-repl.html")

4.4.1 An example

Let’s see what beginner-to-javascript.ss gives us:

> (define p '((define (f x)

                (* x x))

 

              (f 3)))

 

> (define cp (program->compiled-program p))

program->compiled-program consumes a program – a list of s-expressions – and produces a compiled-program structure.

> cp

#<compiled-program>

The compiled program consists of a list of toplevel definitions and expressions.

> (compiled-program-defns cp)

"\nfunction f(x) { return plt.Kernel._star_([x,x]); }"

 

> (compiled-program-toplevel-exprs cp)

> cp

#<compiled-program>

The compiled program consists of a list of toplevel definitions and expressions.

> (compiled-program-defns cp)

"\nfunction f(x) { return plt.Kernel._star_([x,x]); }"

 

> (compiled-program-toplevel-exprs cp)

"(function (toplevel_dash_expression_dash_show0) { \n\ntoplevel_dash_expression_dash_show0((f((plt.types.Rational.makeInstance(3, 1))))); })"

If we want to embed the evaluation of this program in a web page, we can use the two strings above to do so. For convenience, we provide a helper function compiled-program-main that ties both the definitions and expression evaluation together.

4.5 Runtime

The Javascript program that’s emitted depends on a runtime kernel that’s currently implemented in Javascript. See the files in "support/js/runtime".

4.6 Ugly Hacks

The afterAttach() hack: one problem with excanvases in IE is that they can’t render until they’re attached to a parent node. Unfortunately, this means that we can’t render a canvas at a call to a value’s pretty-printing routine, because that value isn’t yet attached to the DOM.

This affects the implementation of plt.Kernel.BaseImage.toDomNode() We currently add an DomNodeInserted listener to the dom node value, so it knows when it’s time to render. However, this doesn’t work under IE (again), so we also add an afterAttach method that all of our methods will call as soon as we add to a DOM node. So you’ll see code sprinkled around that says:

if (node.afterAttach) { node.afterAttach(); }

in the following files:
  • "support/js/runtime/jsworld.js"

  • "support/js/runtime/jsworld/jsworld.js"

  • "support/js/runtime/types.js"

  • "support/js/runtime/kernel.js"

5 Appendix

5.1 Bindings from ASL

The following toplevel bindings are available from Moby, and have the same meaning as in Advanced Student Language.

5.2 Unimplemented forms

The following ASL forms are currently unimplemented:
  • begin0

  • delay

  • shared

  • recur

  • when

  • unless