瀏覽代碼

Added compiler environment class.

master
Bryan Miller 5 年之前
父節點
當前提交
7e92c653b7
共有 1 個文件被更改,包括 46 次插入0 次删除
  1. +46
    -0
      src/compiler/env.js

+ 46
- 0
src/compiler/env.js 查看文件

@@ -0,0 +1,46 @@

// ALL Environments share the same program counter!
var PC = 0;


class Environment{
constructor(parent){
this.__parent = (parent instanceof Environment) ? parent : null;
this.__vars = {};
}

get PC(){return PC;}
set PC(val){
if (val < 0)
throw new RangeError("Program Counter value is out of bounds.");
PC = val;
}

hasVar(name){
if (name in Object.keys(this.__vars))
return true;
if (this.__parent !== null)
return this.__parent.hasVar(name);
return false;
}

getVarValue(name){
if (name in Object.keys(this.__vars))
return this.__vars[name];
if (this.__parent !== null)
return this.__parent.getVarValue(name);
throw new Error("No var '" + name + "' defined.");
}

setVarValue(name, val){
if (!(name in Object.keys(this.__vars))){
if (this.__parent.hasVar(name))
return this.__parent.setVarVal(name, val);
}
this.__vars[name] = val;
return this;
}
}


module.exports = Environment;

Loading…
取消
儲存