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

https://github.com/ujihisa/jinaw

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("hello".ujihisa());
console.log(acc == 'dummy');
console.log({'a': 2}.a == 2);

output:

hello10,9,8,7,6,5,4,3,2,1
true
true

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.

parsing

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.

before:

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

after:

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

Day 1 progress

https://github.com/ujihisa/jinaw/commit/6902cd4e9382e2da58fb9d43f8069256e8fe1ded

  • 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

https://github.com/ujihisa/jinaw/commit/30ad8c898a1c806735eaa990656258537b65a34c

  • 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])])])

No comments:

Post a Comment

Followers