-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSymbolTable.js
63 lines (53 loc) · 1.09 KB
/
SymbolTable.js
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
class SymbolTable {
constructor() {
this.symbols = {};
}
safeGet(name) {
let symbol = this.symbols[name];
if (!symbol) {
throw new Error('Symbol with name: ' + name + ' is not defined.');
}
return symbol;
}
startSubroutine() {
this.symbols = Object.entries(this.symbols).reduce(
(newSymbols, [k, s]) =>
s.kind === SymbolTable.KINDS.FIELD ||
s.kind === SymbolTable.KINDS.STATIC
? { ...newSymbols, [k]: s }
: newSymbols,
{}
);
}
define(name, type, kind) {
const id = this.count(kind);
this.symbols[name] = {
id,
name,
type,
kind
};
}
count(kind) {
return Object.values(this.symbols).filter(s => s.kind === kind).length;
}
has(name) {
return !!this.symbols[name];
}
kindOf(name) {
return this.safeGet(name).kind;
}
typeOf(name) {
return this.safeGet(name).type;
}
indexOf(name) {
return this.safeGet(name).id;
}
}
SymbolTable.KINDS = {
STATIC: 'STATIC',
FIELD: 'FIELD',
ARG: 'ARG',
VAR: 'VAR'
};
module.exports = SymbolTable;