Building Languages in JavaScript

Created by Zach Carter / @zii

fast code

benchmarks

asm.js example


          function DiagModule(stdlib) {
              "use asm";

              var sqrt = stdlib.Math.sqrt;

              function square(x) {
                  x = +x;
                  return +(x*x);
              }

              function diag(x, y) {
                  x = +x;
                  y = +y;
                  return +sqrt(square(x) + square(y));
              }

              return { diag: diag };
          }
          

more realistic asm.js example


function FIBO(N) {
N = N | 0;
var _ = 0, _$1 = 0, _$2 = 0, $output = 0, $cell = 0, $block0 = 0, $i1 = 0, $SP = 0;
U4[1] = (U4[1] | 0) - 400;
$SP = U4[1] | 0;
$output = 0;
$block0 = 0;
for (; ($block0 | 0) < 1; _ = $block0, $block0 = ($block0 | 0) + 1 | 0, _) {
  I4[(($SP) + 0 * 4) >> 2] = 1;
  $i1 = N;
  for (; ($i1 | 0) > 0; _$1 = $i1, $i1 = ($i1 | 0) - 1 | 0, _$1) {
    // block 1
    {
      I4[(($SP) + 1 * 4) >> 2] = ($output | 0) + (I4[(($SP) + 0 * 4) >> 2] | 0) | 0 | 0;
      $output = I4[(($SP) + 0 * 4) >> 2] | 0;
      I4[(($SP) + 0 * 4) >> 2] = I4[(($SP) + 1 * 4) >> 2] | 0;
    }
  }
}
return _$2 = $output | 0, U4[1] = (U4[1] | 0) + 400 | 0, _$2 | 0;
U4[1] = (U4[1] | 0) + 400;
return 0;
}
          

Okay, so how does one build a
language?

Let's build a compiler for FlooP.

High level steps for building a
compiler

  • define language syntax
  • generate a parser
  • instrument parser to build an Abstract Syntax Tree
  • generate JavaScript code from the AST
  • Bonus: generate asm.js from the AST

FlooP Compiler Overview

compiler overview

What!? LLJS?

  • "bastard child of JavaScript and C"
  • Low Level JavaScript, but higher than asm.js
  • simpler to generate than asm.js

THE END

Questions?