-
Notifications
You must be signed in to change notification settings - Fork 15
/
symboltable.ts
80 lines (72 loc) · 2.23 KB
/
symboltable.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { KeywordToken } from "./tokenizer";
type SymbolAttribute = { type: string; kind: string; index: number };
export default class SymbolTable {
private classSymbolTable: { [name: string]: SymbolAttribute } = {};
private subroutineSymbolTable: { [name: string]: SymbolAttribute } = {};
private counts: { [name: string]: number } = {
static: 0,
this: 0,
argument: 0,
local: 0,
};
public startSubroutine(subroutineType: string): void {
this.subroutineSymbolTable = {};
switch (subroutineType) {
case KeywordToken.CONSTRUCTOR:
case KeywordToken.FUNCTION:
this.counts.argument = 0;
break;
case KeywordToken.METHOD:
this.counts.argument = 1;
break;
default:
throw new Error("Invalid subroutine type: " + subroutineType);
}
this.counts.local = 0;
}
public define(name: string, type: string, kind: string): boolean {
let table: { [name: string]: SymbolAttribute };
switch (kind) {
case "static":
case "this":
table = this.classSymbolTable;
break;
case "argument":
case "local":
table = this.subroutineSymbolTable;
break;
default:
throw new Error("Invalid kind: " + kind);
}
if (name in table) return false;
table[name] = { type, kind, index: this.counts[kind]++ };
return true;
}
public count(kind: string): number {
return this.counts[kind];
}
private getSymbol(name: string): SymbolAttribute | null {
if (name in this.subroutineSymbolTable) {
return this.subroutineSymbolTable[name];
}
if (name in this.classSymbolTable) {
return this.classSymbolTable[name];
}
return null;
}
public kindOf(name: string): string | null {
const symbolAttribute = this.getSymbol(name);
if (symbolAttribute === null) return null;
return symbolAttribute.kind;
}
public typeOf(name: string): string | null {
const symbolAttribute = this.getSymbol(name);
if (symbolAttribute === null) return null;
return symbolAttribute.type;
}
public indexOf(name: string): number | null {
const symbolAttribute = this.getSymbol(name);
if (symbolAttribute === null) return null;
return symbolAttribute.index;
}
}