-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.ts
176 lines (161 loc) · 5.04 KB
/
runtime.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
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
import chalk from 'chalk';
import fs from 'node:fs';
import type { Interface } from 'node:readline/promises';
import { handleInput, nameParse, run, typeCheckAst } from '../frontEnd.js';
import type { RA } from '../utils/types.js';
import { AstNode } from '../ast/definitions/AstNode.js';
import { ReturnValue } from '../ast/eval.js';
import { Scope } from '../ast/nameAnalysis.js';
/**
* Provide runtime environment for the interpreter. It will run in the loop
* asking for input and evaluating it until the user enters `return`.
*
* Optionally, a return code can be provided (`return 42`)
*/
export async function runtime(stream: Interface): Promise<void> {
let symbolTable: RA<Scope> = [];
const totalInput = [];
let pendingInput = '';
while (true) {
const line = await stream.question(
pendingInput.length === 0 ? '' : chalk.gray('. ')
);
if (await handleCommand(line.trim(), symbolTable, totalInput)) {
pendingInput = '';
continue;
}
if (pendingInput.length > 0) pendingInput += '\n';
pendingInput = `${pendingInput}${line}`;
const { input, ast } = await inputToAst(pendingInput, symbolTable);
pendingInput = input;
if (ast === undefined) continue;
symbolTable = ast.nameAnalysisContext.symbolTable;
let returnCalled = false;
const result = await ast.evaluate({
output: console.log,
input: handleInput(stream),
onReturnCalled() {
returnCalled = true;
},
});
const returnValue = result instanceof ReturnValue ? result.value : result;
console.log(chalk.gray(returnValue?.toString() ?? 'undefined'));
totalInput.push(pendingInput);
pendingInput = '';
if (returnCalled) {
if (typeof returnValue === 'number') process.exitCode = returnValue;
stream.close();
break;
}
}
}
const reSave = /^:save \s*(?<fileName>.+)$/u;
const reType = /^:type \s*(?<expression>.+)$/u;
/**
* Check if the input string matches one of the meta commands, and if so, handle
* it
*/
async function handleCommand(
line: string,
symbolTable: RA<Scope>,
totalInput: RA<string>
): Promise<boolean> {
if (line === ':help') {
console.log(
chalk.blue(
[
`:help - show this help message\n`,
`:save <fileName> - save the commands entered in the current session `,
`into a file\n`,
`:type <expression> - type check an expression`,
`:cancel - (when in a middle of entering multi-line expression) `,
`clears current expression and awaits further input\n`,
`return 0 - exit the program with exit code 0`,
].join('')
)
);
return true;
} else if (line === ':cancel') return true;
const fileName = reSave.exec(line)?.groups?.fileName;
if (typeof fileName === 'string') {
const { ast } = await inputToAst(totalInput.join('\n'), symbolTable);
if (ast === undefined) {
console.log(chalk.red('Unexpected error when saving'));
return true;
}
fs.writeFileSync(
fileName,
ast.print({
indent: 0,
mode: 'pretty',
debug: false,
needWrapping: false,
})
);
console.log(chalk.blue('Output saved'));
return true;
}
const expression = reType.exec(line)?.groups?.expression;
if (typeof expression === 'string') {
const { ast } = await inputToAst(expression, symbolTable);
if (ast === undefined) return true;
const node = ast?.children.at(-1);
if (typeof node === 'object') {
const type = node.typeCheck({
reportError: () => {
throw new Error('Should not be called');
},
});
console.log(chalk.blue(type.toString()));
}
return true;
}
return false;
}
/**
* Try to create an AST from the pending input and the current symbol table.
* Then, run name analysis and type analysis and report errors if any.
*/
async function inputToAst(
rawInput: string,
symbolTable: RA<Scope>
): Promise<{ readonly input: string; readonly ast: AstNode | undefined }> {
let input = rawInput;
let ast: AstNode | undefined;
try {
ast = await run({ rawText: input });
} catch {
/*
* Automatically insert trailing semicolon if necessary.
* I tried modifying the grammar to make semicolons optional, but that
* resulted in a whole ton of ambiguity errors.
*/
try {
const localInput = `${input};`;
ast = await run({ rawText: localInput });
input = localInput;
} catch {
ast = undefined;
}
}
if (ast === undefined)
return {
input,
ast: undefined,
};
ast.nameAnalysisContext = {
...ast.nameAnalysisContext,
symbolTable: [...symbolTable, ...ast.nameAnalysisContext.symbolTable],
};
const nameErrors = nameParse(ast, false);
if (Array.isArray(nameErrors)) {
nameErrors.forEach((error) => console.error(error));
return { input: '', ast: undefined };
}
const typeErrors = typeCheckAst(ast, input);
if (typeErrors.length > 0) {
typeErrors.forEach((error) => console.error(error));
return { input: '', ast: undefined };
}
return { input, ast };
}