squiffy-compiler 7.0.0-beta.1 → 7.0.0-beta.3
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 +2 -0
- package/dist/analyse.js +80 -10
- package/dist/compiler.d.ts +3 -0
- package/dist/compiler.js +1 -0
- package/dist/language-service.d.ts +13 -1
- package/dist/language-service.js +118 -39
- package/dist/node.d.ts +13 -0
- package/dist/node.js +105 -0
- package/dist/parse.js +5 -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 +7 -3
- package/package.json +12 -5
- package/syntaxes/squiffy.tmLanguage.json +972 -0
package/dist/analyse.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export interface AnalyseSettings {
|
|
|
11
11
|
externalFiles?: ExternalFiles;
|
|
12
12
|
parseCache?: ParseCache;
|
|
13
13
|
recover?: boolean;
|
|
14
|
+
storyFiles?: string[];
|
|
14
15
|
}
|
|
15
16
|
export declare class ParseCache {
|
|
16
17
|
private files;
|
|
@@ -31,6 +32,7 @@ export interface Analysis {
|
|
|
31
32
|
files: SquiffyFile[];
|
|
32
33
|
diagnostics: Diagnostic[];
|
|
33
34
|
sections: SectionSymbol[];
|
|
35
|
+
start: string;
|
|
34
36
|
}
|
|
35
37
|
export declare class Story {
|
|
36
38
|
sections: Record<string, Section>;
|
package/dist/analyse.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parse } from "./parse.js";
|
|
2
2
|
import { positionMapper, transformText } from "./text.js";
|
|
3
|
+
import { PROJECT_FILENAME } from "./project.js";
|
|
3
4
|
import { findV5Syntax } from "./v5.js";
|
|
4
5
|
// Caches the syntax tree of each file by filename, reparsing a file only when its text changes.
|
|
5
6
|
export class ParseCache {
|
|
@@ -194,29 +195,56 @@ export async function analyse(settings) {
|
|
|
194
195
|
const legacyErrors = [];
|
|
195
196
|
const legacyWarnings = [];
|
|
196
197
|
let autoSectionCount = 0;
|
|
198
|
+
// The story starts at the main file's first section by default, even if an @import
|
|
199
|
+
// above it has already added sections from other files.
|
|
200
|
+
let mainFirstSection;
|
|
197
201
|
const report = (severity, code, filename, range, message, legacyLine) => {
|
|
198
202
|
diagnostics.push({ file: filename ?? "", range, severity, code, message });
|
|
203
|
+
if (severity == "hint")
|
|
204
|
+
return;
|
|
199
205
|
const legacy = `${severity.toUpperCase()}: ${filename} line ${legacyLine}: ${message}`;
|
|
200
206
|
(severity == "error" ? legacyErrors : legacyWarnings).push(legacy);
|
|
201
207
|
};
|
|
208
|
+
const storyFiles = settings.storyFiles && new Set(settings.storyFiles);
|
|
209
|
+
// The .squiffy files processed so far, so a story file the main file has already @imported
|
|
210
|
+
// isn't processed again
|
|
211
|
+
const processed = new Set();
|
|
202
212
|
async function processFile(text, filename, isFirst) {
|
|
203
213
|
const file = cache.parse(text, filename);
|
|
204
214
|
files.push(file);
|
|
215
|
+
processed.add(filename);
|
|
205
216
|
const lines = text.replace(/\r/g, "").split("\n");
|
|
206
217
|
warnAboutV5Syntax(text, lines, filename);
|
|
207
218
|
let section = null;
|
|
208
219
|
let passage = null;
|
|
209
220
|
let inUiBlock = false;
|
|
221
|
+
// Where an earlier section or passage was defined, for a duplicate's warning
|
|
222
|
+
const earlierLocation = (earlierFilename, line) => earlierFilename == filename || !earlierFilename ? `line ${line}` : `${earlierFilename} line ${line}`;
|
|
223
|
+
const addSection = (name, line, node) => {
|
|
224
|
+
if (isFirst && !mainFirstSection)
|
|
225
|
+
mainFirstSection = name;
|
|
226
|
+
const earlier = hasOwn(story.sections, name) ? story.sections[name] : undefined;
|
|
227
|
+
// The compiler's own names (_default, _continue1, ...) only clash with a section the
|
|
228
|
+
// author named the same way. The main file's preamble can add "_default" more than
|
|
229
|
+
// once, each replacing the last, but that's not a clash the author can see.
|
|
230
|
+
if (earlier && node && !(node.kind == "preamble" && earlier.node?.kind == "preamble")) {
|
|
231
|
+
// A --- in the preamble starts a section that has no node of its own
|
|
232
|
+
const range = node.nameRange ?? node.header?.range
|
|
233
|
+
?? { start: { line: line - 1, character: 0 }, end: { line: line - 1, character: lines[line - 1]?.length ?? 0 } };
|
|
234
|
+
report("warning", "squiffy/duplicate-section", filename, range, `There's already a section called [[${name}]], at ${earlierLocation(earlier.filename, earlier.line)}. This one replaces it.`, range.start.line + 1);
|
|
235
|
+
}
|
|
236
|
+
return story.addSection(name, filename, line, node);
|
|
237
|
+
};
|
|
210
238
|
const ensureSectionExists = (line) => {
|
|
211
239
|
if (!section && isFirst) {
|
|
212
|
-
return
|
|
240
|
+
return addSection("_default", line, file.preamble);
|
|
213
241
|
}
|
|
214
242
|
return section;
|
|
215
243
|
};
|
|
216
244
|
const addAutoSection = (node, line) => {
|
|
217
245
|
autoSectionCount++;
|
|
218
246
|
const autoSectionName = `_continue${autoSectionCount}`;
|
|
219
|
-
section =
|
|
247
|
+
section = addSection(autoSectionName, line, node);
|
|
220
248
|
passage = null;
|
|
221
249
|
return autoSectionName;
|
|
222
250
|
};
|
|
@@ -230,7 +258,7 @@ export async function analyse(settings) {
|
|
|
230
258
|
const lineCount = header.range.start.line + 1;
|
|
231
259
|
switch (header.type) {
|
|
232
260
|
case "section-header":
|
|
233
|
-
section =
|
|
261
|
+
section = addSection(header.name, lineCount, node);
|
|
234
262
|
passage = null;
|
|
235
263
|
return true;
|
|
236
264
|
case "continue": {
|
|
@@ -262,6 +290,10 @@ export async function analyse(settings) {
|
|
|
262
290
|
report("error", "squiffy/passage-without-section", filename, node.nameRange, `Can't add passage "${node.name}" as no section has been created.`, lineCount);
|
|
263
291
|
return false;
|
|
264
292
|
}
|
|
293
|
+
if (hasOwn(section.passages, node.name)) {
|
|
294
|
+
const earlier = section.passages[node.name];
|
|
295
|
+
report("warning", "squiffy/duplicate-passage", filename, node.nameRange, `There's already a passage called [${node.name}] in section '${section.name}', at ${earlierLocation(section.filename, earlier.line)}. This one replaces it.`, lineCount);
|
|
296
|
+
}
|
|
265
297
|
passage = section.addPassage(node.name, lineCount, node);
|
|
266
298
|
return true;
|
|
267
299
|
};
|
|
@@ -292,18 +324,40 @@ export async function analyse(settings) {
|
|
|
292
324
|
passage.clear = true;
|
|
293
325
|
}
|
|
294
326
|
return true;
|
|
295
|
-
case "
|
|
296
|
-
|
|
327
|
+
case "end":
|
|
328
|
+
// Only for the language service's dead end check
|
|
329
|
+
if (!passage) {
|
|
330
|
+
section = ensureSectionExists(lineCount);
|
|
331
|
+
if (!section)
|
|
332
|
+
return sectionRequired(node);
|
|
333
|
+
}
|
|
297
334
|
return true;
|
|
335
|
+
case "title":
|
|
298
336
|
case "start":
|
|
299
|
-
|
|
337
|
+
// In folder mode, a file that isn't the main file could otherwise quietly
|
|
338
|
+
// change the story's title or where it starts
|
|
339
|
+
if (storyFiles && !isFirst) {
|
|
340
|
+
report("warning", "squiffy/not-in-main-file", filename, lineRange(node), `@${node.type} only works in the story's main file, so this was ignored.`, lineCount);
|
|
341
|
+
}
|
|
342
|
+
else if (node.type == "title") {
|
|
343
|
+
story.title = node.value;
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
story.start = node.value;
|
|
347
|
+
}
|
|
300
348
|
return true;
|
|
301
|
-
case "import":
|
|
349
|
+
case "import": {
|
|
302
350
|
if (!settings.externalFiles) {
|
|
303
351
|
warnExternalFilesUnavailable(`@import ${node.pattern}`, node, filename);
|
|
304
352
|
return true;
|
|
305
353
|
}
|
|
306
|
-
|
|
354
|
+
const matches = await settings.externalFiles.getMatchingFilenames(node.pattern);
|
|
355
|
+
const squiffyMatches = matches.filter(m => m.endsWith(".squiffy"));
|
|
356
|
+
if (storyFiles && squiffyMatches.length && squiffyMatches.length == matches.length
|
|
357
|
+
&& squiffyMatches.every(m => storyFiles.has(m))) {
|
|
358
|
+
report("hint", "squiffy/redundant-import", filename, lineRange(node), `${squiffyMatches.length == 1 ? "This file is" : "These files are"} already part of the story, as ${PROJECT_FILENAME} includes every .squiffy file in the folder, so this @import isn't needed.`, lineCount);
|
|
359
|
+
}
|
|
360
|
+
for (const importFilename of matches) {
|
|
307
361
|
if (importFilename.endsWith(".squiffy")) {
|
|
308
362
|
const content = await settings.externalFiles.getContent(importFilename);
|
|
309
363
|
const success = await processFile(content, importFilename, false);
|
|
@@ -318,6 +372,7 @@ export async function analyse(settings) {
|
|
|
318
372
|
}
|
|
319
373
|
}
|
|
320
374
|
return true;
|
|
375
|
+
}
|
|
321
376
|
case "attribute": {
|
|
322
377
|
section = ensureSectionExists(lineCount);
|
|
323
378
|
let attribute;
|
|
@@ -467,13 +522,27 @@ export async function analyse(settings) {
|
|
|
467
522
|
}
|
|
468
523
|
}
|
|
469
524
|
// With recover, processFile carries on after errors, so check for them too
|
|
470
|
-
|
|
525
|
+
let success = await processFile(settings.script, settings.scriptBaseFilename, true);
|
|
526
|
+
// In folder mode, the rest of the story's files, in order
|
|
527
|
+
for (const storyFile of settings.storyFiles ?? []) {
|
|
528
|
+
if (!success && !settings.recover)
|
|
529
|
+
break;
|
|
530
|
+
if (processed.has(storyFile))
|
|
531
|
+
continue;
|
|
532
|
+
if (!settings.externalFiles) {
|
|
533
|
+
report("warning", "squiffy/external-files-unavailable", settings.scriptBaseFilename, { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, "The story's other files were ignored, as other files can't be loaded here", 1);
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
const content = await settings.externalFiles.getContent(storyFile);
|
|
537
|
+
success = await processFile(content, storyFile, false) && success;
|
|
538
|
+
}
|
|
539
|
+
success && (success = !legacyErrors.length);
|
|
471
540
|
if (success || settings.recover) {
|
|
472
541
|
if (!Object.keys(story.sections).length) {
|
|
473
542
|
story.addSection("_default", settings.scriptBaseFilename, 0, undefined);
|
|
474
543
|
}
|
|
475
544
|
if (!story.start) {
|
|
476
|
-
story.start = Object.keys(story.sections)[0];
|
|
545
|
+
story.start = mainFirstSection ?? Object.keys(story.sections)[0];
|
|
477
546
|
}
|
|
478
547
|
sectionNames = Object.keys(story.sections);
|
|
479
548
|
sectionIndexes = new Map(sectionNames.map((name, i) => [name, i]));
|
|
@@ -494,6 +563,7 @@ export async function analyse(settings) {
|
|
|
494
563
|
...(section.node ? { node: section.node } : {}),
|
|
495
564
|
passages: Object.values(section.passages).map(passage => ({ name: passage.name, node: passage.node })),
|
|
496
565
|
})),
|
|
566
|
+
start: story.start,
|
|
497
567
|
};
|
|
498
568
|
analysisInternals.set(analysis, { story, legacyErrors, legacyWarnings });
|
|
499
569
|
return analysis;
|
package/dist/compiler.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export type { AnalyseSettings, Analysis, ExternalFiles, SectionSymbol, PassageSy
|
|
|
9
9
|
export { emit } from "./emit.js";
|
|
10
10
|
export type { EmitSettings, Output, UiInfo, CompileSuccess } from "./emit.js";
|
|
11
11
|
export { formatDiagnostic } from "./syntax.js";
|
|
12
|
+
export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
|
|
13
|
+
export type { MapPositions, ProjectFile, ParsedProjectFile, StoryFiles } from "./project.js";
|
|
12
14
|
export type * from "./syntax.js";
|
|
13
15
|
interface CompilerSettings {
|
|
14
16
|
scriptBaseFilename?: string;
|
|
@@ -17,6 +19,7 @@ interface CompilerSettings {
|
|
|
17
19
|
externalFiles?: ExternalFiles;
|
|
18
20
|
globalJs?: boolean;
|
|
19
21
|
parseCache?: ParseCache;
|
|
22
|
+
storyFiles?: string[];
|
|
20
23
|
}
|
|
21
24
|
export interface CompileError {
|
|
22
25
|
success: false;
|
package/dist/compiler.js
CHANGED
|
@@ -9,6 +9,7 @@ export { parse } from "./parse.js";
|
|
|
9
9
|
export { analyse, ParseCache } from "./analyse.js";
|
|
10
10
|
export { emit } from "./emit.js";
|
|
11
11
|
export { formatDiagnostic } from "./syntax.js";
|
|
12
|
+
export { PROJECT_FILENAME, PROJECT_FILE_VERSION, PROJECT_SCHEMA_URL, parseProjectFile, getStoryFiles, isExcluded, isAlwaysSkipped, formatProjectFile, updateProjectFile, } from "./project.js";
|
|
12
13
|
export async function compile(settings) {
|
|
13
14
|
const analysis = await analyse(settings);
|
|
14
15
|
const { legacyErrors, legacyWarnings } = analysisInternals.get(analysis);
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Analysis } from "./analyse.js";
|
|
2
2
|
import type { Diagnostic, Position, Range } from "./syntax.js";
|
|
3
|
+
import { ProjectFile } from "./project.js";
|
|
4
|
+
import { StoryGraph } from "./story-graph.js";
|
|
3
5
|
export type { Diagnostic, Position, Range } from "./syntax.js";
|
|
6
|
+
export type { GraphEdge, GraphEdgeKind, GraphNode, StoryGraph } from "./story-graph.js";
|
|
4
7
|
export interface ProjectFiles {
|
|
5
8
|
list(): Promise<{
|
|
6
9
|
path: string;
|
|
@@ -11,6 +14,13 @@ export interface LanguageServiceOptions {
|
|
|
11
14
|
files: ProjectFiles;
|
|
12
15
|
mainFile: string;
|
|
13
16
|
}
|
|
17
|
+
export interface ProjectInfo {
|
|
18
|
+
projectFile?: ProjectFile;
|
|
19
|
+
error?: string;
|
|
20
|
+
mainFile: string;
|
|
21
|
+
storyFiles: string[];
|
|
22
|
+
excludedFiles: string[];
|
|
23
|
+
}
|
|
14
24
|
export interface TextEdit {
|
|
15
25
|
range: Range;
|
|
16
26
|
newText: string;
|
|
@@ -30,7 +40,7 @@ export interface DocumentSymbol {
|
|
|
30
40
|
}
|
|
31
41
|
export interface CompletionItem {
|
|
32
42
|
label: string;
|
|
33
|
-
kind: "section" | "passage" | "attribute" | "snippet";
|
|
43
|
+
kind: "section" | "passage" | "attribute" | "snippet" | "directive";
|
|
34
44
|
insertText?: string;
|
|
35
45
|
detail?: string;
|
|
36
46
|
range: Range;
|
|
@@ -62,6 +72,7 @@ export interface LanguageService {
|
|
|
62
72
|
updateFile(path: string, text: string | undefined): void;
|
|
63
73
|
fileChanged(path: string): void;
|
|
64
74
|
setMainFile(path: string): void;
|
|
75
|
+
getProjectInfo(): Promise<ProjectInfo>;
|
|
65
76
|
getAnalysis(): Promise<Analysis>;
|
|
66
77
|
getDiagnostics(path: string): Promise<Diagnostic[]>;
|
|
67
78
|
getDocumentSymbols(path: string): Promise<DocumentSymbol[]>;
|
|
@@ -73,5 +84,6 @@ export interface LanguageService {
|
|
|
73
84
|
getFoldingRanges(path: string): Promise<FoldingRange[]>;
|
|
74
85
|
getCodeActions(path: string, range: Range): Promise<CodeAction[]>;
|
|
75
86
|
getSectionAt(path: string, position: Position): Promise<SectionAt | undefined>;
|
|
87
|
+
getStoryGraph(): Promise<StoryGraph>;
|
|
76
88
|
}
|
|
77
89
|
export declare function createLanguageService(options: LanguageServiceOptions): LanguageService;
|
package/dist/language-service.js
CHANGED
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
// The Squiffy language service: outline, diagnostics, go to definition, references, rename,
|
|
2
|
-
// completion, hover, folding, quick fixes
|
|
2
|
+
// completion, hover, folding, quick fixes, "which section is this" and the story graph, for a
|
|
3
|
+
// multi-file project.
|
|
3
4
|
// It has no UI or DOM dependencies, so the web editor, the desktop app (from a Web Worker) and an
|
|
4
5
|
// LSP adapter for VS Code can all call it directly.
|
|
5
6
|
//
|
|
6
7
|
// Positions and ranges are zero-based { line, character }, following LSP conventions.
|
|
7
8
|
import { analyse, ParseCache } from "./analyse.js";
|
|
9
|
+
import { getStoryFiles, globToRegExp, parseProjectFile, PROJECT_FILENAME } from "./project.js";
|
|
8
10
|
import { convertV5Syntax, findV5Syntax } from "./v5.js";
|
|
11
|
+
import { buildStoryGraph, storyGraphDiagnostics } from "./story-graph.js";
|
|
9
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
|
+
];
|
|
10
26
|
const contains = (range, pos) => comparePositions(range.start, pos) <= 0 && comparePositions(pos, range.end) <= 0;
|
|
11
27
|
function comparePositions(a, b) {
|
|
12
28
|
return a.line - b.line || a.character - b.character;
|
|
@@ -50,35 +66,6 @@ function relativePath(fromDir, path) {
|
|
|
50
66
|
common++;
|
|
51
67
|
return [...from.slice(common).map(() => ".."), ...to.slice(common)].join("/");
|
|
52
68
|
}
|
|
53
|
-
// "*" and "?" match within one path segment; "**" matches across segments.
|
|
54
|
-
function globToRegExp(pattern) {
|
|
55
|
-
let out = "";
|
|
56
|
-
for (let i = 0; i < pattern.length; i++) {
|
|
57
|
-
const c = pattern[i];
|
|
58
|
-
if (c == "*") {
|
|
59
|
-
if (pattern[i + 1] == "*") {
|
|
60
|
-
i++;
|
|
61
|
-
if (pattern[i + 1] == "/") {
|
|
62
|
-
i++;
|
|
63
|
-
out += "(?:.*/)?";
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
out += ".*";
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
else {
|
|
70
|
-
out += "[^/]*";
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
else if (c == "?") {
|
|
74
|
-
out += "[^/]";
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return new RegExp(`^${out}$`);
|
|
81
|
-
}
|
|
82
69
|
const endOfText = (text) => {
|
|
83
70
|
const lines = text.split("\n");
|
|
84
71
|
return { line: lines.length - 1, character: lines[lines.length - 1].length };
|
|
@@ -111,19 +98,17 @@ export function createLanguageService(options) {
|
|
|
111
98
|
}
|
|
112
99
|
// The compiler's ExternalFiles, resolving @import patterns and @ui paths against the main
|
|
113
100
|
// file's folder and never importing a file twice, as the CLI does.
|
|
114
|
-
function externalFiles(texts) {
|
|
101
|
+
function externalFiles(texts, mainFile, storyFiles) {
|
|
115
102
|
const baseDir = dirname(mainFile);
|
|
116
103
|
const included = new Set([mainFile]);
|
|
117
|
-
const matched = new Set();
|
|
104
|
+
const matched = new Set(storyFiles);
|
|
118
105
|
return {
|
|
119
106
|
async getMatchingFilenames(pattern) {
|
|
120
107
|
const resolved = resolvePath(baseDir, pattern);
|
|
121
108
|
if (resolved === null)
|
|
122
109
|
return [];
|
|
123
110
|
const regex = globToRegExp(resolved);
|
|
124
|
-
const paths =
|
|
125
|
-
for (const open of openFiles.keys())
|
|
126
|
-
paths.add(open);
|
|
111
|
+
const paths = await listPaths();
|
|
127
112
|
const result = [...paths].filter(p => regex.test(p) && !included.has(p)).sort();
|
|
128
113
|
for (const p of result)
|
|
129
114
|
matched.add(p);
|
|
@@ -146,8 +131,35 @@ export function createLanguageService(options) {
|
|
|
146
131
|
getLocalFilename: (filename) => relativePath(baseDir, filename),
|
|
147
132
|
};
|
|
148
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
|
+
}
|
|
149
159
|
async function buildIndex() {
|
|
150
160
|
const texts = new Map();
|
|
161
|
+
const project = await getProject();
|
|
162
|
+
const mainFile = project.mainFile;
|
|
151
163
|
let script = "";
|
|
152
164
|
try {
|
|
153
165
|
script = await readFile(mainFile);
|
|
@@ -159,12 +171,25 @@ export function createLanguageService(options) {
|
|
|
159
171
|
const analysis = await analyse({
|
|
160
172
|
script,
|
|
161
173
|
scriptBaseFilename: mainFile,
|
|
162
|
-
externalFiles: externalFiles(texts),
|
|
174
|
+
externalFiles: externalFiles(texts, mainFile, project.storyFiles),
|
|
163
175
|
parseCache,
|
|
164
176
|
recover: true,
|
|
177
|
+
...(project.projectFile ? { storyFiles: project.storyFiles } : {}),
|
|
165
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
|
+
}
|
|
166
190
|
const index = {
|
|
167
191
|
analysis,
|
|
192
|
+
project,
|
|
168
193
|
files: new Map(),
|
|
169
194
|
texts,
|
|
170
195
|
sectionNames: analysis.sections.map(s => s.name),
|
|
@@ -243,6 +268,24 @@ export function createLanguageService(options) {
|
|
|
243
268
|
return undefined;
|
|
244
269
|
}
|
|
245
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
|
+
}
|
|
246
289
|
// The passages a passage link or embed in this section can reach
|
|
247
290
|
function passagesOf(index, sectionNode) {
|
|
248
291
|
const name = index.nodeNames.get(sectionNode);
|
|
@@ -396,12 +439,15 @@ export function createLanguageService(options) {
|
|
|
396
439
|
mainFile = path;
|
|
397
440
|
changed();
|
|
398
441
|
},
|
|
442
|
+
async getProjectInfo() {
|
|
443
|
+
return (await getIndex()).project;
|
|
444
|
+
},
|
|
399
445
|
async getAnalysis() {
|
|
400
446
|
return (await getIndex()).analysis;
|
|
401
447
|
},
|
|
402
448
|
async getDiagnostics(path) {
|
|
403
449
|
const index = await getIndex();
|
|
404
|
-
return index.
|
|
450
|
+
return allDiagnostics(index).filter(d => d.file == path);
|
|
405
451
|
},
|
|
406
452
|
async getDocumentSymbols(path) {
|
|
407
453
|
const index = await getIndex();
|
|
@@ -435,7 +481,7 @@ export function createLanguageService(options) {
|
|
|
435
481
|
// Only a section if the story made it one (the main file's _default section)
|
|
436
482
|
if (storyName === undefined)
|
|
437
483
|
continue;
|
|
438
|
-
symbols.push({ name: storyName, kind: "section", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
|
|
484
|
+
symbols.push({ name: storyName, kind: "section", detail: "(Start)", range: node.range, selectionRange: node.range, children: passageSymbols(node) });
|
|
439
485
|
continue;
|
|
440
486
|
}
|
|
441
487
|
const header = node.header;
|
|
@@ -536,6 +582,11 @@ export function createLanguageService(options) {
|
|
|
536
582
|
if ((match = /(?<![![])\[([^[\]]*)$/.exec(prefix))) {
|
|
537
583
|
return passageItems(match[1]);
|
|
538
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
|
+
}
|
|
539
590
|
if ((match = /^\s*@(?:set|unset|inc|dec)\s+(?:not\s+)?([^\s=]*)$/.exec(prefix))) {
|
|
540
591
|
return [...index.attributes].sort().map(name => ({ label: name, kind: "attribute", range: replace(match[1]) }));
|
|
541
592
|
}
|
|
@@ -598,7 +649,7 @@ export function createLanguageService(options) {
|
|
|
598
649
|
if (!tree)
|
|
599
650
|
return [];
|
|
600
651
|
const actions = [];
|
|
601
|
-
const diagnostics = index.
|
|
652
|
+
const diagnostics = allDiagnostics(index).filter(d => d.file == path && overlaps(d.range, range));
|
|
602
653
|
const v5 = findV5Syntax(tree.text);
|
|
603
654
|
const lines = tree.text.replace(/\r/g, "").split("\n");
|
|
604
655
|
for (const diagnostic of diagnostics) {
|
|
@@ -640,6 +691,31 @@ export function createLanguageService(options) {
|
|
|
640
691
|
actions.push({ title: `Convert to ${match.suggestion}`, kind: "quickfix", diagnostic, edit });
|
|
641
692
|
}
|
|
642
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
|
+
}
|
|
643
719
|
if (diagnostics.some(d => d.code == "squiffy/v5-syntax")) {
|
|
644
720
|
const converted = convertV5Syntax(tree.text);
|
|
645
721
|
if (converted.converted > 0) {
|
|
@@ -650,6 +726,9 @@ export function createLanguageService(options) {
|
|
|
650
726
|
}
|
|
651
727
|
return actions;
|
|
652
728
|
},
|
|
729
|
+
async getStoryGraph() {
|
|
730
|
+
return getGraph(await getIndex()).graph;
|
|
731
|
+
},
|
|
653
732
|
async getSectionAt(path, position) {
|
|
654
733
|
const index = await getIndex();
|
|
655
734
|
const tree = await getFile(index, path);
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface StoryOnDisk {
|
|
2
|
+
mainFile: string;
|
|
3
|
+
storyFiles?: string[];
|
|
4
|
+
projectFile?: string;
|
|
5
|
+
note?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class StoryNotFoundError extends Error {
|
|
8
|
+
}
|
|
9
|
+
export interface FindStoryOptions {
|
|
10
|
+
skip?: string[];
|
|
11
|
+
}
|
|
12
|
+
export declare function listSquiffyFiles(folder: string): Promise<string[]>;
|
|
13
|
+
export declare function findStory(input: string, options?: FindStoryOptions): Promise<StoryOnDisk>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// Finding a story on disk, for the CLI and the Vite plugin. This is the only part of the compiler
|
|
3
|
+
// that touches the file system, and it's a separate entry point (squiffy-compiler/node), so the
|
|
4
|
+
// rest of the compiler stays free of Node dependencies.
|
|
5
|
+
import fs from "fs/promises";
|
|
6
|
+
import path from "path";
|
|
7
|
+
import { getStoryFiles, isAlwaysSkipped, parseProjectFile, PROJECT_FILENAME } from "./project.js";
|
|
8
|
+
// A problem finding the story, with a message to show the author as is
|
|
9
|
+
export class StoryNotFoundError extends Error {
|
|
10
|
+
}
|
|
11
|
+
const exists = async (filename) => {
|
|
12
|
+
try {
|
|
13
|
+
await fs.access(filename);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const isDirectory = async (filename) => {
|
|
21
|
+
try {
|
|
22
|
+
return (await fs.stat(filename)).isDirectory();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
// The nearest squiffy.json in a folder or the folders above it
|
|
29
|
+
async function findProjectFile(folder) {
|
|
30
|
+
for (let dir = path.resolve(folder);; dir = path.dirname(dir)) {
|
|
31
|
+
const candidate = path.join(dir, PROJECT_FILENAME);
|
|
32
|
+
if (await exists(candidate))
|
|
33
|
+
return candidate;
|
|
34
|
+
if (path.dirname(dir) == dir)
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Every .squiffy file in a folder and its subfolders, relative to it with "/" separators, without
|
|
39
|
+
// looking inside the folders that are never part of a story.
|
|
40
|
+
export async function listSquiffyFiles(folder) {
|
|
41
|
+
const result = [];
|
|
42
|
+
const walk = async (relative) => {
|
|
43
|
+
const entries = await fs.readdir(path.join(folder, relative), { withFileTypes: true });
|
|
44
|
+
for (const entry of entries) {
|
|
45
|
+
const child = relative ? `${relative}/${entry.name}` : entry.name;
|
|
46
|
+
if (entry.isDirectory()) {
|
|
47
|
+
if (!isAlwaysSkipped(`${child}/x`))
|
|
48
|
+
await walk(child);
|
|
49
|
+
}
|
|
50
|
+
else if (entry.name.endsWith(".squiffy")) {
|
|
51
|
+
result.push(child);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
await walk("");
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
async function readProject(projectFile) {
|
|
59
|
+
const parsed = parseProjectFile(await fs.readFile(projectFile, "utf8"));
|
|
60
|
+
if (!parsed.success) {
|
|
61
|
+
throw new StoryNotFoundError(`${parsed.error} (${projectFile})`);
|
|
62
|
+
}
|
|
63
|
+
return parsed.project;
|
|
64
|
+
}
|
|
65
|
+
async function folderStory(projectFile, options) {
|
|
66
|
+
const root = path.dirname(projectFile);
|
|
67
|
+
const project = await readProject(projectFile);
|
|
68
|
+
const mainFile = path.resolve(root, project.main);
|
|
69
|
+
if (!await exists(mainFile)) {
|
|
70
|
+
throw new StoryNotFoundError(`The main file in ${projectFile}, ${project.main}, doesn't exist.`);
|
|
71
|
+
}
|
|
72
|
+
const story = getStoryFiles(project, await listSquiffyFiles(root), options.skip);
|
|
73
|
+
return { mainFile, storyFiles: story.included.map(file => path.resolve(root, file)), projectFile };
|
|
74
|
+
}
|
|
75
|
+
// Finds the story to build from what the author gave: a folder with a squiffy.json in it, or a
|
|
76
|
+
// .squiffy file.
|
|
77
|
+
//
|
|
78
|
+
// - A folder builds the project in its squiffy.json.
|
|
79
|
+
// - A project's main file (with a squiffy.json in its folder or above) builds the project.
|
|
80
|
+
// - Any other .squiffy file builds just that file and its @imports, as it would with no
|
|
81
|
+
// squiffy.json, with a note saying so. So several stories can share a folder.
|
|
82
|
+
export async function findStory(input, options = {}) {
|
|
83
|
+
const resolved = path.resolve(input);
|
|
84
|
+
if (await isDirectory(resolved)) {
|
|
85
|
+
const projectFile = path.join(resolved, PROJECT_FILENAME);
|
|
86
|
+
if (!await exists(projectFile)) {
|
|
87
|
+
throw new StoryNotFoundError(`There's no ${PROJECT_FILENAME} in ${resolved}. Give the story's .squiffy file instead, or add a ${PROJECT_FILENAME} to make the folder one story.`);
|
|
88
|
+
}
|
|
89
|
+
return folderStory(projectFile, options);
|
|
90
|
+
}
|
|
91
|
+
if (!await exists(resolved)) {
|
|
92
|
+
throw new StoryNotFoundError(`${input} doesn't exist.`);
|
|
93
|
+
}
|
|
94
|
+
const projectFile = await findProjectFile(path.dirname(resolved));
|
|
95
|
+
if (!projectFile)
|
|
96
|
+
return { mainFile: resolved };
|
|
97
|
+
const project = await readProject(projectFile);
|
|
98
|
+
if (path.resolve(path.dirname(projectFile), project.main) == resolved) {
|
|
99
|
+
return folderStory(projectFile, options);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
mainFile: resolved,
|
|
103
|
+
note: `Building just ${path.basename(resolved)}, as it isn't the main file in ${projectFile} (${project.main}).`,
|
|
104
|
+
};
|
|
105
|
+
}
|
package/dist/parse.js
CHANGED
|
@@ -158,6 +158,11 @@ export function parse(text, filename) {
|
|
|
158
158
|
haveSection = true;
|
|
159
159
|
add({ type: "clear", range });
|
|
160
160
|
}
|
|
161
|
+
else if (stripLine == "@end") {
|
|
162
|
+
if (!passage)
|
|
163
|
+
haveSection = true;
|
|
164
|
+
add({ type: "end", range });
|
|
165
|
+
}
|
|
161
166
|
else if (match.title) {
|
|
162
167
|
add({ type: "title", value: match.title[1], valueRange: valueRange(i, match.title[1]), range });
|
|
163
168
|
}
|