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

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.
@@ -0,0 +1,201 @@
1
+ // Expressions shared by the Harlowe and SugarCube converters: each parses its own format's
2
+ // expressions into this tree, which is written out as a Squiffy expression, as {{#if}}, @set and
3
+ // {{set}} take (see runtime/src/infixExpressions.ts).
4
+ // Thrown when something can't be converted. The message says why, for the list of problems.
5
+ export class Unconvertible extends Error {
6
+ }
7
+ const precedence = {
8
+ "or": 1, "and": 2,
9
+ "=": 4, "!=": 4, ">": 4, ">=": 4, "<": 4, "<=": 4,
10
+ "+": 5, "-": 5,
11
+ "*": 6, "/": 6, "%": 6,
12
+ };
13
+ const notPrecedence = 3;
14
+ const atomPrecedence = 8;
15
+ function precedenceOf(e) {
16
+ if (e.k == "bin")
17
+ return precedence[e.op];
18
+ if (e.k == "not")
19
+ return notPrecedence;
20
+ if (e.k == "neg")
21
+ return 7;
22
+ return atomPrecedence;
23
+ }
24
+ // Text as a quoted string. Handlebars and Squiffy's expression tokenizer both take a backslash
25
+ // before the quote character, but Handlebars leaves other backslashes in, so those can't be
26
+ // written exactly.
27
+ export function quote(text, options = {}) {
28
+ if (text.includes("\\"))
29
+ throw new Unconvertible("text with a backslash in it");
30
+ // }} would end the {{...}} the expression is in
31
+ text = text.replace(/\}\}/g, "}&#125;").replace(/\n/g, " ");
32
+ const hasDouble = text.includes("\"");
33
+ const hasSingle = text.includes("'");
34
+ if (hasDouble && hasSingle)
35
+ return `"${text.replace(/"/g, "&quot;")}"`;
36
+ if (hasDouble || (options.preferSingle && !hasSingle))
37
+ return `'${text}'`;
38
+ return `"${text}"`;
39
+ }
40
+ const reservedWords = new Set(["and", "or", "not", "true", "false", "null", "undefined"]);
41
+ // An attribute name in an expression: the name, or [name] if it isn't one word
42
+ export function attributeRef(name) {
43
+ if (/^[A-Za-z_]\w*$/.test(name) && !reservedWords.has(name))
44
+ return name;
45
+ return `[${name}]`;
46
+ }
47
+ export function print(e, options = {}) {
48
+ switch (e.k) {
49
+ case "num": return String(e.v);
50
+ case "str": return quote(e.v, options);
51
+ case "bool": return String(e.v);
52
+ case "null": return "null";
53
+ case "var": return attributeRef(e.name);
54
+ case "array": return `(array${e.items.map(i => " " + printArgument(i, options)).join("")})`;
55
+ case "call": return `(${e.fn}${e.args.map(a => " " + printArgument(a, options)).join("")})`;
56
+ case "neg": {
57
+ const inner = print(e.e, options);
58
+ return precedenceOf(e.e) < atomPrecedence ? `-(${inner})` : `-${inner}`;
59
+ }
60
+ case "not": {
61
+ const inner = print(e.e, options);
62
+ return `not ${precedenceOf(e.e) < notPrecedence ? `(${inner})` : inner}`;
63
+ }
64
+ case "bin": {
65
+ const p = precedence[e.op];
66
+ const comparison = p == 4;
67
+ const left = print(e.l, options);
68
+ const right = print(e.r, options);
69
+ const lp = precedenceOf(e.l);
70
+ const rp = precedenceOf(e.r);
71
+ const l = lp < p || (comparison && lp == p) ? `(${left})` : left;
72
+ const r = rp <= p || e.r.k == "neg" ? `(${right})` : right;
73
+ return `${l} ${e.op} ${r}`;
74
+ }
75
+ }
76
+ }
77
+ // A helper's argument: anything but a single value or call needs brackets
78
+ function printArgument(e, options) {
79
+ const text = print(e, options);
80
+ return precedenceOf(e) < atomPrecedence || e.k == "neg" ? `(${text})` : text;
81
+ }
82
+ // Whether an expression can only be true or false, for Harlowe's "$a is 1 or 2"
83
+ export function isBoolean(e) {
84
+ if (e.k == "bool" || e.k == "not")
85
+ return true;
86
+ if (e.k == "bin")
87
+ return precedence[e.op] <= 4;
88
+ if (e.k == "call")
89
+ return e.fn == "seen" || e.fn == "contains" || e.fn == "at";
90
+ return false;
91
+ }
92
+ // A random whole number from min to max, as Squiffy's {{random}} picks from an array
93
+ export function randomInteger(min, max) {
94
+ if (min.k != "num" || max.k != "num")
95
+ throw new Unconvertible("a random number with a range that isn't fixed");
96
+ const low = Math.ceil(Math.min(min.v, max.v));
97
+ const high = Math.floor(Math.max(min.v, max.v));
98
+ if (high - low > 100)
99
+ throw new Unconvertible("a random number from a range of more than 100 numbers");
100
+ const items = [];
101
+ for (let n = low; n <= high; n++)
102
+ items.push({ k: "num", v: n });
103
+ return { k: "call", fn: "random", args: [{ k: "array", items }] };
104
+ }
105
+ // Expressions shown in text: {{name}} for an attribute, or {{= expression}}
106
+ export function display(e) {
107
+ // Fixed text is just text
108
+ if (e.k == "str")
109
+ return e.v.replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{").replace(/\}\}/g, "}&#125;");
110
+ if (e.k == "num" || e.k == "bool")
111
+ return String(e.v);
112
+ if (e.k == "var") {
113
+ return /^[A-Za-z_]\w*$/.test(e.name) && !reservedWords.has(e.name) ? `{{${e.name}}}` : `{{get ${quote(e.name)}}}`;
114
+ }
115
+ if (e.k == "call")
116
+ return `{{${print(e).slice(1, -1)}}}`;
117
+ return `{{= ${print(e)}}}`;
118
+ }
119
+ // A token stream for the expression parsers
120
+ export class Tokens {
121
+ constructor(items) {
122
+ Object.defineProperty(this, "items", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: items
127
+ });
128
+ Object.defineProperty(this, "pos", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: 0
133
+ });
134
+ }
135
+ peek(offset = 0) {
136
+ return this.items[this.pos + offset];
137
+ }
138
+ next() {
139
+ const token = this.items[this.pos++];
140
+ if (!token)
141
+ throw new Unconvertible("an expression that ends too soon");
142
+ return token;
143
+ }
144
+ is(text, offset = 0) {
145
+ return this.peek(offset)?.text == text;
146
+ }
147
+ accept(text) {
148
+ if (this.is(text)) {
149
+ this.pos++;
150
+ return true;
151
+ }
152
+ return false;
153
+ }
154
+ expect(text) {
155
+ if (!this.accept(text))
156
+ throw new Unconvertible(`an expression Squiffy can't read (expected "${text}")`);
157
+ }
158
+ get done() {
159
+ return this.pos >= this.items.length;
160
+ }
161
+ }
162
+ // Finds the end of a bracketed or quoted run, starting at the opening character. Returns the
163
+ // index just after the closing character, or -1.
164
+ export function skipBalanced(s, start, open, close, quotes = "\"'`") {
165
+ let depth = 0;
166
+ for (let i = start; i < s.length; i++) {
167
+ const c = s[i];
168
+ // Harlowe's possessive: $player's hp
169
+ if (c == "'" && s[i + 1] == "s" && /\s/.test(s[i + 2] ?? "") && /[\w)]/.test(s[i - 1] ?? ""))
170
+ continue;
171
+ if (quotes.includes(c)) {
172
+ const end = skipString(s, i);
173
+ if (end == -1)
174
+ return -1;
175
+ i = end - 1;
176
+ }
177
+ else if (c == open) {
178
+ depth++;
179
+ }
180
+ else if (c == close) {
181
+ depth--;
182
+ if (depth == 0)
183
+ return i + 1;
184
+ }
185
+ }
186
+ return -1;
187
+ }
188
+ // The index after a quoted string starting at start, or -1 if it isn't closed
189
+ export function skipString(s, start) {
190
+ const q = s[start];
191
+ for (let i = start + 1; i < s.length; i++) {
192
+ if (s[i] == "\\")
193
+ i++;
194
+ else if (s[i] == q)
195
+ return i + 1;
196
+ }
197
+ return -1;
198
+ }
199
+ export function unescapeString(literal) {
200
+ return literal.slice(1, -1).replace(/\\(.)/g, (_m, c) => c == "n" ? "\n" : c == "t" ? "\t" : c);
201
+ }
@@ -0,0 +1,17 @@
1
+ import type { Expr } from "./expression.js";
2
+ import type { ConvertedPassage, PassageContext } from "./convert.js";
3
+ export declare function splitArgs(args: string): string[];
4
+ export declare class HarloweExpressions {
5
+ readonly ctx: PassageContext;
6
+ constructor(ctx: PassageContext);
7
+ attribute(name: string, temp: boolean): string;
8
+ parse(source: string, it?: Expr): Expr;
9
+ passageName(source: string): {
10
+ name: string;
11
+ } | {
12
+ expr: Expr;
13
+ };
14
+ macro(name: string, raw: string, it?: Expr): Expr;
15
+ visits(): Expr;
16
+ }
17
+ export declare function convertHarlowePassage(text: string, ctx: PassageContext): ConvertedPassage;