paseo-plugin-genui 0.1.1 → 0.1.3

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.
@@ -1,6 +1,7 @@
1
1
  import type { BinaryOperator, Expr, NamedArg, Statement } from "./ast";
2
2
  import type { DiagnosticList, Pos } from "./diagnostics";
3
3
  import type { Token } from "./lexer";
4
+ import { defineClass } from "./define-class";
4
5
 
5
6
  const PRECEDENCE: Record<string, number> = {
6
7
  "??": 1,
@@ -17,13 +18,22 @@ const KEYWORDS: Record<string, true | false | null> = { true: true, false: false
17
18
  /** AST depth beyond this is rejected so later tree walks cannot overflow the stack. */
18
19
  const MAX_NESTING = 100;
19
20
 
20
- class ParseError {
21
- constructor(
22
- readonly pos: Pos,
23
- readonly message: string,
24
- ) {}
21
+ interface ParseErrorFields {
22
+ pos: Pos;
23
+ message: string;
25
24
  }
26
25
 
26
+ const ParseError = defineClass(
27
+ function (this: ParseErrorFields, pos: Pos, message: string): void {
28
+ this.pos = pos;
29
+ this.message = message;
30
+ },
31
+ {
32
+
33
+ },
34
+ );
35
+ type ParseError = InstanceType<typeof ParseError>;
36
+
27
37
  function describe(token: Token): string {
28
38
  switch (token.t) {
29
39
  case "num":
@@ -62,294 +72,301 @@ export function parse(tokens: readonly Token[], diagnostics: DiagnosticList): St
62
72
  }
63
73
  }
64
74
 
65
- class Parser {
66
- i = 0;
67
-
68
- constructor(
69
- private readonly tokens: readonly Token[],
70
- private depth: number,
71
- ) {}
75
+ interface ParserFields {
76
+ i: number;
77
+ tokens: readonly Token[];
78
+ depth: number;
79
+ }
72
80
 
73
- peek(offset = 0): Token {
74
- return this.tokens[Math.min(this.i + offset, this.tokens.length - 1)];
75
- }
81
+ const Parser = defineClass(
82
+ function (this: ParserFields, tokens: readonly Token[], depth: number): void {
83
+ this.tokens = tokens;
84
+ this.depth = depth;
85
+ this.i = 0;
86
+ },
87
+ {
88
+ peek(offset = 0): Token {
89
+ return this.tokens[Math.min(this.i + offset, this.tokens.length - 1)];
90
+ },
76
91
 
77
- private isPunct(value: string, offset = 0): boolean {
78
- const token = this.peek(offset);
79
- return token.t === "punct" && token.value === value;
80
- }
92
+ isPunct(value: string, offset = 0): boolean {
93
+ const token = this.peek(offset);
94
+ return token.t === "punct" && token.value === value;
95
+ },
81
96
 
82
- private eat(value: string): boolean {
83
- if (!this.isPunct(value)) return false;
84
- this.i++;
85
- return true;
86
- }
97
+ eat(value: string): boolean {
98
+ if (!this.isPunct(value)) return false;
99
+ this.i++;
100
+ return true;
101
+ },
87
102
 
88
- /** Consumes the closer of `open`, or fails naming what else was acceptable. */
89
- private close(closer: string, open: Token, alternatives = ""): void {
90
- if (this.eat(closer)) return;
91
- const opener = open.t === "punct" ? open.value : "(";
92
- throw new ParseError(
93
- this.peek(),
94
- `expected ${alternatives}\`${closer}\` to close \`${opener}\` from ${open.line}:${open.column}, found ${describe(this.peek())}`,
95
- );
96
- }
103
+ /** Consumes the closer of `open`, or fails naming what else was acceptable. */
104
+ close(closer: string, open: Token, alternatives = ""): void {
105
+ if (this.eat(closer)) return;
106
+ const opener = open.t === "punct" ? open.value : "(";
107
+ throw new ParseError(
108
+ this.peek(),
109
+ `expected ${alternatives}\`${closer}\` to close \`${opener}\` from ${open.line}:${open.column}, found ${describe(this.peek())}`,
110
+ );
111
+ },
97
112
 
98
- private ident(what: string): Pos & { readonly value: string } {
99
- const token = this.peek();
100
- if (token.t !== "ident") throw new ParseError(token, `expected ${what}, found ${describe(token)}`);
101
- this.i++;
102
- return token;
103
- }
113
+ ident(what: string): Pos & { readonly value: string } {
114
+ const token = this.peek();
115
+ if (token.t !== "ident") throw new ParseError(token, `expected ${what}, found ${describe(token)}`);
116
+ this.i++;
117
+ return token;
118
+ },
104
119
 
105
- statement(): Statement {
106
- this.depth = 0;
107
- const first = this.peek();
108
- let statement: Statement;
109
- if ((first.t === "state" || first.t === "ident") && this.isPunct("=", 1)) {
110
- if (first.t === "ident" && Object.hasOwn(KEYWORDS, first.value)) {
111
- throw new ParseError(first, `\`${first.value}\` is a keyword and cannot be assigned`);
120
+ statement(): Statement {
121
+ this.depth = 0;
122
+ const first = this.peek();
123
+ let statement: Statement;
124
+ if ((first.t === "state" || first.t === "ident") && this.isPunct("=", 1)) {
125
+ if (first.t === "ident" && Object.hasOwn(KEYWORDS, first.value)) {
126
+ throw new ParseError(first, `\`${first.value}\` is a keyword and cannot be assigned`);
127
+ }
128
+ this.i += 2;
129
+ const kind = first.t === "state" ? "state" : "named";
130
+ statement = { kind, name: first.value, value: this.expr(), pos: first };
131
+ } else {
132
+ statement = { kind: "root", value: this.expr() };
112
133
  }
113
- this.i += 2;
114
- const kind = first.t === "state" ? "state" : "named";
115
- statement = { kind, name: first.value, value: this.expr(), pos: first };
116
- } else {
117
- statement = { kind: "root", value: this.expr() };
118
- }
119
- const next = this.peek();
120
- if (next.t !== "sep" && next.t !== "eof") {
121
- throw new ParseError(
122
- next,
123
- `expected a new line or \`;\` after the statement, found ${describe(next)}; wrap multi-line expressions in brackets`,
124
- );
125
- }
126
- return statement;
127
- }
134
+ const next = this.peek();
135
+ if (next.t !== "sep" && next.t !== "eof") {
136
+ throw new ParseError(
137
+ next,
138
+ `expected a new line or \`;\` after the statement, found ${describe(next)}; wrap multi-line expressions in brackets`,
139
+ );
140
+ }
141
+ return statement;
142
+ },
128
143
 
129
- /** Counts one level of AST nesting; callers restore `depth` when their subtree is done. */
130
- private nest(at: Token): void {
131
- if (++this.depth > MAX_NESTING) throw new ParseError(at, "expression is nested too deeply; split it into named values");
132
- }
144
+ /** Counts one level of AST nesting; callers restore `depth` when their subtree is done. */
145
+ nest(at: Token): void {
146
+ if (++this.depth > MAX_NESTING) throw new ParseError(at, "expression is nested too deeply; split it into named values");
147
+ },
133
148
 
134
- private expr(): Expr {
135
- const saved = this.depth;
136
- this.nest(this.peek());
137
- const expr = this.isArrowStart() ? this.arrow() : this.conditional();
138
- this.depth = saved;
139
- return expr;
140
- }
149
+ expr(): Expr {
150
+ const saved = this.depth;
151
+ this.nest(this.peek());
152
+ const expr = this.isArrowStart() ? this.arrow() : this.conditional();
153
+ this.depth = saved;
154
+ return expr;
155
+ },
141
156
 
142
- private isArrowStart(): boolean {
143
- if (this.peek().t === "ident") return this.isPunct("=>", 1);
144
- if (!this.isPunct("(")) return false;
145
- let offset = 1;
146
- if (this.peek(offset).t === "ident") {
147
- offset++;
148
- while (this.isPunct(",", offset) && this.peek(offset + 1).t === "ident") offset += 2;
149
- }
150
- return this.isPunct(")", offset) && this.isPunct("=>", offset + 1);
151
- }
157
+ isArrowStart(): boolean {
158
+ if (this.peek().t === "ident") return this.isPunct("=>", 1);
159
+ if (!this.isPunct("(")) return false;
160
+ let offset = 1;
161
+ if (this.peek(offset).t === "ident") {
162
+ offset++;
163
+ while (this.isPunct(",", offset) && this.peek(offset + 1).t === "ident") offset += 2;
164
+ }
165
+ return this.isPunct(")", offset) && this.isPunct("=>", offset + 1);
166
+ },
152
167
 
153
- private arrow(): Expr {
154
- const start = this.peek();
155
- const params: string[] = [];
156
- if (this.eat("(")) {
157
- while (!this.eat(")")) {
168
+ arrow(): Expr {
169
+ const start = this.peek();
170
+ const params: string[] = [];
171
+ if (this.eat("(")) {
172
+ while (!this.eat(")")) {
173
+ params.push(this.ident("a parameter name").value);
174
+ this.eat(",");
175
+ }
176
+ } else {
158
177
  params.push(this.ident("a parameter name").value);
159
- this.eat(",");
160
178
  }
161
- } else {
162
- params.push(this.ident("a parameter name").value);
163
- }
164
- const keyword = params.find((name) => Object.hasOwn(KEYWORDS, name));
165
- if (keyword !== undefined) throw new ParseError(start, `\`${keyword}\` cannot be a parameter name`);
166
- this.i++; // `=>`, guaranteed by isArrowStart
167
- return { type: "arrow", params, body: this.expr(), pos: start };
168
- }
179
+ const keyword = params.find((name) => Object.hasOwn(KEYWORDS, name));
180
+ if (keyword !== undefined) throw new ParseError(start, `\`${keyword}\` cannot be a parameter name`);
181
+ this.i++; // `=>`, guaranteed by isArrowStart
182
+ return { type: "arrow", params, body: this.expr(), pos: start };
183
+ },
169
184
 
170
- private conditional(): Expr {
171
- const test = this.binary(1);
172
- const question = this.peek();
173
- if (!this.eat("?")) return test;
174
- const then = this.expr();
175
- if (!this.eat(":")) {
176
- throw new ParseError(this.peek(), `expected \`:\` for the \`?\` at ${question.line}:${question.column}, found ${describe(this.peek())}`);
177
- }
178
- return { type: "conditional", test, then, else: this.expr(), pos: question };
179
- }
185
+ conditional(): Expr {
186
+ const test = this.binary(1);
187
+ const question = this.peek();
188
+ if (!this.eat("?")) return test;
189
+ const then = this.expr();
190
+ if (!this.eat(":")) {
191
+ throw new ParseError(this.peek(), `expected \`:\` for the \`?\` at ${question.line}:${question.column}, found ${describe(this.peek())}`);
192
+ }
193
+ return { type: "conditional", test, then, else: this.expr(), pos: question };
194
+ },
180
195
 
181
- private binary(minPrecedence: number): Expr {
182
- const saved = this.depth;
183
- let left = this.unary();
184
- for (;;) {
185
- const token = this.peek();
186
- if (token.t !== "punct") break;
187
- const precedence = PRECEDENCE[token.value];
188
- if (precedence === undefined || precedence < minPrecedence) break;
189
- this.nest(token);
190
- this.i++;
191
- const right = this.binary(precedence + 1);
192
- left = { type: "binary", op: token.value as BinaryOperator, left, right, pos: token };
193
- }
194
- this.depth = saved;
195
- return left;
196
- }
196
+ binary(minPrecedence: number): Expr {
197
+ const saved = this.depth;
198
+ let left = this.unary();
199
+ for (;;) {
200
+ const token = this.peek();
201
+ if (token.t !== "punct") break;
202
+ const precedence = PRECEDENCE[token.value];
203
+ if (precedence === undefined || precedence < minPrecedence) break;
204
+ this.nest(token);
205
+ this.i++;
206
+ const right = this.binary(precedence + 1);
207
+ left = { type: "binary", op: token.value as BinaryOperator, left, right, pos: token };
208
+ }
209
+ this.depth = saved;
210
+ return left;
211
+ },
197
212
 
198
- private unary(): Expr {
199
- const saved = this.depth;
200
- const operators: Token[] = [];
201
- while (this.isPunct("!") || this.isPunct("-")) {
202
- this.nest(this.peek());
203
- operators.push(this.tokens[this.i++]);
204
- }
205
- let expr = this.postfix();
206
- // `**` binds tighter than a prefix operator and associates to the right,
207
- // as in maths and Python: `-a ** b` is `-(a ** b)`, `a ** b ** c` is `a ** (b ** c)`.
208
- if (this.isPunct("**")) {
209
- const token = this.peek();
210
- this.nest(token);
211
- this.i++;
212
- expr = { type: "binary", op: "**", left: expr, right: this.unary(), pos: token };
213
- }
214
- for (let k = operators.length - 1; k >= 0; k--) {
215
- const token = operators[k];
216
- expr = { type: "unary", op: token.t === "punct" && token.value === "!" ? "!" : "-", operand: expr, pos: token };
217
- }
218
- this.depth = saved;
219
- return expr;
220
- }
213
+ unary(): Expr {
214
+ const saved = this.depth;
215
+ const operators: Token[] = [];
216
+ while (this.isPunct("!") || this.isPunct("-")) {
217
+ this.nest(this.peek());
218
+ operators.push(this.tokens[this.i++]);
219
+ }
220
+ let expr = this.postfix();
221
+ // `**` binds tighter than a prefix operator and associates to the right,
222
+ // as in maths and Python: `-a ** b` is `-(a ** b)`, `a ** b ** c` is `a ** (b ** c)`.
223
+ if (this.isPunct("**")) {
224
+ const token = this.peek();
225
+ this.nest(token);
226
+ this.i++;
227
+ expr = { type: "binary", op: "**", left: expr, right: this.unary(), pos: token };
228
+ }
229
+ for (let k = operators.length - 1; k >= 0; k--) {
230
+ const token = operators[k];
231
+ expr = { type: "unary", op: token.t === "punct" && token.value === "!" ? "!" : "-", operand: expr, pos: token };
232
+ }
233
+ this.depth = saved;
234
+ return expr;
235
+ },
221
236
 
222
- private postfix(): Expr {
223
- let expr = this.primary();
224
- for (;;) {
225
- if (this.isPunct(".") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
226
- if (this.eat(".")) {
227
- const name = this.ident("a property or method name after `.`");
228
- if (this.isPunct("(")) {
229
- // `Math.round(x)` and `Object.entries(o)` are how models write the
230
- // built-ins; they parse as the plain calls `round(x)` and `entries(o)`.
231
- expr =
232
- expr.type === "ident" && (expr.name === "Math" || expr.name === "Object")
233
- ? { type: "call", name: name.value, ...this.args(), pos: name }
234
- : { type: "method", object: expr, name: name.value, ...this.args(), pos: name };
237
+ postfix(): Expr {
238
+ let expr = this.primary();
239
+ for (;;) {
240
+ if (this.isPunct(".") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
241
+ if (this.eat(".")) {
242
+ const name = this.ident("a property or method name after `.`");
243
+ if (this.isPunct("(")) {
244
+ // `Math.round(x)` and `Object.entries(o)` are how models write the
245
+ // built-ins; they parse as the plain calls `round(x)` and `entries(o)`.
246
+ expr =
247
+ expr.type === "ident" && (expr.name === "Math" || expr.name === "Object")
248
+ ? { type: "call", name: name.value, ...this.args(), pos: name }
249
+ : { type: "method", object: expr, name: name.value, ...this.args(), pos: name };
250
+ } else {
251
+ expr = { type: "member", object: expr, name: name.value, pos: name };
252
+ }
253
+ } else if (this.isPunct("[")) {
254
+ const open = this.tokens[this.i++];
255
+ const index = this.expr();
256
+ this.close("]", open);
257
+ expr = { type: "index", object: expr, index, pos: open };
258
+ } else if (this.isPunct("(")) {
259
+ if (expr.type !== "ident") {
260
+ throw new ParseError(this.peek(), "only components, actions, functions and methods can be called");
261
+ }
262
+ expr = { type: "call", name: expr.name, ...this.args(), pos: expr.pos };
235
263
  } else {
236
- expr = { type: "member", object: expr, name: name.value, pos: name };
237
- }
238
- } else if (this.isPunct("[")) {
239
- const open = this.tokens[this.i++];
240
- const index = this.expr();
241
- this.close("]", open);
242
- expr = { type: "index", object: expr, index, pos: open };
243
- } else if (this.isPunct("(")) {
244
- if (expr.type !== "ident") {
245
- throw new ParseError(this.peek(), "only components, actions, functions and methods can be called");
264
+ return expr;
246
265
  }
247
- expr = { type: "call", name: expr.name, ...this.args(), pos: expr.pos };
248
- } else {
249
- return expr;
250
266
  }
251
- }
252
- }
267
+ },
253
268
 
254
- private args(): { args: Expr[]; named: NamedArg[] } {
255
- const open = this.tokens[this.i++];
256
- const args: Expr[] = [];
257
- const named: NamedArg[] = [];
258
- while (!this.eat(")")) {
259
- const token = this.peek();
260
- if (token.t === "ident" && this.isPunct(":", 1)) {
261
- this.i += 2;
262
- named.push({ name: token.value, value: this.expr(), pos: token });
263
- } else {
264
- if (named.length > 0) {
265
- throw new ParseError(token, "positional arguments must come before named ones");
269
+ args(): { args: Expr[]; named: NamedArg[] } {
270
+ const open = this.tokens[this.i++];
271
+ const args: Expr[] = [];
272
+ const named: NamedArg[] = [];
273
+ while (!this.eat(")")) {
274
+ const token = this.peek();
275
+ if (token.t === "ident" && this.isPunct(":", 1)) {
276
+ this.i += 2;
277
+ named.push({ name: token.value, value: this.expr(), pos: token });
278
+ } else {
279
+ if (named.length > 0) {
280
+ throw new ParseError(token, "positional arguments must come before named ones");
281
+ }
282
+ args.push(this.expr());
283
+ }
284
+ if (!this.eat(",")) {
285
+ this.close(")", open, "`,` or ");
286
+ break;
266
287
  }
267
- args.push(this.expr());
268
- }
269
- if (!this.eat(",")) {
270
- this.close(")", open, "`,` or ");
271
- break;
272
288
  }
273
- }
274
- return { args, named };
275
- }
289
+ return { args, named };
290
+ },
276
291
 
277
- private primary(): Expr {
278
- const token = this.peek();
279
- switch (token.t) {
280
- case "num":
281
- case "str":
282
- this.i++;
283
- return { type: "literal", value: token.value, pos: token };
284
- case "tpl": {
285
- this.i++;
286
- const parts = token.parts.map((tokens) => {
287
- const sub = new Parser(tokens, this.depth);
288
- const part = sub.expr();
289
- const end = sub.peek();
290
- if (end.t !== "eof") {
291
- throw new ParseError(end, `expected \`}\` to end the template expression, found ${describe(end)}`);
292
- }
293
- return part;
294
- });
295
- return { type: "template", quasis: token.quasis, parts, pos: token };
296
- }
297
- case "ident":
298
- this.i++;
299
- if (Object.hasOwn(KEYWORDS, token.value)) return { type: "literal", value: KEYWORDS[token.value], pos: token };
300
- return { type: "ident", name: token.value, pos: token };
301
- case "state":
302
- this.i++;
303
- return { type: "state", name: token.value, pos: token };
304
- case "punct":
305
- if (token.value === "(") {
292
+ primary(): Expr {
293
+ const token = this.peek();
294
+ switch (token.t) {
295
+ case "num":
296
+ case "str":
297
+ this.i++;
298
+ return { type: "literal", value: token.value, pos: token };
299
+ case "tpl": {
306
300
  this.i++;
307
- const inner = this.expr();
308
- this.close(")", token);
309
- return inner;
301
+ const parts = token.parts.map((tokens) => {
302
+ const sub = new Parser(tokens, this.depth);
303
+ const part = sub.expr();
304
+ const end = sub.peek();
305
+ if (end.t !== "eof") {
306
+ throw new ParseError(end, `expected \`}\` to end the template expression, found ${describe(end)}`);
307
+ }
308
+ return part;
309
+ });
310
+ return { type: "template", quasis: token.quasis, parts, pos: token };
310
311
  }
311
- if (token.value === "[") {
312
+ case "ident":
313
+ this.i++;
314
+ if (Object.hasOwn(KEYWORDS, token.value)) return { type: "literal", value: KEYWORDS[token.value], pos: token };
315
+ return { type: "ident", name: token.value, pos: token };
316
+ case "state":
312
317
  this.i++;
313
- const items: Expr[] = [];
314
- while (!this.eat("]")) {
315
- items.push(this.expr());
316
- if (!this.eat(",")) {
317
- this.close("]", token, "`,` or ");
318
- break;
318
+ return { type: "state", name: token.value, pos: token };
319
+ case "punct":
320
+ if (token.value === "(") {
321
+ this.i++;
322
+ const inner = this.expr();
323
+ this.close(")", token);
324
+ return inner;
325
+ }
326
+ if (token.value === "[") {
327
+ this.i++;
328
+ const items: Expr[] = [];
329
+ while (!this.eat("]")) {
330
+ items.push(this.expr());
331
+ if (!this.eat(",")) {
332
+ this.close("]", token, "`,` or ");
333
+ break;
334
+ }
319
335
  }
336
+ return { type: "list", items, pos: token };
320
337
  }
321
- return { type: "list", items, pos: token };
322
- }
323
- if (token.value === "{") return this.object(token);
324
- break;
325
- }
326
- throw new ParseError(token, `expected an expression, found ${describe(token)}`);
327
- }
328
-
329
- private object(open: Token): Expr {
330
- this.i++;
331
- const entries: { key: string; value: Expr; pos: Pos }[] = [];
332
- while (!this.eat("}")) {
333
- const key = this.peek();
334
- if (key.t !== "ident" && key.t !== "str") {
335
- throw new ParseError(key, `expected an object key (a name or a string), found ${describe(key)}`);
338
+ if (token.value === "{") return this.object(token);
339
+ break;
336
340
  }
341
+ throw new ParseError(token, `expected an expression, found ${describe(token)}`);
342
+ },
343
+
344
+ object(open: Token): Expr {
337
345
  this.i++;
338
- // `{Good for: …}`: models write labels as bare words; nothing else may follow a key, so read them as one.
339
- let name = key.value;
340
- if (key.t === "ident") {
341
- for (let next = this.peek(); next.t === "ident" || next.t === "num"; next = this.peek()) {
342
- name += ` ${next.value}`;
343
- this.i++;
346
+ const entries: { key: string; value: Expr; pos: Pos }[] = [];
347
+ while (!this.eat("}")) {
348
+ const key = this.peek();
349
+ if (key.t !== "ident" && key.t !== "str") {
350
+ throw new ParseError(key, `expected an object key (a name or a string), found ${describe(key)}`);
351
+ }
352
+ this.i++;
353
+ // `{Good for: …}`: models write labels as bare words; nothing else may follow a key, so read them as one.
354
+ let name = key.value;
355
+ if (key.t === "ident") {
356
+ for (let next = this.peek(); next.t === "ident" || next.t === "num"; next = this.peek()) {
357
+ name += ` ${next.value}`;
358
+ this.i++;
359
+ }
360
+ }
361
+ if (!this.eat(":")) throw new ParseError(this.peek(), `expected \`:\` after the object key, found ${describe(this.peek())}`);
362
+ entries.push({ key: name, value: this.expr(), pos: key });
363
+ if (!this.eat(",")) {
364
+ this.close("}", open, "`,` or ");
365
+ break;
344
366
  }
345
367
  }
346
- if (!this.eat(":")) throw new ParseError(this.peek(), `expected \`:\` after the object key, found ${describe(this.peek())}`);
347
- entries.push({ key: name, value: this.expr(), pos: key });
348
- if (!this.eat(",")) {
349
- this.close("}", open, "`,` or ");
350
- break;
351
- }
352
- }
353
- return { type: "object", entries, pos: open };
354
- }
355
- }
368
+ return { type: "object", entries, pos: open };
369
+ },
370
+ },
371
+ );
372
+ type Parser = InstanceType<typeof Parser>;