-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeEnvironment.ts
More file actions
62 lines (53 loc) · 1.5 KB
/
TypeEnvironment.ts
File metadata and controls
62 lines (53 loc) · 1.5 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { ParserRuleContext } from "antlr4ng";
import { TypeVariable } from "./ChicoryTypes";
import { ChicoryType } from "./env";
export interface EnvironmentEntry {
type: ChicoryType;
genericParams: TypeVariable[];
}
export class TypeEnvironment {
private bindings: Map<string, EnvironmentEntry>;
constructor(public parent: TypeEnvironment | null) {
this.bindings = new Map();
}
getEntry(identifier: string): EnvironmentEntry | undefined {
const entry = this.bindings.get(identifier);
if (entry) {
return entry;
}
if (this.parent) {
return this.parent.getEntry(identifier);
}
return undefined;
}
getType(identifier: string): ChicoryType | undefined {
return this.getEntry(identifier)?.type;
}
declare(
identifier: string,
type: ChicoryType,
context: ParserRuleContext | null,
pushError: (str) => void,
genericParams: TypeVariable[] = []
): 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, genericParams });
}
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);
}
}