view py.js @ 0:e985e6d762b9 default tip

Origination.
author Atul Varma <varmaa@toolness.com>
date Wed, 24 Sep 2008 16:47:18 -0700
parents
children
line wrap: on
line source

function Py(code) {
  if ('Py' in this)
    throw new Error("Py() must be called with 'new' keyword");

  var self = this;

  var co_code = code.co_code;
  var co_consts = code.co_consts;
  var co_names = code.co_names;

  var ops = {};
  var stack = [];
  var globals = {};
  var locals = {};

  ops.LOAD_CONST = function LOAD_CONST(index) {
    stack.push(co_consts[index]);
  };

  ops.LOAD_NAME = function LOAD_NAME(index) {
    stack.push(locals[co_names[index]]);
  };

  ops.BINARY_ADD = function BINARY_ADD() {
    stack.push(stack.pop() + stack.pop());
  };

  ops.STORE_NAME = function STORE_NAME(index) {
    locals[co_names[index]] = stack.pop();
  };

  ops.STORE_GLOBAL = function STORE_GLOBAL(index) {
    globals[co_names[index]] = stack.pop();
  };

  ops.RETURN_VALUE = function RETURN_VALUE() {
    self.returnValue = stack.pop();
  };

  for (var i = 0; i < co_code.ops.length; i++) {
    var op = co_code.ops[i].op;
    var arg = co_code.ops[i].arg;
    if (!(op in ops))
      throw new Error('No implementation for op ' + op);
    ops[op](arg);
  }

  self.locals = locals;
  self.globals = globals;
}