squiffy-compiler 6.0.1 → 7.0.0-beta.11

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 (62) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +96 -0
  3. package/dist/analyse.js +951 -0
  4. package/dist/compiler.d.ts +32 -40
  5. package/dist/compiler.js +26 -691
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +71 -0
  9. package/dist/emit.js +192 -0
  10. package/dist/helpers.d.ts +1 -0
  11. package/dist/helpers.js +14 -0
  12. package/dist/ignore.d.ts +8 -0
  13. package/dist/ignore.js +71 -0
  14. package/dist/infix-expressions.d.ts +19 -0
  15. package/dist/infix-expressions.js +713 -0
  16. package/dist/language-service.d.ts +90 -0
  17. package/dist/language-service.js +883 -0
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +22 -0
  21. package/dist/parse.js +316 -0
  22. package/dist/project.d.ts +129 -0
  23. package/dist/project.js +488 -0
  24. package/dist/quest/aslx.d.ts +51 -0
  25. package/dist/quest/aslx.js +184 -0
  26. package/dist/quest/convert.d.ts +20 -0
  27. package/dist/quest/convert.js +552 -0
  28. package/dist/quest/script.d.ts +92 -0
  29. package/dist/quest/script.js +453 -0
  30. package/dist/quest/scripts.d.ts +24 -0
  31. package/dist/quest/scripts.js +506 -0
  32. package/dist/quest/text.d.ts +18 -0
  33. package/dist/quest/text.js +323 -0
  34. package/dist/section-labels.d.ts +4 -0
  35. package/dist/section-labels.js +64 -0
  36. package/dist/setters.d.ts +49 -0
  37. package/dist/setters.js +477 -0
  38. package/dist/story-graph.d.ts +71 -0
  39. package/dist/story-graph.js +445 -0
  40. package/dist/syntax.d.ts +198 -0
  41. package/dist/syntax.js +8 -0
  42. package/dist/templates.d.ts +17 -0
  43. package/dist/templates.js +180 -0
  44. package/dist/text.d.ts +44 -0
  45. package/dist/text.js +348 -0
  46. package/dist/twine/audio.d.ts +21 -0
  47. package/dist/twine/audio.js +80 -0
  48. package/dist/twine/convert.d.ts +131 -0
  49. package/dist/twine/convert.js +1057 -0
  50. package/dist/twine/expression.d.ts +88 -0
  51. package/dist/twine/expression.js +318 -0
  52. package/dist/twine/harlowe.d.ts +27 -0
  53. package/dist/twine/harlowe.js +2341 -0
  54. package/dist/twine/settings.d.ts +9 -0
  55. package/dist/twine/settings.js +322 -0
  56. package/dist/twine/story.d.ts +24 -0
  57. package/dist/twine/story.js +231 -0
  58. package/dist/twine/sugarcube.d.ts +40 -0
  59. package/dist/twine/sugarcube.js +2172 -0
  60. package/dist/v5.js +2 -1
  61. package/package.json +35 -6
  62. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -0,0 +1,883 @@
1
+ // The Squiffy language service: outline, diagnostics, go to definition, references, rename,
2
+ // completion, hover, folding, quick fixes, "which section is this" and the story graph, for a
3
+ // multi-file project.
4
+ // It has no UI or DOM dependencies, so the web editor, the desktop app (from a Web Worker) and an
5
+ // LSP adapter for VS Code can all call it directly.
6
+ //
7
+ // Positions and ranges are zero-based { line, character }, following LSP conventions.
8
+ import { analyse, ParseCache } from "./analyse.js";
9
+ import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME, storyFileList } from "./project.js";
10
+ import { convertV5Syntax, findV5Syntax } from "./v5.js";
11
+ import { findUnquotedText, splitWithOffsets } from "./setters.js";
12
+ import { ignoredDiagnostics } from "./ignore.js";
13
+ import { buildStoryGraph, firstScreenSoundDiagnostics, storyGraphDiagnostics } from "./story-graph.js";
14
+ const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
15
+ const usageRange = (usage) => (usage.link ?? usage.embed ?? usage.goto ?? usage.deactivate).range;
16
+ // Directives, for completion, with what they do
17
+ const DIRECTIVES = [
18
+ ["title", "Sets the story's title"],
19
+ ["start", "Sets the section the story starts at"],
20
+ ["import", "Adds another file to the story"],
21
+ ["set", "Sets an attribute"],
22
+ ["unset", "Sets an attribute to false"],
23
+ ["inc", "Adds to an attribute"],
24
+ ["dec", "Subtracts from an attribute"],
25
+ ["clear", "Clears the screen"],
26
+ ["repeat", "Lets the player click this passage's links again"],
27
+ ["end", "Marks this section as an ending"],
28
+ ["music", "Plays music until it's changed, or stops it with @music stop"],
29
+ ["sound", "Plays a sound once, or stops the sounds playing with @sound stop"],
30
+ ["class", "Puts classes on the story while this section is shown, for its stylesheet"],
31
+ ["tag", "Tags this section or passage, so the story can list them with (passages tagged=\"...\")"],
32
+ ["transition", "How this section or passage appears, such as @transition fade 1s"],
33
+ ["leave", "How the old text goes when this clears the screen, such as @leave fade 1s"],
34
+ ["ui", "JavaScript for the story's user interface"],
35
+ ];
36
+ // The warnings with a quick fix that adds a squiffy-ignore comment
37
+ const IGNORE_ACTION_CODES = new Set(["squiffy/unknown-name", "squiffy/sound-on-first-screen", "squiffy/unreachable-section"]);
38
+ const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
39
+ function comparePositions(a, b) {
40
+ return a.line - b.line || a.character - b.character;
41
+ }
42
+ const overlaps = (a, b) => comparePositions(a.start, b.end) <= 0 && comparePositions(b.start, a.end) <= 0;
43
+ // Same as the compiler: the whole target if it's a name, otherwise the part before the first comma.
44
+ function resolveName(target, has) {
45
+ const trimmed = target.trim();
46
+ if (has(trimmed))
47
+ return trimmed;
48
+ const destination = trimmed.split(",")[0].trim();
49
+ return has(destination) ? destination : undefined;
50
+ }
51
+ // The name a broken link was trying to reach
52
+ const intendedName = (target) => target.trim().split(",")[0].trim();
53
+ // The attribute a setter sets, e.g. gold in gold += 1, or hero.hp in hero.hp = 10 (#442)
54
+ function attributeName(expression) {
55
+ return /^\s*(?:not\s+)?(\w+(?:\.\w+)*)/.exec(expression)?.[1] ?? "";
56
+ }
57
+ function resolvePath(baseDir, relative) {
58
+ const parts = baseDir ? baseDir.split("/") : [];
59
+ for (const part of relative.split("/")) {
60
+ if (part == "" || part == ".")
61
+ continue;
62
+ if (part == "..") {
63
+ if (!parts.length)
64
+ return null;
65
+ parts.pop();
66
+ }
67
+ else {
68
+ parts.push(part);
69
+ }
70
+ }
71
+ return parts.join("/");
72
+ }
73
+ const dirname = (path) => path.includes("/") ? path.substring(0, path.lastIndexOf("/")) : "";
74
+ function relativePath(fromDir, path) {
75
+ const from = fromDir ? fromDir.split("/") : [];
76
+ const to = path.split("/");
77
+ let common = 0;
78
+ while (common < from.length && common < to.length - 1 && from[common] == to[common])
79
+ common++;
80
+ return [...from.slice(common).map(() => ".."), ...to.slice(common)].join("/");
81
+ }
82
+ const endOfText = (text) => {
83
+ const lines = text.split("\n");
84
+ return { line: lines.length - 1, character: lines[lines.length - 1].length };
85
+ };
86
+ const lineRange = (line, start, end) => ({
87
+ start: { line, character: start },
88
+ end: { line, character: end },
89
+ });
90
+ export function createLanguageService(options) {
91
+ const files = options.files;
92
+ let mainFile = options.mainFile;
93
+ const openFiles = new Map();
94
+ const diskTexts = new Map();
95
+ const parseCache = new ParseCache();
96
+ let version = 0;
97
+ let cached;
98
+ const changed = () => { version++; };
99
+ async function readFile(path) {
100
+ const open = openFiles.get(path);
101
+ if (open !== undefined)
102
+ return open;
103
+ let text = diskTexts.get(path);
104
+ if (!text) {
105
+ text = files.readText(path);
106
+ diskTexts.set(path, text);
107
+ // Don't cache a failed read
108
+ text.catch(() => diskTexts.delete(path));
109
+ }
110
+ return text;
111
+ }
112
+ // The compiler's ExternalFiles, resolving @import patterns and @ui paths against the main
113
+ // file's folder and never importing a file twice, as the CLI does.
114
+ function externalFiles(texts, mainFile, storyFiles) {
115
+ const baseDir = dirname(mainFile);
116
+ const included = new Set([mainFile]);
117
+ const matched = new Set(storyFiles);
118
+ return {
119
+ async getMatchingFilenames(pattern) {
120
+ const resolved = resolvePath(baseDir, pattern);
121
+ if (resolved === null)
122
+ return [];
123
+ const regex = globToRegExp(resolved);
124
+ const paths = await listPaths();
125
+ const result = [...paths].filter(p => regex.test(p) && !included.has(p)).sort();
126
+ for (const p of result)
127
+ matched.add(p);
128
+ return result;
129
+ },
130
+ async getContent(filename) {
131
+ const path = matched.has(filename) ? filename : resolvePath(baseDir, filename);
132
+ if (path === null)
133
+ return "";
134
+ included.add(path);
135
+ try {
136
+ const text = await readFile(path);
137
+ texts.set(path, text);
138
+ return text;
139
+ }
140
+ catch {
141
+ return "";
142
+ }
143
+ },
144
+ getLocalFilename: (filename) => relativePath(baseDir, filename),
145
+ };
146
+ }
147
+ async function listPaths() {
148
+ const paths = new Set((await files.list()).map(f => f.path));
149
+ for (const open of openFiles.keys())
150
+ paths.add(open);
151
+ return paths;
152
+ }
153
+ async function getProject() {
154
+ const fallback = { mainFile, storyFiles: [], excludedFiles: [] };
155
+ const paths = await listPaths();
156
+ if (!paths.has(PROJECT_FILENAME))
157
+ return fallback;
158
+ let text;
159
+ try {
160
+ text = await readFile(PROJECT_FILENAME);
161
+ }
162
+ catch {
163
+ return fallback;
164
+ }
165
+ const parsed = parseProjectFile(text);
166
+ if (!parsed.success)
167
+ return { ...fallback, error: parsed.error };
168
+ const project = parsed.project;
169
+ const story = getStoryFiles(project, paths);
170
+ return { projectFile: project, mainFile: project.main, storyFiles: storyFileList(story), excludedFiles: story.excluded };
171
+ }
172
+ async function buildIndex() {
173
+ const texts = new Map();
174
+ const project = await getProject();
175
+ const mainFile = project.mainFile;
176
+ let script = "";
177
+ try {
178
+ script = await readFile(mainFile);
179
+ }
180
+ catch {
181
+ // A missing main file analyses as an empty story
182
+ }
183
+ texts.set(mainFile, script);
184
+ const analysis = await analyse({
185
+ script,
186
+ scriptBaseFilename: mainFile,
187
+ externalFiles: externalFiles(texts, mainFile, project.storyFiles),
188
+ parseCache,
189
+ recover: true,
190
+ ...(project.projectFile ? { storyFiles: project.storyFiles } : {}),
191
+ expressions: !!project.projectFile,
192
+ });
193
+ if (project.error) {
194
+ // A broken squiffy.json stops the story building, as it does in the CLI
195
+ analysis.success = false;
196
+ analysis.diagnostics.unshift({
197
+ file: PROJECT_FILENAME,
198
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
199
+ severity: "error",
200
+ code: "squiffy/project-file",
201
+ message: project.error,
202
+ });
203
+ }
204
+ const index = {
205
+ analysis,
206
+ project,
207
+ files: new Map(),
208
+ texts,
209
+ sectionNames: analysis.sections.map(s => s.name),
210
+ sections: new Map(),
211
+ nodeNames: new Map(),
212
+ usages: [],
213
+ attributes: new Set(),
214
+ snippets: [],
215
+ };
216
+ for (const file of analysis.files) {
217
+ if (file.filename !== undefined && !index.files.has(file.filename)) {
218
+ index.files.set(file.filename, file);
219
+ }
220
+ }
221
+ for (const section of analysis.sections) {
222
+ index.sections.set(section.name, {
223
+ file: section.file,
224
+ node: section.node,
225
+ passages: new Map(section.passages.map(p => [p.name, p.node])),
226
+ });
227
+ if (section.node)
228
+ index.nodeNames.set(section.node, section.name);
229
+ }
230
+ // An attribute, and for a value inside an object, the object too: hero.hp adds hero
231
+ const addAttribute = (name) => {
232
+ const parts = name.split(".");
233
+ for (let i = 1; i <= parts.length; i++) {
234
+ if (parts[i - 1])
235
+ index.attributes.add(parts.slice(0, i).join("."));
236
+ }
237
+ };
238
+ for (const [path, file] of index.files) {
239
+ for (const node of [file.preamble, ...file.sections]) {
240
+ if (node.type == "snippet") {
241
+ index.snippets.push({ file: path, node });
242
+ continue;
243
+ }
244
+ for (const container of [node, ...node.passages]) {
245
+ for (const link of container.links) {
246
+ index.usages.push({ file: path, container, sectionNode: node, link });
247
+ const comma = link.target.indexOf(",");
248
+ const setters = comma == -1 ? [] : splitWithOffsets(link.target.substring(comma + 1)).map(part => part.text);
249
+ for (const setter of setters) {
250
+ addAttribute(attributeName(setter));
251
+ }
252
+ }
253
+ for (const embed of container.embeds) {
254
+ index.usages.push({ file: path, container, sectionNode: node, embed });
255
+ }
256
+ for (const goto of container.gotos) {
257
+ index.usages.push({ file: path, container, sectionNode: node, goto });
258
+ }
259
+ for (const deactivate of container.deactivates) {
260
+ index.usages.push({ file: path, container, sectionNode: node, deactivate });
261
+ }
262
+ for (const statement of container.body) {
263
+ if (statement.type == "attribute") {
264
+ addAttribute(attributeName(statement.value));
265
+ }
266
+ else if (statement.type == "js") {
267
+ for (const match of statement.code.matchAll(/\bset\(\s*["']([^"']+)["']/g)) {
268
+ index.attributes.add(match[1]);
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+ return index;
276
+ }
277
+ function getIndex() {
278
+ if (!cached || cached.version != version) {
279
+ cached = { version, index: buildIndex() };
280
+ }
281
+ return cached.index;
282
+ }
283
+ // The syntax tree of a file, whether or not it's part of the story
284
+ async function getFile(index, path) {
285
+ const file = index.files.get(path);
286
+ if (file)
287
+ return { file, text: index.texts.get(path) ?? "" };
288
+ try {
289
+ const text = await readFile(path);
290
+ return { file: parseCache.parse(text, path), text };
291
+ }
292
+ catch {
293
+ return undefined;
294
+ }
295
+ }
296
+ function getGraph(index) {
297
+ if (!index.graph) {
298
+ const source = {
299
+ files: index.files,
300
+ sections: index.sections,
301
+ nodeNames: index.nodeNames,
302
+ usages: index.usages,
303
+ start: index.analysis.start,
304
+ resolve: (usage) => resolveUsage(index, usage),
305
+ };
306
+ const graph = buildStoryGraph(source);
307
+ const diagnostics = [...storyGraphDiagnostics(graph), ...firstScreenSoundDiagnostics(source)];
308
+ const ignored = ignoredDiagnostics(index.analysis.files, diagnostics);
309
+ index.graph = { graph, diagnostics: diagnostics.filter(d => !ignored.has(d)) };
310
+ }
311
+ return index.graph;
312
+ }
313
+ // The analysis's diagnostics, and the story graph's
314
+ function allDiagnostics(index) {
315
+ return [...index.analysis.diagnostics, ...getGraph(index).diagnostics];
316
+ }
317
+ // The passages a passage link or embed in this section can reach
318
+ function passagesOf(index, sectionNode) {
319
+ const name = index.nodeNames.get(sectionNode);
320
+ return name === undefined ? undefined : index.sections.get(name)?.passages;
321
+ }
322
+ function resolveUsage(index, usage) {
323
+ const sectionName = index.nodeNames.get(usage.sectionNode);
324
+ if (usage.embed) {
325
+ const name = usage.embed.name;
326
+ const passages = passagesOf(index, usage.sectionNode);
327
+ if (sectionName !== undefined && passages?.has(name))
328
+ return { kind: "passage", section: sectionName, name };
329
+ if (index.sections.has(name))
330
+ return { kind: "section", name };
331
+ // Like the runtime, the master section's passages can be embedded from any section
332
+ if (index.sections.get("")?.passages.has(name))
333
+ return { kind: "passage", section: "", name };
334
+ return undefined;
335
+ }
336
+ if (usage.goto) {
337
+ const name = usage.goto.name;
338
+ return name && index.sections.has(name) ? { kind: "section", name } : undefined;
339
+ }
340
+ if (usage.deactivate) {
341
+ const name = usage.deactivate.name;
342
+ const passages = passagesOf(index, usage.sectionNode);
343
+ return sectionName !== undefined && passages?.has(name) ? { kind: "passage", section: sectionName, name } : undefined;
344
+ }
345
+ const link = usage.link;
346
+ if (link.linkType == "section") {
347
+ if (link.form == "next") {
348
+ if (sectionName === undefined)
349
+ return undefined;
350
+ const next = index.sectionNames[index.sectionNames.indexOf(sectionName) + 1];
351
+ return next === undefined ? undefined : { kind: "section", name: next };
352
+ }
353
+ const name = resolveName(link.target, n => index.sections.has(n));
354
+ return name === undefined ? undefined : { kind: "section", name };
355
+ }
356
+ const passages = passagesOf(index, usage.sectionNode);
357
+ if (sectionName === undefined || !passages)
358
+ return undefined;
359
+ const name = resolveName(link.target, n => passages.has(n));
360
+ if (name !== undefined)
361
+ return { kind: "passage", section: sectionName, name };
362
+ // Like the runtime, a passage link can go to one of the master section's passages
363
+ const masterPassages = index.sections.get("")?.passages;
364
+ const masterName = masterPassages && resolveName(link.target, n => masterPassages.has(n));
365
+ return masterName === undefined ? undefined : { kind: "passage", section: "", name: masterName };
366
+ }
367
+ // Where a symbol is defined: the name in its header.
368
+ function definitionOf(index, symbol) {
369
+ if (symbol.kind == "section") {
370
+ const section = index.sections.get(symbol.name);
371
+ if (!section?.node)
372
+ return undefined;
373
+ const range = section.node.nameRange ?? section.node.header?.range ?? section.node.range;
374
+ return { file: section.file, range };
375
+ }
376
+ const section = index.sections.get(symbol.section);
377
+ const passage = section?.passages.get(symbol.name);
378
+ if (!section || !passage)
379
+ return undefined;
380
+ return { file: section.file, range: passage.nameRange };
381
+ }
382
+ // What's at a position: a link, an embed, a goto, or the name in a section or passage header.
383
+ async function symbolAt(index, path, position) {
384
+ for (const usage of index.usages) {
385
+ if (usage.file != path)
386
+ continue;
387
+ const range = usageRange(usage);
388
+ if (!contains(range, position))
389
+ continue;
390
+ const symbol = resolveUsage(index, usage);
391
+ return symbol ? { symbol, range, usage } : undefined;
392
+ }
393
+ const tree = await getFile(index, path);
394
+ if (!tree)
395
+ return undefined;
396
+ for (const node of tree.file.sections) {
397
+ if (node.type != "section")
398
+ continue;
399
+ if (node.nameRange && contains(node.nameRange, position)) {
400
+ const name = index.nodeNames.get(node);
401
+ return name === undefined ? undefined : { symbol: { kind: "section", name }, range: node.nameRange };
402
+ }
403
+ }
404
+ for (const node of [tree.file.preamble, ...tree.file.sections]) {
405
+ if (node.type != "section")
406
+ continue;
407
+ for (const passage of node.passages) {
408
+ if (contains(passage.nameRange, position)) {
409
+ const section = index.nodeNames.get(node);
410
+ return section === undefined ? undefined : { symbol: { kind: "passage", section, name: passage.name }, range: passage.nameRange };
411
+ }
412
+ }
413
+ }
414
+ return undefined;
415
+ }
416
+ // The range of the name within a link's target, for rename. Undefined if it can't be found
417
+ // exactly, e.g. a target that spans lines.
418
+ function nameRangeInLink(index, usage, name) {
419
+ if (usage.embed)
420
+ return usage.embed.nameRange;
421
+ if (usage.goto)
422
+ return usage.goto.nameRange;
423
+ if (usage.deactivate)
424
+ return usage.deactivate.nameRange;
425
+ const link = usage.link;
426
+ if (link.form == "next")
427
+ return undefined;
428
+ const range = link.targetRange;
429
+ if (range.start.line != range.end.line)
430
+ return undefined;
431
+ const offset = link.target.length - link.target.trimStart().length;
432
+ const start = range.start.character + offset;
433
+ const line = (index.texts.get(usage.file) ?? "").split("\n")[range.start.line] ?? "";
434
+ if (line.substring(start, start + name.length) != name)
435
+ return undefined;
436
+ return lineRange(range.start.line, start, start + name.length);
437
+ }
438
+ function referencesTo(index, symbol, includeDeclaration) {
439
+ const result = [];
440
+ if (includeDeclaration) {
441
+ const definition = definitionOf(index, symbol);
442
+ if (definition)
443
+ result.push(definition);
444
+ }
445
+ for (const usage of index.usages) {
446
+ const target = resolveUsage(index, usage);
447
+ if (target && sameSymbol(target, symbol)) {
448
+ result.push({ file: usage.file, range: usageRange(usage) });
449
+ }
450
+ }
451
+ return result;
452
+ }
453
+ function addEdit(edit, file, textEdit) {
454
+ (edit[file] ?? (edit[file] = [])).push(textEdit);
455
+ }
456
+ // The section and passage containing a position in a file
457
+ function containerAt(file, position) {
458
+ let current = file.preamble;
459
+ for (const node of file.sections) {
460
+ if (node.range.start.line <= position.line)
461
+ current = node;
462
+ }
463
+ if (current.type == "snippet")
464
+ return { snippet: current };
465
+ let passage;
466
+ for (const p of current.passages) {
467
+ if (p.range.start.line <= position.line)
468
+ passage = p;
469
+ }
470
+ return { section: current, passage };
471
+ }
472
+ // The master section, [[]]:, if the story has one
473
+ function masterSection(index) {
474
+ for (const [file, tree] of index.files) {
475
+ for (const node of tree.sections) {
476
+ if (node.type == "section" && node.header?.type == "section-header" && node.header.name == "")
477
+ return { file, node };
478
+ }
479
+ }
480
+ return undefined;
481
+ }
482
+ // Adds a squiffy-ignore comment to a section: before its text, as a line of text before
483
+ // @set and JavaScript would stop them being read as such, or after them if it has no text
484
+ function ignoreCommentEdit(section, lines, comment) {
485
+ const text = section.body.find(n => n.type == "text");
486
+ if (text)
487
+ return { range: lineRange(text.range.start.line, 0, 0), newText: `${comment}\n` };
488
+ const last = section.body[section.body.length - 1] ?? section.header;
489
+ const line = last.range.end.line;
490
+ return { range: lineRange(line, lines[line].length, lines[line].length), newText: `\n${comment}` };
491
+ }
492
+ function firstLines(node, count) {
493
+ return node.body.filter(n => n.type == "text").map(n => n.text).join("\n").trim().split("\n").slice(0, count).join("\n");
494
+ }
495
+ return {
496
+ updateFile(path, text) {
497
+ if (text === undefined)
498
+ openFiles.delete(path);
499
+ else
500
+ openFiles.set(path, text);
501
+ changed();
502
+ },
503
+ fileChanged(path) {
504
+ diskTexts.delete(path);
505
+ changed();
506
+ },
507
+ setMainFile(path) {
508
+ mainFile = path;
509
+ changed();
510
+ },
511
+ async getProjectInfo() {
512
+ return (await getIndex()).project;
513
+ },
514
+ async getAnalysis() {
515
+ return (await getIndex()).analysis;
516
+ },
517
+ async getDiagnostics(path) {
518
+ const index = await getIndex();
519
+ return allDiagnostics(index).filter(d => d.file == path);
520
+ },
521
+ async getAllDiagnostics() {
522
+ return allDiagnostics(await getIndex());
523
+ },
524
+ async getDocumentSymbols(path) {
525
+ const index = await getIndex();
526
+ const tree = await getFile(index, path);
527
+ if (!tree)
528
+ return [];
529
+ const { file } = tree;
530
+ const symbols = [];
531
+ const passageSymbols = (node) => node.passages.map((p) => ({
532
+ name: p.name, kind: "passage", range: p.range, selectionRange: p.nameRange, children: [],
533
+ }));
534
+ for (const node of [file.preamble, ...file.sections]) {
535
+ if (node.type == "snippet") {
536
+ symbols.push({ name: node.name, kind: "snippet", range: node.range, selectionRange: node.nameRange, children: [] });
537
+ continue;
538
+ }
539
+ for (const statement of node.body) {
540
+ if (statement.type == "title") {
541
+ symbols.push({ name: statement.value, kind: "title", range: statement.range, selectionRange: statement.valueRange, children: [] });
542
+ }
543
+ }
544
+ for (const passage of node.passages) {
545
+ for (const statement of passage.body) {
546
+ if (statement.type == "title") {
547
+ symbols.push({ name: statement.value, kind: "title", range: statement.range, selectionRange: statement.valueRange, children: [] });
548
+ }
549
+ }
550
+ }
551
+ const storyName = index.nodeNames.get(node);
552
+ if (node.kind == "preamble") {
553
+ // Only a section if the story made it one (the main file's _default section)
554
+ if (storyName === undefined)
555
+ continue;
556
+ symbols.push({ name: storyName, kind: "section", detail: "(Start)", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
557
+ continue;
558
+ }
559
+ const header = node.header;
560
+ const detail = header.type == "continue" ? `+++${header.text}` : header.type == "separator" ? "---" : undefined;
561
+ symbols.push({
562
+ name: node.name ?? storyName ?? detail ?? "",
563
+ kind: "section",
564
+ ...(node.kind != "named" && detail ? { detail } : {}),
565
+ range: node.range,
566
+ selectionRange: node.nameRange ?? header.range,
567
+ children: passageSymbols(node),
568
+ });
569
+ }
570
+ return symbols;
571
+ },
572
+ async getDefinition(path, position) {
573
+ const index = await getIndex();
574
+ const found = await symbolAt(index, path, position);
575
+ return found && definitionOf(index, found.symbol);
576
+ },
577
+ async getReferences(path, position, includeDeclaration = true) {
578
+ const index = await getIndex();
579
+ const found = await symbolAt(index, path, position);
580
+ return found ? referencesTo(index, found.symbol, includeDeclaration) : [];
581
+ },
582
+ async getRenameEdits(path, position, newName) {
583
+ const index = await getIndex();
584
+ const found = await symbolAt(index, path, position);
585
+ if (!found)
586
+ return undefined;
587
+ const { symbol } = found;
588
+ if (newName != newName.trim() || !newName)
589
+ return { error: "A name can't be empty or start or end with a space." };
590
+ if (/[[\]\n,"]/.test(newName))
591
+ return { error: "A name can't contain [, ], a comma or a double quote." };
592
+ if (symbol.kind == "passage" && (symbol.name.startsWith("@") || newName.startsWith("@"))) {
593
+ return { error: "Passages whose names start with @ are special, and can't be renamed." };
594
+ }
595
+ const definition = definitionOf(index, symbol);
596
+ const definitionNode = symbol.kind == "section" ? index.sections.get(symbol.name)?.node : undefined;
597
+ if (!definition || (symbol.kind == "section" && !definitionNode?.nameRange)) {
598
+ return { error: `'${symbol.name}' doesn't have a name of its own to rename.` };
599
+ }
600
+ const exists = symbol.kind == "section"
601
+ ? index.sections.has(newName)
602
+ : index.sections.get(symbol.section)?.passages.has(newName);
603
+ if (exists && newName != symbol.name) {
604
+ return { error: `There's already a ${symbol.kind} called '${newName}'.` };
605
+ }
606
+ const edit = {};
607
+ addEdit(edit, definition.file, { range: definition.range, newText: newName });
608
+ for (const usage of index.usages) {
609
+ const target = resolveUsage(index, usage);
610
+ if (!target || !sameSymbol(target, symbol))
611
+ continue;
612
+ const range = nameRangeInLink(index, usage, symbol.name);
613
+ if (range)
614
+ addEdit(edit, usage.file, { range, newText: newName });
615
+ }
616
+ return { edit };
617
+ },
618
+ async getCompletions(path, position) {
619
+ const index = await getIndex();
620
+ const tree = await getFile(index, path);
621
+ if (!tree)
622
+ return [];
623
+ // A section, passage or snippet header names something new, so nothing on its line
624
+ // is completed: "[my pass" there looks like the start of a passage link, but isn't one
625
+ const headers = [tree.file.preamble, ...tree.file.sections].flatMap((node) => node.type == "snippet" ? [node.header] : [node.header, ...node.passages.map(p => p.header)]);
626
+ if (headers.some(header => header?.range.start.line == position.line))
627
+ return [];
628
+ const prefix = (tree.text.replace(/\r/g, "").split("\n")[position.line] ?? "").substring(0, position.character);
629
+ const { section } = containerAt(tree.file, position);
630
+ const sectionName = section && index.nodeNames.get(section);
631
+ const replace = (typed) => lineRange(position.line, position.character - typed.length, position.character);
632
+ const sectionItems = (typed) => index.sectionNames
633
+ .filter(name => !name.startsWith("_continue"))
634
+ .map(name => ({ label: name, kind: "section", range: replace(typed) }));
635
+ const passageItems = (typed) => {
636
+ const passages = sectionName === undefined ? undefined : index.sections.get(sectionName)?.passages;
637
+ return [...(passages?.keys() ?? [])]
638
+ .filter(name => !name.startsWith("@"))
639
+ .map(name => ({ label: name, kind: "passage", range: replace(typed) }));
640
+ };
641
+ let match;
642
+ if ((match = /\{\{~?\s*#?embed\s+["']([^"']*)$/.exec(prefix))) {
643
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
644
+ }
645
+ // {{seen "name"}}, (visits "name") etc., which take a section or passage (#377)
646
+ if ((match = /(?:\{\{~?|\()\s*(?:seen|visits)\s+["']([^"']*)$/.exec(prefix))) {
647
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
648
+ }
649
+ // (passages "section") and (tags "name") (#527)
650
+ if ((match = /(?:\{\{~?|\()\s*passages\s+["']([^"']*)$/.exec(prefix))) {
651
+ return sectionItems(match[1]);
652
+ }
653
+ if ((match = /(?:\{\{~?|\()\s*tags\s+["']([^"']*)$/.exec(prefix))) {
654
+ return [...passageItems(match[1]), ...sectionItems(match[1])];
655
+ }
656
+ if ((match = /\{\{~?\s*goto\s+["']([^"']*)$/.exec(prefix))) {
657
+ return sectionItems(match[1]);
658
+ }
659
+ if ((match = /\{\{~?\s*deactivate\s+["']([^"']*)$/.exec(prefix))) {
660
+ return passageItems(match[1]);
661
+ }
662
+ // A text box that goes somewhere when Enter is pressed (#454)
663
+ if ((match = /<input\b[^>]*\sdata-(section|passage)\s*=\s*["']([^"']*)$/i.exec(prefix))) {
664
+ return match[1].toLowerCase() == "section" ? sectionItems(match[2]) : passageItems(match[2]);
665
+ }
666
+ if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
667
+ return sectionItems(match[1]);
668
+ }
669
+ if ((match = /(?<![![])\[[^\]]*\]\(([^),]*)$/.exec(prefix))) {
670
+ return passageItems(match[1]);
671
+ }
672
+ if ((match = /\[\[([^\]>]*)$/.exec(prefix))) {
673
+ return sectionItems(match[1]);
674
+ }
675
+ if ((match = /(?<![![])\[([^[\]]*)$/.exec(prefix))) {
676
+ return passageItems(match[1]);
677
+ }
678
+ if ((match = /^\s*(@\w*)$/.exec(prefix))) {
679
+ return DIRECTIVES.map(([name, detail]) => ({
680
+ label: `@${name}`, kind: "directive", detail, range: replace(match[1]),
681
+ }));
682
+ }
683
+ if ((match = /^\s*@(?:set|unset|inc|dec)\s+(?:not\s+)?([^\s=]*)$/.exec(prefix))) {
684
+ return [...index.attributes].sort().map(name => ({ label: name, kind: "attribute", range: replace(match[1]) }));
685
+ }
686
+ if ((match = /^(\w*)$/.exec(prefix))) {
687
+ return index.snippets.map(({ node }) => ({
688
+ label: node.name,
689
+ kind: "snippet",
690
+ insertText: node.content.replace(/\s+$/, ""),
691
+ range: replace(match[1]),
692
+ }));
693
+ }
694
+ return [];
695
+ },
696
+ async getHover(path, position) {
697
+ const index = await getIndex();
698
+ const found = await symbolAt(index, path, position);
699
+ if (!found?.usage)
700
+ return undefined;
701
+ const { symbol } = found;
702
+ let node;
703
+ let heading;
704
+ if (symbol.kind == "section") {
705
+ node = index.sections.get(symbol.name)?.node;
706
+ heading = `[[${symbol.name}]]`;
707
+ }
708
+ else {
709
+ node = index.sections.get(symbol.section)?.passages.get(symbol.name);
710
+ heading = `[${symbol.name}] in [[${symbol.section}]]`;
711
+ }
712
+ if (!node)
713
+ return undefined;
714
+ const preview = firstLines(node, 5);
715
+ return { contents: preview ? `**${heading}**\n\n${preview}` : `**${heading}**`, range: found.range };
716
+ },
717
+ async getFoldingRanges(path) {
718
+ const index = await getIndex();
719
+ const tree = await getFile(index, path);
720
+ if (!tree)
721
+ return [];
722
+ const lines = tree.text.replace(/\r/g, "").split("\n");
723
+ const ranges = [];
724
+ const add = (range) => {
725
+ let end = range.end.line;
726
+ while (end > range.start.line && !lines[end]?.trim())
727
+ end--;
728
+ if (end > range.start.line)
729
+ ranges.push({ startLine: range.start.line, endLine: end });
730
+ };
731
+ for (const node of tree.file.sections) {
732
+ add(node.range);
733
+ if (node.type == "section")
734
+ node.passages.forEach(p => add(p.range));
735
+ }
736
+ tree.file.preamble.passages.forEach(p => add(p.range));
737
+ return ranges;
738
+ },
739
+ async getCodeActions(path, range) {
740
+ const index = await getIndex();
741
+ const tree = await getFile(index, path);
742
+ if (!tree)
743
+ return [];
744
+ const actions = [];
745
+ const diagnostics = allDiagnostics(index).filter(d => d.file == path && overlaps(d.range, range));
746
+ const v5 = findV5Syntax(tree.text);
747
+ const lines = tree.text.replace(/\r/g, "").split("\n");
748
+ for (const diagnostic of diagnostics) {
749
+ if (diagnostic.code == "squiffy/unknown-section-link" || diagnostic.code == "squiffy/unknown-passage-link") {
750
+ const usage = index.usages.find(u => u.file == path && u.link
751
+ && comparePositions(u.link.range.start, diagnostic.range.start) == 0);
752
+ if (!usage?.link)
753
+ continue;
754
+ const name = intendedName(usage.link.target);
755
+ if (!name)
756
+ continue;
757
+ const edit = {};
758
+ if (diagnostic.code == "squiffy/unknown-section-link") {
759
+ const end = endOfText(tree.text.replace(/\r/g, ""));
760
+ const before = lines[lines.length - 1] == "" ? "\n" : "\n\n";
761
+ addEdit(edit, path, { range: { start: end, end }, newText: `${before}[[${name}]]:\n` });
762
+ actions.push({ title: `Create section '${name}'`, kind: "quickfix", diagnostic, edit });
763
+ }
764
+ else {
765
+ // At the end of the section the link is in
766
+ const end = usage.sectionNode.range.end;
767
+ const blank = !lines[end.line]?.trim();
768
+ addEdit(edit, path, { range: { start: end, end }, newText: `${blank ? "" : "\n\n"}[${name}]:\n` });
769
+ actions.push({ title: `Create passage '${name}'`, kind: "quickfix", diagnostic, edit });
770
+ }
771
+ }
772
+ else if (diagnostic.code == "squiffy/at-attribute") {
773
+ const start = diagnostic.range.start;
774
+ const name = lines[start.line].substring(start.character + 1, diagnostic.range.end.character);
775
+ const edit = {};
776
+ addEdit(edit, path, { range: { start, end: { line: start.line, character: start.character + 1 } }, newText: "" });
777
+ actions.push({ title: `Change to ${name}`, kind: "quickfix", diagnostic, edit });
778
+ }
779
+ else if (diagnostic.code == "squiffy/unquoted-text") {
780
+ const start = diagnostic.range.start;
781
+ const found = findUnquotedText(tree.file, () => false)
782
+ .find(u => comparePositions(u.range.start, start) == 0);
783
+ if (!found?.quoted)
784
+ continue;
785
+ const edit = {};
786
+ addEdit(edit, path, { range: found.range, newText: found.quoted });
787
+ actions.push({ title: `Change to ${found.quoted}`, kind: "quickfix", diagnostic, edit });
788
+ }
789
+ else if (diagnostic.code == "squiffy/v5-syntax") {
790
+ const line = diagnostic.range.start.line;
791
+ const match = v5.find(m => m.line == line + 1
792
+ && lines[line].substring(diagnostic.range.start.character).startsWith(m.text));
793
+ if (!match?.suggestion || match.text.includes("\n"))
794
+ continue;
795
+ const start = diagnostic.range.start;
796
+ const edit = {};
797
+ addEdit(edit, path, {
798
+ range: { start, end: { line, character: start.character + match.text.length } },
799
+ newText: match.suggestion,
800
+ });
801
+ actions.push({ title: `Convert to ${match.suggestion}`, kind: "quickfix", diagnostic, edit });
802
+ }
803
+ }
804
+ for (const diagnostic of diagnostics) {
805
+ if (diagnostic.code != "squiffy/dead-end")
806
+ continue;
807
+ const { section } = containerAt(tree.file, diagnostic.range.start);
808
+ if (!section)
809
+ continue;
810
+ // A line after the header, or at the top of the file for the text before the first section
811
+ const line = section.header ? section.header.range.start.line + 1 : 0;
812
+ const edit = {};
813
+ addEdit(edit, path, line < lines.length
814
+ ? { range: lineRange(line, 0, 0), newText: "@end\n" }
815
+ : { range: lineRange(line - 1, lines[line - 1].length, lines[line - 1].length), newText: "\n@end" });
816
+ actions.push({ title: "Mark this section as an ending", kind: "quickfix", diagnostic, edit });
817
+ }
818
+ for (const diagnostic of diagnostics) {
819
+ if (diagnostic.code != "squiffy/redundant-import")
820
+ continue;
821
+ // Remove the whole line, including its line break
822
+ const line = diagnostic.range.start.line;
823
+ const end = line + 1 < lines.length ? { line: line + 1, character: 0 } : { line, character: lines[line].length };
824
+ const start = line + 1 < lines.length || line == 0 ? { line, character: 0 } : { line: line - 1, character: lines[line - 1].length };
825
+ const edit = {};
826
+ addEdit(edit, path, { range: { start, end }, newText: "" });
827
+ actions.push({ title: "Remove this @import", kind: "quickfix", diagnostic, edit });
828
+ }
829
+ // A warning that may be what the author meant can be turned off with a squiffy-ignore
830
+ // comment, in the section it's in, and an unknown name in the master section too,
831
+ // which turns it off everywhere. (Any warning can, but for the others there's a fix.)
832
+ for (const diagnostic of diagnostics) {
833
+ if (!IGNORE_ACTION_CODES.has(diagnostic.code))
834
+ continue;
835
+ const { section } = containerAt(tree.file, diagnostic.range.start);
836
+ const code = diagnostic.code.replace(/^squiffy\//, "");
837
+ const comment = `{{!-- squiffy-ignore ${code}${diagnostic.subject ? ` ${diagnostic.subject}` : ""} --}}`;
838
+ const what = diagnostic.code == "squiffy/unknown-name" ? `{{${diagnostic.subject}}}` : "this warning";
839
+ if (section?.header && !(section.header.type == "section-header" && section.header.name == "")) {
840
+ const edit = {};
841
+ addEdit(edit, path, ignoreCommentEdit(section, lines, comment));
842
+ actions.push({ title: `Ignore ${what} in this section`, kind: "quickfix", diagnostic, edit });
843
+ }
844
+ if (diagnostic.code == "squiffy/unknown-name") {
845
+ const master = masterSection(index);
846
+ const masterText = master && index.texts.get(master.file);
847
+ if (!master || masterText === undefined)
848
+ continue;
849
+ const edit = {};
850
+ addEdit(edit, master.file, ignoreCommentEdit(master.node, masterText.replace(/\r/g, "").split("\n"), comment));
851
+ actions.push({ title: `Ignore ${what} everywhere`, kind: "quickfix", diagnostic, edit });
852
+ }
853
+ }
854
+ if (diagnostics.some(d => d.code == "squiffy/v5-syntax")) {
855
+ const converted = convertV5Syntax(tree.text);
856
+ if (converted.converted > 0) {
857
+ const edit = {};
858
+ addEdit(edit, path, { range: { start: { line: 0, character: 0 }, end: endOfText(tree.text) }, newText: converted.script });
859
+ actions.push({ title: "Convert all Squiffy 5 syntax in this file", kind: "quickfix", edit });
860
+ }
861
+ }
862
+ return actions;
863
+ },
864
+ async getStoryGraph() {
865
+ return getGraph(await getIndex()).graph;
866
+ },
867
+ async getSectionAt(path, position) {
868
+ const index = await getIndex();
869
+ const tree = await getFile(index, path);
870
+ if (!tree)
871
+ return undefined;
872
+ const { section, passage } = containerAt(tree.file, position);
873
+ if (!section)
874
+ return undefined;
875
+ const name = index.nodeNames.get(section);
876
+ if (name === undefined)
877
+ return undefined;
878
+ return passage && index.sections.get(name)?.passages.get(passage.name) === passage
879
+ ? { section: name, passage: passage.name }
880
+ : { section: name };
881
+ },
882
+ };
883
+ }