Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Monday, December 31, 2012

Day 1 -- JavaScript in a week

I'll make an implementation of a subset of programming language JavaScript within a week.

next post

Defining a subset of JavaScript

The implementation should execute the following JavaScript code.

var acc = 'dummy';
var f = function() {
  var acc = [];
  return function(x) {
    return x ? acc.push(x)&&f(x - 1) : acc;
  console.log("this won't show up!");

String.prototype.ujihisa = function() {
  var x = 10;
  return this + f(x);

console.log(acc == 'dummy');
console.log({'a': 2}.a == 2);



That sample JS code covers the following important aspects.

  • statements and expressions
  • literals (String, Number, Function, Array and Object)
  • function call, method call, operators, and index/key access of Object
  • implicit convertion (String + Number)
  • lexical scope (see acc var)
  • method addition by prototype
  • return exits from the current function

The implementation consists of the following 2 parts.

  • parser (JS code to internal representation in S-expression)
  • runtime

I'll work on runtime first in Clojure, then work on parser in Haskell with parsec.


I don't implement the parser for now but I simply parse the sample code by hand. the first 2 statements will be like the below.


var acc = 'dummy';
var f = function() {
    var acc = [];
    return function(x) {
        return x ? acc.push(x)&&f(x - 1) : acc;


'[(var 'acc "dummy")
  (var 'f
         (function []
                   [[(var 'acc (array))
                       (function ['x]
                                 [[(return (if 'x
                                             (and (mcall 'push 'acc ['x])
                                                  (call 'f [(minus 'x 1)]))

Day 1 progress

  • just finished implementing var and console.log

    (run '[(var x "hello")
           (fcall 'console.log ['x])])
  • currently console.log is just a single name of built-in function

  • changed the structure a little bit.. to separate run to handle statements and evaluate to handle an expression
  • now it supports nested function calls

    (run '[(var x 1)
           (fcall 'console.log [(fcall '+ ['x 2])])])