squiffy-compiler 6.0.1 → 7.0.0-beta.2
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.
- package/dist/analyse.d.ts +79 -0
- package/dist/analyse.js +590 -0
- package/dist/compiler.d.ts +15 -40
- package/dist/compiler.js +19 -691
- package/dist/emit.d.ts +43 -0
- package/dist/emit.js +114 -0
- package/dist/language-service.d.ts +89 -0
- package/dist/language-service.js +748 -0
- package/dist/node.d.ts +13 -0
- package/dist/node.js +105 -0
- package/dist/parse.d.ts +17 -0
- package/dist/parse.js +263 -0
- package/dist/project.d.ts +40 -0
- package/dist/project.js +222 -0
- package/dist/story-graph.d.ts +64 -0
- package/dist/story-graph.js +359 -0
- package/dist/syntax.d.ts +150 -0
- package/dist/syntax.js +8 -0
- package/dist/text.d.ts +37 -0
- package/dist/text.js +288 -0
- package/package.json +24 -6
- package/syntaxes/squiffy.tmLanguage.json +972 -0
|
@@ -0,0 +1,748 @@
|
|
|
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 } from "./project.js";
|
|
10
|
+
import { convertV5Syntax, findV5Syntax } from "./v5.js";
|
|
11
|
+
import { buildStoryGraph, storyGraphDiagnostics } from "./story-graph.js";
|
|
12
|
+
const sameSymbol = (a, b) => a.kind == b.kind && a.name == b.name && (a.kind == "section" || a.section == b.section);
|
|
13
|
+
// Directives, for completion, with what they do
|
|
14
|
+
const DIRECTIVES = [
|
|
15
|
+
["title", "Sets the story's title"],
|
|
16
|
+
["start", "Sets the section the story starts at"],
|
|
17
|
+
["import", "Adds another file to the story"],
|
|
18
|
+
["set", "Sets an attribute"],
|
|
19
|
+
["unset", "Sets an attribute to false"],
|
|
20
|
+
["inc", "Adds to an attribute"],
|
|
21
|
+
["dec", "Subtracts from an attribute"],
|
|
22
|
+
["clear", "Clears the screen"],
|
|
23
|
+
["end", "Marks this section as an ending"],
|
|
24
|
+
["ui", "JavaScript for the story's user interface"],
|
|
25
|
+
];
|
|
26
|
+
const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
|
|
27
|
+
function comparePositions(a, b) {
|
|
28
|
+
return a.line - b.line || a.character - b.character;
|
|
29
|
+
}
|
|
30
|
+
const overlaps = (a, b) => comparePositions(a.start, b.end) <= 0 && comparePositions(b.start, a.end) <= 0;
|
|
31
|
+
// Same as the compiler: the whole target if it's a name, otherwise the part before the first comma.
|
|
32
|
+
function resolveName(target, has) {
|
|
33
|
+
const trimmed = target.trim();
|
|
34
|
+
if (has(trimmed))
|
|
35
|
+
return trimmed;
|
|
36
|
+
const destination = trimmed.split(",")[0].trim();
|
|
37
|
+
return has(destination) ? destination : undefined;
|
|
38
|
+
}
|
|
39
|
+
// The name a broken link was trying to reach
|
|
40
|
+
const intendedName = (target) => target.trim().split(",")[0].trim();
|
|
41
|
+
function attributeName(expression) {
|
|
42
|
+
return expression.replace(/^\s*not\s+/, "").split(/[-+]?=/)[0].trim();
|
|
43
|
+
}
|
|
44
|
+
function resolvePath(baseDir, relative) {
|
|
45
|
+
const parts = baseDir ? baseDir.split("/") : [];
|
|
46
|
+
for (const part of relative.split("/")) {
|
|
47
|
+
if (part == "" || part == ".")
|
|
48
|
+
continue;
|
|
49
|
+
if (part == "..") {
|
|
50
|
+
if (!parts.length)
|
|
51
|
+
return null;
|
|
52
|
+
parts.pop();
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
parts.push(part);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return parts.join("/");
|
|
59
|
+
}
|
|
60
|
+
const dirname = (path) => path.includes("/") ? path.substring(0, path.lastIndexOf("/")) : "";
|
|
61
|
+
function relativePath(fromDir, path) {
|
|
62
|
+
const from = fromDir ? fromDir.split("/") : [];
|
|
63
|
+
const to = path.split("/");
|
|
64
|
+
let common = 0;
|
|
65
|
+
while (common < from.length && common < to.length - 1 && from[common] == to[common])
|
|
66
|
+
common++;
|
|
67
|
+
return [...from.slice(common).map(() => ".."), ...to.slice(common)].join("/");
|
|
68
|
+
}
|
|
69
|
+
const endOfText = (text) => {
|
|
70
|
+
const lines = text.split("\n");
|
|
71
|
+
return { line: lines.length - 1, character: lines[lines.length - 1].length };
|
|
72
|
+
};
|
|
73
|
+
const lineRange = (line, start, end) => ({
|
|
74
|
+
start: { line, character: start },
|
|
75
|
+
end: { line, character: end },
|
|
76
|
+
});
|
|
77
|
+
export function createLanguageService(options) {
|
|
78
|
+
const files = options.files;
|
|
79
|
+
let mainFile = options.mainFile;
|
|
80
|
+
const openFiles = new Map();
|
|
81
|
+
const diskTexts = new Map();
|
|
82
|
+
const parseCache = new ParseCache();
|
|
83
|
+
let version = 0;
|
|
84
|
+
let cached;
|
|
85
|
+
const changed = () => { version++; };
|
|
86
|
+
async function readFile(path) {
|
|
87
|
+
const open = openFiles.get(path);
|
|
88
|
+
if (open !== undefined)
|
|
89
|
+
return open;
|
|
90
|
+
let text = diskTexts.get(path);
|
|
91
|
+
if (!text) {
|
|
92
|
+
text = files.readText(path);
|
|
93
|
+
diskTexts.set(path, text);
|
|
94
|
+
// Don't cache a failed read
|
|
95
|
+
text.catch(() => diskTexts.delete(path));
|
|
96
|
+
}
|
|
97
|
+
return text;
|
|
98
|
+
}
|
|
99
|
+
// The compiler's ExternalFiles, resolving @import patterns and @ui paths against the main
|
|
100
|
+
// file's folder and never importing a file twice, as the CLI does.
|
|
101
|
+
function externalFiles(texts, mainFile, storyFiles) {
|
|
102
|
+
const baseDir = dirname(mainFile);
|
|
103
|
+
const included = new Set([mainFile]);
|
|
104
|
+
const matched = new Set(storyFiles);
|
|
105
|
+
return {
|
|
106
|
+
async getMatchingFilenames(pattern) {
|
|
107
|
+
const resolved = resolvePath(baseDir, pattern);
|
|
108
|
+
if (resolved === null)
|
|
109
|
+
return [];
|
|
110
|
+
const regex = globToRegExp(resolved);
|
|
111
|
+
const paths = await listPaths();
|
|
112
|
+
const result = [...paths].filter(p => regex.test(p) && !included.has(p)).sort();
|
|
113
|
+
for (const p of result)
|
|
114
|
+
matched.add(p);
|
|
115
|
+
return result;
|
|
116
|
+
},
|
|
117
|
+
async getContent(filename) {
|
|
118
|
+
const path = matched.has(filename) ? filename : resolvePath(baseDir, filename);
|
|
119
|
+
if (path === null)
|
|
120
|
+
return "";
|
|
121
|
+
included.add(path);
|
|
122
|
+
try {
|
|
123
|
+
const text = await readFile(path);
|
|
124
|
+
texts.set(path, text);
|
|
125
|
+
return text;
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return "";
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
getLocalFilename: (filename) => relativePath(baseDir, filename),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
async function listPaths() {
|
|
135
|
+
const paths = new Set((await files.list()).map(f => f.path));
|
|
136
|
+
for (const open of openFiles.keys())
|
|
137
|
+
paths.add(open);
|
|
138
|
+
return paths;
|
|
139
|
+
}
|
|
140
|
+
async function getProject() {
|
|
141
|
+
const fallback = { mainFile, storyFiles: [], excludedFiles: [] };
|
|
142
|
+
const paths = await listPaths();
|
|
143
|
+
if (!paths.has(PROJECT_FILENAME))
|
|
144
|
+
return fallback;
|
|
145
|
+
let text;
|
|
146
|
+
try {
|
|
147
|
+
text = await readFile(PROJECT_FILENAME);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return fallback;
|
|
151
|
+
}
|
|
152
|
+
const parsed = parseProjectFile(text);
|
|
153
|
+
if (!parsed.success)
|
|
154
|
+
return { ...fallback, error: parsed.error };
|
|
155
|
+
const project = parsed.project;
|
|
156
|
+
const story = getStoryFiles(project, paths);
|
|
157
|
+
return { projectFile: project, mainFile: project.main, storyFiles: story.included, excludedFiles: story.excluded };
|
|
158
|
+
}
|
|
159
|
+
async function buildIndex() {
|
|
160
|
+
const texts = new Map();
|
|
161
|
+
const project = await getProject();
|
|
162
|
+
const mainFile = project.mainFile;
|
|
163
|
+
let script = "";
|
|
164
|
+
try {
|
|
165
|
+
script = await readFile(mainFile);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
// A missing main file analyses as an empty story
|
|
169
|
+
}
|
|
170
|
+
texts.set(mainFile, script);
|
|
171
|
+
const analysis = await analyse({
|
|
172
|
+
script,
|
|
173
|
+
scriptBaseFilename: mainFile,
|
|
174
|
+
externalFiles: externalFiles(texts, mainFile, project.storyFiles),
|
|
175
|
+
parseCache,
|
|
176
|
+
recover: true,
|
|
177
|
+
...(project.projectFile ? { storyFiles: project.storyFiles } : {}),
|
|
178
|
+
});
|
|
179
|
+
if (project.error) {
|
|
180
|
+
// A broken squiffy.json stops the story building, as it does in the CLI
|
|
181
|
+
analysis.success = false;
|
|
182
|
+
analysis.diagnostics.unshift({
|
|
183
|
+
file: PROJECT_FILENAME,
|
|
184
|
+
range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
|
|
185
|
+
severity: "error",
|
|
186
|
+
code: "squiffy/project-file",
|
|
187
|
+
message: project.error,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
const index = {
|
|
191
|
+
analysis,
|
|
192
|
+
project,
|
|
193
|
+
files: new Map(),
|
|
194
|
+
texts,
|
|
195
|
+
sectionNames: analysis.sections.map(s => s.name),
|
|
196
|
+
sections: new Map(),
|
|
197
|
+
nodeNames: new Map(),
|
|
198
|
+
usages: [],
|
|
199
|
+
attributes: new Set(),
|
|
200
|
+
snippets: [],
|
|
201
|
+
};
|
|
202
|
+
for (const file of analysis.files) {
|
|
203
|
+
if (file.filename !== undefined && !index.files.has(file.filename)) {
|
|
204
|
+
index.files.set(file.filename, file);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
for (const section of analysis.sections) {
|
|
208
|
+
index.sections.set(section.name, {
|
|
209
|
+
file: section.file,
|
|
210
|
+
node: section.node,
|
|
211
|
+
passages: new Map(section.passages.map(p => [p.name, p.node])),
|
|
212
|
+
});
|
|
213
|
+
if (section.node)
|
|
214
|
+
index.nodeNames.set(section.node, section.name);
|
|
215
|
+
}
|
|
216
|
+
for (const [path, file] of index.files) {
|
|
217
|
+
for (const node of [file.preamble, ...file.sections]) {
|
|
218
|
+
if (node.type == "snippet") {
|
|
219
|
+
index.snippets.push({ file: path, node });
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
for (const container of [node, ...node.passages]) {
|
|
223
|
+
for (const link of container.links) {
|
|
224
|
+
index.usages.push({ file: path, container, sectionNode: node, link });
|
|
225
|
+
const setters = link.target.split(",").slice(1);
|
|
226
|
+
for (const setter of setters) {
|
|
227
|
+
const name = attributeName(setter);
|
|
228
|
+
if (name)
|
|
229
|
+
index.attributes.add(name);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
for (const embed of container.embeds) {
|
|
233
|
+
index.usages.push({ file: path, container, sectionNode: node, embed });
|
|
234
|
+
}
|
|
235
|
+
for (const statement of container.body) {
|
|
236
|
+
if (statement.type == "attribute") {
|
|
237
|
+
const name = attributeName(statement.value);
|
|
238
|
+
if (name)
|
|
239
|
+
index.attributes.add(name);
|
|
240
|
+
}
|
|
241
|
+
else if (statement.type == "js") {
|
|
242
|
+
for (const match of statement.code.matchAll(/\bset\(\s*["']([^"']+)["']/g)) {
|
|
243
|
+
index.attributes.add(match[1]);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return index;
|
|
251
|
+
}
|
|
252
|
+
function getIndex() {
|
|
253
|
+
if (!cached || cached.version != version) {
|
|
254
|
+
cached = { version, index: buildIndex() };
|
|
255
|
+
}
|
|
256
|
+
return cached.index;
|
|
257
|
+
}
|
|
258
|
+
// The syntax tree of a file, whether or not it's part of the story
|
|
259
|
+
async function getFile(index, path) {
|
|
260
|
+
const file = index.files.get(path);
|
|
261
|
+
if (file)
|
|
262
|
+
return { file, text: index.texts.get(path) ?? "" };
|
|
263
|
+
try {
|
|
264
|
+
const text = await readFile(path);
|
|
265
|
+
return { file: parseCache.parse(text, path), text };
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function getGraph(index) {
|
|
272
|
+
if (!index.graph) {
|
|
273
|
+
const graph = buildStoryGraph({
|
|
274
|
+
files: index.files,
|
|
275
|
+
sections: index.sections,
|
|
276
|
+
nodeNames: index.nodeNames,
|
|
277
|
+
usages: index.usages,
|
|
278
|
+
start: index.analysis.start,
|
|
279
|
+
resolve: usage => resolveUsage(index, usage),
|
|
280
|
+
});
|
|
281
|
+
index.graph = { graph, diagnostics: storyGraphDiagnostics(graph) };
|
|
282
|
+
}
|
|
283
|
+
return index.graph;
|
|
284
|
+
}
|
|
285
|
+
// The analysis's diagnostics, and the story graph's
|
|
286
|
+
function allDiagnostics(index) {
|
|
287
|
+
return [...index.analysis.diagnostics, ...getGraph(index).diagnostics];
|
|
288
|
+
}
|
|
289
|
+
// The passages a passage link or embed in this section can reach
|
|
290
|
+
function passagesOf(index, sectionNode) {
|
|
291
|
+
const name = index.nodeNames.get(sectionNode);
|
|
292
|
+
return name === undefined ? undefined : index.sections.get(name)?.passages;
|
|
293
|
+
}
|
|
294
|
+
function resolveUsage(index, usage) {
|
|
295
|
+
const sectionName = index.nodeNames.get(usage.sectionNode);
|
|
296
|
+
if (usage.embed) {
|
|
297
|
+
const name = usage.embed.name;
|
|
298
|
+
const passages = passagesOf(index, usage.sectionNode);
|
|
299
|
+
if (sectionName !== undefined && passages?.has(name))
|
|
300
|
+
return { kind: "passage", section: sectionName, name };
|
|
301
|
+
if (index.sections.has(name))
|
|
302
|
+
return { kind: "section", name };
|
|
303
|
+
return undefined;
|
|
304
|
+
}
|
|
305
|
+
const link = usage.link;
|
|
306
|
+
if (link.linkType == "section") {
|
|
307
|
+
if (link.form == "next") {
|
|
308
|
+
if (sectionName === undefined)
|
|
309
|
+
return undefined;
|
|
310
|
+
const next = index.sectionNames[index.sectionNames.indexOf(sectionName) + 1];
|
|
311
|
+
return next === undefined ? undefined : { kind: "section", name: next };
|
|
312
|
+
}
|
|
313
|
+
const name = resolveName(link.target, n => index.sections.has(n));
|
|
314
|
+
return name === undefined ? undefined : { kind: "section", name };
|
|
315
|
+
}
|
|
316
|
+
const passages = passagesOf(index, usage.sectionNode);
|
|
317
|
+
if (sectionName === undefined || !passages)
|
|
318
|
+
return undefined;
|
|
319
|
+
const name = resolveName(link.target, n => passages.has(n));
|
|
320
|
+
return name === undefined ? undefined : { kind: "passage", section: sectionName, name };
|
|
321
|
+
}
|
|
322
|
+
// Where a symbol is defined: the name in its header.
|
|
323
|
+
function definitionOf(index, symbol) {
|
|
324
|
+
if (symbol.kind == "section") {
|
|
325
|
+
const section = index.sections.get(symbol.name);
|
|
326
|
+
if (!section?.node)
|
|
327
|
+
return undefined;
|
|
328
|
+
const range = section.node.nameRange ?? section.node.header?.range ?? section.node.range;
|
|
329
|
+
return { file: section.file, range };
|
|
330
|
+
}
|
|
331
|
+
const section = index.sections.get(symbol.section);
|
|
332
|
+
const passage = section?.passages.get(symbol.name);
|
|
333
|
+
if (!section || !passage)
|
|
334
|
+
return undefined;
|
|
335
|
+
return { file: section.file, range: passage.nameRange };
|
|
336
|
+
}
|
|
337
|
+
// What's at a position: a link, an embed, or the name in a section or passage header.
|
|
338
|
+
async function symbolAt(index, path, position) {
|
|
339
|
+
for (const usage of index.usages) {
|
|
340
|
+
if (usage.file != path)
|
|
341
|
+
continue;
|
|
342
|
+
const range = usage.link?.range ?? usage.embed.range;
|
|
343
|
+
if (!contains(range, position))
|
|
344
|
+
continue;
|
|
345
|
+
const symbol = resolveUsage(index, usage);
|
|
346
|
+
return symbol ? { symbol, range, usage } : undefined;
|
|
347
|
+
}
|
|
348
|
+
const tree = await getFile(index, path);
|
|
349
|
+
if (!tree)
|
|
350
|
+
return undefined;
|
|
351
|
+
for (const node of tree.file.sections) {
|
|
352
|
+
if (node.type != "section")
|
|
353
|
+
continue;
|
|
354
|
+
if (node.nameRange && contains(node.nameRange, position)) {
|
|
355
|
+
const name = index.nodeNames.get(node);
|
|
356
|
+
return name === undefined ? undefined : { symbol: { kind: "section", name }, range: node.nameRange };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
for (const node of [tree.file.preamble, ...tree.file.sections]) {
|
|
360
|
+
if (node.type != "section")
|
|
361
|
+
continue;
|
|
362
|
+
for (const passage of node.passages) {
|
|
363
|
+
if (contains(passage.nameRange, position)) {
|
|
364
|
+
const section = index.nodeNames.get(node);
|
|
365
|
+
return section === undefined ? undefined : { symbol: { kind: "passage", section, name: passage.name }, range: passage.nameRange };
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
// The range of the name within a link's target, for rename. Undefined if it can't be found
|
|
372
|
+
// exactly, e.g. a target that spans lines.
|
|
373
|
+
function nameRangeInLink(index, usage, name) {
|
|
374
|
+
if (usage.embed)
|
|
375
|
+
return usage.embed.nameRange;
|
|
376
|
+
const link = usage.link;
|
|
377
|
+
if (link.form == "next")
|
|
378
|
+
return undefined;
|
|
379
|
+
const range = link.targetRange;
|
|
380
|
+
if (range.start.line != range.end.line)
|
|
381
|
+
return undefined;
|
|
382
|
+
const offset = link.target.length - link.target.trimStart().length;
|
|
383
|
+
const start = range.start.character + offset;
|
|
384
|
+
const line = (index.texts.get(usage.file) ?? "").split("\n")[range.start.line] ?? "";
|
|
385
|
+
if (line.substring(start, start + name.length) != name)
|
|
386
|
+
return undefined;
|
|
387
|
+
return lineRange(range.start.line, start, start + name.length);
|
|
388
|
+
}
|
|
389
|
+
function referencesTo(index, symbol, includeDeclaration) {
|
|
390
|
+
const result = [];
|
|
391
|
+
if (includeDeclaration) {
|
|
392
|
+
const definition = definitionOf(index, symbol);
|
|
393
|
+
if (definition)
|
|
394
|
+
result.push(definition);
|
|
395
|
+
}
|
|
396
|
+
for (const usage of index.usages) {
|
|
397
|
+
const target = resolveUsage(index, usage);
|
|
398
|
+
if (target && sameSymbol(target, symbol)) {
|
|
399
|
+
result.push({ file: usage.file, range: usage.link?.range ?? usage.embed.range });
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return result;
|
|
403
|
+
}
|
|
404
|
+
function addEdit(edit, file, textEdit) {
|
|
405
|
+
(edit[file] ?? (edit[file] = [])).push(textEdit);
|
|
406
|
+
}
|
|
407
|
+
// The section and passage containing a position in a file
|
|
408
|
+
function containerAt(file, position) {
|
|
409
|
+
let current = file.preamble;
|
|
410
|
+
for (const node of file.sections) {
|
|
411
|
+
if (node.range.start.line <= position.line)
|
|
412
|
+
current = node;
|
|
413
|
+
}
|
|
414
|
+
if (current.type == "snippet")
|
|
415
|
+
return { snippet: current };
|
|
416
|
+
let passage;
|
|
417
|
+
for (const p of current.passages) {
|
|
418
|
+
if (p.range.start.line <= position.line)
|
|
419
|
+
passage = p;
|
|
420
|
+
}
|
|
421
|
+
return { section: current, passage };
|
|
422
|
+
}
|
|
423
|
+
function firstLines(node, count) {
|
|
424
|
+
return node.body.filter(n => n.type == "text").map(n => n.text).join("\n").trim().split("\n").slice(0, count).join("\n");
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
updateFile(path, text) {
|
|
428
|
+
if (text === undefined)
|
|
429
|
+
openFiles.delete(path);
|
|
430
|
+
else
|
|
431
|
+
openFiles.set(path, text);
|
|
432
|
+
changed();
|
|
433
|
+
},
|
|
434
|
+
fileChanged(path) {
|
|
435
|
+
diskTexts.delete(path);
|
|
436
|
+
changed();
|
|
437
|
+
},
|
|
438
|
+
setMainFile(path) {
|
|
439
|
+
mainFile = path;
|
|
440
|
+
changed();
|
|
441
|
+
},
|
|
442
|
+
async getProjectInfo() {
|
|
443
|
+
return (await getIndex()).project;
|
|
444
|
+
},
|
|
445
|
+
async getAnalysis() {
|
|
446
|
+
return (await getIndex()).analysis;
|
|
447
|
+
},
|
|
448
|
+
async getDiagnostics(path) {
|
|
449
|
+
const index = await getIndex();
|
|
450
|
+
return allDiagnostics(index).filter(d => d.file == path);
|
|
451
|
+
},
|
|
452
|
+
async getDocumentSymbols(path) {
|
|
453
|
+
const index = await getIndex();
|
|
454
|
+
const tree = await getFile(index, path);
|
|
455
|
+
if (!tree)
|
|
456
|
+
return [];
|
|
457
|
+
const { file } = tree;
|
|
458
|
+
const symbols = [];
|
|
459
|
+
const passageSymbols = (node) => node.passages.map((p) => ({
|
|
460
|
+
name: p.name, kind: "passage", range: p.range, selectionRange: p.nameRange, children: [],
|
|
461
|
+
}));
|
|
462
|
+
for (const node of [file.preamble, ...file.sections]) {
|
|
463
|
+
if (node.type == "snippet") {
|
|
464
|
+
symbols.push({ name: node.name, kind: "snippet", range: node.range, selectionRange: node.nameRange, children: [] });
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
for (const statement of node.body) {
|
|
468
|
+
if (statement.type == "title") {
|
|
469
|
+
symbols.push({ name: statement.value, kind: "title", range: statement.range, selectionRange: statement.valueRange, children: [] });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
for (const passage of node.passages) {
|
|
473
|
+
for (const statement of passage.body) {
|
|
474
|
+
if (statement.type == "title") {
|
|
475
|
+
symbols.push({ name: statement.value, kind: "title", range: statement.range, selectionRange: statement.valueRange, children: [] });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const storyName = index.nodeNames.get(node);
|
|
480
|
+
if (node.kind == "preamble") {
|
|
481
|
+
// Only a section if the story made it one (the main file's _default section)
|
|
482
|
+
if (storyName === undefined)
|
|
483
|
+
continue;
|
|
484
|
+
symbols.push({ name: storyName, kind: "section", detail: "(Start)", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
const header = node.header;
|
|
488
|
+
const detail = header.type == "continue" ? `+++${header.text}` : header.type == "separator" ? "---" : undefined;
|
|
489
|
+
symbols.push({
|
|
490
|
+
name: node.name ?? storyName ?? detail ?? "",
|
|
491
|
+
kind: "section",
|
|
492
|
+
...(node.kind != "named" && detail ? { detail } : {}),
|
|
493
|
+
range: node.range,
|
|
494
|
+
selectionRange: node.nameRange ?? header.range,
|
|
495
|
+
children: passageSymbols(node),
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
return symbols;
|
|
499
|
+
},
|
|
500
|
+
async getDefinition(path, position) {
|
|
501
|
+
const index = await getIndex();
|
|
502
|
+
const found = await symbolAt(index, path, position);
|
|
503
|
+
return found && definitionOf(index, found.symbol);
|
|
504
|
+
},
|
|
505
|
+
async getReferences(path, position, includeDeclaration = true) {
|
|
506
|
+
const index = await getIndex();
|
|
507
|
+
const found = await symbolAt(index, path, position);
|
|
508
|
+
return found ? referencesTo(index, found.symbol, includeDeclaration) : [];
|
|
509
|
+
},
|
|
510
|
+
async getRenameEdits(path, position, newName) {
|
|
511
|
+
const index = await getIndex();
|
|
512
|
+
const found = await symbolAt(index, path, position);
|
|
513
|
+
if (!found)
|
|
514
|
+
return undefined;
|
|
515
|
+
const { symbol } = found;
|
|
516
|
+
if (newName != newName.trim() || !newName)
|
|
517
|
+
return { error: "A name can't be empty or start or end with a space." };
|
|
518
|
+
if (/[[\]\n,"]/.test(newName))
|
|
519
|
+
return { error: "A name can't contain [, ], a comma or a double quote." };
|
|
520
|
+
if (symbol.kind == "passage" && (symbol.name.startsWith("@") || newName.startsWith("@"))) {
|
|
521
|
+
return { error: "Passages whose names start with @ are special, and can't be renamed." };
|
|
522
|
+
}
|
|
523
|
+
const definition = definitionOf(index, symbol);
|
|
524
|
+
const definitionNode = symbol.kind == "section" ? index.sections.get(symbol.name)?.node : undefined;
|
|
525
|
+
if (!definition || (symbol.kind == "section" && !definitionNode?.nameRange)) {
|
|
526
|
+
return { error: `'${symbol.name}' doesn't have a name of its own to rename.` };
|
|
527
|
+
}
|
|
528
|
+
const exists = symbol.kind == "section"
|
|
529
|
+
? index.sections.has(newName)
|
|
530
|
+
: index.sections.get(symbol.section)?.passages.has(newName);
|
|
531
|
+
if (exists && newName != symbol.name) {
|
|
532
|
+
return { error: `There's already a ${symbol.kind} called '${newName}'.` };
|
|
533
|
+
}
|
|
534
|
+
const edit = {};
|
|
535
|
+
addEdit(edit, definition.file, { range: definition.range, newText: newName });
|
|
536
|
+
for (const usage of index.usages) {
|
|
537
|
+
const target = resolveUsage(index, usage);
|
|
538
|
+
if (!target || !sameSymbol(target, symbol))
|
|
539
|
+
continue;
|
|
540
|
+
const range = nameRangeInLink(index, usage, symbol.name);
|
|
541
|
+
if (range)
|
|
542
|
+
addEdit(edit, usage.file, { range, newText: newName });
|
|
543
|
+
}
|
|
544
|
+
return { edit };
|
|
545
|
+
},
|
|
546
|
+
async getCompletions(path, position) {
|
|
547
|
+
const index = await getIndex();
|
|
548
|
+
const tree = await getFile(index, path);
|
|
549
|
+
if (!tree)
|
|
550
|
+
return [];
|
|
551
|
+
// A section, passage or snippet header names something new, so nothing on its line
|
|
552
|
+
// is completed: "[my pass" there looks like the start of a passage link, but isn't one
|
|
553
|
+
const headers = [tree.file.preamble, ...tree.file.sections].flatMap((node) => node.type == "snippet" ? [node.header] : [node.header, ...node.passages.map(p => p.header)]);
|
|
554
|
+
if (headers.some(header => header?.range.start.line == position.line))
|
|
555
|
+
return [];
|
|
556
|
+
const prefix = (tree.text.replace(/\r/g, "").split("\n")[position.line] ?? "").substring(0, position.character);
|
|
557
|
+
const { section } = containerAt(tree.file, position);
|
|
558
|
+
const sectionName = section && index.nodeNames.get(section);
|
|
559
|
+
const replace = (typed) => lineRange(position.line, position.character - typed.length, position.character);
|
|
560
|
+
const sectionItems = (typed) => index.sectionNames
|
|
561
|
+
.filter(name => !name.startsWith("_continue"))
|
|
562
|
+
.map(name => ({ label: name, kind: "section", range: replace(typed) }));
|
|
563
|
+
const passageItems = (typed) => {
|
|
564
|
+
const passages = sectionName === undefined ? undefined : index.sections.get(sectionName)?.passages;
|
|
565
|
+
return [...(passages?.keys() ?? [])]
|
|
566
|
+
.filter(name => !name.startsWith("@"))
|
|
567
|
+
.map(name => ({ label: name, kind: "passage", range: replace(typed) }));
|
|
568
|
+
};
|
|
569
|
+
let match;
|
|
570
|
+
if ((match = /\{\{~?\s*embed\s+["']([^"']*)$/.exec(prefix))) {
|
|
571
|
+
return [...passageItems(match[1]), ...sectionItems(match[1])];
|
|
572
|
+
}
|
|
573
|
+
if ((match = /\[\[[^\]]*\]\]\(([^),]*)$/.exec(prefix))) {
|
|
574
|
+
return sectionItems(match[1]);
|
|
575
|
+
}
|
|
576
|
+
if ((match = /(?<![![])\[[^\]]*\]\(([^),]*)$/.exec(prefix))) {
|
|
577
|
+
return passageItems(match[1]);
|
|
578
|
+
}
|
|
579
|
+
if ((match = /\[\[([^\]>]*)$/.exec(prefix))) {
|
|
580
|
+
return sectionItems(match[1]);
|
|
581
|
+
}
|
|
582
|
+
if ((match = /(?<![![])\[([^[\]]*)$/.exec(prefix))) {
|
|
583
|
+
return passageItems(match[1]);
|
|
584
|
+
}
|
|
585
|
+
if ((match = /^\s*(@\w*)$/.exec(prefix))) {
|
|
586
|
+
return DIRECTIVES.map(([name, detail]) => ({
|
|
587
|
+
label: `@${name}`, kind: "directive", detail, range: replace(match[1]),
|
|
588
|
+
}));
|
|
589
|
+
}
|
|
590
|
+
if ((match = /^\s*@(?:set|unset|inc|dec)\s+(?:not\s+)?([^\s=]*)$/.exec(prefix))) {
|
|
591
|
+
return [...index.attributes].sort().map(name => ({ label: name, kind: "attribute", range: replace(match[1]) }));
|
|
592
|
+
}
|
|
593
|
+
if ((match = /^(\w*)$/.exec(prefix))) {
|
|
594
|
+
return index.snippets.map(({ node }) => ({
|
|
595
|
+
label: node.name,
|
|
596
|
+
kind: "snippet",
|
|
597
|
+
insertText: node.content.replace(/\s+$/, ""),
|
|
598
|
+
range: replace(match[1]),
|
|
599
|
+
}));
|
|
600
|
+
}
|
|
601
|
+
return [];
|
|
602
|
+
},
|
|
603
|
+
async getHover(path, position) {
|
|
604
|
+
const index = await getIndex();
|
|
605
|
+
const found = await symbolAt(index, path, position);
|
|
606
|
+
if (!found?.usage)
|
|
607
|
+
return undefined;
|
|
608
|
+
const { symbol } = found;
|
|
609
|
+
let node;
|
|
610
|
+
let heading;
|
|
611
|
+
if (symbol.kind == "section") {
|
|
612
|
+
node = index.sections.get(symbol.name)?.node;
|
|
613
|
+
heading = `[[${symbol.name}]]`;
|
|
614
|
+
}
|
|
615
|
+
else {
|
|
616
|
+
node = index.sections.get(symbol.section)?.passages.get(symbol.name);
|
|
617
|
+
heading = `[${symbol.name}] in [[${symbol.section}]]`;
|
|
618
|
+
}
|
|
619
|
+
if (!node)
|
|
620
|
+
return undefined;
|
|
621
|
+
const preview = firstLines(node, 5);
|
|
622
|
+
return { contents: preview ? `**${heading}**\n\n${preview}` : `**${heading}**`, range: found.range };
|
|
623
|
+
},
|
|
624
|
+
async getFoldingRanges(path) {
|
|
625
|
+
const index = await getIndex();
|
|
626
|
+
const tree = await getFile(index, path);
|
|
627
|
+
if (!tree)
|
|
628
|
+
return [];
|
|
629
|
+
const lines = tree.text.replace(/\r/g, "").split("\n");
|
|
630
|
+
const ranges = [];
|
|
631
|
+
const add = (range) => {
|
|
632
|
+
let end = range.end.line;
|
|
633
|
+
while (end > range.start.line && !lines[end]?.trim())
|
|
634
|
+
end--;
|
|
635
|
+
if (end > range.start.line)
|
|
636
|
+
ranges.push({ startLine: range.start.line, endLine: end });
|
|
637
|
+
};
|
|
638
|
+
for (const node of tree.file.sections) {
|
|
639
|
+
add(node.range);
|
|
640
|
+
if (node.type == "section")
|
|
641
|
+
node.passages.forEach(p => add(p.range));
|
|
642
|
+
}
|
|
643
|
+
tree.file.preamble.passages.forEach(p => add(p.range));
|
|
644
|
+
return ranges;
|
|
645
|
+
},
|
|
646
|
+
async getCodeActions(path, range) {
|
|
647
|
+
const index = await getIndex();
|
|
648
|
+
const tree = await getFile(index, path);
|
|
649
|
+
if (!tree)
|
|
650
|
+
return [];
|
|
651
|
+
const actions = [];
|
|
652
|
+
const diagnostics = allDiagnostics(index).filter(d => d.file == path && overlaps(d.range, range));
|
|
653
|
+
const v5 = findV5Syntax(tree.text);
|
|
654
|
+
const lines = tree.text.replace(/\r/g, "").split("\n");
|
|
655
|
+
for (const diagnostic of diagnostics) {
|
|
656
|
+
if (diagnostic.code == "squiffy/unknown-section-link" || diagnostic.code == "squiffy/unknown-passage-link") {
|
|
657
|
+
const usage = index.usages.find(u => u.file == path && u.link
|
|
658
|
+
&& comparePositions(u.link.range.start, diagnostic.range.start) == 0);
|
|
659
|
+
if (!usage?.link)
|
|
660
|
+
continue;
|
|
661
|
+
const name = intendedName(usage.link.target);
|
|
662
|
+
if (!name)
|
|
663
|
+
continue;
|
|
664
|
+
const edit = {};
|
|
665
|
+
if (diagnostic.code == "squiffy/unknown-section-link") {
|
|
666
|
+
const end = endOfText(tree.text.replace(/\r/g, ""));
|
|
667
|
+
const before = lines[lines.length - 1] == "" ? "\n" : "\n\n";
|
|
668
|
+
addEdit(edit, path, { range: { start: end, end }, newText: `${before}[[${name}]]:\n` });
|
|
669
|
+
actions.push({ title: `Create section '${name}'`, kind: "quickfix", diagnostic, edit });
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
// At the end of the section the link is in
|
|
673
|
+
const end = usage.sectionNode.range.end;
|
|
674
|
+
const blank = !lines[end.line]?.trim();
|
|
675
|
+
addEdit(edit, path, { range: { start: end, end }, newText: `${blank ? "" : "\n\n"}[${name}]:\n` });
|
|
676
|
+
actions.push({ title: `Create passage '${name}'`, kind: "quickfix", diagnostic, edit });
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
else if (diagnostic.code == "squiffy/v5-syntax") {
|
|
680
|
+
const line = diagnostic.range.start.line;
|
|
681
|
+
const match = v5.find(m => m.line == line + 1
|
|
682
|
+
&& lines[line].substring(diagnostic.range.start.character).startsWith(m.text));
|
|
683
|
+
if (!match?.suggestion || match.text.includes("\n"))
|
|
684
|
+
continue;
|
|
685
|
+
const start = diagnostic.range.start;
|
|
686
|
+
const edit = {};
|
|
687
|
+
addEdit(edit, path, {
|
|
688
|
+
range: { start, end: { line, character: start.character + match.text.length } },
|
|
689
|
+
newText: match.suggestion,
|
|
690
|
+
});
|
|
691
|
+
actions.push({ title: `Convert to ${match.suggestion}`, kind: "quickfix", diagnostic, edit });
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
for (const diagnostic of diagnostics) {
|
|
695
|
+
if (diagnostic.code != "squiffy/dead-end")
|
|
696
|
+
continue;
|
|
697
|
+
const { section } = containerAt(tree.file, diagnostic.range.start);
|
|
698
|
+
if (!section)
|
|
699
|
+
continue;
|
|
700
|
+
// A line after the header, or at the top of the file for the text before the first section
|
|
701
|
+
const line = section.header ? section.header.range.start.line + 1 : 0;
|
|
702
|
+
const edit = {};
|
|
703
|
+
addEdit(edit, path, line < lines.length
|
|
704
|
+
? { range: lineRange(line, 0, 0), newText: "@end\n" }
|
|
705
|
+
: { range: lineRange(line - 1, lines[line - 1].length, lines[line - 1].length), newText: "\n@end" });
|
|
706
|
+
actions.push({ title: "Mark this section as an ending", kind: "quickfix", diagnostic, edit });
|
|
707
|
+
}
|
|
708
|
+
for (const diagnostic of diagnostics) {
|
|
709
|
+
if (diagnostic.code != "squiffy/redundant-import")
|
|
710
|
+
continue;
|
|
711
|
+
// Remove the whole line, including its line break
|
|
712
|
+
const line = diagnostic.range.start.line;
|
|
713
|
+
const end = line + 1 < lines.length ? { line: line + 1, character: 0 } : { line, character: lines[line].length };
|
|
714
|
+
const start = line + 1 < lines.length || line == 0 ? { line, character: 0 } : { line: line - 1, character: lines[line - 1].length };
|
|
715
|
+
const edit = {};
|
|
716
|
+
addEdit(edit, path, { range: { start, end }, newText: "" });
|
|
717
|
+
actions.push({ title: "Remove this @import", kind: "quickfix", diagnostic, edit });
|
|
718
|
+
}
|
|
719
|
+
if (diagnostics.some(d => d.code == "squiffy/v5-syntax")) {
|
|
720
|
+
const converted = convertV5Syntax(tree.text);
|
|
721
|
+
if (converted.converted > 0) {
|
|
722
|
+
const edit = {};
|
|
723
|
+
addEdit(edit, path, { range: { start: { line: 0, character: 0 }, end: endOfText(tree.text) }, newText: converted.script });
|
|
724
|
+
actions.push({ title: "Convert all Squiffy 5 syntax in this file", kind: "quickfix", edit });
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return actions;
|
|
728
|
+
},
|
|
729
|
+
async getStoryGraph() {
|
|
730
|
+
return getGraph(await getIndex()).graph;
|
|
731
|
+
},
|
|
732
|
+
async getSectionAt(path, position) {
|
|
733
|
+
const index = await getIndex();
|
|
734
|
+
const tree = await getFile(index, path);
|
|
735
|
+
if (!tree)
|
|
736
|
+
return undefined;
|
|
737
|
+
const { section, passage } = containerAt(tree.file, position);
|
|
738
|
+
if (!section)
|
|
739
|
+
return undefined;
|
|
740
|
+
const name = index.nodeNames.get(section);
|
|
741
|
+
if (name === undefined)
|
|
742
|
+
return undefined;
|
|
743
|
+
return passage && index.sections.get(name)?.passages.get(passage.name) === passage
|
|
744
|
+
? { section: name, passage: passage.name }
|
|
745
|
+
: { section: name };
|
|
746
|
+
},
|
|
747
|
+
};
|
|
748
|
+
}
|