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

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 (47) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +6 -0
  3. package/dist/analyse.js +101 -11
  4. package/dist/compiler.d.ts +9 -2
  5. package/dist/compiler.js +5 -2
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +13 -0
  9. package/dist/emit.js +45 -1
  10. package/dist/language-service.d.ts +1 -0
  11. package/dist/language-service.js +39 -13
  12. package/dist/node.d.ts +7 -1
  13. package/dist/node.js +16 -5
  14. package/dist/parse.d.ts +3 -0
  15. package/dist/parse.js +25 -2
  16. package/dist/project.d.ts +56 -0
  17. package/dist/project.js +148 -15
  18. package/dist/quest/aslx.d.ts +50 -0
  19. package/dist/quest/aslx.js +181 -0
  20. package/dist/quest/convert.d.ts +20 -0
  21. package/dist/quest/convert.js +504 -0
  22. package/dist/quest/script.d.ts +92 -0
  23. package/dist/quest/script.js +453 -0
  24. package/dist/quest/scripts.d.ts +24 -0
  25. package/dist/quest/scripts.js +505 -0
  26. package/dist/quest/text.d.ts +17 -0
  27. package/dist/quest/text.js +305 -0
  28. package/dist/setters.d.ts +4 -0
  29. package/dist/setters.js +10 -5
  30. package/dist/story-graph.d.ts +2 -1
  31. package/dist/story-graph.js +2 -0
  32. package/dist/syntax.d.ts +27 -2
  33. package/dist/text.d.ts +2 -0
  34. package/dist/text.js +24 -15
  35. package/dist/twine/audio.d.ts +21 -0
  36. package/dist/twine/audio.js +80 -0
  37. package/dist/twine/convert.d.ts +15 -1
  38. package/dist/twine/convert.js +217 -21
  39. package/dist/twine/expression.d.ts +26 -1
  40. package/dist/twine/expression.js +111 -6
  41. package/dist/twine/harlowe.d.ts +10 -0
  42. package/dist/twine/harlowe.js +417 -58
  43. package/dist/twine/sugarcube.d.ts +4 -0
  44. package/dist/twine/sugarcube.js +388 -86
  45. package/dist/v5.js +2 -1
  46. package/package.json +3 -2
  47. package/syntaxes/squiffy.tmLanguage.json +9 -4
@@ -4,7 +4,8 @@
4
4
  // variables), which is then written out: (if:) chains become {{#if}}, (set:) becomes @set or
5
5
  // {{set}}, (link:) and friends become links to generated passages and sections, and Harlowe's
6
6
  // markup becomes Markdown and HTML.
7
- import { display, isBoolean, print, randomInteger, skipBalanced, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
7
+ import { conditional, display, isBoolean, isListCall, lengthOf, member, print, randomInteger, targetName, skipBalanced, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { audioHelper, leadingAudio, pickSource, STOP_ALL_AUDIO } from "./audio.js";
8
9
  import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
10
  // Macro names ignore case, - and _
10
11
  function normalise(name) {
@@ -21,7 +22,7 @@ const changers = new Set([
21
22
  "opacity", "textrotate", "textrotatez", "box", "border", "b4r", "bordercolour", "bordercolor", "b4rcolour",
22
23
  "cornerradius", "textindent", "float", "hookname", "action", "linkundo", "linkfullscreen", "more",
23
24
  "clickgoto", "mouseovergoto", "mouseoverreplace", "mouseoverappend", "mouseoverprepend", "mouseoutreplace",
24
- "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink",
25
+ "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink", "output", "out",
25
26
  ]);
26
27
  class Parser {
27
28
  constructor(src) {
@@ -121,12 +122,14 @@ class Parser {
121
122
  continue;
122
123
  }
123
124
  }
124
- if (/^\(\$[\w]+:/.test(rest) || /^\(_[\w]+:/.test(rest)) {
125
+ const call = /^\(([$_])(\w+):/.exec(rest);
126
+ if (call) {
125
127
  // A call to a custom macro
126
128
  const end = skipBalanced(src, i, "(", ")");
127
129
  if (end != -1) {
128
130
  flush();
129
- nodes.push({ t: "comment", text: src.substring(i, end), reason: "Custom macros, made with (macro:), can't be converted." });
131
+ const raw = src.substring(i, end);
132
+ nodes.push({ t: "call", name: call[2], temp: call[1] == "_", args: raw.substring(call[0].length, raw.length - 1), raw });
130
133
  i = end;
131
134
  continue;
132
135
  }
@@ -302,9 +305,10 @@ function tokenize(s) {
302
305
  i += 2;
303
306
  continue;
304
307
  }
305
- const ordinal = /^(\d+)(st|nd|rd|th)\b/.exec(s.substring(i));
308
+ // 2nd, or 2ndlast, which is a negative position: from the end
309
+ const ordinal = /^(\d+)(st|nd|rd|th)(last)?\b/.exec(s.substring(i));
306
310
  if (ordinal) {
307
- tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) });
311
+ tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) * (ordinal[3] ? -1 : 1) });
308
312
  i += ordinal[0].length;
309
313
  continue;
310
314
  }
@@ -374,6 +378,10 @@ export class HarloweExpressions {
374
378
  attribute(name, temp) {
375
379
  return this.ctx.story.attribute(name, temp);
376
380
  }
381
+ // A Harlowe variable's value: its attribute, or inside a (for:), the loop's item
382
+ variable(name, temp) {
383
+ return this.ctx.story.variable(name, temp);
384
+ }
377
385
  parse(source, it) {
378
386
  const tokens = new Tokens(tokenize(source));
379
387
  const e = new ExpressionParser(this, tokens, it).expression();
@@ -392,6 +400,32 @@ export class HarloweExpressions {
392
400
  macro(name, raw, it) {
393
401
  const args = splitArgs(raw.substring(raw.indexOf(":") + 1, raw.length - 1));
394
402
  const values = () => args.map(a => this.parse(a, it));
403
+ const one = () => {
404
+ if (args.length != 1)
405
+ throw new Unconvertible(`(${name}:) with ${args.length ? "more than one value" : "no value"}`);
406
+ return values();
407
+ };
408
+ // The values of a macro like (sorted:) as a list: ...$bag is the list itself, and values
409
+ // are a list of them
410
+ const list = (from) => {
411
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.parse(v.replace(/^\s*\.\.\./, ""), it) : null;
412
+ if (from.length == 1) {
413
+ const e = spread(from[0]);
414
+ if (e)
415
+ return e;
416
+ }
417
+ const items = [];
418
+ for (const v of from) {
419
+ const e = spread(v);
420
+ if (!e)
421
+ items.push(this.parse(v, it));
422
+ else if (e.k == "array")
423
+ items.push(...e.items);
424
+ else
425
+ throw new Unconvertible(`(${name}:) with an array and other values`);
426
+ }
427
+ return { k: "array", items };
428
+ };
395
429
  switch (name) {
396
430
  case "either":
397
431
  return { k: "call", fn: "random", args: [{ k: "array", items: values() }] };
@@ -402,6 +436,21 @@ export class HarloweExpressions {
402
436
  case "a":
403
437
  case "array":
404
438
  return { k: "array", items: values() };
439
+ case "range": {
440
+ // The whole numbers from one to the other
441
+ if (args.length != 2)
442
+ throw new Unconvertible("(range:) without two numbers");
443
+ const [from, to] = values();
444
+ // Squiffy's (range from to) works it out as the story runs (#447). A short one
445
+ // with fixed numbers is written out, as it reads more simply.
446
+ if (from.k != "num" || to.k != "num" || Math.abs(to.v - from.v) > 20)
447
+ return { k: "call", fn: "range", args: [from, to] };
448
+ const step = to.v >= from.v ? 1 : -1;
449
+ const items = [];
450
+ for (let n = Math.round(from.v); n != Math.round(to.v) + step; n += step)
451
+ items.push({ k: "num", v: n });
452
+ return { k: "array", items };
453
+ }
405
454
  case "visited": {
406
455
  if (args.length == 0)
407
456
  return { k: "bin", op: ">", l: this.visits(), r: { k: "num", v: 0 } };
@@ -423,12 +472,62 @@ export class HarloweExpressions {
423
472
  case "passage":
424
473
  throw new Unconvertible("(passage:)");
425
474
  case "dm":
426
- case "datamap":
475
+ case "datamap": {
476
+ // An object (#442)
477
+ const items = values();
478
+ if (items.length % 2)
479
+ throw new Unconvertible("a datamap with a name that has no value");
480
+ const entries = [];
481
+ for (let n = 0; n < items.length; n += 2) {
482
+ const key = items[n];
483
+ if (key.k != "str" && key.k != "num")
484
+ throw new Unconvertible("a datamap with names that aren't fixed");
485
+ entries.push([String(key.v), items[n + 1]]);
486
+ }
487
+ return { k: "object", entries };
488
+ }
427
489
  case "ds":
428
490
  case "dataset":
429
- throw new Unconvertible("Harlowe datamaps and datasets");
491
+ throw new Unconvertible("Harlowe datasets");
430
492
  case "cond":
431
- throw new Unconvertible("(cond:), which Squiffy has no equivalent for in an expression");
493
+ return conditional(values(), "(cond:)");
494
+ // Text and numbers (#446)
495
+ case "lowercase":
496
+ case "uppercase":
497
+ case "upperfirst": {
498
+ const [text] = one();
499
+ return { k: "call", fn: name == "lowercase" ? "lower" : name == "uppercase" ? "upper" : "capitalise", args: [text] };
500
+ }
501
+ case "round":
502
+ case "floor":
503
+ case "ceil":
504
+ case "abs":
505
+ return { k: "call", fn: name, args: one() };
506
+ case "min":
507
+ case "max": {
508
+ const items = values();
509
+ if (!items.length)
510
+ throw new Unconvertible(`(${name}:) with no values`);
511
+ return { k: "call", fn: name, args: items };
512
+ }
513
+ // Lists (#447)
514
+ case "joined": {
515
+ if (!args.length)
516
+ throw new Unconvertible("(joined:) with nothing to join");
517
+ const separator = this.parse(args[0], it);
518
+ return { k: "call", fn: "join", args: [list(args.slice(1)), separator] };
519
+ }
520
+ case "sorted":
521
+ case "shuffled":
522
+ if (args.length && /^\s*(via|each)\b/.test(args[0]))
523
+ throw new Unconvertible(`(${name}:) with "${args[0].trim().split(/\s/)[0]}"`);
524
+ return { k: "call", fn: name == "sorted" ? "sort" : "shuffle", args: [list(args)] };
525
+ case "count": {
526
+ if (args.length != 2)
527
+ throw new Unconvertible("(count:) with more than one value to count");
528
+ const [container, value] = values();
529
+ return { k: "call", fn: "count", args: [container, value] };
530
+ }
432
531
  default:
433
532
  throw new Unconvertible(`the (${name}:) macro`);
434
533
  }
@@ -550,17 +649,14 @@ class ExpressionParser {
550
649
  default: return { k: "bin", op, l: left, r: right };
551
650
  }
552
651
  }
652
+ // A list, text or datamap that contains a value (#446)
553
653
  contains(collection, value) {
554
- if (collection.k == "var")
555
- return { k: "call", fn: "contains", args: [{ k: "str", v: collection.name }, value] };
556
- if (collection.k == "array")
557
- return { k: "call", fn: "contains", args: [collection, value] };
558
654
  if (collection.k == "call" && collection.fn == "__history") {
559
655
  if (value.k != "str")
560
656
  throw new Unconvertible("(history:) contains something other than a passage name");
561
657
  return { k: "call", fn: "seen", args: [{ k: "str", v: this.h.ctx.story.sectionForUnknown(value.v) }] };
562
658
  }
563
- throw new Unconvertible("\"contains\" with something other than a variable or an array");
659
+ return { k: "bin", op: "contains", l: collection, r: value };
564
660
  }
565
661
  additive() {
566
662
  let left = this.multiplicative();
@@ -592,22 +688,21 @@ class ExpressionParser {
592
688
  this.tokens.next();
593
689
  const property = this.tokens.next();
594
690
  if (property.text == "length") {
595
- if (e.k == "var")
596
- e = { k: "call", fn: "length", args: [{ k: "str", v: e.name }] };
597
- else if (e.k == "array")
598
- e = { k: "call", fn: "length", args: [e] };
599
- else if (e.k == "call" && e.fn == "__history")
600
- e = { k: "var", name: "turns" };
601
- else
602
- throw new Unconvertible("the length of something other than a variable or an array");
691
+ // A list's or text's length (#446)
692
+ e = e.k == "call" && e.fn == "__history" ? { k: "var", name: "turns" } : lengthOf(e);
693
+ }
694
+ else if (property.text == "ordinal" && (e.k == "var" || e.k == "array" || e.k == "member")) {
695
+ // $list's 1st, or $list's 2ndlast, which is bag[bag.length - 2]
696
+ const n = property.value;
697
+ e = n > 0 ? member(e, { k: "num", v: n - 1 }) : member(e, { k: "bin", op: "-", l: lengthOf(e), r: { k: "num", v: -n } });
603
698
  }
604
- else if (property.text == "ordinal" && (e.k == "var" || e.k == "array")) {
605
- // $list's 1st
606
- e = { k: "call", fn: "lookup", args: [e, { k: "num", v: property.value - 1 }] };
699
+ else if (property.text == "last" && (e.k == "var" || e.k == "array" || e.k == "member")) {
700
+ // $list's last (#447)
701
+ e = { k: "call", fn: "last", args: [e] };
607
702
  }
608
- else if (e.k == "var" && (property.type == "word" || property.type == "str") && /^[A-Za-z_]\w*$/.test(String(property.value ?? property.text))) {
609
- // A datamap's value is its own attribute: $player's hp is player_hp
610
- e = { k: "var", name: `${e.name}_${property.value ?? property.text}` };
703
+ else if ((e.k == "var" || e.k == "member") && (property.type == "word" || property.type == "str")) {
704
+ // A value in a datamap: $player's hp is player.hp (#442)
705
+ e = member(e, { k: "str", v: String(property.value ?? property.text) });
611
706
  }
612
707
  else {
613
708
  throw new Unconvertible(`properties of variables ('s ${property.text})`);
@@ -620,8 +715,8 @@ class ExpressionParser {
620
715
  switch (t.type) {
621
716
  case "str": return { k: "str", v: t.value };
622
717
  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) };
718
+ case "var": return this.h.variable(t.value, false);
719
+ case "temp": return this.h.variable(t.value, true);
625
720
  case "hook": throw new Unconvertible("a hook name in an expression");
626
721
  case "(": {
627
722
  const e = this.expression();
@@ -717,6 +812,13 @@ class Writer {
717
812
  writable: true,
718
813
  value: false
719
814
  });
815
+ // Whether this is the body of a custom macro, where (output:) is what it shows
816
+ Object.defineProperty(this, "inMacro", {
817
+ enumerable: true,
818
+ configurable: true,
819
+ writable: true,
820
+ value: false
821
+ });
720
822
  this.expr = new HarloweExpressions(ctx);
721
823
  this.referenced = referencedHooks(ctx);
722
824
  }
@@ -858,9 +960,12 @@ class Writer {
858
960
  return node.s;
859
961
  case "comment":
860
962
  return this.ctx.unconvertible(node.text, node.reason);
963
+ case "call":
964
+ state.leading = false;
965
+ return this.call(node);
861
966
  case "var":
862
967
  state.leading = false;
863
- return display({ k: "var", name: this.expr.attribute(node.name, node.temp) });
968
+ return display(this.expr.variable(node.name, node.temp));
864
969
  case "link":
865
970
  state.leading = false;
866
971
  return this.link(node);
@@ -1070,7 +1175,7 @@ class Writer {
1070
1175
  throw e;
1071
1176
  state.leading = false;
1072
1177
  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)) {
1178
+ if (m.hook && !["link", "linkreveal", "linkrepeat", "linkrerun", "click", "replace", "append", "prepend", "show", "for", "loop"].includes(m.name)) {
1074
1179
  // Keep the hook's text, since most changers only change how it looks
1075
1180
  return this.ctx.unconvertible(m.raw, reason) + this.hookContent(m.hook, state);
1076
1181
  }
@@ -1087,6 +1192,19 @@ class Writer {
1087
1192
  case "set":
1088
1193
  case "put":
1089
1194
  return this.set(m, args, state);
1195
+ // What a custom macro shows (#450)
1196
+ case "output":
1197
+ case "out":
1198
+ case "outputdata":
1199
+ case "outdata":
1200
+ if (!this.inMacro)
1201
+ throw new Unconvertible(`(${m.name}:) outside a custom macro`);
1202
+ state.leading = false;
1203
+ if (m.hook && !args.length && (name == "output" || name == "out"))
1204
+ return this.hookContent(m.hook, state);
1205
+ if (args.length != 1)
1206
+ throw new Unconvertible(`(${m.name}:) with more than one value`);
1207
+ return display(this.expr.parse(args[0]));
1090
1208
  case "print":
1091
1209
  state.leading = false;
1092
1210
  if (args.length != 1)
@@ -1356,6 +1474,24 @@ class Writer {
1356
1474
  }
1357
1475
  throw new Unconvertible(`(${name}:) on ${hookName ? "a hook that isn't in this passage" : "text rather than a named hook"}`);
1358
1476
  }
1477
+ case "for":
1478
+ case "loop": {
1479
+ state.leading = false;
1480
+ if (!m.hook)
1481
+ throw new Unconvertible(`(${name}:) without a hook`);
1482
+ // each _item, or _item where ... (which only shows the items it's true for)
1483
+ const lambda = /^\s*(each\s+)?_([A-Za-z_]\w*)(?:\s+where\s+([\s\S]+))?$/i.exec(args[0] ?? "");
1484
+ if (!lambda || (!lambda[1] && !lambda[3]))
1485
+ throw new Unconvertible(`(${name}:) with something other than "each _item" or "_item where ..."`);
1486
+ const collection = this.forCollection(args.slice(1), name);
1487
+ const hook = m.hook;
1488
+ const numbers = collection.k == "call" && collection.fn == "range";
1489
+ return this.ctx.story.inLoop(new Map([["_" + lambda[2], "item"]]), undefined, () => {
1490
+ const body = this.hookContent(hook, state);
1491
+ const shown = lambda[3] ? `{{#if ${print(this.expr.parse(lambda[3]))}}}${body}{{/if}}` : body;
1492
+ return `{{#each ${print(collection)}}}${shown}{{/each}}`;
1493
+ }, numbers);
1494
+ }
1359
1495
  case "linkstorylet": {
1360
1496
  state.leading = false;
1361
1497
  // Every storylet whose condition is true, the first time (link-storylet:) is in a passage
@@ -1388,10 +1524,109 @@ class Writer {
1388
1524
  case "else":
1389
1525
  // Handled in nodes()
1390
1526
  return "";
1527
+ case "track":
1528
+ return leadingAudio(this.track(m, args), state);
1529
+ case "newtrack":
1530
+ // Found before the story's converted
1531
+ return "";
1532
+ case "masteraudio":
1533
+ if (args.length == 1 && String(literal(args[0])).toLowerCase() == "stopall")
1534
+ return leadingAudio(STOP_ALL_AUDIO, state);
1535
+ throw new Unconvertible("(masteraudio:), which changes all the story's sound at once, except to stop it");
1536
+ case "playlist":
1537
+ case "newplaylist":
1538
+ throw new Unconvertible("playlists");
1539
+ case "group":
1540
+ case "newgroup":
1541
+ throw new Unconvertible("audio groups");
1391
1542
  default:
1392
1543
  throw new Unconvertible(`the (${m.raw.substring(1, m.raw.indexOf(":"))}:) macro, which Squiffy has no equivalent for`);
1393
1544
  }
1394
1545
  }
1546
+ // (track: "name", "command", ...values), from the Harlowe Audio Library
1547
+ track(m, args) {
1548
+ const track = literal(args[0]);
1549
+ const command = literal(args[1]);
1550
+ if (typeof track != "string")
1551
+ throw new Unconvertible("(track:) with a track that isn't fixed");
1552
+ if (typeof command != "string")
1553
+ throw new Unconvertible("(track:) with a command that isn't fixed");
1554
+ const action = { play: false, stop: false, loop: false };
1555
+ const num = (i) => {
1556
+ const n = literal(args[i]);
1557
+ if (typeof n != "number")
1558
+ throw new Unconvertible(`(track:) "${command}" with a value that isn't a fixed number`);
1559
+ return n;
1560
+ };
1561
+ switch (command.toLowerCase()) {
1562
+ case "play":
1563
+ case "playwhenpossible":
1564
+ action.play = true;
1565
+ break;
1566
+ case "fadein":
1567
+ action.play = true;
1568
+ if (args[2] !== undefined)
1569
+ action.fade = num(2);
1570
+ break;
1571
+ case "stop":
1572
+ action.stop = true;
1573
+ break;
1574
+ case "fadeout":
1575
+ action.stop = true;
1576
+ if (args[2] !== undefined)
1577
+ action.fade = num(2);
1578
+ break;
1579
+ case "fadeto":
1580
+ if (num(2) > 0)
1581
+ action.play = true;
1582
+ else
1583
+ action.stop = true;
1584
+ if (args[3] !== undefined)
1585
+ action.fade = num(3);
1586
+ break;
1587
+ case "loop":
1588
+ // Found before the story's converted
1589
+ return "";
1590
+ case "volume":
1591
+ if (harloweAudio(this.ctx.story).looping.has(track)) {
1592
+ this.ctx.story.note("audio-music-volume", m.raw, "Squiffy plays music at full volume, so the music's volume has been left out");
1593
+ return "";
1594
+ }
1595
+ throw new Unconvertible("(track:) changing the volume of a sound on its own: give {{sound}} a volume= instead");
1596
+ case "pause":
1597
+ throw new Unconvertible("pausing a track");
1598
+ case "mute":
1599
+ case "unmute":
1600
+ throw new Unconvertible("muting a track");
1601
+ case "time":
1602
+ throw new Unconvertible("playing a track from part of the way through");
1603
+ default:
1604
+ throw new Unconvertible(`(track:) with "${command}"`);
1605
+ }
1606
+ return audioHelper(this.ctx, m.raw, harloweAudio(this.ctx.story), track, action);
1607
+ }
1608
+ // What a (for:) goes through: an array spread out (...$list), or values, as {{#each}} takes
1609
+ forCollection(values, name) {
1610
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.expr.parse(v.replace(/^\s*\.\.\./, "")) : null;
1611
+ if (values.length == 1) {
1612
+ const e = spread(values[0]);
1613
+ if (e && (e.k == "var" || e.k == "array" || (e.k == "loop" && e.kind == "item") || isListCall(e)))
1614
+ return e;
1615
+ }
1616
+ const items = [];
1617
+ for (const v of values) {
1618
+ const e = spread(v);
1619
+ if (!e)
1620
+ items.push(this.expr.parse(v));
1621
+ else if (e.k == "array")
1622
+ items.push(...e.items);
1623
+ else
1624
+ throw new Unconvertible(`(${name}:) with an array and other values`);
1625
+ }
1626
+ if (!items.length)
1627
+ throw new Unconvertible(`(${name}:) with nothing to go through`);
1628
+ return { k: "array", items };
1629
+ }
1395
1630
  sectionName(passage, raw) {
1396
1631
  const section = this.ctx.story.sectionFor(passage);
1397
1632
  if (section === undefined) {
@@ -1426,20 +1661,23 @@ class Writer {
1426
1661
  if (navigation) {
1427
1662
  if (navigation.setters)
1428
1663
  return this.linkTo(text, navigation.target, m.raw, navigation.setters);
1429
- // It does more than set variables, so do that in a section of its own
1430
- const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, navigation.content());
1431
- return sectionLink(text, section);
1432
- }
1433
- const content = this.nodes(m.hook.nodes, { leading: false, directives: [] });
1664
+ // It does more than set variables, so do that in a section of its own. In a loop, it can
1665
+ // use the loop's item, which the link sets an attribute to (#448).
1666
+ const { result, setters } = this.ctx.story.linkBody(() => navigation.content());
1667
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, result);
1668
+ return sectionLink(text, section, setters);
1669
+ }
1670
+ const hook = m.hook;
1671
+ const { result: content, setters } = this.ctx.story.linkBody(() => this.nodes(hook.nodes, { leading: false, directives: [] }));
1434
1672
  if (m.name == "linkrepeat" || m.name == "linkrerun") {
1435
1673
  this.ctx.approximate(m.raw, "In Squiffy, this link can only be clicked once.");
1436
1674
  const passage = this.ctx.addPassage(textExpr.v, content);
1437
- return passageLink(text, passage);
1675
+ return passageLink(text, passage, setters);
1438
1676
  }
1439
1677
  const label = this.ctx.newLabel(textExpr.v);
1440
1678
  const replacement = m.name == "linkreveal" ? text + content : content;
1441
1679
  const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1442
- return `{{#label "${label}"}}${passageLink(text, passage)}{{/label}}`;
1680
+ return `{{#label "${label}"}}${passageLink(text, passage, setters)}{{/label}}`;
1443
1681
  }
1444
1682
  // If a hook only sets variables and then goes to a passage, the setters and the passage.
1445
1683
  // If it does other things before going to a passage, content is the Squiffy text for a
@@ -1619,23 +1857,7 @@ class Writer {
1619
1857
  throw new Unconvertible("a colour that isn't fixed");
1620
1858
  }
1621
1859
  // ---- (set:) ----
1622
- // An assignment, with a datamap flattened into one for each of its values
1623
1860
  assignments(source, put) {
1624
- const datamap = /^\s*([$_])([A-Za-z]\w*)\s+to\s+\((?:dm|datamap):([\s\S]*)\)\s*$/i.exec(source);
1625
- if (datamap && !put) {
1626
- const name = this.expr.attribute(datamap[2], datamap[1] == "_");
1627
- const values = splitArgs(datamap[3]);
1628
- if (values.length % 2)
1629
- throw new Unconvertible("a datamap with a name that has no value");
1630
- const result = [];
1631
- for (let n = 0; n < values.length; n += 2) {
1632
- const key = this.expr.parse(values[n]);
1633
- if (key.k != "str" || !/^[A-Za-z_]\w*$/.test(key.v))
1634
- throw new Unconvertible("a datamap with names that aren't words");
1635
- result.push({ kind: "set", name: `${name}_${key.v}`, value: this.expr.parse(values[n + 1]) });
1636
- }
1637
- return result;
1638
- }
1639
1861
  return [this.assignment(source, put)];
1640
1862
  }
1641
1863
  assignment(source, put) {
@@ -1658,10 +1880,10 @@ class Writer {
1658
1880
  const target = /^([$_])([A-Za-z]\w*)((?:'s\s+(?:[A-Za-z_]\w*|"[A-Za-z_]\w*"))*)$/.exec(targetSource.trim());
1659
1881
  if (!target)
1660
1882
  throw new Unconvertible("setting something other than a variable");
1661
- // $player's hp is player_hp
1883
+ // $player's hp is player.hp (#442)
1662
1884
  const properties = [...target[3].matchAll(/'s\s+"?([A-Za-z_]\w*)"?/g)].map(m => m[1]);
1663
- const name = [this.expr.attribute(target[2], target[1] == "_"), ...properties].join("_");
1664
- const variable = { k: "var", name };
1885
+ const variable = properties.reduce((e, property) => member(e, { k: "str", v: property }), { k: "var", name: this.expr.attribute(target[2], target[1] == "_") });
1886
+ const name = targetName(variable);
1665
1887
  const value = this.expr.parse(valueSource, variable);
1666
1888
  // $x to it + 1, and $x to $x - 2
1667
1889
  if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
@@ -1675,8 +1897,56 @@ class Writer {
1675
1897
  }
1676
1898
  return { kind: "set", name, value };
1677
1899
  }
1900
+ // A call to a custom macro embeds its section, with its arguments as the parameters (#450)
1901
+ call(node) {
1902
+ const macro = node.temp ? undefined : harloweMacros(this.ctx.story).get(node.name);
1903
+ if (!macro)
1904
+ return this.ctx.unconvertible(node.raw, "Custom macros, made with (macro:), can only be converted when they're kept in a story variable ($), and only show text.");
1905
+ try {
1906
+ const args = splitArgs(node.args);
1907
+ if (args.length > macro.params.length)
1908
+ throw new Unconvertible("more values than the macro has parameters");
1909
+ const params = args.map((a, n) => ` ${macro.params[n]}=${print(this.expr.parse(a))}`).join("");
1910
+ return `{{embed ${print({ k: "str", v: macro.section })}${params}}}`;
1911
+ }
1912
+ catch (e) {
1913
+ if (!(e instanceof Unconvertible))
1914
+ throw e;
1915
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
1916
+ }
1917
+ }
1918
+ // A custom macro's body (#450), which becomes a section that calls to it embed. It's a code
1919
+ // hook, so the whitespace between its macros isn't shown.
1920
+ macroBody(source) {
1921
+ const nodes = new Parser(source).parse(0).nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1922
+ this.collectHooks(nodes);
1923
+ this.inMacro = true;
1924
+ const state = { leading: false, directives: [] };
1925
+ let body = this.nodes(nodes, state);
1926
+ body += this.closeAll();
1927
+ return { directives: [], body };
1928
+ }
1678
1929
  set(m, args, state) {
1679
1930
  let out = "";
1931
+ // A custom macro becomes a section when it's defined (#450)
1932
+ args = args.filter(source => {
1933
+ const definition = /^\s*\$(\w+)\s+to\s+\(macro:/i.exec(source);
1934
+ const macro = definition && harloweMacros(this.ctx.story).get(definition[1]);
1935
+ if (!macro || macro.defined)
1936
+ return !macro;
1937
+ macro.defined = true;
1938
+ let converted;
1939
+ try {
1940
+ converted = new Writer(this.ctx).macroBody(macro.body);
1941
+ }
1942
+ catch (e) {
1943
+ if (!(e instanceof Unconvertible))
1944
+ throw e;
1945
+ converted = { directives: [], body: this.ctx.unconvertible(macro.body, `This macro couldn't be converted: ${e.message}.`) };
1946
+ }
1947
+ this.ctx.fillSection(macro.section, converted);
1948
+ return false;
1949
+ });
1680
1950
  for (const a of args.flatMap(source => this.assignments(source, m.name == "put"))) {
1681
1951
  const amount = a.value.k == "num" && Number.isInteger(a.value.v) && a.value.v >= 0 ? a.value.v : null;
1682
1952
  if (state.leading) {
@@ -1784,6 +2054,9 @@ function splitOutsideStrings(s, keyword) {
1784
2054
  let depth = 0;
1785
2055
  for (let i = 0; i < s.length; i++) {
1786
2056
  const c = s[i];
2057
+ // Harlowe's possessive: $player's hp
2058
+ if (c == "'" && s[i + 1] == "s" && /\s/.test(s[i + 2] ?? "") && /[\w)"]/.test(s[i - 1] ?? ""))
2059
+ continue;
1787
2060
  if (c == "\"" || c == "'") {
1788
2061
  const end = skipString(s, i);
1789
2062
  if (end == -1)
@@ -1848,6 +2121,92 @@ function clickableText(source, ctx) {
1848
2121
  result = withHookName.substring(0, at) + `|${hook}>[${text}]` + withHookName.substring(at + text.length);
1849
2122
  }
1850
2123
  }
2124
+ // A string, number or boolean written as it is, or undefined for anything else
2125
+ function literal(arg) {
2126
+ if (arg === undefined)
2127
+ return undefined;
2128
+ const a = arg.trim();
2129
+ if (/^["']/.test(a) && skipString(a, 0) == a.length)
2130
+ return unescapeString(a);
2131
+ if (/^-?(\d+\.?\d*|\.\d+)$/.test(a))
2132
+ return Number(a);
2133
+ if (/^(true|false)$/i.test(a))
2134
+ return a.toLowerCase() == "true";
2135
+ return undefined;
2136
+ }
2137
+ // The special passages of the Harlowe Audio Library, which aren't part of the story
2138
+ export const harloweAudioPassages = new Set(["hal.tracks", "hal.config"]);
2139
+ // The story's tracks, from the Harlowe Audio Library's hal.tracks passage ("name: file") and
2140
+ // (newtrack:), and the ones (track:) sets to loop
2141
+ export function harloweAudio(story) {
2142
+ return story.cached("harlowe-audio", () => {
2143
+ const audio = { files: new Map(), looping: new Set() };
2144
+ const definitions = story.twine.passages.find(p => p.name == "hal.tracks")?.text ?? "";
2145
+ for (const line of definitions.split(/\r?\n/)) {
2146
+ // The name ends at the first colon: the files can be web addresses
2147
+ const colon = line.indexOf(":");
2148
+ if (colon == -1)
2149
+ continue;
2150
+ const name = line.substring(0, colon).trim();
2151
+ const file = pickSource(line.substring(colon + 1).split(",").map(f => f.trim()).filter(f => f));
2152
+ if (name && file && !audio.files.has(name))
2153
+ audio.files.set(name, file);
2154
+ }
2155
+ for (const p of story.twine.passages) {
2156
+ for (const m of p.text.matchAll(/\((new-?track|track):/gi)) {
2157
+ const end = skipBalanced(p.text, m.index, "(", ")");
2158
+ if (end == -1)
2159
+ continue;
2160
+ const args = splitArgs(p.text.substring(m.index + m[0].length, end - 1)).map(literal);
2161
+ if (typeof args[0] != "string")
2162
+ continue;
2163
+ if (m[1].toLowerCase() == "track") {
2164
+ if (typeof args[1] == "string" && args[1].toLowerCase() == "loop" && args[2] === true)
2165
+ audio.looping.add(args[0]);
2166
+ }
2167
+ else {
2168
+ const file = pickSource(args.slice(1).filter((a) => typeof a == "string"));
2169
+ if (file && !audio.files.has(args[0]))
2170
+ audio.files.set(args[0], file);
2171
+ }
2172
+ }
2173
+ }
2174
+ return audio;
2175
+ });
2176
+ }
2177
+ // The story's custom macros (#450): (set: $name to (macro: str-type _who, [ ... ])). Each becomes
2178
+ // a section, named before anything's converted so calls know where they go, with its parameters
2179
+ // as the attributes the body's temporary variables become. A macro with a parameter that takes
2180
+ // any number of values (...) isn't one of them, and stays unconverted.
2181
+ export function harloweMacros(story) {
2182
+ return story.cached("harlowe-macros", () => {
2183
+ const result = new Map();
2184
+ for (const p of story.twine.passages) {
2185
+ for (const m of p.text.matchAll(/\$(\w+)\s+to\s+(?=\(macro:)/gi)) {
2186
+ if (result.has(m[1]))
2187
+ continue;
2188
+ const start = m.index + m[0].length;
2189
+ const end = skipBalanced(p.text, start, "(", ")");
2190
+ if (end == -1)
2191
+ continue;
2192
+ const args = splitArgs(p.text.substring(start + "(macro:".length, end - 1));
2193
+ const hook = args.pop()?.trim();
2194
+ if (!hook?.startsWith("[") || !hook.endsWith("]"))
2195
+ continue;
2196
+ const params = args.map(a => /^\s*(?:[\w-]+-type\s+)?_(\w+)\s*$/.exec(a)?.[1]);
2197
+ if (params.some(name => !name))
2198
+ continue;
2199
+ result.set(m[1], {
2200
+ section: story.uniqueSectionName(`macro ${m[1]}`),
2201
+ params: params.map(name => story.attribute(name, true)),
2202
+ body: hook.substring(1, hook.length - 1),
2203
+ defined: false,
2204
+ });
2205
+ }
2206
+ }
2207
+ return result;
2208
+ });
2209
+ }
1851
2210
  export function convertHarlowePassage(text, ctx) {
1852
2211
  // A backslash at the end or start of a line joins it to the next or previous line
1853
2212
  const source = clickableText(text.replace(/\\\n/g, "").replace(/\n\\/g, ""), ctx);