@psdo/compiler 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,382 @@
1
+ const newFlow = (names) => ({ vars: new Set(names), fields: new Set(), returns: false });
2
+ const clone = (f) => ({ vars: new Set(f.vars), fields: new Set(f.fields), returns: f.returns });
3
+ const intersect = (a, b) => new Set([...a].filter(x => b.has(x)));
4
+ function merge(a, b) {
5
+ if (a.returns)
6
+ return b;
7
+ if (b.returns)
8
+ return a;
9
+ return { vars: intersect(a.vars, b.vars), fields: intersect(a.fields, b.fields), returns: false };
10
+ }
11
+ function assertNever(x) {
12
+ throw new Error(`Unhandled node: ${JSON.stringify(x)}`);
13
+ }
14
+ class Checker {
15
+ errors = [];
16
+ functions = new Map();
17
+ classes = new Map();
18
+ ctx = { kind: "top" };
19
+ err(line, message) {
20
+ this.errors.push({ message, line });
21
+ }
22
+ // phase A -- collect every function so order doesnt matter
23
+ declare(program) {
24
+ for (const item of program) {
25
+ if (item.kind === "Function") {
26
+ if (this.classes.has(item.name) || this.functions.has(item.name)) {
27
+ this.err(item.line, `"${item.name}" is already defined`);
28
+ }
29
+ else {
30
+ this.functions.set(item.name, item);
31
+ }
32
+ }
33
+ else if (item.kind === "Class") {
34
+ if (this.classes.has(item.name) || this.functions.has(item.name)) {
35
+ this.err(item.line, `"${item.name}" is already defined`);
36
+ continue;
37
+ }
38
+ const fields = new Map();
39
+ for (const f of item.fields) {
40
+ if (fields.has(f.name))
41
+ this.err(f.line, `Field "${f.name}" is declared twice in class ${item.name}`);
42
+ else
43
+ fields.set(f.name, f);
44
+ }
45
+ const methods = new Map();
46
+ for (const m of item.methods) {
47
+ if (methods.has(m.fn.name))
48
+ this.err(m.fn.line, `Method "${m.fn.name}" is defined twice in class ${item.name}`);
49
+ else if (fields.has(m.fn.name))
50
+ this.err(m.fn.line, `"${m.fn.name}" is both a field and a method in class ${item.name}`);
51
+ else
52
+ methods.set(m.fn.name, m);
53
+ }
54
+ this.classes.set(item.name, { def: item, fields, methods });
55
+ }
56
+ }
57
+ }
58
+ // phase B -- walk every body in order
59
+ run(program, vars = []) {
60
+ const top = newFlow(vars);
61
+ for (const item of program) {
62
+ if (item.kind === "Function")
63
+ this.checkFunction(item, { kind: "function" });
64
+ else if (item.kind === "Class")
65
+ this.checkClass(item);
66
+ else {
67
+ this.ctx = { kind: "top" };
68
+ this.stmt(item, top);
69
+ }
70
+ }
71
+ }
72
+ checkFunction(fn, ctx) {
73
+ this.ctx = ctx;
74
+ this.checkParams(fn.params, fn.line);
75
+ // a function only has its parameters
76
+ const flow = this.block(fn.block, newFlow(fn.params.map(p => p.name)));
77
+ if (!flow.returns)
78
+ this.err(fn.line, `Function "${fn.name}" must return on every path`);
79
+ }
80
+ checkClass(def) {
81
+ const cls = this.classes.get(def.name);
82
+ if (!cls || cls.def !== def)
83
+ return;
84
+ if (def.ctor) {
85
+ this.ctx = { kind: "constructor", cls };
86
+ this.checkParams(def.ctor.params, def.ctor.line);
87
+ const flow = this.block(def.ctor.block, newFlow(def.ctor.params.map(p => p.name)));
88
+ if (!flow.returns) {
89
+ for (const name of cls.fields.keys()) {
90
+ if (!flow.fields.has(name)) {
91
+ this.err(def.ctor.line, `Field "${name}" is never assigned in the constructor of ${def.name}`);
92
+ }
93
+ }
94
+ }
95
+ }
96
+ else if (cls.fields.size > 0) {
97
+ this.err(def.line, `Class ${def.name} has fields but no constructor to assign them`);
98
+ }
99
+ for (const m of def.methods)
100
+ this.checkFunction(m.fn, { kind: "method", cls });
101
+ }
102
+ block(stmts, flow) {
103
+ for (const s of stmts)
104
+ this.stmt(s, flow);
105
+ return flow;
106
+ }
107
+ stmt(s, flow) {
108
+ switch (s.kind) {
109
+ case "Assign":
110
+ this.assign(s, flow);
111
+ return;
112
+ case "Return":
113
+ if (s.value)
114
+ this.expr(s.value, flow);
115
+ if (this.ctx.kind === "top")
116
+ this.err(s.line, `"return" can only be used inside a function`);
117
+ if (this.ctx.kind === "constructor")
118
+ this.err(s.line, "A constructor can't return");
119
+ flow.returns = true;
120
+ return;
121
+ case "If": {
122
+ this.expr(s.condition, flow);
123
+ const thenFlow = this.block(s.thenBranch, clone(flow));
124
+ const elseFlow = this.block(s.elseBranch ?? [], clone(flow));
125
+ const after = merge(thenFlow, elseFlow);
126
+ flow.vars = after.vars;
127
+ flow.fields = after.fields;
128
+ flow.returns = after.returns;
129
+ return;
130
+ }
131
+ case "While":
132
+ this.expr(s.condition, flow);
133
+ this.block(s.block, clone(flow));
134
+ return;
135
+ case "For": {
136
+ this.expr(s.from, flow);
137
+ this.expr(s.to, flow);
138
+ const body = clone(flow);
139
+ if (flow.vars.has(s.name))
140
+ this.err(s.line, `Loop variable "${s.name}" is already in use`);
141
+ body.vars.add(s.name);
142
+ this.block(s.block, body);
143
+ return;
144
+ }
145
+ case "Call":
146
+ this.call(s, flow);
147
+ return;
148
+ default:
149
+ return assertNever(s);
150
+ }
151
+ }
152
+ assign(s, flow) {
153
+ this.expr(s.value, flow);
154
+ const { root, path } = s.target;
155
+ this.indices(s.target, flow);
156
+ if (root.kind === "Name") {
157
+ if (path.length === 0)
158
+ flow.vars.add(root.name);
159
+ else
160
+ this.requireVar(root.name, s.target.line, flow);
161
+ return;
162
+ }
163
+ const cls = this.thisClass(s.target.line);
164
+ if (!cls)
165
+ return;
166
+ const first = path[0];
167
+ if (!first) {
168
+ this.err(s.target.line, `Can't assign to "this" itself`);
169
+ return;
170
+ }
171
+ if (first.kind === "Index") {
172
+ this.err(s.target.line, `"this" can't be indexed`);
173
+ return;
174
+ }
175
+ if (!this.thisField(cls, first.name, s.target.line))
176
+ return;
177
+ if (path.length === 1 && this.ctx.kind === "constructor")
178
+ flow.fields.add(first.name);
179
+ else
180
+ this.requireFieldSet(first.name, s.target.line, flow);
181
+ }
182
+ expr(e, flow) {
183
+ switch (e.kind) {
184
+ case "Number":
185
+ return;
186
+ case "Array":
187
+ e.elements.forEach(x => this.expr(x, flow));
188
+ return;
189
+ case "Binary":
190
+ this.expr(e.left, flow);
191
+ this.expr(e.right, flow);
192
+ return;
193
+ case "Unary":
194
+ this.expr(e.operand, flow);
195
+ return;
196
+ case "Path":
197
+ this.read(e.target, flow);
198
+ return;
199
+ case "Call":
200
+ this.call(e, flow);
201
+ return;
202
+ case "New":
203
+ this.newExpr(e, flow);
204
+ return;
205
+ default: return assertNever(e);
206
+ }
207
+ }
208
+ newExpr(e, flow) {
209
+ e.args.forEach(a => this.expr(a, flow));
210
+ const cls = this.classes.get(e.name);
211
+ if (!cls) {
212
+ this.err(e.line, `Class "${e.name}" is not defined`);
213
+ return;
214
+ }
215
+ this.checkArgs(`Constructor of ${e.name}`, cls.def.ctor?.params ?? [], e.args, e.line);
216
+ }
217
+ read(t, flow) {
218
+ this.indices(t, flow);
219
+ if (t.root.kind === "Name") {
220
+ this.requireVar(t.root.name, t.line, flow);
221
+ return;
222
+ }
223
+ const cls = this.thisClass(t.line);
224
+ if (!cls)
225
+ return;
226
+ const first = t.path[0];
227
+ if (!first) {
228
+ this.requireAllFields(cls, t.line, flow, `"this"`);
229
+ return;
230
+ }
231
+ if (first.kind === "Index") {
232
+ this.err(t.line, `"this" can't be indexed`);
233
+ return;
234
+ }
235
+ if (this.thisField(cls, first.name, t.line))
236
+ this.requireFieldSet(first.name, t.line, flow);
237
+ }
238
+ call(c, flow) {
239
+ const { root, path } = c.callee;
240
+ this.indices(c.callee, flow);
241
+ c.args.forEach(a => this.expr(a, flow));
242
+ if (root.kind === "Name" && path.length === 0) {
243
+ this.functionCall(c, root.name);
244
+ return;
245
+ }
246
+ if (path.at(-1)?.kind === "Index") {
247
+ this.err(c.line, "Only functions and methods can be called, not array elements");
248
+ return;
249
+ }
250
+ if (root.kind === "Name") {
251
+ this.requireVar(root.name, c.line, flow);
252
+ return;
253
+ }
254
+ const cls = this.thisClass(c.line);
255
+ if (!cls)
256
+ return;
257
+ const first = path[0];
258
+ if (!first) {
259
+ this.err(c.line, `"this" can't be called`);
260
+ return;
261
+ }
262
+ if (first.kind === "Index") {
263
+ this.err(c.line, `"this" can't be indexed`);
264
+ return;
265
+ }
266
+ if (path.length > 1) {
267
+ if (this.thisField(cls, first.name, c.line))
268
+ this.requireFieldSet(first.name, c.line, flow);
269
+ return;
270
+ }
271
+ const method = cls.methods.get(first.name);
272
+ if (!method) {
273
+ this.err(c.line, cls.fields.has(first.name)
274
+ ? `"this.${first.name}" is a field, not a method`
275
+ : `Class ${cls.def.name} has no method "${first.name}"`);
276
+ return;
277
+ }
278
+ this.requireAllFields(cls, c.line, flow, `Method "${first.name}"`);
279
+ this.checkArgs(`Method "${first.name}"`, method.fn.params, c.args, c.line);
280
+ }
281
+ functionCall(c, name) {
282
+ const fn = this.functions.get(name);
283
+ if (fn) {
284
+ this.checkArgs(`Function "${name}"`, fn.params, c.args, c.line);
285
+ return;
286
+ }
287
+ if (this.classes.has(name))
288
+ this.err(c.line, `"${name}" is a class, create one with "new ${name}()"`);
289
+ else if (this.currentClass()?.methods.has(name))
290
+ this.err(c.line, `"${name}" is a method, call it with "this.${name}()"`);
291
+ else
292
+ this.err(c.line, `Function "${name}" is not defined`);
293
+ }
294
+ // helpers
295
+ indices(t, flow) {
296
+ for (const a of t.path)
297
+ if (a.kind === "Index")
298
+ this.expr(a.index, flow);
299
+ }
300
+ requireVar(name, line, flow) {
301
+ if (flow.vars.has(name))
302
+ return;
303
+ if (this.functions.has(name))
304
+ this.err(line, `"${name}" is a function, call it with "${name}()"`);
305
+ else if (this.classes.has(name))
306
+ this.err(line, `"${name}" is a class, create one with "new ${name}()"`);
307
+ else if (this.currentClass()?.fields.has(name))
308
+ this.err(line, `"${name}" is a field, use "this.${name}"`);
309
+ else
310
+ this.err(line, `Variable "${name}" is not assigned before this point`);
311
+ }
312
+ currentClass() {
313
+ return this.ctx.kind === "method" || this.ctx.kind === "constructor" ? this.ctx.cls : null;
314
+ }
315
+ thisClass(line) {
316
+ const cls = this.currentClass();
317
+ if (!cls)
318
+ this.err(line, `"this" can only be used inside a class`);
319
+ return cls;
320
+ }
321
+ thisField(cls, name, line) {
322
+ if (cls.fields.has(name))
323
+ return true;
324
+ if (cls.methods.has(name))
325
+ this.err(line, `"this.${name}" is a method, not a field`);
326
+ else
327
+ this.err(line, `Class ${cls.def.name} has no field "${name}"`);
328
+ return false;
329
+ }
330
+ requireFieldSet(name, line, flow) {
331
+ if (this.ctx.kind === "constructor" && !flow.fields.has(name)) {
332
+ this.err(line, `Field "${name}" is used in the constructor before it is assigned`);
333
+ }
334
+ }
335
+ requireAllFields(cls, line, flow, what) {
336
+ if (this.ctx.kind !== "constructor")
337
+ return;
338
+ const missing = [...cls.fields.keys()].filter(f => !flow.fields.has(f));
339
+ if (missing.length > 0) {
340
+ this.err(line, `${what} can't be used in the constructor until every field is assigned (missing: ${missing.join(", ")})`);
341
+ }
342
+ }
343
+ checkParams(params, line) {
344
+ const seen = new Set();
345
+ for (const p of params) {
346
+ if (seen.has(p.name))
347
+ this.err(line, `Parameter "${p.name}" is declared twice`);
348
+ else
349
+ seen.add(p.name);
350
+ }
351
+ }
352
+ checkArgs(label, params, args, line) {
353
+ if (params.length !== args.length) {
354
+ this.err(line, `${label} takes ${params.length} argument${params.length === 1 ? '' : 's'} but got ${args.length}`);
355
+ return;
356
+ }
357
+ params.forEach((p, i) => {
358
+ if (p.byRef && args[i].kind !== "Path") {
359
+ this.err(line, `Argument ${i + 1} of ${label} is passed by ref, so it must be a variable`);
360
+ }
361
+ });
362
+ }
363
+ }
364
+ export function checkProgram(program) {
365
+ const checker = new Checker();
366
+ checker.declare(program);
367
+ checker.run(program);
368
+ return checker.errors.sort((a, b) => a.line - b.line);
369
+ }
370
+ export function checkChunk(chunk, known) {
371
+ const checker = new Checker();
372
+ checker.declare(known.defs);
373
+ checker.declare(chunk);
374
+ checker.run(chunk, known.vars);
375
+ return checker.errors.sort((a, b) => a.line - b.line);
376
+ }
377
+ export function checkExpression(expr, known) {
378
+ const checker = new Checker();
379
+ checker.declare(known.defs);
380
+ checker.expr(expr, newFlow(known.vars));
381
+ return checker.errors.sort((a, b) => a.line - b.line);
382
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ import * as readline from "node:readline";
3
+ import { formatValue, isComplete, Session } from "./session.js";
4
+ import { readFileSync } from "node:fs";
5
+ import { resolve } from "node:path";
6
+ const PRIMARY = ">>> ";
7
+ const CONTINUE = "... ";
8
+ const useColour = !process.env.NO_COLOR;
9
+ const paint = (code, text) => (useColour ? `\x1b[${code}m${text}\x1b[0m` : text);
10
+ const red = (t) => paint(31, t);
11
+ const dim = (t) => paint(2, t);
12
+ const cyan = (t) => paint(36, t);
13
+ const HELP = [
14
+ "Type psdo code. A block (if, while, for, function, class) keeps asking for lines until it is closed.",
15
+ "Type an expression to see its value: 1 + 2, double(4), new Counter(0, 1)",
16
+ "",
17
+ " :load <file> run a .psdo file and keep its variables, functions and classes (:l)",
18
+ " :reload forget everything, then load the last file again (:rl)",
19
+ " :vars show the variables",
20
+ " :stats comparisons, swaps, visits and array cells so far",
21
+ " :trace switch the frame trace on or off (what psdo-viz would be given)",
22
+ " :reset forget everything",
23
+ " :help this text",
24
+ " :quit leave (Ctrl-D works too)",
25
+ ];
26
+ const STATS = {
27
+ comparisons: " compares: ",
28
+ swaps: " swaps: ",
29
+ visits: " visits: ",
30
+ arrayCells: " cells: "
31
+ };
32
+ function describe(frame) {
33
+ const e = frame.event;
34
+ switch (e.kind) {
35
+ case "assign": return `assign ${e.name} = ${formatValue(e.value)}`;
36
+ case "return": return `return ${e.name} -> ${formatValue(e.value)}`;
37
+ case "branch": return `branch ${e.taken ? "taken" : "not taken"}`;
38
+ case "compare": return `compare ${formatValue(e.a)}, ${formatValue(e.b)} -> ${e.result}`;
39
+ case "swap": return `swap ${formatValue(e.a)} <-> ${formatValue(e.b)}`;
40
+ case "visit": return `visit ${e.nodeId}`;
41
+ case "end": return undefined;
42
+ }
43
+ }
44
+ function render(outcome, lines, trace) {
45
+ const out = [];
46
+ if (outcome.kind === "error") {
47
+ const err = outcome.error;
48
+ if (err.phase === "compile") {
49
+ for (const d of err.diagnostics)
50
+ out.push(red(`error: ${d.message}${lines > 1 ? ` (line ${d.line})` : ""}`));
51
+ }
52
+ else {
53
+ out.push(red(`runtime error: ${err.message}${lines > 1 && err.line !== undefined ? ` (line ${err.line})` : ""}`));
54
+ }
55
+ return out;
56
+ }
57
+ if (trace) {
58
+ for (const f of outcome.frames) {
59
+ const text = describe(f);
60
+ if (text)
61
+ out.push(dim(` line ${f.line}: ${text}`));
62
+ }
63
+ }
64
+ if (outcome.kind === "value")
65
+ out.push(cyan(formatValue(outcome.value)));
66
+ return out;
67
+ }
68
+ const session = new Session();
69
+ let trace = false;
70
+ let lastLoaded;
71
+ let buffer = [];
72
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: PRIMARY });
73
+ // if stdin is a pipe then there is nothing to prompt
74
+ const ask = () => {
75
+ if (process.stdin.isTTY) {
76
+ rl.setPrompt(buffer.length === 0 ? PRIMARY : CONTINUE);
77
+ rl.prompt();
78
+ }
79
+ };
80
+ function loadFile(path, reload) {
81
+ let code;
82
+ try {
83
+ code = readFileSync(resolve(path), "utf8").replace(/\r\n/g, "\n");
84
+ }
85
+ catch {
86
+ console.log(red(`error loading file: ${path}`));
87
+ return;
88
+ }
89
+ if (reload)
90
+ session.reset();
91
+ const outcome = session.feed(code);
92
+ for (const l of render(outcome, code.split("\n").length, trace))
93
+ console.log(l);
94
+ if (outcome.kind !== "error") {
95
+ lastLoaded = path;
96
+ console.log(`successfully loaded: ${path}`);
97
+ }
98
+ }
99
+ function command(line) {
100
+ const [name, ...args] = line.trim().split(/\s+/);
101
+ switch (name) {
102
+ case ":h":
103
+ case ":help":
104
+ HELP.forEach((l) => console.log(l));
105
+ break;
106
+ case ":v":
107
+ case ":vars": {
108
+ const vars = Object.entries(session.variables());
109
+ if (vars.length === 0)
110
+ console.log(dim("(no variables)"));
111
+ for (const [k, v] of vars)
112
+ console.log(`${k} = ${formatValue(v)}`);
113
+ break;
114
+ }
115
+ case ":l":
116
+ case ":load": {
117
+ if (args.length != 1) {
118
+ console.log(red(`load command expected 1 path but got ${args.length}`));
119
+ break;
120
+ }
121
+ loadFile(args[0], false);
122
+ break;
123
+ }
124
+ case ":rl":
125
+ case ":reload": {
126
+ if (!lastLoaded) {
127
+ console.log(red("no file loaded yet, use :load <path>"));
128
+ break;
129
+ }
130
+ loadFile(lastLoaded, true);
131
+ break;
132
+ }
133
+ case ":s":
134
+ case ":stats": {
135
+ const s = Object.entries(session.stats());
136
+ s.forEach(([k, v]) => v > 0 && console.log(STATS[k] + v));
137
+ break;
138
+ }
139
+ case ":t":
140
+ case ":trace":
141
+ trace = !trace;
142
+ console.log(`trace ${trace ? "on" : "off"}`);
143
+ break;
144
+ case ":reset":
145
+ case ":r":
146
+ session.reset();
147
+ console.log("session cleared");
148
+ break;
149
+ case ":quit":
150
+ case ":q":
151
+ rl.close();
152
+ return false;
153
+ default: console.log(red(`unknown command ${name}, try :help`));
154
+ }
155
+ return true;
156
+ }
157
+ if (process.stdout.isTTY)
158
+ process.stdout.write("\x1b[2J\x1b[3J\x1b[H");
159
+ if (process.stdin.isTTY)
160
+ console.log(cyan("psdo") + " REPL. :help for commands, :quit or Ctrl-D to leave.");
161
+ ask();
162
+ rl.on("line", (line) => {
163
+ if (buffer.length === 0 && line.trim().startsWith(":")) {
164
+ if (command(line))
165
+ ask();
166
+ return;
167
+ }
168
+ buffer.push(line);
169
+ const text = buffer.join("\n");
170
+ if (!isComplete(text)) {
171
+ ask();
172
+ return;
173
+ }
174
+ buffer = [];
175
+ const outcome = session.feed(text);
176
+ for (const l of render(outcome, text.split("\n").length, trace))
177
+ console.log(l);
178
+ ask();
179
+ });
180
+ rl.on("SIGINT", () => {
181
+ const somethingTyped = buffer.length > 0 || rl.line.length > 0;
182
+ const line = rl.line;
183
+ rl.write(null, { ctrl: true, name: "k" });
184
+ rl.write(null, { ctrl: true, name: "u" });
185
+ buffer = [];
186
+ console.log(dim(somethingTyped ? line + "\n(input cancelled)" : "\n(use :quit or Ctrl-D to leave)"));
187
+ ask();
188
+ });
189
+ rl.on("close", () => {
190
+ if (process.stdin.isTTY)
191
+ console.log();
192
+ process.exit(0);
193
+ });
@@ -0,0 +1,16 @@
1
+ import type { RuntimeCode } from "./messages.js";
2
+ export interface Diagnostic {
3
+ message: string;
4
+ line: number;
5
+ }
6
+ export declare class CompileError extends Error {
7
+ readonly diagnostics: Diagnostic[];
8
+ constructor(diagnostics: Diagnostic[]);
9
+ }
10
+ export declare class RuntimeError extends Error {
11
+ readonly code: RuntimeCode;
12
+ readonly detail: string;
13
+ readonly line: number | undefined;
14
+ constructor(code: RuntimeCode, detail: string, line?: number);
15
+ withLine(line: number): RuntimeError;
16
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ export class CompileError extends Error {
2
+ diagnostics;
3
+ constructor(diagnostics) {
4
+ const seen = new Set();
5
+ const unique = diagnostics.filter(d => {
6
+ const key = `${d.line}:${d.message}`;
7
+ return seen.has(key) ? false : (seen.add(key), true);
8
+ });
9
+ const sorted = unique.sort((a, b) => a.line - b.line);
10
+ super(sorted.map(d => `${d.message} (line ${d.line})`).join("\n"));
11
+ this.name = "CompileError";
12
+ this.diagnostics = sorted;
13
+ }
14
+ }
15
+ export class RuntimeError extends Error {
16
+ code;
17
+ detail;
18
+ line;
19
+ constructor(code, detail, line) {
20
+ super(line === undefined ? detail : `${detail} (line ${line})`);
21
+ this.name = "RuntimeError";
22
+ this.code = code;
23
+ this.detail = detail;
24
+ this.line = line;
25
+ }
26
+ withLine(line) {
27
+ return new RuntimeError(this.code, this.detail, line);
28
+ }
29
+ }
@@ -0,0 +1,15 @@
1
+ export { tokenise, KEYWORDS } from "./lexer.js";
2
+ export type { Token, TokenType } from "./lexer.js";
3
+ export { parseProgram } from "./ast.js";
4
+ export { interpret } from "./interpreter.js";
5
+ export type { Program, Stmt, Expr, FunctionDef, Frame, FrameEvent, ObjectValue, Value, Env, Scope, Memory, Counters, GraphNode, GraphEdge, Structure, Location } from "./types.js";
6
+ export { COUNTERS_DEFAULT, MEMORY_DEFAULTS } from './types.js';
7
+ export { Session, isComplete, formatValue } from "./session.js";
8
+ export type { Outcome, SessionError } from "./session.js";
9
+ export { CompileError, RuntimeError } from "./errors.js";
10
+ export type { Diagnostic } from "./errors.js";
11
+ import type { Frame, Program } from "./types.js";
12
+ import { type Diagnostic } from "./errors.js";
13
+ export declare function compile(source: string, inject?: string): Program;
14
+ export declare function run(source: string, inject?: string): Frame[];
15
+ export declare function diagnose(source: string, inject?: string): Diagnostic[];
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ export { tokenise, KEYWORDS } from "./lexer.js";
2
+ export { parseProgram } from "./ast.js";
3
+ export { interpret } from "./interpreter.js";
4
+ export { COUNTERS_DEFAULT, MEMORY_DEFAULTS } from './types.js';
5
+ export { Session, isComplete, formatValue } from "./session.js";
6
+ export { CompileError, RuntimeError } from "./errors.js";
7
+ import { tokenise } from "./lexer.js";
8
+ import { parseProgram } from "./ast.js";
9
+ import { interpret, PRELUDE_DEFS } from "./interpreter.js";
10
+ import { checkProgram } from "./checker.js";
11
+ import { CompileError, RuntimeError } from "./errors.js";
12
+ const offsetOf = (inject) => inject.split("\n").length;
13
+ function toSourceLines(found, offset) {
14
+ const mapped = found.map((d) => d.line > offset
15
+ ? { ...d, line: d.line - offset }
16
+ : { line: 1, message: `In the injected code: ${d.message}` });
17
+ return new CompileError(mapped).diagnostics;
18
+ }
19
+ export function compile(source, inject = "") {
20
+ const isPrelude = /\/\/\s+IGNORE_PRELUDE/.test(source);
21
+ try {
22
+ const program = parseProgram(tokenise(`${inject}\n${source}\n`));
23
+ const problems = checkProgram([...(isPrelude ? [] : PRELUDE_DEFS), ...program]);
24
+ if (problems.length > 0)
25
+ throw new CompileError(problems);
26
+ return program;
27
+ }
28
+ catch (e) {
29
+ if (e instanceof CompileError)
30
+ throw new CompileError(toSourceLines(e.diagnostics, offsetOf(inject)));
31
+ throw e;
32
+ }
33
+ }
34
+ export function run(source, inject = "") {
35
+ const offset = offsetOf(inject);
36
+ try {
37
+ const frames = interpret(compile(source, inject));
38
+ return frames.map((f) => ({ ...f, line: Math.max(0, f.line - offset) }));
39
+ }
40
+ catch (e) {
41
+ if (e instanceof RuntimeError && e.line !== undefined) {
42
+ throw e.withLine(Math.max(0, e.line - offset));
43
+ }
44
+ throw e;
45
+ }
46
+ }
47
+ export function diagnose(source, inject = "") {
48
+ try {
49
+ compile(source, inject);
50
+ return [];
51
+ }
52
+ catch (e) {
53
+ if (e instanceof CompileError)
54
+ return e.diagnostics;
55
+ throw e;
56
+ }
57
+ }