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

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.
@@ -10,11 +10,12 @@ import { parseTwine } from "./story.js";
10
10
  import { formatProjectFile } from "../project.js";
11
11
  // The Squiffy names that would be read as a helper, rather than an attribute, in {{name}} and
12
12
  // expressions, and the ones Squiffy sets itself
13
- const reservedAttributes = new Set([
13
+ export const reservedAttributes = new Set([
14
14
  "get", "set", "unset", "inc", "dec", "seen", "visits", "at", "goto", "embed", "array", "random", "contains",
15
15
  "length", "append", "prepend", "pop", "remove", "section", "passage", "label", "replace", "rotate", "sequence",
16
16
  "live", "animate", "eq", "ne", "gt", "gte", "lt", "lte", "and", "or", "not", "add", "sub", "mul", "div", "mod",
17
- "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "true", "false", "null", "undefined",
17
+ "if", "unless", "each", "with", "lookup", "log", "else", "this", "turns", "previous", "previous_section",
18
+ "true", "false", "null", "undefined",
18
19
  ]);
19
20
  export class StoryContext {
20
21
  constructor(twine, passages) {
@@ -94,6 +95,14 @@ export class StoryContext {
94
95
  writable: true,
95
96
  value: new Map()
96
97
  });
98
+ // The loops being converted to {{#each}}, innermost last, with the Twine variables (with their
99
+ // $ or _) that stand for each one's item and position
100
+ Object.defineProperty(this, "loops", {
101
+ enumerable: true,
102
+ configurable: true,
103
+ writable: true,
104
+ value: []
105
+ });
97
106
  for (const p of passages) {
98
107
  this.passagesByName.set(p.name, p);
99
108
  }
@@ -185,9 +194,36 @@ export class StoryContext {
185
194
  this.usedLabels.add(name);
186
195
  return name;
187
196
  }
197
+ get looping() {
198
+ return this.loops.length > 0;
199
+ }
200
+ inLoop(vars, array, convert) {
201
+ this.loops.push({ vars, array });
202
+ try {
203
+ return convert();
204
+ }
205
+ finally {
206
+ this.loops.pop();
207
+ }
208
+ }
209
+ loopVariable(name, temporary) {
210
+ const key = (temporary ? "_" : "$") + name;
211
+ for (let i = this.loops.length - 1; i >= 0; i--) {
212
+ const kind = this.loops[i].vars.get(key);
213
+ if (kind)
214
+ return { k: "loop", kind, up: this.loops.length - 1 - i, array: this.loops[i].array };
215
+ }
216
+ return undefined;
217
+ }
218
+ // A Twine variable's value: its attribute, or inside a loop, the loop's item or position
219
+ variable(name, temporary) {
220
+ return this.loopVariable(name, temporary) ?? { k: "var", name: this.attribute(name, temporary) };
221
+ }
188
222
  // The Squiffy attribute for a Twine variable, given without its $ or _: a temporary (_)
189
223
  // variable keeps its name unless a story variable ($) has the same name
190
224
  attribute(name, temporary) {
225
+ if (this.loopVariable(name, temporary))
226
+ throw new Unconvertible("changing a loop's variable inside the loop");
191
227
  let result = name;
192
228
  if (temporary && this.permanentVars.has(name))
193
229
  result = "temp_" + name;
@@ -252,6 +288,9 @@ export function urlLink(text, url) {
252
288
  }
253
289
  // A link to a section whose name is worked out as the story runs
254
290
  export function dynamicSectionLink(text, target, setters = []) {
291
+ // quote() would break the {{this}} of a loop's item
292
+ if (setters.some(s => s.includes("{{")))
293
+ throw new Unconvertible("a link in a loop, to a passage worked out as the story runs, that sets a variable to the loop's item");
255
294
  const set = setters.length ? ` set=${quote(setters.join(", "))}` : "";
256
295
  return `{{section ${print(target)} text=${quote(text)}${set}}}`;
257
296
  }
@@ -261,7 +300,7 @@ export function passageLink(text, target) {
261
300
  }
262
301
  // A Squiffy setter, as in @set or a link, for name = value
263
302
  export function setter(name, op, value, inLink) {
264
- return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink })}`;
303
+ return `${attributeRef(name)} ${op} ${print(value, { preferSingle: inLink, inLink })}`;
265
304
  }
266
305
  // A comment in the story, for Twine code that couldn't be converted. Handlebars comments can't
267
306
  // contain --}}, and line breaks would let the compiler read a line of it as something else.
@@ -269,8 +308,11 @@ export function comment(text) {
269
308
  const clean = text.replace(/--\}\}/g, "-- }}").replace(/\s*\n\s*/g, " ").trim();
270
309
  return `{{!-- Twine: ${clean} --}}`;
271
310
  }
311
+ // SugarCube's passages for its sidebar that become panels beside the story (#443), in the order
312
+ // SugarCube shows them, with the labels of the buttons they have on a narrow screen
313
+ const sugarCubePanels = { StoryBanner: "Banner", StoryCaption: "Status" };
272
314
  // Passages a format treats specially, which aren't part of the story as sections
273
- // (StoryCaption, StoryBanner and so on are kept, as their text might be included elsewhere)
315
+ // (StorySubtitle, StoryAuthor and so on are kept, as their text might be included elsewhere)
274
316
  const sugarCubeSpecial = new Set(["StoryMenu", "StoryInterface", "StoryShare", "StoryTitle", "StoryData", "StorySettings"]);
275
317
  // The problems as a text file, to keep with the converted story: the ones about the whole story,
276
318
  // then each passage's, in the order of the story
@@ -313,6 +355,7 @@ export function convertTwineStory(twine, options = {}) {
313
355
  const startup = [];
314
356
  const widgets = [];
315
357
  const skipped = [];
358
+ const panelPassages = [];
316
359
  const storyPassages = [];
317
360
  const seenNames = new Set();
318
361
  for (const p of twine.passages) {
@@ -344,9 +387,11 @@ export function convertTwineStory(twine, options = {}) {
344
387
  widgets.push(p);
345
388
  else if (sugarCubeSpecial.has(p.name))
346
389
  skipped.push(p);
390
+ else if (p.name in sugarCubePanels)
391
+ panelPassages.push(p);
347
392
  else {
348
- if (["StoryCaption", "StoryBanner", "StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
349
- problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar or banner, so this passage is an ordinary section, which nothing links to." });
393
+ if (["StorySubtitle", "StoryAuthor", "StoryDisplayTitle"].includes(p.name)) {
394
+ problems.push({ passage: p.name, text: p.name, reason: "Squiffy has no sidebar, so this passage is an ordinary section, which nothing links to." });
350
395
  }
351
396
  storyPassages.push(p);
352
397
  }
@@ -366,7 +411,9 @@ export function convertTwineStory(twine, options = {}) {
366
411
  for (const p of skipped) {
367
412
  problems.push({
368
413
  passage: p.name, text: p.name,
369
- reason: p.name == "StoryMenu" ? "Squiffy has no sidebar, so this passage has been left out." : "This special passage has been left out.",
414
+ reason: p.name == "StoryMenu"
415
+ ? "Squiffy has no sidebar, so this passage has been left out. Its links go to passages, which a panel can't do, but a panel can show a passage in the master section [[]] from a button in the header: see \"panels\" in squiffy.json."
416
+ : "This special passage has been left out.",
370
417
  });
371
418
  }
372
419
  const context = (passage, section, extraPassages) => ({
@@ -386,17 +433,31 @@ export function convertTwineStory(twine, options = {}) {
386
433
  return reserved.name;
387
434
  },
388
435
  reservePassage(hint) {
436
+ const looping = story.looping;
389
437
  const base = sanitisePassageName(hint) || "more";
390
438
  let name = base;
391
439
  for (let n = 2; extraPassages.some(p => p.startsWith(`[${name}]:\n`)) || name == section; n++)
392
440
  name = `${base} ${n}`;
393
441
  const index = extraPassages.length;
394
442
  extraPassages.push(`[${name}]:\n`);
395
- return { name, fill: content => extraPassages[index] = `[${name}]:\n${block(content)}` };
443
+ return {
444
+ name,
445
+ fill: content => {
446
+ // Left out, rather than empty, if it can't be converted
447
+ extraPassages[index] = "";
448
+ extraPassages[index] = `[${name}]:\n${generated(content)}`;
449
+ if (looping) {
450
+ story.addProblem({
451
+ passage: passage.name, text: oneLine(hint),
452
+ reason: "This link is in a loop, and every item's link goes to the same passage, so once one has been clicked, they all have.",
453
+ });
454
+ }
455
+ },
456
+ };
396
457
  },
397
458
  addSection(hint, content) {
398
459
  const name = story.uniqueSectionName(hint);
399
- story.extraSections.push(`[[${name}]]:\n${block(content)}`);
460
+ story.extraSections.push(`[[${name}]]:\n${generated(content)}`);
400
461
  return name;
401
462
  },
402
463
  newLabel: hint => story.newLabel(hint),
@@ -423,6 +484,24 @@ export function convertTwineStory(twine, options = {}) {
423
484
  if (converted.body.trim())
424
485
  master.body += converted.body.trim() + "\n";
425
486
  }
487
+ // SugarCube's sidebar passages, as panels beside the story, rendered again after each passage
488
+ sortPanelPassages(panelPassages);
489
+ const panels = [];
490
+ for (const p of panelPassages) {
491
+ const converted = convert(p, "", masterPassages);
492
+ let passageName = p.name;
493
+ for (let n = 2; masterPassages.some(text => text.startsWith(`[${passageName}]:\n`)); n++)
494
+ passageName = `${p.name} ${n}`;
495
+ const body = converted.body.trim();
496
+ if (converted.directives.length) {
497
+ story.addProblem({ passage: p.name, text: converted.directives.join(" "), reason: "A panel only shows its text, so this doesn't run." });
498
+ }
499
+ if (/\[\[|\]\(|\{\{(section|passage)\b/.test(body)) {
500
+ story.addProblem({ passage: p.name, text: p.name, reason: "This is a panel beside the story, where links don't work." });
501
+ }
502
+ masterPassages.push(`[${passageName}]:\n${finishText(body)}`.trimEnd());
503
+ panels.push({ passage: passageName, label: sugarCubePanels[p.name], position: "side" });
504
+ }
426
505
  // Passages that run once at the start
427
506
  const init = { directives: [], body: "" };
428
507
  for (const p of startup) {
@@ -446,7 +525,7 @@ export function convertTwineStory(twine, options = {}) {
446
525
  if (!footers.includes(p) && footerEmbeds.length) {
447
526
  body = (body + "\n" + footerEmbeds.join("\n")).trim();
448
527
  }
449
- sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages].join("\n\n"));
528
+ sections.push([`[[${section}]]:\n${block({ directives, body })}`.trimEnd(), ...extraPassages.filter(p => p)].join("\n\n"));
450
529
  }
451
530
  for (const p of widgets) {
452
531
  const extraPassages = [];
@@ -461,7 +540,7 @@ export function convertTwineStory(twine, options = {}) {
461
540
  continue;
462
541
  }
463
542
  for (const w of converted) {
464
- sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages].join("\n\n"));
543
+ sections.push([`[[${w.section}]]:\n${block(w.converted)}`, ...extraPassages.filter(p => p)].join("\n\n"));
465
544
  extraPassages.length = 0;
466
545
  }
467
546
  }
@@ -472,18 +551,21 @@ export function convertTwineStory(twine, options = {}) {
472
551
  if (startSection !== undefined)
473
552
  header.push(`@start ${startSection}`);
474
553
  if (twine.stylesheet) {
554
+ // squiffy.json makes it part of the story
475
555
  files[`${name}.css`] = twine.stylesheet + "\n";
476
- header.push(`@import ${name}.css`);
477
556
  problems.push({
478
557
  text: `${name}.css`,
479
558
  reason: `The story's stylesheet is in ${name}.css. Its rules for ${harlowe ? "Harlowe's elements (tw-story, tw-passage, tw-link and so on)" : "SugarCube's elements (#story, .passage, #ui-bar and so on)"} won't apply to Squiffy's, so check how it looks.`,
480
559
  });
481
560
  }
561
+ // The story's JavaScript is left out of it, as it was written for another story format
562
+ const exclude = [];
482
563
  if (twine.script) {
483
564
  files[`${name}.js`] = twine.script + "\n";
565
+ exclude.push(`${name}.js`);
484
566
  problems.push({
485
567
  text: `${name}.js`,
486
- reason: `The story's JavaScript is in ${name}.js, but it isn't part of the story yet, since it was written for ${twine.formatName || "Twine"}. To use it, change it to work with Squiffy, then add @ui ${name}.js at the top of ${name}.squiffy.`,
568
+ reason: `The story's JavaScript is in ${name}.js, but it isn't part of the story yet, since it was written for ${twine.formatName || "Twine"}. To use it, change it to work with Squiffy, then remove "${name}.js" from "exclude" in squiffy.json (in the editor, choose Include in story from its menu in the files list).`,
487
569
  });
488
570
  }
489
571
  const masterPassageText = masterPassages.length ? "\n\n" + masterPassages.join("\n\n") : "";
@@ -495,7 +577,7 @@ export function convertTwineStory(twine, options = {}) {
495
577
  ].filter(s => s.length).join("\n\n") + "\n";
496
578
  files[`${name}.squiffy`] = script;
497
579
  const map = mapPositions(sectionPassages, story);
498
- files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, ...(map ? { map } : {}) });
580
+ files["squiffy.json"] = formatProjectFile({ main: `${name}.squiffy`, exclude, panels, ...(map ? { map } : {}) });
499
581
  return {
500
582
  title: twine.title,
501
583
  format: `${twine.formatName} ${twine.formatVersion}`.trim(),
@@ -505,6 +587,11 @@ export function convertTwineStory(twine, options = {}) {
505
587
  problems: [...problems, ...story.noteProblems(), ...story.problems],
506
588
  };
507
589
  }
590
+ // SugarCube's sidebar passages in the order SugarCube shows them
591
+ function sortPanelPassages(passages) {
592
+ const order = Object.keys(sugarCubePanels);
593
+ passages.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name));
594
+ }
508
595
  // Where the sections go on the editor's story map, so it looks like the story's map in Twine.
509
596
  // Twine's boxes are 100 by 100, on a grid of 25, and usually 125 apart; the map's are short and
510
597
  // wide, up to 190 across, so the map is stretched sideways to keep them from overlapping (which
@@ -544,6 +631,37 @@ function block(content) {
544
631
  const c = typeof content == "string" ? { directives: [], body: content } : content;
545
632
  return [...c.directives, finishText(c.body)].filter(l => l.length).join("\n");
546
633
  }
634
+ // A passage or section made for a link, e.g. one in a loop, which can't use the loop's item or
635
+ // position: it's shown on its own, after the loop has finished
636
+ function generated(content) {
637
+ const c = typeof content == "string" ? { directives: [], body: content } : content;
638
+ // Directives are expressions, rather than text with {{...}} in it
639
+ if (c.directives.some(d => usesOuterLoop(`{{${d}}}`)) || usesOuterLoop(c.body)) {
640
+ throw new Unconvertible("a link in a loop that does more than set variables to the loop's item");
641
+ }
642
+ return block(c);
643
+ }
644
+ // Whether Squiffy text uses the item or position of a loop it isn't in
645
+ export function usesOuterLoop(text) {
646
+ let depth = 0;
647
+ // Comments keep the Twine code, which can have "this" in it
648
+ for (const tag of text.replace(/\{\{!--[\s\S]*?--\}\}/g, "").matchAll(/\{\{([\s\S]*?)\}\}/g)) {
649
+ // Text in quotes isn't a reference
650
+ const inner = tag[1].replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, "\"\"");
651
+ if (inner.startsWith("/each")) {
652
+ depth--;
653
+ continue;
654
+ }
655
+ for (const ref of inner.matchAll(/(?<![\w$@.])((?:\.\.\/)*)this\b|@((?:\.\.\/)*)index\b/g)) {
656
+ const up = (ref[1] ?? ref[2] ?? "").length / 3;
657
+ if (up >= depth)
658
+ return true;
659
+ }
660
+ if (inner.startsWith("#each"))
661
+ depth++;
662
+ }
663
+ return false;
664
+ }
547
665
  // A name for a generated passage, from a link's text, which can have markup in it
548
666
  function sanitisePassageName(name) {
549
667
  const plain = name
@@ -31,11 +31,17 @@ export type Expr = {
31
31
  } | {
32
32
  k: "array";
33
33
  items: Expr[];
34
+ } | {
35
+ k: "loop";
36
+ kind: "item" | "index";
37
+ up: number;
38
+ array?: string;
34
39
  };
35
40
  export declare class Unconvertible extends Error {
36
41
  }
37
42
  export interface PrintOptions {
38
43
  preferSingle?: boolean;
44
+ inLink?: boolean;
39
45
  }
40
46
  export declare function quote(text: string, options?: PrintOptions): string;
41
47
  export declare function attributeRef(name: string): string;
@@ -21,6 +21,11 @@ function precedenceOf(e) {
21
21
  return 7;
22
22
  return atomPrecedence;
23
23
  }
24
+ // How a loop's item or position is written in Handlebars, e.g. this, ../this or @index
25
+ function loopRef(e) {
26
+ const up = "../".repeat(e.up);
27
+ return e.kind == "item" ? up + "this" : "@" + up + "index";
28
+ }
24
29
  // Text as a quoted string. Handlebars and Squiffy's expression tokenizer both take a backslash
25
30
  // before the quote character, but Handlebars leaves other backslashes in, so those can't be
26
31
  // written exactly.
@@ -51,6 +56,13 @@ export function print(e, options = {}) {
51
56
  case "bool": return String(e.v);
52
57
  case "null": return "null";
53
58
  case "var": return attributeRef(e.name);
59
+ case "loop":
60
+ if (!options.inLink)
61
+ return loopRef(e);
62
+ // A link fills in its setters with only its own loop's item
63
+ if (e.up)
64
+ throw new Unconvertible("a link in a loop that sets a variable to an outer loop's item");
65
+ return `'{{${loopRef(e)}}}'`;
54
66
  case "array": return `(array${e.items.map(i => " " + printArgument(i, options)).join("")})`;
55
67
  case "call": return `(${e.fn}${e.args.map(a => " " + printArgument(a, options)).join("")})`;
56
68
  case "neg": {
@@ -112,6 +124,8 @@ export function display(e) {
112
124
  if (e.k == "var") {
113
125
  return /^[A-Za-z_]\w*$/.test(e.name) && !reservedWords.has(e.name) ? `{{${e.name}}}` : `{{get ${quote(e.name)}}}`;
114
126
  }
127
+ if (e.k == "loop")
128
+ return `{{${loopRef(e)}}}`;
115
129
  if (e.k == "call")
116
130
  return `{{${print(e).slice(1, -1)}}}`;
117
131
  return `{{= ${print(e)}}}`;
@@ -5,6 +5,7 @@ export declare class HarloweExpressions {
5
5
  readonly ctx: PassageContext;
6
6
  constructor(ctx: PassageContext);
7
7
  attribute(name: string, temp: boolean): string;
8
+ variable(name: string, temp: boolean): Expr;
8
9
  parse(source: string, it?: Expr): Expr;
9
10
  passageName(source: string): {
10
11
  name: string;
@@ -374,6 +374,10 @@ export class HarloweExpressions {
374
374
  attribute(name, temp) {
375
375
  return this.ctx.story.attribute(name, temp);
376
376
  }
377
+ // A Harlowe variable's value: its attribute, or inside a (for:), the loop's item
378
+ variable(name, temp) {
379
+ return this.ctx.story.variable(name, temp);
380
+ }
377
381
  parse(source, it) {
378
382
  const tokens = new Tokens(tokenize(source));
379
383
  const e = new ExpressionParser(this, tokens, it).expression();
@@ -402,6 +406,19 @@ export class HarloweExpressions {
402
406
  case "a":
403
407
  case "array":
404
408
  return { k: "array", items: values() };
409
+ case "range": {
410
+ // The whole numbers from one to the other
411
+ const [from, to] = values();
412
+ if (from?.k != "num" || to?.k != "num")
413
+ throw new Unconvertible("(range:) with numbers that aren't fixed");
414
+ const step = to.v >= from.v ? 1 : -1;
415
+ if (Math.abs(to.v - from.v) > 100)
416
+ throw new Unconvertible("(range:) of more than 100 numbers");
417
+ const items = [];
418
+ for (let n = Math.round(from.v); n != Math.round(to.v) + step; n += step)
419
+ items.push({ k: "num", v: n });
420
+ return { k: "array", items };
421
+ }
405
422
  case "visited": {
406
423
  if (args.length == 0)
407
424
  return { k: "bin", op: ">", l: this.visits(), r: { k: "num", v: 0 } };
@@ -620,8 +637,8 @@ class ExpressionParser {
620
637
  switch (t.type) {
621
638
  case "str": return { k: "str", v: t.value };
622
639
  case "num": return { k: "num", v: t.value };
623
- case "var": return { k: "var", name: this.h.attribute(t.value, false) };
624
- case "temp": return { k: "var", name: this.h.attribute(t.value, true) };
640
+ case "var": return this.h.variable(t.value, false);
641
+ case "temp": return this.h.variable(t.value, true);
625
642
  case "hook": throw new Unconvertible("a hook name in an expression");
626
643
  case "(": {
627
644
  const e = this.expression();
@@ -860,7 +877,7 @@ class Writer {
860
877
  return this.ctx.unconvertible(node.text, node.reason);
861
878
  case "var":
862
879
  state.leading = false;
863
- return display({ k: "var", name: this.expr.attribute(node.name, node.temp) });
880
+ return display(this.expr.variable(node.name, node.temp));
864
881
  case "link":
865
882
  state.leading = false;
866
883
  return this.link(node);
@@ -1070,7 +1087,7 @@ class Writer {
1070
1087
  throw e;
1071
1088
  state.leading = false;
1072
1089
  const reason = `This couldn't be converted: ${e.message}.`;
1073
- if (m.hook && !["link", "linkreveal", "linkrepeat", "linkrerun", "click", "replace", "append", "prepend", "show"].includes(m.name)) {
1090
+ if (m.hook && !["link", "linkreveal", "linkrepeat", "linkrerun", "click", "replace", "append", "prepend", "show", "for", "loop"].includes(m.name)) {
1074
1091
  // Keep the hook's text, since most changers only change how it looks
1075
1092
  return this.ctx.unconvertible(m.raw, reason) + this.hookContent(m.hook, state);
1076
1093
  }
@@ -1356,6 +1373,23 @@ class Writer {
1356
1373
  }
1357
1374
  throw new Unconvertible(`(${name}:) on ${hookName ? "a hook that isn't in this passage" : "text rather than a named hook"}`);
1358
1375
  }
1376
+ case "for":
1377
+ case "loop": {
1378
+ state.leading = false;
1379
+ if (!m.hook)
1380
+ throw new Unconvertible(`(${name}:) without a hook`);
1381
+ // each _item, or _item where ... (which only shows the items it's true for)
1382
+ const lambda = /^\s*(each\s+)?_([A-Za-z_]\w*)(?:\s+where\s+([\s\S]+))?$/i.exec(args[0] ?? "");
1383
+ if (!lambda || (!lambda[1] && !lambda[3]))
1384
+ throw new Unconvertible(`(${name}:) with something other than "each _item" or "_item where ..."`);
1385
+ const collection = this.forCollection(args.slice(1), name);
1386
+ const hook = m.hook;
1387
+ return this.ctx.story.inLoop(new Map([["_" + lambda[2], "item"]]), undefined, () => {
1388
+ const body = this.hookContent(hook, state);
1389
+ const shown = lambda[3] ? `{{#if ${print(this.expr.parse(lambda[3]))}}}${body}{{/if}}` : body;
1390
+ return `{{#each ${print(collection)}}}${shown}{{/each}}`;
1391
+ });
1392
+ }
1359
1393
  case "linkstorylet": {
1360
1394
  state.leading = false;
1361
1395
  // Every storylet whose condition is true, the first time (link-storylet:) is in a passage
@@ -1392,6 +1426,28 @@ class Writer {
1392
1426
  throw new Unconvertible(`the (${m.raw.substring(1, m.raw.indexOf(":"))}:) macro, which Squiffy has no equivalent for`);
1393
1427
  }
1394
1428
  }
1429
+ // What a (for:) goes through: an array spread out (...$list), or values, as {{#each}} takes
1430
+ forCollection(values, name) {
1431
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.expr.parse(v.replace(/^\s*\.\.\./, "")) : null;
1432
+ if (values.length == 1) {
1433
+ const e = spread(values[0]);
1434
+ if (e && (e.k == "var" || e.k == "array" || (e.k == "loop" && e.kind == "item")))
1435
+ return e;
1436
+ }
1437
+ const items = [];
1438
+ for (const v of values) {
1439
+ const e = spread(v);
1440
+ if (!e)
1441
+ items.push(this.expr.parse(v));
1442
+ else if (e.k == "array")
1443
+ items.push(...e.items);
1444
+ else
1445
+ throw new Unconvertible(`(${name}:) with an array and other values`);
1446
+ }
1447
+ if (!items.length)
1448
+ throw new Unconvertible(`(${name}:) with nothing to go through`);
1449
+ return { k: "array", items };
1450
+ }
1395
1451
  sectionName(passage, raw) {
1396
1452
  const section = this.ctx.story.sectionFor(passage);
1397
1453
  if (section === undefined) {
@@ -4,6 +4,7 @@ export declare class SugarCubeExpressions {
4
4
  readonly ctx: PassageContext;
5
5
  constructor(ctx: PassageContext);
6
6
  attribute(name: string, temp: boolean): string;
7
+ variable(name: string, temp: boolean): Expr;
7
8
  parse(source: string): Expr;
8
9
  statements(source: string): Statement[];
9
10
  passageName(source: string): {
@@ -308,6 +308,9 @@ export class SugarCubeExpressions {
308
308
  attribute(name, temp) {
309
309
  return this.ctx.story.attribute(name, temp);
310
310
  }
311
+ variable(name, temp) {
312
+ return this.ctx.story.variable(name, temp);
313
+ }
311
314
  parse(source) {
312
315
  const tokens = new Tokens(tokenize(source));
313
316
  const e = new ExpressionParser(this, tokens).expression();
@@ -378,6 +381,8 @@ class ExpressionParser {
378
381
  // Objects are flattened, so $player to { hp: 10 } sets player_hp
379
382
  statement() {
380
383
  const target = this.postfixValue();
384
+ if (target.v == "expr" && target.e.k == "loop")
385
+ throw new Unconvertible("changing a loop's variable inside the loop");
381
386
  const t = this.tokens.peek();
382
387
  if (target.v == "expr" && target.e.k == "var" && t?.text == "=") {
383
388
  const start = this.tokens.pos;
@@ -575,6 +580,10 @@ class ExpressionParser {
575
580
  const index = this.expression();
576
581
  this.tokens.expect("]");
577
582
  // A widget's arguments, which a call to it puts in args_0, args_1 and so on
583
+ if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
584
+ value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
585
+ continue;
586
+ }
578
587
  if (value.v == "expr" && value.e.k == "var" && value.e.name == "args" && index.k == "num") {
579
588
  value = { v: "expr", e: { k: "var", name: `args_${index.v}` } };
580
589
  continue;
@@ -614,7 +623,7 @@ class ExpressionParser {
614
623
  if (object.name == "State.variables" || object.name == "variables")
615
624
  return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
616
625
  if (object.name == "State.temporary" || object.name == "temporary")
617
- return { v: "expr", e: { k: "var", name: this.s.attribute(property, true) } };
626
+ return { v: "expr", e: this.s.variable(property, true) };
618
627
  return { v: "global", name: path };
619
628
  }
620
629
  return { v: "member", object, property };
@@ -701,8 +710,8 @@ class ExpressionParser {
701
710
  switch (t.type) {
702
711
  case "str": return { v: "expr", e: { k: "str", v: t.value } };
703
712
  case "num": return { v: "expr", e: { k: "num", v: t.value } };
704
- case "var": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, false) } };
705
- case "temp": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, true) } };
713
+ case "var": return { v: "expr", e: this.s.variable(t.value, false) };
714
+ case "temp": return { v: "expr", e: this.s.variable(t.value, true) };
706
715
  case "ident":
707
716
  switch (t.text) {
708
717
  case "true": return { v: "expr", e: { k: "bool", v: true } };
@@ -1298,8 +1307,14 @@ class Writer {
1298
1307
  }
1299
1308
  case "script":
1300
1309
  throw new Unconvertible("<<script>>, which runs SugarCube JavaScript");
1301
- case "for":
1302
- throw new Unconvertible("<<for>> loops");
1310
+ case "for": {
1311
+ state.leading = false;
1312
+ if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1313
+ throw new Unconvertible("<<break>> and <<continue>>");
1314
+ const loop = this.forLoop(m.args);
1315
+ const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state));
1316
+ return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1317
+ }
1303
1318
  case "widget":
1304
1319
  return "";
1305
1320
  case "back":
@@ -1340,6 +1355,27 @@ class Writer {
1340
1355
  throw new Unconvertible(`the <<${m.name}>> macro, which Squiffy has no equivalent for`);
1341
1356
  }
1342
1357
  }
1358
+ // What a <<for>> goes through, as {{#each}} does, and the variables (with their $ or _) that
1359
+ // stand for its item and position. It can go through an array with range, or by position:
1360
+ // <<for _i to 0; _i lt $list.length; _i++>>. Either way, $list[_i] is the item.
1361
+ forLoop(args) {
1362
+ const range = /^\s*([$_][A-Za-z_]\w*)\s*(?:,\s*([$_][A-Za-z_]\w*)\s*)?\brange\b([\s\S]+)$/.exec(args);
1363
+ if (range) {
1364
+ const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1365
+ const collection = this.expr.parse(range[3]);
1366
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item")) {
1367
+ throw new Unconvertible("<<for>> with range over something other than an array");
1368
+ }
1369
+ // With a position as well, $list[_i] is the item too
1370
+ return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
1371
+ }
1372
+ const counted = /^\s*_([A-Za-z_]\w*)\s*(?:to|=)\s*0\s*;\s*_\1\s*(?:lt|<)\s*([$_])([A-Za-z_]\w*)\.length\s*;\s*(?:_\1\s*\+\+|\+\+\s*_\1|_\1\s*\+=\s*1)\s*$/.exec(args);
1373
+ if (counted) {
1374
+ const array = this.expr.attribute(counted[3], counted[2] == "_");
1375
+ return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1376
+ }
1377
+ throw new Unconvertible("<<for>> loops, except ones that go through an array (with range, or from 0 to its length)");
1378
+ }
1343
1379
  // The attribute a form macro like <<textbox "$name">> sets
1344
1380
  receiver(arg) {
1345
1381
  const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
@@ -1353,9 +1389,10 @@ class Writer {
1353
1389
  return { plain: node.text, squiffy: this.inlineText(node.text) };
1354
1390
  }
1355
1391
  const e = this.expr.parse(arg);
1356
- if (e.k != "str")
1357
- throw new Unconvertible("a link whose text isn't fixed");
1358
- return { plain: e.v, squiffy: this.inlineText(e.v) };
1392
+ if (e.k == "str")
1393
+ return { plain: e.v, squiffy: this.inlineText(e.v) };
1394
+ // Text worked out as the story runs, e.g. a loop's item: named after the expression
1395
+ return { plain: arg.replace(/[^\w\s]+/g, " ").trim() || "link", squiffy: display(e) };
1359
1396
  }
1360
1397
  sectionName(passage, raw) {
1361
1398
  const section = this.ctx.story.sectionFor(passage);
package/dist/v5.js CHANGED
@@ -132,7 +132,8 @@ function findCommands(text, section, names) {
132
132
  let i = 0;
133
133
  while (i < text.length) {
134
134
  if (text.startsWith("{{", i)) {
135
- const closeToken = text.startsWith("{{{", i) ? "}}}" : "}}";
135
+ // A comment ends at --}}, and can have }} in it before that
136
+ const closeToken = text.startsWith("{{!--", i) ? "--}}" : text.startsWith("{{{", i) ? "}}}" : "}}";
136
137
  const close = text.indexOf(closeToken, i + 2);
137
138
  i = close == -1 ? i + 2 : close + closeToken.length;
138
139
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-compiler",
3
- "version": "7.0.0-beta.5",
3
+ "version": "7.0.0-beta.6",
4
4
  "description": "A tool for creating multiple-choice interactive stories",
5
5
  "author": "Alex Warren",
6
6
  "contributors": [
@@ -23,6 +23,7 @@
23
23
  "vitest": "^5.1.0"
24
24
  },
25
25
  "scripts": {
26
+ "dev": "vitest",
26
27
  "test": "vitest --run",
27
28
  "build": "tsc",
28
29
  "prepublishOnly": "npm run build && npm run test"
@@ -50,5 +51,5 @@
50
51
  "syntaxes/squiffy.tmLanguage.json"
51
52
  ],
52
53
  "type": "module",
53
- "gitHead": "9495ea44822999ad3e5c8fa305a88c5f5e43f1d8"
54
+ "gitHead": "90756c3ea9d782aa3f5f6cc41d9946a0a6cb8a45"
54
55
  }
@@ -302,7 +302,7 @@
302
302
  }
303
303
  },
304
304
  {
305
- "match": "^\\s*(@)(clear|end)\\s*$",
305
+ "match": "^\\s*(@)(clear|repeat|end)\\s*$",
306
306
  "captures": {
307
307
  "1": {
308
308
  "name": "punctuation.definition.directive.squiffy keyword.control.directive.squiffy"