1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-21 18:48:12 +03:00
mal/ts/env.ts

49 lines
1.1 KiB
TypeScript
Raw Normal View History

2017-02-24 07:21:11 +03:00
import { MalType, MalSymbol, MalList } from "./types";
2017-02-24 02:37:25 +03:00
export class Env {
data: Map<MalSymbol, MalType>;
2017-02-24 07:21:11 +03:00
constructor(public outer?: Env, binds: MalSymbol[] = [], exprts: MalType[] = []) {
2017-02-24 02:37:25 +03:00
this.data = new Map();
2017-02-24 07:21:11 +03:00
for (let i = 0; i < binds.length; i++) {
const bind = binds[i];
if (bind.v === "&") {
this.set(binds[i + 1], new MalList(exprts.slice(i)));
break;
}
this.set(bind, exprts[i]);
}
2017-02-24 02:37:25 +03:00
}
set(key: MalSymbol, value: MalType): MalType {
this.data.set(key, value);
return value;
}
find(key: MalSymbol): Env | undefined {
if (this.data.has(key)) {
return this;
}
if (this.outer) {
return this.outer.find(key);
}
return void 0;
}
get(key: MalSymbol): MalType {
const env = this.find(key);
if (!env) {
2017-02-24 18:21:30 +03:00
throw new Error(`'${key.v}' not found`);
2017-02-24 02:37:25 +03:00
}
const v = env.data.get(key);
if (!v) {
2017-02-24 18:21:30 +03:00
throw new Error(`'${key.v}' not found`);
2017-02-24 02:37:25 +03:00
}
return v;
}
}