-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeEnvironment.ts
45 lines (38 loc) · 1.31 KB
/
TypeEnvironment.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { ParserRuleContext } from 'antlr4ng';
import { ChicoryType } from './ChicoryTypes';
import { CompilationError } from './env';
export class TypeEnvironment {
private bindings: Map<string, ChicoryType>;
constructor(public parent: TypeEnvironment | null) {
this.bindings = new Map();
}
getType(identifier: string): ChicoryType | undefined {
let type = this.bindings.get(identifier);
if (type) {
return type;
}
if (this.parent) {
return this.parent.getType(identifier);
}
return undefined;
}
declare(identifier: string, type: ChicoryType, context: ParserRuleContext, pushError: (str) => void): void {
if (this.bindings.has(identifier)) {
pushError(`Identifier '${identifier}' is already declared in this scope.`)
return // We don't want to continue because this is an error
}
this.bindings.set(identifier, type);
}
pushScope(): TypeEnvironment {
return new TypeEnvironment(this);
}
popScope(): TypeEnvironment {
if (this.parent === null) {
throw new Error('Cannot pop the global scope.');
}
return this.parent;
}
getAllTypes(): Map<string, ChicoryType> {
return new Map(this.bindings);
}
}