块状作用域的解释器变量表实现

建立映射关系

首先变量表应该采取一种将变量名对应到变量的方法,这种方法大致两种,一种是将变量名parse时hash成数字,一种是直接建立string->value的map。

  • int|速度快|动态性弱,无法实现诸如getvar("abc")的功能
  • string|速度慢|动态性强
    其次选择数据结构
  • 平衡树|速度慢,费空间
  • hash表|速度快,省空间
  • 数组|速度巨快,费空间(因为变量hash后的数字是不连续的)
    注:当然也可以采用那个类似编译型语言的在栈上分配内存,不过这样牺牲了语言的动态性
    处理继承关系

我们使用链表结构,每一个块状作用域指向父作用域,接口实现getvar()方法,递归查找变量,利用exception机制处理未定义变量行为。

 class VariableTable {
public:
	VariableTable *prev;
	unordered_map<int,Value*> table;
	VariableTable() {
		prev = nullptr;  
	}
	VariableTable(VariableTable * t) {
		prev = t;
	}
	void defineVar( int name ) {
		auto t = table.find(name);
		if (t != table.end()) 
			throw RedefinedVariableException(name);
		this->table.emplace(name, new Value());	
	}
	Value & getVar( const int & name )  {
		auto t = table.find(name);
		if (t == table.end()) {
			if (prev == nullptr)
				throw UndefinedVariableException(name);	
			else
				return prev->getVar(name);
		}
		else {
			return *t->second;
		}
	}
	~VariableTable() {
		for (auto &x : table)
			delete x.second;
	}
};

Object类型的属性


我们完全可以采用类似思路。

const int __proto__ = getNameInt("__proto__");
class Object {
public:
	bool mark;
	unordered_map<int, Value*> data;
	Object() {

	}
	Value & __getVar(int name) {
		auto t = data.find(name);
		if (t != data.end())return *t->second;
		else {
			auto pro = data.find(__proto__);
			if (pro == data.end() || pro->second->type != Value::Type::Obj)
				throw UndefinedVariableException(1);
			else
				return pro->second->data.Obj->__getVar(name);
		}
	}
	inline Value & getVar(int name) {
		try {
			return this->__getVar(name);
		}
		catch (UndefinedVariableException) {
			data.emplace(name, new Value());
			return this->__getVar(name);
		}
	}
	~Object() {
		for (auto &x : data)
			delete x.second;
	}
};
posted on 2016-03-11 20:29  蓝田田长  阅读(246)  评论(0)    收藏  举报