squiffy-compiler 7.0.0-beta.6 → 7.0.0-beta.8

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.
Files changed (46) hide show
  1. package/dist/analyse.d.ts +12 -1
  2. package/dist/analyse.js +156 -9
  3. package/dist/compiler.d.ts +5 -3
  4. package/dist/compiler.js +3 -2
  5. package/dist/css-urls.d.ts +4 -0
  6. package/dist/css-urls.js +59 -0
  7. package/dist/emit.d.ts +18 -1
  8. package/dist/emit.js +46 -0
  9. package/dist/infix-expressions.d.ts +19 -0
  10. package/dist/infix-expressions.js +713 -0
  11. package/dist/language-service.d.ts +1 -0
  12. package/dist/language-service.js +34 -15
  13. package/dist/node.d.ts +2 -1
  14. package/dist/node.js +1 -0
  15. package/dist/parse.d.ts +4 -0
  16. package/dist/parse.js +29 -0
  17. package/dist/project.d.ts +31 -0
  18. package/dist/project.js +98 -0
  19. package/dist/quest/convert.js +67 -11
  20. package/dist/quest/scripts.js +13 -9
  21. package/dist/quest/text.js +17 -8
  22. package/dist/section-labels.d.ts +4 -0
  23. package/dist/section-labels.js +64 -0
  24. package/dist/setters.d.ts +4 -0
  25. package/dist/setters.js +11 -9
  26. package/dist/story-graph.d.ts +2 -0
  27. package/dist/story-graph.js +61 -16
  28. package/dist/syntax.d.ts +24 -3
  29. package/dist/templates.d.ts +6 -0
  30. package/dist/templates.js +128 -0
  31. package/dist/text.d.ts +3 -1
  32. package/dist/text.js +45 -11
  33. package/dist/twine/audio.d.ts +21 -0
  34. package/dist/twine/audio.js +80 -0
  35. package/dist/twine/convert.d.ts +45 -3
  36. package/dist/twine/convert.js +305 -37
  37. package/dist/twine/expression.d.ts +21 -1
  38. package/dist/twine/expression.js +105 -8
  39. package/dist/twine/harlowe.d.ts +9 -0
  40. package/dist/twine/harlowe.js +461 -86
  41. package/dist/twine/settings.d.ts +9 -0
  42. package/dist/twine/settings.js +322 -0
  43. package/dist/twine/sugarcube.d.ts +3 -0
  44. package/dist/twine/sugarcube.js +438 -114
  45. package/package.json +9 -2
  46. package/syntaxes/squiffy.tmLanguage.json +8 -3
@@ -0,0 +1,713 @@
1
+ // Rewrites infix expressions into the equivalent prefix helper calls, before the text reaches
2
+ // Handlebars. They're accepted in:
3
+ // conditions: {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
4
+ // (also {{#unless}}, {{else if}} and {{else unless}}, and what {{#each}} and
5
+ // {{#with}} go through: {{#each (range 1 (count + 1))}} (#447), and {{#every}}'s
6
+ // delay: {{#every delay * 1000}} (#451))
7
+ // values: {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
8
+ // (also {{inc}} and {{dec}}, and {{append}}, {{prepend}} and {{remove}})
9
+ // display: {{= price * 2}} -> {{mul price 2}}
10
+ // parameters: {{goto "x" after=delay * 1000}} -> {{goto "x" after=(mul delay 1000)}}
11
+ // (also {{embed}} (#450) and {{#animate}} (#451))
12
+ //
13
+ // Two operators work on values rather than numbers (#446):
14
+ // bag contains "key" -> (__contains bag "key") (lists, text and objects)
15
+ // hp > 0 ? "alive" : "dead" -> (cond (gt hp 0) "alive" "dead")
16
+ //
17
+ // Precedence, from tightest to loosest: unary minus, * / %, + -, comparisons (and contains),
18
+ // not/!, and/&&, or/||, and then ? :. So "not" applies to a whole comparison, as it reads in English: not gender = "male"
19
+ // means not (gender = "male").
20
+ // Expressions that don't use any infix operator are passed through unchanged (except {{= }},
21
+ // which isn't valid Handlebars, so it's always rewritten).
22
+ //
23
+ // "-" and "/" can appear inside Handlebars names and paths (my-score, ../score), so they're only
24
+ // operators at the start of a token: a - b and a -b subtract, but a-b is the attribute "a-b".
25
+ //
26
+ // Objects and lists (#442):
27
+ // { hp: 10, name: "Ann" } -> (__object "hp" 10 "name" "Ann")
28
+ // [1, 2, 3] -> (array 1 2 3)
29
+ // inventory[i].name -> (lookup (lookup inventory i) "name")
30
+ // hero.hp needs no rewriting: it's a Handlebars path. A "[" at the start of a value is a list if
31
+ // it's empty, or has a comma in it, or starts with a literal value; otherwise it's a Handlebars
32
+ // name that isn't a plain word, such as [my attribute], as before. A list of one attribute is
33
+ // written (array name).
34
+ const punctuation = new Set(["{", "}", ":", ",", "]"]);
35
+ const comparisonHelpers = {
36
+ "=": "eq",
37
+ "==": "eq",
38
+ "!=": "ne",
39
+ ">": "gt",
40
+ "<": "lt",
41
+ ">=": "gte",
42
+ "<=": "lte",
43
+ // a contains b (#446): see the __contains helper
44
+ "contains": "__contains",
45
+ };
46
+ const arithmeticHelpers = {
47
+ "+": "add",
48
+ "-": "sub",
49
+ "*": "mul",
50
+ "/": "div",
51
+ "%": "mod",
52
+ };
53
+ const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!", "+", "*", "%", "-", "/", "?"];
54
+ const keywordOps = ["and", "or", "not"];
55
+ const literals = ["true", "false", "null", "undefined"];
56
+ // Characters that end an identifier/path. "[" starts a Handlebars literal segment,
57
+ // e.g. [my attribute], which may contain any of these.
58
+ // "-" and "/" aren't here: see above.
59
+ const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~+*%:,]?"]);
60
+ const numberPattern = /^-?\d+(\.\d+)?$/;
61
+ class ExpressionError extends Error {
62
+ }
63
+ // Whether the "[" at `open`, at the start of a value, starts a list rather than a Handlebars name
64
+ // like [my attribute]: it's empty, or it has a comma in it, or it starts with a literal value
65
+ function startsList(expr, open) {
66
+ const after = expr.substring(open + 1).trimStart();
67
+ if (/^[\]"'{[(\d-]/.test(after))
68
+ return true;
69
+ const close = expr.indexOf("]", open);
70
+ return close !== -1 && expr.substring(open, close).includes(",");
71
+ }
72
+ // Whether a token can be the end of a value, so that what follows it is an operator
73
+ function endsValue(token) {
74
+ return token?.type === "ident" || token?.type === "value" || token?.type === ")" || token?.type === "]" || token?.type === "}";
75
+ }
76
+ function tokenize(expr) {
77
+ const tokens = [];
78
+ let i = 0;
79
+ while (i < expr.length) {
80
+ const c = expr[i];
81
+ if (/\s/.test(c)) {
82
+ i++;
83
+ continue;
84
+ }
85
+ if (c === "(" || c === ")" || punctuation.has(c)) {
86
+ tokens.push({ type: c, text: c });
87
+ i++;
88
+ continue;
89
+ }
90
+ if (c === "\"" || c === "'") {
91
+ let j = i + 1;
92
+ while (j < expr.length && expr[j] !== c) {
93
+ if (expr[j] === "\\")
94
+ j++;
95
+ j++;
96
+ }
97
+ if (j >= expr.length) {
98
+ throw new ExpressionError("unterminated string");
99
+ }
100
+ tokens.push({ type: "value", text: expr.slice(i, j + 1) });
101
+ i = j + 1;
102
+ continue;
103
+ }
104
+ // A "[" straight after a value is an index, as in inventory[0] or inventory[i][j]
105
+ if (c === "[" && /[\w\])]/.test(expr[i - 1] ?? "")) {
106
+ tokens.push({ type: "index", text: c });
107
+ i++;
108
+ continue;
109
+ }
110
+ if (c === "[" && startsList(expr, i)) {
111
+ tokens.push({ type: "[", text: c });
112
+ i++;
113
+ continue;
114
+ }
115
+ // A "-" before a digit starts a negative number, as before (the parser treats
116
+ // a -1 as a - 1 where it needs an operator)
117
+ const op = symbolicOps.find(o => expr.startsWith(o, i) && !(o === "-" && /\d/.test(expr[i + 1] ?? "")));
118
+ if (op) {
119
+ tokens.push({ type: "op", text: op });
120
+ i += op.length;
121
+ continue;
122
+ }
123
+ let j = i;
124
+ while (j < expr.length && !identTerminators.has(expr[j])) {
125
+ // A "[" straight after a name is an index, as in inventory[0]. After "." or "/", or at
126
+ // the start, it's a Handlebars name, as in inventory.[0] or [my attribute].
127
+ if (expr[j] === "[" && j > i && expr[j - 1] !== "." && expr[j - 1] !== "/") {
128
+ break;
129
+ }
130
+ if (expr[j] === "[") {
131
+ const close = expr.indexOf("]", j);
132
+ if (close === -1) {
133
+ throw new ExpressionError("missing ']'");
134
+ }
135
+ j = close;
136
+ }
137
+ j++;
138
+ }
139
+ if (j === i) {
140
+ throw new ExpressionError(`unexpected '${c}'`);
141
+ }
142
+ const word = expr.slice(i, j);
143
+ if (keywordOps.includes(word) || (word === "contains" && endsValue(tokens[tokens.length - 1]))) {
144
+ // "contains" is only an operator after a value, so (contains "bag" "key") is still
145
+ // the helper
146
+ tokens.push({ type: "op", text: word });
147
+ }
148
+ else if (literals.includes(word) || numberPattern.test(word)) {
149
+ tokens.push({ type: "value", text: word });
150
+ }
151
+ else {
152
+ tokens.push({ type: "ident", text: word });
153
+ }
154
+ i = j;
155
+ }
156
+ return tokens;
157
+ }
158
+ class Parser {
159
+ constructor(tokens) {
160
+ Object.defineProperty(this, "tokens", {
161
+ enumerable: true,
162
+ configurable: true,
163
+ writable: true,
164
+ value: tokens
165
+ });
166
+ Object.defineProperty(this, "pos", {
167
+ enumerable: true,
168
+ configurable: true,
169
+ writable: true,
170
+ value: 0
171
+ });
172
+ Object.defineProperty(this, "usedInfix", {
173
+ enumerable: true,
174
+ configurable: true,
175
+ writable: true,
176
+ value: false
177
+ });
178
+ }
179
+ peek(offset = 0) {
180
+ return this.tokens[this.pos + offset];
181
+ }
182
+ next() {
183
+ return this.tokens[this.pos++];
184
+ }
185
+ isOp(token, ...ops) {
186
+ return token?.type === "op" && ops.includes(token.text);
187
+ }
188
+ startsPrimary(token) {
189
+ return token?.type === "ident" || token?.type === "value" || token?.type === "(" || token?.type === "[" || token?.type === "{";
190
+ }
191
+ describe(token) {
192
+ return token ? `'${token.text}'` : "end of expression";
193
+ }
194
+ // A value: an expression with nothing after it
195
+ parseExpression() {
196
+ const result = this.parseConditional();
197
+ if (this.peek()) {
198
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
199
+ }
200
+ return result;
201
+ }
202
+ // Arguments to a helper: `count` plain values (e.g. the attribute name), then an expression
203
+ parseArguments(count) {
204
+ const result = [];
205
+ for (let i = 0; i < count; i++) {
206
+ result.push(this.parsePrimary());
207
+ }
208
+ if (!this.peek()) {
209
+ throw new ExpressionError("expected a value");
210
+ }
211
+ result.push(this.parseExpression());
212
+ return result;
213
+ }
214
+ // {{embed}}'s arguments (#450): the name, then parameters, each of which can be an expression,
215
+ // e.g. {{embed "say" who=name hp=hp - 1}}
216
+ parseEmbed() {
217
+ const result = [this.parsePrimary()];
218
+ while (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
219
+ const key = this.next().text;
220
+ this.next(); // "="
221
+ if (!this.peek()) {
222
+ throw new ExpressionError(`expected a value after '${key}='`);
223
+ }
224
+ result.push({ kind: "raw", text: `${key}=${emit(this.parseConditional())}` });
225
+ }
226
+ if (this.peek()) {
227
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
228
+ }
229
+ return result;
230
+ }
231
+ // Top level: an expression, optionally followed by hash arguments (e.g. includeZero=true)
232
+ parseCondition() {
233
+ const result = [this.parseConditional()];
234
+ while (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
235
+ result.push(this.parseHashPair());
236
+ }
237
+ if (this.peek()) {
238
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
239
+ }
240
+ return result;
241
+ }
242
+ parseHashPair() {
243
+ const key = this.next().text;
244
+ this.next(); // "="
245
+ return { kind: "raw", text: `${key}=${emit(this.parsePrimary())}` };
246
+ }
247
+ // test ? a : b (#446), the loosest of all, and right-associative, so a ? b : c ? d : e
248
+ // is a ? b : (c ? d : e)
249
+ parseConditional() {
250
+ const test = this.parseOr();
251
+ if (!this.isOp(this.peek(), "?"))
252
+ return test;
253
+ this.next();
254
+ if (!this.peek()) {
255
+ throw new ExpressionError("expected a value after '?'");
256
+ }
257
+ const ifTrue = this.parseConditional();
258
+ this.expect(":");
259
+ if (!this.peek()) {
260
+ throw new ExpressionError("expected a value after ':'");
261
+ }
262
+ const ifFalse = this.parseConditional();
263
+ this.usedInfix = true;
264
+ return { kind: "call", name: "cond", args: [test, ifTrue, ifFalse] };
265
+ }
266
+ parseOr() {
267
+ return this.parseChain(["or", "||"], "or", () => this.parseAnd());
268
+ }
269
+ parseAnd() {
270
+ return this.parseChain(["and", "&&"], "and", () => this.parseNot());
271
+ }
272
+ parseChain(ops, helper, parseOperand) {
273
+ const operands = [parseOperand()];
274
+ while (this.isOp(this.peek(), ...ops)) {
275
+ const op = this.next().text;
276
+ if (!this.peek()) {
277
+ throw new ExpressionError(`expected a value after '${op}'`);
278
+ }
279
+ operands.push(parseOperand());
280
+ }
281
+ if (operands.length === 1)
282
+ return operands[0];
283
+ this.usedInfix = true;
284
+ return { kind: "call", name: helper, args: operands };
285
+ }
286
+ parseNot() {
287
+ if (this.isOp(this.peek(), "not", "!")) {
288
+ const op = this.next().text;
289
+ if (!this.peek()) {
290
+ throw new ExpressionError(`expected a value after '${op}'`);
291
+ }
292
+ this.usedInfix = true;
293
+ return { kind: "call", name: "not", args: [this.parseNot()] };
294
+ }
295
+ return this.parseComparison();
296
+ }
297
+ parseComparison() {
298
+ const left = this.parseAdditive();
299
+ const opToken = this.peek();
300
+ if (opToken?.type !== "op" || !(opToken.text in comparisonHelpers)) {
301
+ return left;
302
+ }
303
+ this.next();
304
+ if (!this.peek()) {
305
+ throw new ExpressionError(`expected a value after '${opToken.text}'`);
306
+ }
307
+ const right = this.parseAdditive();
308
+ const following = this.peek();
309
+ if (following?.type === "op" && following.text in comparisonHelpers) {
310
+ throw new ExpressionError(`comparisons can't be chained (at '${following.text}'), use "and" to combine them`);
311
+ }
312
+ this.usedInfix = true;
313
+ return { kind: "call", name: comparisonHelpers[opToken.text], args: [left, right] };
314
+ }
315
+ parseAdditive() {
316
+ return this.parseArithmetic(["+", "-"], () => this.parseMultiplicative());
317
+ }
318
+ parseMultiplicative() {
319
+ return this.parseArithmetic(["*", "/", "%"], () => this.parseUnary());
320
+ }
321
+ // Left-associative, so a - b - c is (a - b) - c
322
+ parseArithmetic(ops, parseOperand) {
323
+ let left = parseOperand();
324
+ for (;;) {
325
+ let op;
326
+ const token = this.peek();
327
+ if (this.isOp(token, ...ops)) {
328
+ op = this.next().text;
329
+ if (!this.peek()) {
330
+ throw new ExpressionError(`expected a value after '${op}'`);
331
+ }
332
+ }
333
+ else if (ops.includes("-") && token?.type === "value" && token.text.startsWith("-") && numberPattern.test(token.text)) {
334
+ // a -1 means a - 1. Split the negative number into the operator and the number.
335
+ op = "-";
336
+ this.tokens[this.pos] = { type: "value", text: token.text.slice(1) };
337
+ }
338
+ else {
339
+ return left;
340
+ }
341
+ this.usedInfix = true;
342
+ left = { kind: "call", name: arithmeticHelpers[op], args: [left, parseOperand()] };
343
+ }
344
+ }
345
+ parseUnary() {
346
+ if (this.isOp(this.peek(), "-")) {
347
+ this.next();
348
+ if (!this.peek()) {
349
+ throw new ExpressionError("expected a value after '-'");
350
+ }
351
+ this.usedInfix = true;
352
+ return { kind: "call", name: "sub", args: [{ kind: "raw", text: "0" }, this.parseUnary()] };
353
+ }
354
+ return this.parsePrimary();
355
+ }
356
+ // A value, then any [index] or .name after it, e.g. inventory[i].name
357
+ parsePrimary() {
358
+ let node = this.parseAtom();
359
+ for (;;) {
360
+ const token = this.peek();
361
+ if (token?.type === "index") {
362
+ this.next();
363
+ const index = this.parseConditional();
364
+ this.expect("]");
365
+ this.usedInfix = true;
366
+ node = { kind: "call", name: "lookup", args: [node, index] };
367
+ }
368
+ else if (token?.type === "ident" && token.text.startsWith(".") && this.tokens[this.pos - 1]?.type === "]") {
369
+ // .name after an index: a name, or Handlebars' .[name]
370
+ this.next();
371
+ for (const part of token.text.substring(1).split(".")) {
372
+ const name = /^\[(.*)\]$/.exec(part)?.[1] ?? part;
373
+ if (!name)
374
+ throw new ExpressionError(`unexpected '${token.text}'`);
375
+ node = { kind: "call", name: "lookup", args: [node, { kind: "raw", text: JSON.stringify(name) }] };
376
+ }
377
+ }
378
+ else {
379
+ return node;
380
+ }
381
+ }
382
+ }
383
+ expect(type) {
384
+ if (this.peek()?.type !== type) {
385
+ throw new ExpressionError(`expected '${type}' but found ${this.describe(this.peek())}`);
386
+ }
387
+ this.next();
388
+ }
389
+ // { name: value, ... } (#442)
390
+ parseObject() {
391
+ const args = [];
392
+ while (this.peek()?.type !== "}") {
393
+ const key = this.next();
394
+ if (!key)
395
+ throw new ExpressionError("expected '}' but found end of expression");
396
+ if ((key.type === "ident" || key.type === "value") && /^\w+$/.test(key.text)) {
397
+ args.push({ kind: "raw", text: `"${key.text}"` });
398
+ }
399
+ else if (key.type === "value" && /^["']/.test(key.text)) {
400
+ args.push({ kind: "raw", text: key.text });
401
+ }
402
+ else {
403
+ throw new ExpressionError(`expected a name in the object, e.g. { hp: 10 }, but found '${key.text}'`);
404
+ }
405
+ this.expect(":");
406
+ args.push(this.parseConditional());
407
+ if (this.peek()?.type !== ",")
408
+ break;
409
+ this.next();
410
+ }
411
+ this.expect("}");
412
+ this.usedInfix = true;
413
+ return { kind: "call", name: "__object", args };
414
+ }
415
+ // [value, ...] (#442)
416
+ parseList() {
417
+ const args = [];
418
+ while (this.peek()?.type !== "]") {
419
+ if (!this.peek())
420
+ throw new ExpressionError("expected ']' but found end of expression");
421
+ args.push(this.parseConditional());
422
+ if (this.peek()?.type !== ",")
423
+ break;
424
+ this.next();
425
+ }
426
+ this.expect("]");
427
+ this.usedInfix = true;
428
+ return { kind: "call", name: "array", args };
429
+ }
430
+ parseAtom() {
431
+ const token = this.peek();
432
+ if (token?.type === "{") {
433
+ this.next();
434
+ return this.parseObject();
435
+ }
436
+ if (token?.type === "[") {
437
+ this.next();
438
+ return this.parseList();
439
+ }
440
+ if (token?.type === "ident" || token?.type === "value") {
441
+ this.next();
442
+ return { kind: "raw", text: token.text };
443
+ }
444
+ if (token?.type === "(") {
445
+ this.next();
446
+ const node = this.isHelperCall() ? this.parseHelperCall() : this.parseConditional();
447
+ if (this.peek()?.type !== ")") {
448
+ throw new ExpressionError(`expected ')' but found ${this.describe(this.peek())}`);
449
+ }
450
+ this.next();
451
+ return node;
452
+ }
453
+ if (this.isOp(token, "not", "!")) {
454
+ const example = token?.text === "!" ? "!value" : "not value";
455
+ throw new ExpressionError(`'${token?.text}' must be inside parentheses here, e.g. (${example})`);
456
+ }
457
+ if (token?.type === "op") {
458
+ throw new ExpressionError(`expected a value before '${token.text}'`);
459
+ }
460
+ throw new ExpressionError(token ? `unexpected ${this.describe(token)}` : "expected a value");
461
+ }
462
+ // Inside parentheses, decide between an existing prefix helper call like (seen "intro")
463
+ // or (and a b), and an infix group like (score > 100).
464
+ isHelperCall() {
465
+ const first = this.peek();
466
+ const second = this.peek(1);
467
+ if (this.isOp(first, "and", "or"))
468
+ return true;
469
+ return first?.type === "ident" && this.startsPrimary(second);
470
+ }
471
+ parseHelperCall() {
472
+ const name = this.next().text;
473
+ const args = [];
474
+ while (this.peek() && this.peek()?.type !== ")") {
475
+ if (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
476
+ args.push(this.parseHashPair());
477
+ }
478
+ else {
479
+ args.push(this.parsePrimary());
480
+ }
481
+ }
482
+ return { kind: "call", name, args };
483
+ }
484
+ }
485
+ function emit(node) {
486
+ if (node.kind === "raw")
487
+ return node.text;
488
+ return `(${node.name} ${node.args.map(emit).join(" ")})`;
489
+ }
490
+ // Parses `text` and returns the rewritten nodes, or null if it should be left alone: it
491
+ // doesn't use infix syntax, or it can't be parsed and has no operators (which leaves malformed
492
+ // prefix syntax for Handlebars to report).
493
+ function rewrite(text, mode, label) {
494
+ // Whether errors are always reported, and the result always returned, rather than leaving
495
+ // anything that isn't infix syntax for Handlebars
496
+ const strict = mode === "display" || mode === "value";
497
+ // Errors are thrown after the try/catch blocks, as new errors with the expression in the message
498
+ let error = null;
499
+ let tokens = [];
500
+ try {
501
+ tokens = tokenize(text);
502
+ }
503
+ catch (e) {
504
+ // Leave anything we can't tokenize for Handlebars to report, except {{= }}
505
+ if (!strict || !(e instanceof ExpressionError))
506
+ return null;
507
+ error = e;
508
+ }
509
+ const hasOperators = tokens.some(t => t.type === "op" || t.type === "index" || t.type === "[" || t.type === "{");
510
+ const parser = new Parser(tokens);
511
+ let nodes = [];
512
+ if (!error) {
513
+ try {
514
+ nodes = mode === "condition" ? parser.parseCondition()
515
+ : mode === "arguments" ? parser.parseArguments(1)
516
+ : mode === "embed" ? parser.parseEmbed()
517
+ : [parser.parseExpression()];
518
+ }
519
+ catch (e) {
520
+ if (!(e instanceof ExpressionError) || (!hasOperators && !strict))
521
+ return null;
522
+ error = e;
523
+ }
524
+ }
525
+ if (error) {
526
+ throw new Error(`Invalid ${label} "${text.trim()}": ${error.message}`);
527
+ }
528
+ if (!parser.usedInfix && !strict)
529
+ return null;
530
+ return nodes;
531
+ }
532
+ // Rewrites a single condition. Returns null if it doesn't use infix syntax.
533
+ export function rewriteInfixCondition(condition) {
534
+ const nodes = rewrite(condition, "condition", "condition");
535
+ return nodes && nodes.map(emit).join(" ");
536
+ }
537
+ // Rewrites the arguments to {{set}}, {{inc}}, {{dec}}, {{append}}, {{prepend}} or {{remove}}: an
538
+ // attribute name, then an expression.
539
+ // Returns null if the expression doesn't use infix syntax.
540
+ export function rewriteInfixArguments(args) {
541
+ const nodes = rewrite(args, "arguments", "expression");
542
+ return nodes && nodes.map(emit).join(" ");
543
+ }
544
+ // Rewrites the arguments to {{embed}} (#450), {{goto}} or {{#animate}} (#451): a name, then
545
+ // parameters whose values can be expressions, e.g. after=delay * 1000. Returns null if they don't
546
+ // use infix syntax.
547
+ export function rewriteInfixEmbed(args, label = "embed") {
548
+ const nodes = rewrite(args, "embed", label);
549
+ return nodes && nodes.map(emit).join(" ");
550
+ }
551
+ // Rewrites the expression in {{= expression}} into the contents of a mustache tag, i.e. a
552
+ // helper call without the outer parentheses, or an attribute name.
553
+ export function rewriteDisplayExpression(expression) {
554
+ const node = rewrite(expression, "display", "expression")[0];
555
+ if (node.kind === "call") {
556
+ return `${node.name} ${node.args.map(emit).join(" ")}`;
557
+ }
558
+ if (literals.includes(node.text) || numberPattern.test(node.text) || /^["']/.test(node.text)) {
559
+ throw new Error(`Invalid expression "${expression.trim()}": expected an attribute or a calculation`);
560
+ }
561
+ return node.text;
562
+ }
563
+ // Rewrites an expression whose value is used (the right-hand side of @set and link setters, when a
564
+ // story uses expressions there) into a Handlebars value: a helper call in parentheses, an
565
+ // attribute name or a literal. Throws if it isn't a valid expression.
566
+ export function rewriteValueExpression(expression) {
567
+ return emit(rewrite(expression, "value", "expression")[0]);
568
+ }
569
+ // Splits a list of link setters on the commas between them, but not on commas inside quotes or
570
+ // brackets: greeting = "Hi, there", gold -= price is two setters, and so is
571
+ // hero = { hp: 10, name: "Ann" }, gold = 0.
572
+ export function splitSetters(setters) {
573
+ const result = [];
574
+ let depth = 0;
575
+ let quote = null;
576
+ let start = 0;
577
+ for (let i = 0; i < setters.length; i++) {
578
+ const c = setters[i];
579
+ if (quote) {
580
+ if (c === "\\")
581
+ i++;
582
+ else if (c === quote)
583
+ quote = null;
584
+ }
585
+ else if (c === "\"" || c === "'")
586
+ quote = c;
587
+ else if (c === "(" || c === "[" || c === "{")
588
+ depth++;
589
+ else if (c === ")" || c === "]" || c === "}")
590
+ depth = Math.max(0, depth - 1);
591
+ else if (c === "," && depth === 0) {
592
+ result.push(setters.slice(start, i));
593
+ start = i + 1;
594
+ }
595
+ }
596
+ result.push(setters.slice(start));
597
+ return result.map(s => s.trim()).filter(s => s !== "");
598
+ }
599
+ const tagStart = /(\\*)\{\{(~?\s*)(?:(#if|#unless|#each|#with|#every|else\s+if|else\s+unless)(?=[\s(!])|(set|inc|dec|append|prepend|remove)(?=\s)|(=)|(#?embed|goto|#animate)(?=\s))/g;
600
+ // Finds the end of a mustache tag starting at `from`, skipping over quoted strings and objects,
601
+ // such as {{set "hero" { hp: 10 }}}. Returns the index of the closing "}}" (or "~}}"), or -1.
602
+ export function findTagEnd(text, from) {
603
+ let quote = null;
604
+ let braces = 0;
605
+ for (let i = from; i < text.length; i++) {
606
+ const c = text[i];
607
+ if (quote) {
608
+ if (c === "\\")
609
+ i++;
610
+ else if (c === quote)
611
+ quote = null;
612
+ }
613
+ else if (c === "\"" || c === "'") {
614
+ quote = c;
615
+ }
616
+ else if (c === "{") {
617
+ braces++;
618
+ }
619
+ else if (c === "}" && braces > 0) {
620
+ braces--;
621
+ }
622
+ else if (text.startsWith("~}}", i)) {
623
+ return i;
624
+ }
625
+ else if (text.startsWith("}}", i)) {
626
+ return i;
627
+ }
628
+ }
629
+ return -1;
630
+ }
631
+ // What rewriteInfixExpressions throws for an expression it can't read, such as {{= a +}}: the
632
+ // tag starts at start, and its closing "}}" is at end
633
+ export class InfixRewriteError extends Error {
634
+ constructor(message, start, end) {
635
+ super(message);
636
+ Object.defineProperty(this, "start", {
637
+ enumerable: true,
638
+ configurable: true,
639
+ writable: true,
640
+ value: start
641
+ });
642
+ Object.defineProperty(this, "end", {
643
+ enumerable: true,
644
+ configurable: true,
645
+ writable: true,
646
+ value: end
647
+ });
648
+ }
649
+ }
650
+ // edits, if given, gets each replacement made, in order, so that a position in the rewritten text
651
+ // can be traced back (see mapRewrittenPosition)
652
+ export function rewriteInfixExpressions(text, edits) {
653
+ if (!text.includes("{{"))
654
+ return text;
655
+ let result = "";
656
+ let last = 0;
657
+ tagStart.lastIndex = 0;
658
+ let match;
659
+ while ((match = tagStart.exec(text)) !== null) {
660
+ // An odd number of backslashes escapes the mustache
661
+ if (match[1].length % 2 === 1)
662
+ continue;
663
+ const argStart = match.index + match[0].length;
664
+ const argEnd = findTagEnd(text, argStart);
665
+ if (argEnd === -1)
666
+ break;
667
+ try {
668
+ const args = text.slice(argStart, argEnd);
669
+ if (match[5]) {
670
+ // {{= expression}}: replace the "=" too
671
+ const tagOpen = match.index + match[1].length;
672
+ const replacement = "{{" + match[2] + rewriteDisplayExpression(args);
673
+ result += text.slice(last, tagOpen);
674
+ edits?.push({ start: tagOpen, end: argEnd, length: replacement.length });
675
+ result += replacement;
676
+ last = argEnd;
677
+ }
678
+ else {
679
+ const rewritten = match[3] ? rewriteInfixCondition(args)
680
+ : match[6] ? rewriteInfixEmbed(args, match[6].replace("#", ""))
681
+ : rewriteInfixArguments(args);
682
+ if (rewritten !== null) {
683
+ result += text.slice(last, argStart);
684
+ edits?.push({ start: argStart, end: argEnd, length: rewritten.length + 1 });
685
+ result += " " + rewritten;
686
+ last = argEnd;
687
+ }
688
+ }
689
+ }
690
+ catch (e) {
691
+ // Say which tag it was, for the compiler's diagnostics (see templates.ts)
692
+ if (e instanceof Error)
693
+ throw new InfixRewriteError(e.message, match.index + match[1].length, argEnd);
694
+ throw e;
695
+ }
696
+ tagStart.lastIndex = argEnd;
697
+ }
698
+ return result + text.slice(last);
699
+ }
700
+ // Maps a position in the text rewriteInfixExpressions returned to the text it was given. A
701
+ // position inside a replacement maps to the start of what was replaced.
702
+ export function mapRewrittenPosition(edits, pos) {
703
+ let shift = 0;
704
+ for (const edit of edits) {
705
+ const start = edit.start + shift;
706
+ if (pos < start)
707
+ break;
708
+ if (pos < start + edit.length)
709
+ return edit.start;
710
+ shift += edit.length - (edit.end - edit.start);
711
+ }
712
+ return pos - shift;
713
+ }