@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.
package/dist/ast.js ADDED
@@ -0,0 +1,664 @@
1
+ /**
2
+ * The parser is the second step in the language interpretation pipeline. It takes
3
+ * the `Token[]` the lexer produces and turns it into a `Program` (an AST). This
4
+ * is where actual language syntax is checked.
5
+ *
6
+ * This is a recursive-descent parser, each grammar rule in `grammar.md` has a
7
+ * matching `parseX` function below, and each one takes the current token position
8
+ * and returns both the node it built and the position just past it so the caller
9
+ * knows where to resume. There is no separate cursor object and rather `pos` is
10
+ * just threaded through every call manually.
11
+ *
12
+ * Read this file along with the grammar.md's EBNF if you're trying to follow how a
13
+ * specific construct parses, or adding a new one.
14
+ */
15
+ import { CompileError } from "./errors.js";
16
+ const found = (t) => !t || t.type === "EOF" ? "end of input"
17
+ : t.type === "NEWLINE" ? "end of line" : `${t.value}`;
18
+ let errors = [];
19
+ // the closing keywords of every block being parsed right now
20
+ let openBlocks = [];
21
+ class ParseError extends Error {
22
+ line;
23
+ pos;
24
+ constructor(message, line, pos) {
25
+ super(message);
26
+ this.name = "ParseError";
27
+ this.line = line;
28
+ this.pos = pos;
29
+ }
30
+ }
31
+ // stop parsing the current token, where pos is the offending token
32
+ function fail(tokens, pos, message) {
33
+ const line = tokens[pos]?.line ?? tokens[pos - 1].line;
34
+ throw new ParseError(message, line, pos);
35
+ }
36
+ // records a problem without stopping the parse
37
+ function report(line, message) {
38
+ errors.push({ message, line });
39
+ }
40
+ const BLOCK_ENDERS = new Set([
41
+ "ELSE", "ENDIF", "ENDWHILE", "ENDFOR", "ENDFUNCTION", "ENDCONSTRUCTOR", "ENDCLASS"
42
+ ]);
43
+ // where to resume after the bad statement
44
+ function skipToLineEnd(tokens, from) {
45
+ let pos = from;
46
+ while (true) {
47
+ const type = tokens[pos]?.type;
48
+ if (!type || type === "EOF" || type === "NEWLINE" || BLOCK_ENDERS.has(type))
49
+ return pos;
50
+ pos++;
51
+ }
52
+ }
53
+ // resume point after a bad class member
54
+ function skipToMemberEnd(tokens, from) {
55
+ let pos = from;
56
+ const first = tokens[pos]?.type;
57
+ if (first && first !== "ENDCLASS" && BLOCK_ENDERS.has(first))
58
+ pos++;
59
+ while (true) {
60
+ const type = tokens[pos]?.type;
61
+ if (!type || type === "EOF" || type === "NEWLINE" || type === "ENDCLASS")
62
+ return pos;
63
+ pos++;
64
+ }
65
+ }
66
+ // records a caught ParseError and returns where parsing should resume
67
+ function recover(e, tokens, start, sync) {
68
+ if (!(e instanceof ParseError))
69
+ throw e;
70
+ report(e.line, e.message);
71
+ return Math.max(sync(tokens, Math.max(e.pos, start)), start + 1);
72
+ }
73
+ // stand in for an expression that couldnt be parsed
74
+ // the tree is never used and only has to have the right shape
75
+ const PLACEHOLDER = { kind: 'Number', value: 0 };
76
+ function parseHeader(tokens, start, fallback, parse) {
77
+ try {
78
+ return parse();
79
+ }
80
+ catch (e) {
81
+ return { value: fallback, nextPos: recover(e, tokens, start, skipToLineEnd) };
82
+ }
83
+ }
84
+ function skipNewLines(tokens, pos) {
85
+ let nextPos = pos;
86
+ while (tokens[nextPos]?.type === "NEWLINE")
87
+ nextPos++;
88
+ return nextPos;
89
+ }
90
+ function expect(tokens, pos, type) {
91
+ const token = tokens[pos];
92
+ if (!token || token.type !== type) {
93
+ fail(tokens, pos, `Expected ${type} but found ${found(token)}.`);
94
+ }
95
+ return pos + 1;
96
+ }
97
+ function parseArrayLiteral(tokens, pos) {
98
+ let nextPos = pos + 1;
99
+ if (tokens[nextPos]?.type === "RBRACK") {
100
+ nextPos = expect(tokens, nextPos, "RBRACK");
101
+ return { node: { kind: "Array", elements: [] }, nextPos };
102
+ }
103
+ const elements = [];
104
+ let el = parseExpression(tokens, nextPos);
105
+ elements.push(el.node);
106
+ nextPos = el.nextPos;
107
+ while (tokens[el.nextPos]?.type === "COMMA") {
108
+ el = parseExpression(tokens, nextPos + 1);
109
+ elements.push(el.node);
110
+ nextPos = el.nextPos;
111
+ }
112
+ nextPos = expect(tokens, nextPos, "RBRACK");
113
+ return { node: { kind: "Array", elements }, nextPos };
114
+ }
115
+ // primary := NUMBER | "true" | "false" | arrayLiteral |
116
+ // "(" expression ")" | "new" IDENTIFIER "(" arguments ")"
117
+ // the base case of the expression grammar -- everything that hasn't built out of a
118
+ // binary/unary operator around another expression
119
+ function parsePrimary(tokens, pos) {
120
+ const token = tokens[pos];
121
+ if (token.type === "NUMBER") {
122
+ return { node: { kind: "Number", value: Number(token.value) }, nextPos: pos + 1 };
123
+ }
124
+ if (token.type === "TRUE") {
125
+ return { node: { kind: "Number", value: 1 }, nextPos: pos + 1 };
126
+ }
127
+ if (token.type === "FALSE") {
128
+ return { node: { kind: "Number", value: 0 }, nextPos: pos + 1 };
129
+ }
130
+ if (token.type === "LBRACK") {
131
+ return parseArrayLiteral(tokens, pos);
132
+ }
133
+ if (token.type === "LPAREN") {
134
+ let { node, nextPos } = parseExpression(tokens, pos + 1);
135
+ nextPos = expect(tokens, nextPos, "RPAREN");
136
+ return { node, nextPos };
137
+ }
138
+ if (token.type === "NEW") {
139
+ let nextPos = expect(tokens, pos + 1, "IDENTIFIER");
140
+ const name = tokens[nextPos - 1].value;
141
+ nextPos = expect(tokens, nextPos, "LPAREN");
142
+ const args = parseArguments(tokens, nextPos);
143
+ nextPos = expect(tokens, args.nextPos, "RPAREN");
144
+ return { node: { kind: "New", name, args: args.args, line: token.line }, nextPos };
145
+ }
146
+ fail(tokens, pos, `Unexpected ${found(token)}.`);
147
+ }
148
+ // postfix := primary | (target call?)
149
+ function parsePostfix(tokens, pos) {
150
+ const type = tokens[pos].type;
151
+ if (type === "IDENTIFIER" || type === "THIS") {
152
+ const t = parseTarget(tokens, pos);
153
+ if (tokens[t.nextPos]?.type === "LPAREN") {
154
+ return parseCall(tokens, t.nextPos, t.target);
155
+ }
156
+ return { node: { kind: "Path", target: t.target }, nextPos: t.nextPos };
157
+ }
158
+ return parsePrimary(tokens, pos);
159
+ }
160
+ // power := postfix (("*" | "/") postfix)*
161
+ function parsePower(tokens, pos) {
162
+ let { node: left, nextPos } = parsePostfix(tokens, pos);
163
+ while (tokens[nextPos]?.type === "CARET") {
164
+ const right = parsePostfix(tokens, nextPos + 1);
165
+ left = { kind: "Binary", op: "^", left, right: right.node };
166
+ nextPos = right.nextPos;
167
+ }
168
+ return { node: left, nextPos };
169
+ }
170
+ // factor := "-" factor | power
171
+ // Unary minus recurses into itself (not postfix) so "--x" parses as
172
+ // nested negation rather than being rejected.
173
+ function parseFactor(tokens, pos) {
174
+ const token = tokens[pos];
175
+ if (token.type === "MINUS") {
176
+ const { node: operand, nextPos } = parseFactor(tokens, pos + 1);
177
+ return { node: { kind: "Unary", op: "-", operand }, nextPos };
178
+ }
179
+ return parsePower(tokens, pos);
180
+ }
181
+ // term := factor (("*" | "/" | "%") factor)*
182
+ // "*" and "/" bind tighter than "+" and "-" simply by being one level deeper in the chain
183
+ function parseTerm(tokens, pos) {
184
+ let { node: left, nextPos } = parseFactor(tokens, pos);
185
+ let token = tokens[nextPos]?.type;
186
+ while (token === "STAR" || token === "SLASH" || token === "PERCENT") {
187
+ const op = token === "STAR" ? "*" : token === "SLASH" ? "/" : "%";
188
+ const right = parseFactor(tokens, nextPos + 1);
189
+ left = { kind: "Binary", op, left, right: right.node };
190
+ nextPos = right.nextPos;
191
+ token = tokens[nextPos]?.type;
192
+ }
193
+ return { node: left, nextPos };
194
+ }
195
+ // arithmetic := term (("+" | "-") term )*
196
+ function parseArithmetic(tokens, pos) {
197
+ let { node: left, nextPos } = parseTerm(tokens, pos);
198
+ while (tokens[nextPos]?.type === "PLUS" || tokens[nextPos]?.type === "MINUS") {
199
+ const opToken = tokens[nextPos];
200
+ const op = opToken.type === "PLUS" ? "+" : "-";
201
+ const right = parseTerm(tokens, nextPos + 1);
202
+ left = { kind: "Binary", op, left, right: right.node };
203
+ nextPos = right.nextPos;
204
+ }
205
+ return { node: left, nextPos };
206
+ }
207
+ const COMPARISON_OP = {
208
+ LT: "<", GT: ">", LE: "<=", GE: ">=", EQEQ: "==", NE: "!="
209
+ };
210
+ // comparison := arithmetic (("<" | ">" | "<=" | ">=" | "==" | "!=") arithmatic)?
211
+ // deliberatley left a "?" not a "*" as comparisons do not chain. "a < b < c" parses the
212
+ // first "a < b" and then fails on the second since comparison doesn't call itself
213
+ function parseComparison(tokens, pos) {
214
+ let { node: left, nextPos } = parseArithmetic(tokens, pos);
215
+ const opToken = tokens[nextPos];
216
+ const op = opToken && COMPARISON_OP[opToken.type];
217
+ if (op) {
218
+ const right = parseArithmetic(tokens, nextPos + 1);
219
+ left = { kind: "Binary", op, left, right: right.node };
220
+ nextPos = right.nextPos;
221
+ }
222
+ return { node: left, nextPos };
223
+ }
224
+ // not := "not" not | comparison
225
+ function parseNot(tokens, pos) {
226
+ if (tokens[pos]?.type === "NOT") {
227
+ const { node: operand, nextPos } = parseNot(tokens, ++pos);
228
+ return { node: { kind: "Unary", op: "not", operand }, nextPos };
229
+ }
230
+ return parseComparison(tokens, pos);
231
+ }
232
+ // and := not ("and" not)*
233
+ function parseAnd(tokens, pos) {
234
+ let { node: left, nextPos } = parseNot(tokens, pos);
235
+ while (tokens[nextPos]?.type === "AND") {
236
+ const right = parseNot(tokens, nextPos + 1);
237
+ left = { kind: "Binary", op: "and", left, right: right.node };
238
+ nextPos = right.nextPos;
239
+ }
240
+ return { node: left, nextPos };
241
+ }
242
+ // or := and ("or" and)*
243
+ function parseOr(tokens, pos) {
244
+ let { node: left, nextPos } = parseAnd(tokens, pos);
245
+ while (tokens[nextPos]?.type === "OR") {
246
+ const right = parseAnd(tokens, nextPos + 1);
247
+ left = { kind: "Binary", op: "or", left, right: right.node };
248
+ nextPos = right.nextPos;
249
+ }
250
+ return { node: left, nextPos };
251
+ }
252
+ // expression := or
253
+ // the named entry point for the chain above (primary -> postfix -> factor ->
254
+ // term -> comparison). every other parseX function that needs "any expression"
255
+ // calls this instead of parseComparison directly
256
+ function parseExpression(tokens, pos) {
257
+ return parseOr(tokens, pos);
258
+ }
259
+ function parseBlock(tokens, pos, terminators) {
260
+ const stmts = [];
261
+ let nextPos = pos;
262
+ openBlocks.push(terminators);
263
+ try {
264
+ while (true) {
265
+ nextPos = skipNewLines(tokens, nextPos);
266
+ const current = tokens[nextPos];
267
+ if (!current || current.type === "EOF" || terminators.includes(current.type))
268
+ break;
269
+ if (BLOCK_ENDERS.has(current.type)) {
270
+ // something further out is waiting for this one
271
+ // stop here and let the caller report its own closer as missing
272
+ if (openBlocks.some(t => t.includes(current.type)))
273
+ break;
274
+ // nothing is waiting for it, so it is extra
275
+ report(current.line, `Unexpected ${found(current)}, there is nothing for it to close.`);
276
+ nextPos++;
277
+ continue;
278
+ }
279
+ try {
280
+ const stmt = parseStatement(tokens, nextPos);
281
+ stmts.push(stmt.node);
282
+ nextPos = skipNewLines(tokens, stmt.nextPos);
283
+ }
284
+ catch (e) {
285
+ nextPos = recover(e, tokens, nextPos, skipToLineEnd);
286
+ }
287
+ }
288
+ }
289
+ finally {
290
+ openBlocks.pop();
291
+ }
292
+ return { stmts, nextPos };
293
+ }
294
+ function parseIfStatement(tokens, pos) {
295
+ const head = parseHeader(tokens, pos, PLACEHOLDER, () => {
296
+ const condition = parseExpression(tokens, pos + 1);
297
+ return { value: condition.node, nextPos: expect(tokens, condition.nextPos, "THEN") };
298
+ });
299
+ const condition = head.value;
300
+ let nextPos = head.nextPos;
301
+ const then = parseBlock(tokens, nextPos, ["ENDIF", "ELSE"]);
302
+ nextPos = then.nextPos;
303
+ let elseBranch = null;
304
+ if (tokens[nextPos]?.type === "ELSE") {
305
+ nextPos++;
306
+ const elseBlock = parseBlock(tokens, nextPos, ["ENDIF"]);
307
+ elseBranch = elseBlock.stmts;
308
+ nextPos = elseBlock.nextPos;
309
+ }
310
+ nextPos = expect(tokens, nextPos, "ENDIF");
311
+ return {
312
+ node: { kind: "If", condition, thenBranch: then.stmts, elseBranch, line: tokens[pos].line },
313
+ nextPos
314
+ };
315
+ }
316
+ const FOR_FALLBACK = { name: "", from: PLACEHOLDER, dir: "TO", to: PLACEHOLDER };
317
+ function parseForStatment(tokens, pos) {
318
+ const line = tokens[pos].line;
319
+ const head = parseHeader(tokens, pos, FOR_FALLBACK, () => {
320
+ let nextPos = expect(tokens, pos + 1, "IDENTIFIER");
321
+ const name = tokens[pos + 1].value;
322
+ nextPos = expect(tokens, nextPos, "EQ");
323
+ const from = parseExpression(tokens, nextPos);
324
+ nextPos = from.nextPos;
325
+ const dir = tokens[nextPos];
326
+ if (dir?.type !== "TO" && dir?.type !== "DOWNTO") {
327
+ fail(tokens, nextPos, `Expected "to" or "downto" but found ${found(dir)}.`);
328
+ }
329
+ nextPos = expect(tokens, nextPos, dir.type);
330
+ const to = parseExpression(tokens, nextPos);
331
+ nextPos = expect(tokens, to.nextPos, "DO");
332
+ return { value: { name, from: from.node, dir: dir.type, to: to.node }, nextPos };
333
+ });
334
+ const block = parseBlock(tokens, head.nextPos, ["ENDFOR"]);
335
+ const nextPos = expect(tokens, block.nextPos, "ENDFOR");
336
+ return {
337
+ node: { kind: "For", ...head.value, block: block.stmts, line },
338
+ nextPos
339
+ };
340
+ }
341
+ function parseWhileStatement(tokens, pos) {
342
+ const line = tokens[pos].line;
343
+ const head = parseHeader(tokens, pos, PLACEHOLDER, () => {
344
+ const condition = parseExpression(tokens, pos + 1);
345
+ return { value: condition.node, nextPos: expect(tokens, condition.nextPos, "DO") };
346
+ });
347
+ const condition = head.value;
348
+ let nextPos = head.nextPos;
349
+ const block = parseBlock(tokens, nextPos, ["ENDWHILE"]);
350
+ nextPos = expect(tokens, block.nextPos, "ENDWHILE");
351
+ return {
352
+ node: { kind: "While", condition, block: block.stmts, line },
353
+ nextPos
354
+ };
355
+ }
356
+ function parseArguments(tokens, pos) {
357
+ const args = [];
358
+ let nextPos = pos;
359
+ const next = tokens[nextPos];
360
+ if (next?.type === "RPAREN")
361
+ return { args, nextPos };
362
+ let expr = parseExpression(tokens, nextPos);
363
+ args.push(expr.node);
364
+ nextPos = expr.nextPos;
365
+ while (tokens[nextPos]?.type === "COMMA") {
366
+ nextPos++;
367
+ expr = parseExpression(tokens, nextPos);
368
+ args.push(expr.node);
369
+ nextPos = expr.nextPos;
370
+ }
371
+ return { args, nextPos };
372
+ }
373
+ function parseOneParameter(tokens, pos) {
374
+ let nextPos = pos;
375
+ let byRef = false;
376
+ if (tokens[nextPos]?.type === "REF") {
377
+ byRef = true;
378
+ nextPos++;
379
+ }
380
+ nextPos = expect(tokens, nextPos, "IDENTIFIER");
381
+ const name = tokens[nextPos - 1].value;
382
+ return { param: { name, byRef }, nextPos };
383
+ }
384
+ function parseParameters(tokens, pos) {
385
+ const params = [];
386
+ let nextPos = pos;
387
+ let next = tokens[nextPos];
388
+ if (next?.type === "RPAREN")
389
+ return { params, nextPos };
390
+ let one = parseOneParameter(tokens, nextPos);
391
+ params.push(one.param);
392
+ nextPos = one.nextPos;
393
+ while (tokens[nextPos]?.type === "COMMA") {
394
+ one = parseOneParameter(tokens, nextPos + 1);
395
+ params.push(one.param);
396
+ nextPos = one.nextPos;
397
+ }
398
+ return { params, nextPos };
399
+ }
400
+ function parseReturnStmt(tokens, pos) {
401
+ let nextPos = pos + 1;
402
+ const next = tokens[nextPos];
403
+ if (!next || next.type === "NEWLINE" || next.type === "EOF" || BLOCK_ENDERS.has(next.type)) {
404
+ return { node: { kind: "Return", value: undefined, line: tokens[pos].line }, nextPos };
405
+ }
406
+ const value = parseExpression(tokens, nextPos);
407
+ nextPos = value.nextPos;
408
+ return { node: { kind: "Return", value: value.node, line: tokens[pos].line }, nextPos };
409
+ }
410
+ // target := ("this" | IDENTIFIER) accessor*
411
+ function parseTarget(tokens, pos) {
412
+ const first = tokens[pos];
413
+ let root;
414
+ if (first.type === "THIS")
415
+ root = { kind: "This" };
416
+ else if (first.type === "IDENTIFIER")
417
+ root = { kind: "Name", name: first.value };
418
+ else
419
+ fail(tokens, pos, `Expected a variable or "this" but found ${found(first)}.`);
420
+ const path = [];
421
+ let nextPos = pos + 1;
422
+ while (true) {
423
+ const token = tokens[nextPos];
424
+ if (token?.type === "DOT") {
425
+ nextPos = expect(tokens, nextPos + 1, "IDENTIFIER");
426
+ path.push({ kind: "Field", name: tokens[nextPos - 1].value });
427
+ }
428
+ else if (token?.type === "LBRACK") {
429
+ const index = parseExpression(tokens, nextPos + 1);
430
+ nextPos = expect(tokens, index.nextPos, "RBRACK");
431
+ path.push({ kind: "Index", index: index.node });
432
+ }
433
+ else
434
+ break;
435
+ }
436
+ return { target: { root, path, line: first.line }, nextPos };
437
+ }
438
+ // assignment and callStatement both start with a target
439
+ // this is parsed and then the next token decides which one
440
+ function parseTargetStatement(tokens, pos) {
441
+ const t = parseTarget(tokens, pos);
442
+ const next = tokens[t.nextPos];
443
+ if (next?.type === "EQ") {
444
+ const value = parseExpression(tokens, t.nextPos + 1);
445
+ return {
446
+ node: { kind: "Assign", target: t.target, value: value.node, line: t.target.line },
447
+ nextPos: value.nextPos
448
+ };
449
+ }
450
+ if (next?.type === "LPAREN") {
451
+ return parseCall(tokens, t.nextPos, t.target);
452
+ }
453
+ fail(tokens, t.nextPos, `Expected "=" or "(" after variable but found ${found(next)}`);
454
+ }
455
+ function parseCall(tokens, pos, callee) {
456
+ let nextPos = expect(tokens, pos, "LPAREN");
457
+ const args = parseArguments(tokens, nextPos);
458
+ nextPos = expect(tokens, args.nextPos, "RPAREN");
459
+ return { node: { kind: "Call", callee, args: args.args, line: callee.line }, nextPos };
460
+ }
461
+ ;
462
+ const FUNCTION_FALLBACK = { name: "", params: [] };
463
+ function parseFunctionDef(tokens, pos) {
464
+ const head = parseHeader(tokens, pos, FUNCTION_FALLBACK, () => {
465
+ let nextPos = expect(tokens, pos + 1, "IDENTIFIER");
466
+ const name = tokens[pos + 1].value;
467
+ nextPos = expect(tokens, nextPos, "LPAREN");
468
+ const params = parseParameters(tokens, nextPos);
469
+ nextPos = expect(tokens, params.nextPos, "RPAREN");
470
+ return { value: { name, params: params.params }, nextPos };
471
+ });
472
+ const block = parseBlock(tokens, head.nextPos, ["ENDFUNCTION"]);
473
+ const nextPos = expect(tokens, block.nextPos, "ENDFUNCTION");
474
+ return {
475
+ node: { kind: "Function", ...head.value, block: block.stmts, line: tokens[pos].line },
476
+ nextPos
477
+ };
478
+ }
479
+ // decides based on the current token which kind of statement this is.
480
+ // IDENTIFIER is ambiguous on its own so it peaks one token ahead to
481
+ // tell them apart
482
+ function parseStatement(tokens, pos) {
483
+ const token = tokens[pos];
484
+ if (token.type === "IF") {
485
+ return parseIfStatement(tokens, pos);
486
+ }
487
+ if (token.type === "WHILE") {
488
+ return parseWhileStatement(tokens, pos);
489
+ }
490
+ if (token.type === "FOR") {
491
+ return parseForStatment(tokens, pos);
492
+ }
493
+ if (token.type === "RETURN") {
494
+ return parseReturnStmt(tokens, pos);
495
+ }
496
+ if (token.type === "IDENTIFIER" || token.type === "THIS") {
497
+ return parseTargetStatement(tokens, pos);
498
+ }
499
+ // these are common mistakes with a likely cause
500
+ // the likely error is reported as a single case
501
+ if (token.type === "FUNCTION") {
502
+ const f = parseFunctionDef(tokens, pos);
503
+ throw new ParseError(`Functions can't be defined inside other blocks. If that's not what you meant, an "end..." keyword may be missing above this.`, token.line, f.nextPos);
504
+ }
505
+ if (token.type === "CLASS") {
506
+ const c = parseClassDef(tokens, pos);
507
+ throw new ParseError("Classes can only be defined at the top level.", token.line, c.nextPos);
508
+ }
509
+ // parseBlock deals with these itself, so this is only reached at the top level
510
+ if (BLOCK_ENDERS.has(token.type)) {
511
+ fail(tokens, pos, `Unexpected ${found(token)}, there is nothing for it to close.`);
512
+ }
513
+ fail(tokens, pos, `Unexpected ${found(token)}.`);
514
+ }
515
+ const DEFAULT_FIELD_ACCESS = "private";
516
+ const DEFAULT_METHOD_ACCESS = "public";
517
+ function parseAccess(tokens, pos) {
518
+ const type = tokens[pos]?.type;
519
+ if (type === "PUBLIC")
520
+ return { access: "public", nextPos: pos + 1 };
521
+ if (type === "PRIVATE")
522
+ return { access: "private", nextPos: pos + 1 };
523
+ return { access: undefined, nextPos: pos };
524
+ }
525
+ // fieldDef := ("public" | "private")? IDENTIFIER
526
+ function parseField(tokens, pos) {
527
+ const { access, nextPos: afterAccess } = parseAccess(tokens, pos);
528
+ const nextPos = expect(tokens, afterAccess, "IDENTIFIER");
529
+ const token = tokens[nextPos - 1];
530
+ return { node: { kind: "Field", name: token.value, access: access ?? DEFAULT_FIELD_ACCESS, line: token.line }, nextPos };
531
+ }
532
+ // constructor := "constructor" "(" parameters ")" statement* "endconstructor"
533
+ function parseConstructor(tokens, pos) {
534
+ const line = tokens[pos].line;
535
+ const head = parseHeader(tokens, pos, [], () => {
536
+ let nextPos = expect(tokens, pos + 1, "LPAREN");
537
+ const params = parseParameters(tokens, nextPos);
538
+ nextPos = expect(tokens, params.nextPos, "RPAREN");
539
+ return { value: params.params, nextPos };
540
+ });
541
+ const block = parseBlock(tokens, head.nextPos, ["ENDCONSTRUCTOR"]);
542
+ const nextPos = expect(tokens, block.nextPos, "ENDCONSTRUCTOR");
543
+ return { node: { kind: "Constructor", params: head.value, block: block.stmts, line }, nextPos };
544
+ }
545
+ // classDef := "class" IDENTIFIER fieldDef* constructor? (("public" | "private")? functionDef)* "endclass"
546
+ // a field and method can both start with public/private, so the token after the
547
+ // modifier says which one it is (IDENTIFIER = field, FUNCTION = method).
548
+ function parseClassDef(tokens, pos) {
549
+ const line = tokens[pos].line;
550
+ let nextPos = expect(tokens, pos + 1, "IDENTIFIER");
551
+ const name = tokens[nextPos - 1].value;
552
+ const fields = [];
553
+ let ctor = null;
554
+ const methods = [];
555
+ openBlocks.push(["ENDCLASS"]);
556
+ try {
557
+ while (true) {
558
+ nextPos = skipNewLines(tokens, nextPos);
559
+ const start = nextPos;
560
+ const type = tokens[start]?.type;
561
+ if (!type || type === "ENDCLASS" || type === "EOF")
562
+ break;
563
+ try {
564
+ const { access, nextPos: afterAccess } = parseAccess(tokens, start);
565
+ const hasAccess = afterAccess !== start;
566
+ const kind = tokens[afterAccess]?.type;
567
+ if (kind === "IDENTIFIER") {
568
+ const field = parseField(tokens, start);
569
+ if (ctor || methods.length > 0) {
570
+ report(field.node.line, "Fields must be declared before the constructor and methods.");
571
+ }
572
+ fields.push(field.node);
573
+ nextPos = field.nextPos;
574
+ if (tokens[nextPos]?.type === "EQ") {
575
+ report(tokens[nextPos].line, "Fields can't have a value where they're declared, assign them in the constructor with this.<name> = ...");
576
+ nextPos = skipToLineEnd(tokens, nextPos);
577
+ }
578
+ }
579
+ else if (kind === "CONSTRUCTOR") {
580
+ const ctorLine = tokens[afterAccess].line;
581
+ if (hasAccess)
582
+ report(ctorLine, "A constructor can't be public or private.");
583
+ if (ctor)
584
+ report(ctorLine, "A class can only have one constructor.");
585
+ else if (methods.length > 0)
586
+ report(ctorLine, "The constructor must come before the methods.");
587
+ const c = parseConstructor(tokens, afterAccess);
588
+ ctor = ctor ?? c.node;
589
+ nextPos = c.nextPos;
590
+ }
591
+ else if (kind === "FUNCTION") {
592
+ const fn = parseFunctionDef(tokens, afterAccess);
593
+ methods.push({ kind: "Method", access: access ?? DEFAULT_METHOD_ACCESS, fn: fn.node });
594
+ nextPos = fn.nextPos;
595
+ }
596
+ else if (hasAccess) {
597
+ fail(tokens, start, `Expected a field name or "function" after "${tokens[start].value}" but found ${found(tokens[afterAccess])}.`);
598
+ }
599
+ else {
600
+ fail(tokens, start, `Unexpected ${found(tokens[start])} in a class body.`);
601
+ }
602
+ }
603
+ catch (e) {
604
+ nextPos = recover(e, tokens, start, skipToMemberEnd);
605
+ }
606
+ }
607
+ }
608
+ finally {
609
+ openBlocks.pop();
610
+ }
611
+ nextPos = expect(tokens, nextPos, "ENDCLASS");
612
+ return { node: { kind: "Class", name, fields, ctor, methods, line }, nextPos };
613
+ }
614
+ export function parseExpressionOnly(tokens) {
615
+ errors = [];
616
+ openBlocks = [];
617
+ try {
618
+ const start = skipNewLines(tokens, 0);
619
+ const { node, nextPos } = parseExpression(tokens, start);
620
+ const end = skipNewLines(tokens, nextPos);
621
+ if (tokens[end] && tokens[end].type !== "EOF")
622
+ fail(tokens, end, `Unexpected ${found(tokens[end])}.`);
623
+ return node;
624
+ }
625
+ catch (e) {
626
+ if (e instanceof ParseError)
627
+ throw new CompileError([{ message: e.message, line: e.line }]);
628
+ throw e;
629
+ }
630
+ }
631
+ /**
632
+ * Parse a full token stream (as produced by `tokenise()`) into a `Program`.
633
+ *
634
+ * A `Program` is a list of top-level statements and function definitions.
635
+ * Function definitions can only appear here, at the top level (see grammar.md
636
+ * for more details of why), never nested in a statment.
637
+ *
638
+ * @param tokens stream of tokens
639
+ * @returns list of statements and function definitions
640
+ * @throws {CompileError} on any token sequence that doesn't match the grammar
641
+ */
642
+ export function parseProgram(tokens) {
643
+ errors = [];
644
+ openBlocks = [];
645
+ const program = [];
646
+ let pos = skipNewLines(tokens, 0);
647
+ while (tokens[pos] && tokens[pos].type !== "EOF") {
648
+ const start = pos;
649
+ try {
650
+ const type = tokens[pos].type;
651
+ const { node, nextPos } = type === "FUNCTION" ? parseFunctionDef(tokens, pos) :
652
+ type === "CLASS" ? parseClassDef(tokens, pos) :
653
+ parseStatement(tokens, pos);
654
+ program.push(node);
655
+ pos = skipNewLines(tokens, nextPos);
656
+ }
657
+ catch (e) {
658
+ pos = skipNewLines(tokens, recover(e, tokens, start, skipToLineEnd));
659
+ }
660
+ }
661
+ if (errors.length > 0)
662
+ throw new CompileError(errors);
663
+ return program;
664
+ }
@@ -0,0 +1,10 @@
1
+ import type { ClassDef, Expr, FunctionDef, Program } from "./types.js";
2
+ import type { Diagnostic } from "./errors.js";
3
+ export type { Diagnostic };
4
+ export type Known = {
5
+ defs: (FunctionDef | ClassDef)[];
6
+ vars: string[];
7
+ };
8
+ export declare function checkProgram(program: Program): Diagnostic[];
9
+ export declare function checkChunk(chunk: Program, known: Known): Diagnostic[];
10
+ export declare function checkExpression(expr: Expr, known: Known): Diagnostic[];