-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.ts
More file actions
236 lines (201 loc) · 8.92 KB
/
Copy pathparse.ts
File metadata and controls
236 lines (201 loc) · 8.92 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*
$add: [R][R] -> [R]
$sub: [R][R] -> [R]
$mul: [R][R] -> [R]
$div: [R][R] -> [R] THROWS
$divint: [R][R] -> [R] THROWS
$mod: [R][R] -> [R] THROWS
$neg: [R] -> [R]
$lt: [R][R] -> [R]
$le: [R][R] -> [R]
$gt: [R][R] -> [R]
$ge: [R][R] -> [R]
$eq: [R][R] -> [R]
$neq: [R][R] -> [R]
$toint: [R] -> [R] THROWS // Guarantees that if no throw, the result is an integer
$tofloat: [R] -> [R] THROWS // Guarantees that if no throw, the result is a float
$read: [] -> [R]
$print: [R]+ -> []
$println: [R]+ -> []
$catFact: [] -> [R] THROWS
$randInt: [R][R] -> [R] THROWS
$randFloat: [R][R] -> [R] THROWS
$if: [R][R] -> []
$goto: [R] -> []
$label: [R] -> []
$return: [R]? -> []
$set: [L][R] -> []
$get: [L] -> [R]
$ref: [L] -> [L]
L is also R
*/
export class TreeNode {
args: (TreeNode | string)[];
command: string;
constructor(command: string) {
this.command = command;
this.args = [];
}
}
export type VType = 'R' | 'L';
export interface Command {
instruction: string;
args: VType[];
throws: boolean;
returnType: VType | null;
async?: boolean;
infiniteArgs?: boolean;
allowNoArgs?: boolean;
}
export const commands = new Map<string, Command>();
commands.set('$add', { instruction: '$add', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$sub', { instruction: '$sub', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$mul', { instruction: '$mul', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$div', { instruction: '$div', args: ['R', 'R'], throws: true, returnType: 'R' });
commands.set('$divint', { instruction: '$divint', args: ['R', 'R'], throws: true, returnType: 'R' });
commands.set('$mod', { instruction: '$mod', args: ['R', 'R'], throws: true, returnType: 'R' });
commands.set('$neg', { instruction: '$neg', args: ['R'], throws: false, returnType: 'R' });
commands.set('$lt', { instruction: '$lt', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$le', { instruction: '$le', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$gt', { instruction: '$gt', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$ge', { instruction: '$ge', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$eq', { instruction: '$eq', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$neq', { instruction: '$neq', args: ['R', 'R'], throws: false, returnType: 'R' });
commands.set('$toint', { instruction: '$toint', args: ['R'], throws: true, returnType: 'R' });
commands.set('$tofloat', { instruction: '$tofloat', args: ['R'], throws: true, returnType: 'R' });
commands.set('$read', { instruction: '$read', args: [], allowNoArgs: true, throws: false, returnType: 'R' });
commands.set('$print', { instruction: '$print', args: ['R'], infiniteArgs: true, throws: false, returnType: null });
commands.set('$println', { instruction: '$println', args: ['R'], allowNoArgs: true, infiniteArgs: true, throws: false, returnType: null });
commands.set('$catFact', { instruction: '$catFact', args: [], throws: true, returnType: 'R', async: true });
commands.set('$randInt', { instruction: '$randInt', args: ['R', 'R'], throws: true, returnType: 'R' });
commands.set('$randFloat', { instruction: '$randFloat', args: ['R', 'R'], throws: true, returnType: 'R' });
commands.set('$if', { instruction: '$if', args: ['R', 'R'], throws: false, returnType: null });
commands.set('$goto', { instruction: '$goto', args: ['R'], throws: false, returnType: null });
commands.set('$label', { instruction: '$label', args: ['R'], throws: false, returnType: null });
commands.set('$return', { instruction: '$return', args: ['R'], allowNoArgs: true, throws: false, returnType: null });
commands.set('$set', { instruction: '$set', args: ['L', 'R'], throws: false, returnType: null });
commands.set('$get', { instruction: '$get', args: ['R'], throws: false, returnType: 'R' });
commands.set('$ref', { instruction: '$ref', args: ['R'], throws: true, returnType: 'L' });
export function parseSource(source: string): (TreeNode | string)[] {
const lines = source.split('\n');
const astLog: (TreeNode | string)[] = [];
for (let p = 0; p < lines.length; p++) {
const line = lines[p];
const trimmed = line.trim();
if (trimmed === '') { astLog.push(''); continue; }
const instruction = trimmed.substring(0, trimmed.indexOf(';') === -1 ? trimmed.length : trimmed.indexOf(';')).trim();
if (instruction === '') { astLog.push(''); continue; }
const parts = instruction.split(' ');
const commandName = parts[0];
const commandDef = commands.get(commandName);
if (!commandDef) {
throw new Error(`Unknown command: ${commandName} (line ${p + 1})`);
}
const rootNode = new TreeNode(commandName);
const stack = [{
node: rootNode,
expectedArgs: commandDef.args,
infiniteArgs: commandDef.infiniteArgs || false,
allowNoArgs: commandDef.allowNoArgs || false,
argsSoFar: [] as any[],
argptr: 0
}];
let i = 1;
while (i < parts.length) {
const current = stack[stack.length - 1];
if (!current) {
throw new Error(`Error parsing line ${p + 1}: ${line} - too many arguments?`);
}
if (current.argptr >= current.expectedArgs.length && !current.infiniteArgs) {
throw new Error(`Too many arguments for command ${current.node.command} (line ${p + 1})`);
}
const part = parts[i];
const partCommandDef = commands.get(part);
if (partCommandDef) {
stack.push({
node: new TreeNode(part),
expectedArgs: partCommandDef.args,
infiniteArgs: partCommandDef.infiniteArgs || false,
allowNoArgs: partCommandDef.allowNoArgs || false,
argsSoFar: [],
argptr: 0
});
i++;
} else {
const expectedType = current.expectedArgs[
current.infiniteArgs
? Math.min(current.argptr, current.expectedArgs.length - 1)
: current.argptr
];
if (expectedType === 'L') {
throw new Error(`Type error: expected L but got R ('${part}') for command ${current.node.command} (line ${p + 1})`);
}
current.node.args.push(part);
current.argsSoFar.push(part);
current.argptr++;
i++;
}
while (stack.length > 0) {
const top = stack[stack.length - 1];
if (top.argptr >= top.expectedArgs.length && !top.infiniteArgs) {
stack.pop();
if (stack.length === 0) break;
const parent = stack[stack.length - 1];
parent.node.args.push(top.node);
parent.argsSoFar.push(top.node.command);
parent.argptr++;
} else {
break;
}
}
}
if (stack.length > 0) {
const unfinished = stack[stack.length - 1];
if (unfinished.allowNoArgs && unfinished.argsSoFar.length === 0 || unfinished.infiniteArgs && unfinished.argptr) {
stack.pop();
if (stack.length > 0) {
const parent = stack[stack.length - 1];
parent.node.args.push(unfinished.node);
parent.argsSoFar.push(unfinished.node.command);
parent.argptr++;
}
} else {
throw new Error(`Not enough arguments for command ${unfinished.node.command} (line ${p + 1})`);
}
}
if (stack.length !== 0) {
throw new Error(`Error parsing line ${p + 1}: ${line}`);
}
astLog.push(rootNode);
}
return astLog;
}
if (import.meta.main) {
const args = process.argv.slice(2);
if (args.length < 1) {
console.log("Usage: bun parse.ts [-d|--dump] [-l|--loud] <source-file>");
process.exit(1);
}
const dumpAST = (args.includes('-d') || args.includes('--dump'));
const loud = (args.includes('-l') || args.includes('--loud'));
const sourceFile = args[args.length - 1];
let source: string;
try {
source = await Bun.file(sourceFile).text();
} catch (e) {
console.error(`Error reading file ${sourceFile}: ${e}`);
process.exit(1);
}
let ast: (TreeNode | string)[];
try {
ast = parseSource(source!);
} catch (e: any) {
console.error(e.message);
process.exit(1);
}
if (dumpAST) {
await Bun.write(`${sourceFile}-ast.json`, JSON.stringify(ast!, null, 2));
if (loud) console.log(`AST dumped to ${sourceFile}-ast.json`);
}
if (loud) console.log('Parsed successfully.');
}