squiffy-compiler 7.0.0-beta.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 +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 +10 -3
- package/syntaxes/squiffy.tmLanguage.json +972 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const PROJECT_FILENAME = "squiffy.json";
|
|
2
|
+
export declare const PROJECT_FILE_VERSION = 1;
|
|
3
|
+
export declare const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
|
|
4
|
+
export interface ProjectFile {
|
|
5
|
+
version: number;
|
|
6
|
+
main: string;
|
|
7
|
+
exclude: string[];
|
|
8
|
+
map?: MapPositions;
|
|
9
|
+
}
|
|
10
|
+
export interface MapPositions {
|
|
11
|
+
sections: Record<string, [number, number]>;
|
|
12
|
+
passages: Record<string, Record<string, [number, number]>>;
|
|
13
|
+
}
|
|
14
|
+
export type ParsedProjectFile = {
|
|
15
|
+
success: true;
|
|
16
|
+
project: ProjectFile;
|
|
17
|
+
} | {
|
|
18
|
+
success: false;
|
|
19
|
+
error: string;
|
|
20
|
+
};
|
|
21
|
+
export declare function parseProjectFile(text: string): ParsedProjectFile;
|
|
22
|
+
export declare function globToRegExp(pattern: string): RegExp;
|
|
23
|
+
export declare function isExcluded(path: string, exclude: string[]): boolean;
|
|
24
|
+
export declare function isAlwaysSkipped(path: string): boolean;
|
|
25
|
+
export interface StoryFiles {
|
|
26
|
+
main: string;
|
|
27
|
+
included: string[];
|
|
28
|
+
excluded: string[];
|
|
29
|
+
}
|
|
30
|
+
export declare const comparePaths: (a: string, b: string) => 1 | 0 | -1;
|
|
31
|
+
export declare function getStoryFiles(project: ProjectFile, paths: Iterable<string>, skip?: string[]): StoryFiles;
|
|
32
|
+
export declare function formatProjectFile(project: {
|
|
33
|
+
main: string;
|
|
34
|
+
exclude?: string[];
|
|
35
|
+
}): string;
|
|
36
|
+
export declare function updateProjectFile(text: string, changes: {
|
|
37
|
+
main?: string;
|
|
38
|
+
exclude?: string[];
|
|
39
|
+
map?: MapPositions;
|
|
40
|
+
}): string | undefined;
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// The squiffy.json project file, which makes a folder of .squiffy files one story:
|
|
2
|
+
//
|
|
3
|
+
// { "version": 1, "main": "story.squiffy", "exclude": ["drafts/**"] }
|
|
4
|
+
//
|
|
5
|
+
// Without it, a story is its main file plus whatever that @imports. With it, the story is every
|
|
6
|
+
// .squiffy file in the folder and its subfolders, except those `exclude` matches: the main file
|
|
7
|
+
// first, then the rest in path order. These are the rules the CLI, the Vite plugin, the language
|
|
8
|
+
// service and the editor all share. They're pure functions, so each can supply its own file list.
|
|
9
|
+
export const PROJECT_FILENAME = "squiffy.json";
|
|
10
|
+
// The newest project file format this version of Squiffy understands. It counts the file
|
|
11
|
+
// format, not the Squiffy release, and only goes up when the meaning of a project changes.
|
|
12
|
+
export const PROJECT_FILE_VERSION = 1;
|
|
13
|
+
// Where the project file's JSON schema is published
|
|
14
|
+
export const PROJECT_SCHEMA_URL = "https://squiffystory.com/schema/squiffy.json";
|
|
15
|
+
// Parses and checks a squiffy.json. An error is a sentence to show the author as is.
|
|
16
|
+
export function parseProjectFile(text) {
|
|
17
|
+
const fail = (error) => ({ success: false, error });
|
|
18
|
+
let json;
|
|
19
|
+
try {
|
|
20
|
+
json = JSON.parse(text);
|
|
21
|
+
}
|
|
22
|
+
catch (e) {
|
|
23
|
+
return fail(`${PROJECT_FILENAME} isn't valid JSON: ${e instanceof Error ? e.message : String(e)}`);
|
|
24
|
+
}
|
|
25
|
+
if (!json || typeof json != "object" || Array.isArray(json)) {
|
|
26
|
+
return fail(`${PROJECT_FILENAME} should contain an object, such as { "version": 1, "main": "story.squiffy" }.`);
|
|
27
|
+
}
|
|
28
|
+
const data = json;
|
|
29
|
+
const version = data.version;
|
|
30
|
+
if (version === undefined) {
|
|
31
|
+
return fail(`${PROJECT_FILENAME} needs a "version", which should be ${PROJECT_FILE_VERSION}.`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof version != "number" || !Number.isInteger(version) || version < 1) {
|
|
34
|
+
return fail(`${PROJECT_FILENAME}'s "version" should be a whole number, such as ${PROJECT_FILE_VERSION}.`);
|
|
35
|
+
}
|
|
36
|
+
if (version > PROJECT_FILE_VERSION) {
|
|
37
|
+
return fail(`This story's ${PROJECT_FILENAME} is version ${version}, which needs a newer version of Squiffy.`);
|
|
38
|
+
}
|
|
39
|
+
const main = data.main;
|
|
40
|
+
if (main === undefined) {
|
|
41
|
+
return fail(`${PROJECT_FILENAME} needs a "main" file, such as "main": "story.squiffy".`);
|
|
42
|
+
}
|
|
43
|
+
if (typeof main != "string" || !main.trim()) {
|
|
44
|
+
return fail(`${PROJECT_FILENAME}'s "main" should be the name of a .squiffy file, such as "story.squiffy".`);
|
|
45
|
+
}
|
|
46
|
+
const mainPath = normalisePath(main);
|
|
47
|
+
if (mainPath === null) {
|
|
48
|
+
return fail(`${PROJECT_FILENAME}'s "main" should be a path inside the project's folder, not "${main}".`);
|
|
49
|
+
}
|
|
50
|
+
if (!mainPath.endsWith(".squiffy")) {
|
|
51
|
+
return fail(`${PROJECT_FILENAME}'s "main" should be a .squiffy file, not "${main}".`);
|
|
52
|
+
}
|
|
53
|
+
const exclude = data.exclude ?? [];
|
|
54
|
+
if (!Array.isArray(exclude) || exclude.some(pattern => typeof pattern != "string")) {
|
|
55
|
+
return fail(`${PROJECT_FILENAME}'s "exclude" should be a list of file patterns, such as ["drafts/**"].`);
|
|
56
|
+
}
|
|
57
|
+
const map = parseMapPositions(data.map);
|
|
58
|
+
return { success: true, project: { version, main: mainPath, exclude: exclude, ...(map ? { map } : {}) } };
|
|
59
|
+
}
|
|
60
|
+
const isPosition = (value) => Array.isArray(value) && value.length == 2 && value.every(n => typeof n == "number" && Number.isFinite(n));
|
|
61
|
+
const isObject = (value) => !!value && typeof value == "object" && !Array.isArray(value);
|
|
62
|
+
// The story map's positions. Only the editor uses them, so anything that isn't a position is
|
|
63
|
+
// left out rather than stopping the story from building.
|
|
64
|
+
function parseMapPositions(value) {
|
|
65
|
+
if (!isObject(value))
|
|
66
|
+
return undefined;
|
|
67
|
+
const sections = {};
|
|
68
|
+
const passages = {};
|
|
69
|
+
if (isObject(value.sections)) {
|
|
70
|
+
for (const [name, position] of Object.entries(value.sections)) {
|
|
71
|
+
if (isPosition(position))
|
|
72
|
+
sections[name] = position;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (isObject(value.passages)) {
|
|
76
|
+
for (const [section, byName] of Object.entries(value.passages)) {
|
|
77
|
+
if (!isObject(byName))
|
|
78
|
+
continue;
|
|
79
|
+
for (const [name, position] of Object.entries(byName)) {
|
|
80
|
+
if (isPosition(position))
|
|
81
|
+
(passages[section] ?? (passages[section] = {}))[name] = position;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { sections, passages };
|
|
86
|
+
}
|
|
87
|
+
// A project path with "/" separators and no "." segments, or null if it goes outside the folder
|
|
88
|
+
// or is absolute.
|
|
89
|
+
function normalisePath(path) {
|
|
90
|
+
const slashes = path.replace(/\\/g, "/");
|
|
91
|
+
if (slashes.startsWith("/") || /^[a-zA-Z]:/.test(slashes))
|
|
92
|
+
return null;
|
|
93
|
+
const parts = [];
|
|
94
|
+
for (const part of slashes.split("/")) {
|
|
95
|
+
if (part == "" || part == ".")
|
|
96
|
+
continue;
|
|
97
|
+
if (part == "..")
|
|
98
|
+
return null;
|
|
99
|
+
parts.push(part);
|
|
100
|
+
}
|
|
101
|
+
return parts.length ? parts.join("/") : null;
|
|
102
|
+
}
|
|
103
|
+
// "*" and "?" match within one path segment; "**" matches across segments.
|
|
104
|
+
export function globToRegExp(pattern) {
|
|
105
|
+
let out = "";
|
|
106
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
107
|
+
const c = pattern[i];
|
|
108
|
+
if (c == "*") {
|
|
109
|
+
if (pattern[i + 1] == "*") {
|
|
110
|
+
i++;
|
|
111
|
+
if (pattern[i + 1] == "/") {
|
|
112
|
+
i++;
|
|
113
|
+
out += "(?:.*/)?";
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
out += ".*";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
out += "[^/]*";
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else if (c == "?") {
|
|
124
|
+
out += "[^/]";
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return new RegExp(`^${out}$`);
|
|
131
|
+
}
|
|
132
|
+
// Whether `exclude` leaves a file out of the story: a pattern matches it or one of its folders.
|
|
133
|
+
export function isExcluded(path, exclude) {
|
|
134
|
+
const parts = path.split("/");
|
|
135
|
+
return exclude.some(pattern => {
|
|
136
|
+
const normalised = normalisePath(pattern.trim());
|
|
137
|
+
if (normalised === null)
|
|
138
|
+
return false;
|
|
139
|
+
const regex = globToRegExp(normalised);
|
|
140
|
+
for (let i = 1; i <= parts.length; i++) {
|
|
141
|
+
if (regex.test(parts.slice(0, i).join("/")))
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
return false;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
// Folders whose .squiffy files are never part of a story, whatever `exclude` says:
|
|
148
|
+
// node_modules, and folders whose names start with "." (.git, .vscode and the like).
|
|
149
|
+
export function isAlwaysSkipped(path) {
|
|
150
|
+
const folders = path.split("/").slice(0, -1);
|
|
151
|
+
return folders.some(folder => folder == "node_modules" || folder.startsWith("."));
|
|
152
|
+
}
|
|
153
|
+
// Sorts paths by code point, so the order is the same everywhere, whatever the locale.
|
|
154
|
+
export const comparePaths = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
155
|
+
// Which of a project's files make up the story. `paths` are relative to the project file's folder,
|
|
156
|
+
// with "/" separators, as from a recursive listing of the folder; anything that isn't a .squiffy
|
|
157
|
+
// file is ignored. Pass `skip` to leave out more folders, such as a build's output folder.
|
|
158
|
+
export function getStoryFiles(project, paths, skip = []) {
|
|
159
|
+
const included = [];
|
|
160
|
+
const excluded = [];
|
|
161
|
+
const skipped = skip.map(folder => normalisePath(folder)).filter(folder => folder !== null);
|
|
162
|
+
for (const path of new Set(paths)) {
|
|
163
|
+
if (!path.endsWith(".squiffy") || path == project.main || isAlwaysSkipped(path))
|
|
164
|
+
continue;
|
|
165
|
+
if (skipped.some(folder => path.startsWith(folder + "/")))
|
|
166
|
+
continue;
|
|
167
|
+
(isExcluded(path, project.exclude) ? excluded : included).push(path);
|
|
168
|
+
}
|
|
169
|
+
return { main: project.main, included: included.sort(comparePaths), excluded: excluded.sort(comparePaths) };
|
|
170
|
+
}
|
|
171
|
+
// The text of a new project file
|
|
172
|
+
export function formatProjectFile(project) {
|
|
173
|
+
const json = {
|
|
174
|
+
$schema: PROJECT_SCHEMA_URL,
|
|
175
|
+
version: PROJECT_FILE_VERSION,
|
|
176
|
+
main: project.main,
|
|
177
|
+
};
|
|
178
|
+
if (project.exclude?.length)
|
|
179
|
+
json.exclude = project.exclude;
|
|
180
|
+
return JSON.stringify(json, null, 2) + "\n";
|
|
181
|
+
}
|
|
182
|
+
// Changes a project file's text, keeping any other properties it has. Returns undefined if the
|
|
183
|
+
// text isn't a JSON object. A `map` with no positions removes it.
|
|
184
|
+
export function updateProjectFile(text, changes) {
|
|
185
|
+
let json;
|
|
186
|
+
try {
|
|
187
|
+
json = JSON.parse(text);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
if (!json || typeof json != "object" || Array.isArray(json))
|
|
193
|
+
return undefined;
|
|
194
|
+
const data = { ...json };
|
|
195
|
+
if (changes.main !== undefined)
|
|
196
|
+
data.main = changes.main;
|
|
197
|
+
if (changes.exclude !== undefined) {
|
|
198
|
+
if (changes.exclude.length)
|
|
199
|
+
data.exclude = changes.exclude;
|
|
200
|
+
else
|
|
201
|
+
delete data.exclude;
|
|
202
|
+
}
|
|
203
|
+
if (changes.map !== undefined) {
|
|
204
|
+
const { sections, passages } = changes.map;
|
|
205
|
+
const used = Object.fromEntries(Object.entries(passages).filter(([, byName]) => Object.keys(byName).length));
|
|
206
|
+
// Anything else that's in "map" stays, but empty lists of positions don't
|
|
207
|
+
const map = { ...(isObject(data.map) ? data.map : {}) };
|
|
208
|
+
delete map.sections;
|
|
209
|
+
delete map.passages;
|
|
210
|
+
if (Object.keys(sections).length)
|
|
211
|
+
map.sections = sections;
|
|
212
|
+
if (Object.keys(used).length)
|
|
213
|
+
map.passages = used;
|
|
214
|
+
if (Object.keys(map).length)
|
|
215
|
+
data.map = map;
|
|
216
|
+
else
|
|
217
|
+
delete data.map;
|
|
218
|
+
}
|
|
219
|
+
const indent = /^\{\s*\n([ \t]+)/.exec(text)?.[1] ?? 2;
|
|
220
|
+
// Each position on one line, rather than an x and a y on lines of their own
|
|
221
|
+
return JSON.stringify(data, null, indent).replace(/\[\s+(-?[\d.e+-]+),\s+(-?[\d.e+-]+)\s+\]/g, "[$1, $2]") + "\n";
|
|
222
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Location } from "./language-service.js";
|
|
2
|
+
import type { Diagnostic, EmbedNode, LinkNode, PassageNode, Position, SectionNode, SquiffyFile } from "./syntax.js";
|
|
3
|
+
export interface StoryGraph {
|
|
4
|
+
nodes: GraphNode[];
|
|
5
|
+
edges: GraphEdge[];
|
|
6
|
+
}
|
|
7
|
+
export interface GraphNode {
|
|
8
|
+
id: string;
|
|
9
|
+
kind: "section" | "passage";
|
|
10
|
+
name: string;
|
|
11
|
+
section?: string;
|
|
12
|
+
detail?: string;
|
|
13
|
+
location: Location;
|
|
14
|
+
contentEnd: Position;
|
|
15
|
+
start?: boolean;
|
|
16
|
+
reachable: boolean;
|
|
17
|
+
embedded?: boolean;
|
|
18
|
+
deadEnd: boolean;
|
|
19
|
+
ending?: boolean;
|
|
20
|
+
unknownExits?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export type GraphEdgeKind = "section-link" | "passage-link" | "embed" | "goto" | "script";
|
|
23
|
+
export interface GraphEdge {
|
|
24
|
+
from: string;
|
|
25
|
+
to?: string;
|
|
26
|
+
kind: GraphEdgeKind;
|
|
27
|
+
conditional: boolean;
|
|
28
|
+
dynamic?: boolean;
|
|
29
|
+
location: Location;
|
|
30
|
+
text?: string;
|
|
31
|
+
target?: string;
|
|
32
|
+
setters?: string[];
|
|
33
|
+
}
|
|
34
|
+
export declare const sectionId: (name: string) => string;
|
|
35
|
+
export declare const passageId: (section: string, name: string) => string;
|
|
36
|
+
export interface GraphUsage {
|
|
37
|
+
file: string;
|
|
38
|
+
container: SectionNode | PassageNode;
|
|
39
|
+
sectionNode: SectionNode;
|
|
40
|
+
link?: LinkNode;
|
|
41
|
+
embed?: EmbedNode;
|
|
42
|
+
}
|
|
43
|
+
export type GraphTarget = {
|
|
44
|
+
kind: "section";
|
|
45
|
+
name: string;
|
|
46
|
+
} | {
|
|
47
|
+
kind: "passage";
|
|
48
|
+
section: string;
|
|
49
|
+
name: string;
|
|
50
|
+
};
|
|
51
|
+
export interface GraphSource {
|
|
52
|
+
files: Map<string, SquiffyFile>;
|
|
53
|
+
sections: Map<string, {
|
|
54
|
+
file: string;
|
|
55
|
+
node?: SectionNode;
|
|
56
|
+
passages: Map<string, PassageNode>;
|
|
57
|
+
}>;
|
|
58
|
+
nodeNames: Map<SectionNode, string>;
|
|
59
|
+
usages: GraphUsage[];
|
|
60
|
+
start: string;
|
|
61
|
+
resolve(usage: GraphUsage): GraphTarget | undefined;
|
|
62
|
+
}
|
|
63
|
+
export declare function buildStoryGraph(source: GraphSource): StoryGraph;
|
|
64
|
+
export declare function storyGraphDiagnostics(graph: StoryGraph): Diagnostic[];
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// The whole story as a directed graph: its sections and passages, and the links between them,
|
|
2
|
+
// with which can be reached from the start and which sections are dead ends. The language
|
|
3
|
+
// service builds it from its index (see getStoryGraph), for the story map and for the
|
|
4
|
+
// "unreachable section" and "dead end" diagnostics.
|
|
5
|
+
export const sectionId = (name) => `section:${name}`;
|
|
6
|
+
export const passageId = (section, name) => `passage:${section}/${name}`;
|
|
7
|
+
const NAVIGATION = new Set(["section-link", "goto", "script"]);
|
|
8
|
+
const collapsed = (position) => ({ start: position, end: position });
|
|
9
|
+
const comparePositions = (a, b) => a.line - b.line || a.character - b.character;
|
|
10
|
+
// The parts of a container's text inside {{#if}} or {{#unless}} blocks
|
|
11
|
+
function conditionalRanges(container) {
|
|
12
|
+
const ranges = [];
|
|
13
|
+
const open = [];
|
|
14
|
+
for (const statement of container.body) {
|
|
15
|
+
if (statement.type != "text")
|
|
16
|
+
continue;
|
|
17
|
+
for (const match of statement.text.matchAll(/\{\{~?\s*([#/])(if|unless)\b/g)) {
|
|
18
|
+
const position = { line: statement.range.start.line, character: match.index };
|
|
19
|
+
if (match[1] == "#") {
|
|
20
|
+
open.push(position);
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
const start = open.pop();
|
|
24
|
+
if (start)
|
|
25
|
+
ranges.push({ start, end: position });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// An unclosed block runs to the end
|
|
30
|
+
for (const start of open)
|
|
31
|
+
ranges.push({ start, end: container.range.end });
|
|
32
|
+
return ranges;
|
|
33
|
+
}
|
|
34
|
+
// What the outline calls a section without a name of its own
|
|
35
|
+
function sectionDetail(node) {
|
|
36
|
+
if (node.kind == "preamble")
|
|
37
|
+
return "(Start)";
|
|
38
|
+
if (node.header?.type == "continue")
|
|
39
|
+
return `+++${node.header.text}`;
|
|
40
|
+
if (node.header?.type == "separator")
|
|
41
|
+
return "---";
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
// The end of a section's or passage's own text, leaving out blank lines and its passages
|
|
45
|
+
function contentEnd(container) {
|
|
46
|
+
const ownEnd = container.type == "section" && container.passages.length
|
|
47
|
+
? container.passages[0].range.start
|
|
48
|
+
: container.range.end;
|
|
49
|
+
let end = container.header?.range.end ?? container.range.start;
|
|
50
|
+
for (const statement of container.body) {
|
|
51
|
+
if (comparePositions(statement.range.start, ownEnd) >= 0)
|
|
52
|
+
break;
|
|
53
|
+
if (statement.type == "text" && !statement.text.trim())
|
|
54
|
+
continue;
|
|
55
|
+
if (comparePositions(statement.range.end, end) > 0)
|
|
56
|
+
end = statement.range.end;
|
|
57
|
+
}
|
|
58
|
+
return end;
|
|
59
|
+
}
|
|
60
|
+
export function buildStoryGraph(source) {
|
|
61
|
+
const nodes = [];
|
|
62
|
+
const edges = [];
|
|
63
|
+
const nodeById = new Map();
|
|
64
|
+
const containerIds = new Map();
|
|
65
|
+
// Containers with navigation that can't be followed
|
|
66
|
+
const unknown = new Set();
|
|
67
|
+
const endings = new Set();
|
|
68
|
+
// {{live}} helpers that show a section or passage
|
|
69
|
+
const liveEmbeds = [];
|
|
70
|
+
const addNode = (node) => {
|
|
71
|
+
nodes.push(node);
|
|
72
|
+
nodeById.set(node.id, node);
|
|
73
|
+
};
|
|
74
|
+
for (const [name, section] of source.sections) {
|
|
75
|
+
const id = sectionId(name);
|
|
76
|
+
const node = section.node;
|
|
77
|
+
const range = node
|
|
78
|
+
? node.nameRange ?? node.header?.range ?? collapsed(node.range.start)
|
|
79
|
+
: collapsed({ line: 0, character: 0 });
|
|
80
|
+
const detail = node ? sectionDetail(node) : undefined;
|
|
81
|
+
addNode({
|
|
82
|
+
id, kind: "section", name, ...(detail ? { detail } : {}),
|
|
83
|
+
location: { file: section.file, range }, contentEnd: node ? contentEnd(node) : range.end,
|
|
84
|
+
reachable: false, deadEnd: false,
|
|
85
|
+
...(name == source.start ? { start: true } : {}),
|
|
86
|
+
});
|
|
87
|
+
if (node)
|
|
88
|
+
containerIds.set(node, id);
|
|
89
|
+
for (const [passageName, passage] of section.passages) {
|
|
90
|
+
const pid = passageId(name, passageName);
|
|
91
|
+
addNode({
|
|
92
|
+
id: pid, kind: "passage", name: passageName, section: name,
|
|
93
|
+
location: { file: section.file, range: passage.nameRange }, contentEnd: contentEnd(passage),
|
|
94
|
+
reachable: false, deadEnd: false,
|
|
95
|
+
});
|
|
96
|
+
containerIds.set(passage, pid);
|
|
97
|
+
}
|
|
98
|
+
// @end, and navigation the links don't show
|
|
99
|
+
for (const container of node ? [node, ...section.passages.values()] : []) {
|
|
100
|
+
const from = containerIds.get(container);
|
|
101
|
+
for (const statement of container.body) {
|
|
102
|
+
if (statement.type == "end") {
|
|
103
|
+
endings.add(name);
|
|
104
|
+
}
|
|
105
|
+
else if (statement.type == "text") {
|
|
106
|
+
if (/\{\{~?\s*section\s/.test(statement.text))
|
|
107
|
+
unknown.add(from);
|
|
108
|
+
// {{live "x" section="name"}} and passage="name" show that section's or
|
|
109
|
+
// passage's text, and so its links, as {{embed}} does
|
|
110
|
+
for (const match of statement.text.matchAll(/\{\{~?\s*live\s[^}]*?\b(section|passage)\s*=\s*(["'])([^"']*)\2[^}]*\}\}/g)) {
|
|
111
|
+
const line = statement.range.start.line;
|
|
112
|
+
liveEmbeds.push({
|
|
113
|
+
container, from, file: section.file, sectionName: name, kind: match[1], target: match[3],
|
|
114
|
+
range: { start: { line, character: match.index }, end: { line, character: match.index + match[0].length } },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else if (statement.type == "js") {
|
|
119
|
+
for (const match of statement.code.matchAll(/\.go\s*\(\s*(?:(["'])([^"'\\]*)\1\s*\))?/g)) {
|
|
120
|
+
const target = match[2];
|
|
121
|
+
if (target === undefined) {
|
|
122
|
+
unknown.add(from);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const start = statement.codeRange.start.character + match.index;
|
|
126
|
+
edges.push({
|
|
127
|
+
from,
|
|
128
|
+
...(source.sections.has(target) ? { to: sectionId(target) } : {}),
|
|
129
|
+
kind: "script",
|
|
130
|
+
conditional: false,
|
|
131
|
+
location: {
|
|
132
|
+
file: section.file,
|
|
133
|
+
range: { start: { line: statement.range.start.line, character: start }, end: { line: statement.range.start.line, character: start + match[0].length } },
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// The link a +++ line adds to the section before it
|
|
142
|
+
for (const [file, tree] of source.files) {
|
|
143
|
+
const all = [tree.preamble, ...tree.sections];
|
|
144
|
+
for (let i = 1; i < all.length; i++) {
|
|
145
|
+
const node = all[i];
|
|
146
|
+
if (node.type != "section" || node.header?.type != "continue")
|
|
147
|
+
continue;
|
|
148
|
+
const previous = all[i - 1];
|
|
149
|
+
const name = source.nodeNames.get(node);
|
|
150
|
+
const previousName = previous.type == "section" ? source.nodeNames.get(previous) : undefined;
|
|
151
|
+
if (name === undefined || previousName === undefined)
|
|
152
|
+
continue;
|
|
153
|
+
edges.push({
|
|
154
|
+
from: sectionId(previousName),
|
|
155
|
+
to: sectionId(name),
|
|
156
|
+
kind: "section-link",
|
|
157
|
+
conditional: false,
|
|
158
|
+
location: { file, range: node.header.range },
|
|
159
|
+
text: node.header.text || "Continue...",
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const conditionals = new Map();
|
|
164
|
+
const isConditional = (container, position) => {
|
|
165
|
+
let ranges = conditionals.get(container);
|
|
166
|
+
if (!ranges) {
|
|
167
|
+
ranges = conditionalRanges(container);
|
|
168
|
+
conditionals.set(container, ranges);
|
|
169
|
+
}
|
|
170
|
+
return ranges.some(r => comparePositions(r.start, position) <= 0 && comparePositions(position, r.end) <= 0);
|
|
171
|
+
};
|
|
172
|
+
for (const usage of source.usages) {
|
|
173
|
+
const from = containerIds.get(usage.container);
|
|
174
|
+
// Not part of the story, or replaced by a later section or passage of the same name
|
|
175
|
+
if (from === undefined)
|
|
176
|
+
continue;
|
|
177
|
+
const target = source.resolve(usage);
|
|
178
|
+
const to = target && (target.kind == "section" ? sectionId(target.name) : passageId(target.section, target.name));
|
|
179
|
+
const range = usage.link?.range ?? usage.embed.range;
|
|
180
|
+
const conditional = isConditional(usage.container, range.start);
|
|
181
|
+
const location = { file: usage.file, range };
|
|
182
|
+
if (usage.embed) {
|
|
183
|
+
edges.push({ from, ...(to ? { to } : { target: usage.embed.name }), kind: "embed", conditional, location });
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const link = usage.link;
|
|
187
|
+
const dynamic = !to && link.target.includes("{{");
|
|
188
|
+
if (dynamic)
|
|
189
|
+
unknown.add(from);
|
|
190
|
+
const resolvedName = target?.name;
|
|
191
|
+
const setters = link.form != "next" && link.target.trim() == resolvedName
|
|
192
|
+
? []
|
|
193
|
+
: link.target.split(",").slice(1).map(s => s.trim()).filter(Boolean);
|
|
194
|
+
const text = link.text ?? link.target.trim().split(",")[0].trim();
|
|
195
|
+
edges.push({
|
|
196
|
+
from,
|
|
197
|
+
...(to ? { to } : {}),
|
|
198
|
+
kind: link.linkType == "section" ? "section-link" : "passage-link",
|
|
199
|
+
conditional,
|
|
200
|
+
...(dynamic ? { dynamic } : {}),
|
|
201
|
+
location,
|
|
202
|
+
...(text ? { text } : {}),
|
|
203
|
+
...(!to && !dynamic && link.form != "next" ? { target: link.target.split(",")[0].trim() } : {}),
|
|
204
|
+
...(setters.length ? { setters } : {}),
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
for (const live of liveEmbeds) {
|
|
208
|
+
const to = live.kind == "section"
|
|
209
|
+
? source.sections.has(live.target) ? sectionId(live.target) : undefined
|
|
210
|
+
: source.sections.get(live.sectionName)?.passages.has(live.target) ? passageId(live.sectionName, live.target) : undefined;
|
|
211
|
+
edges.push({
|
|
212
|
+
from: live.from,
|
|
213
|
+
...(to ? { to } : { target: live.target }),
|
|
214
|
+
kind: "embed",
|
|
215
|
+
conditional: isConditional(live.container, live.range.start),
|
|
216
|
+
location: { file: live.file, range: live.range },
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
// In the order they're written
|
|
220
|
+
const fileOrder = new Map([...source.files.keys()].map((file, i) => [file, i]));
|
|
221
|
+
edges.sort((a, b) => (fileOrder.get(a.location.file) ?? -1) - (fileOrder.get(b.location.file) ?? -1)
|
|
222
|
+
|| comparePositions(a.location.range.start, b.location.range.start));
|
|
223
|
+
const outgoing = new Map();
|
|
224
|
+
for (const edge of edges) {
|
|
225
|
+
let list = outgoing.get(edge.from);
|
|
226
|
+
if (!list)
|
|
227
|
+
outgoing.set(edge.from, list = []);
|
|
228
|
+
list.push(edge);
|
|
229
|
+
}
|
|
230
|
+
// Passages by section, for special passages
|
|
231
|
+
const passagesOf = new Map();
|
|
232
|
+
for (const node of nodes) {
|
|
233
|
+
if (node.kind != "passage")
|
|
234
|
+
continue;
|
|
235
|
+
let list = passagesOf.get(node.section);
|
|
236
|
+
if (!list)
|
|
237
|
+
passagesOf.set(node.section, list = []);
|
|
238
|
+
list.push(node);
|
|
239
|
+
}
|
|
240
|
+
// ---- Reachability ----
|
|
241
|
+
// Containers whose content is shown: reachable ones, and anything they embed
|
|
242
|
+
const shown = new Set();
|
|
243
|
+
const toShow = [];
|
|
244
|
+
const show = (id) => {
|
|
245
|
+
if (shown.has(id))
|
|
246
|
+
return;
|
|
247
|
+
shown.add(id);
|
|
248
|
+
toShow.push(id);
|
|
249
|
+
};
|
|
250
|
+
const reach = (id) => {
|
|
251
|
+
const node = id === undefined ? undefined : nodeById.get(id);
|
|
252
|
+
if (!node || node.reachable)
|
|
253
|
+
return;
|
|
254
|
+
node.reachable = true;
|
|
255
|
+
show(node.id);
|
|
256
|
+
if (node.kind == "section") {
|
|
257
|
+
// Passages such as @last and @1 run on their own when their section's passages do
|
|
258
|
+
for (const passage of passagesOf.get(node.name) ?? []) {
|
|
259
|
+
if (passage.name.startsWith("@"))
|
|
260
|
+
reach(passage.id);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
else if (node.name != "") {
|
|
264
|
+
// A passage called "" runs whenever another passage in its section does
|
|
265
|
+
reach(passageId(node.section, ""));
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
if (nodeById.has(sectionId(source.start))) {
|
|
269
|
+
reach(sectionId(source.start));
|
|
270
|
+
// The master section's content is part of every section
|
|
271
|
+
reach(sectionId(""));
|
|
272
|
+
}
|
|
273
|
+
while (toShow.length) {
|
|
274
|
+
const id = toShow.pop();
|
|
275
|
+
for (const edge of outgoing.get(id) ?? []) {
|
|
276
|
+
if (edge.to === undefined)
|
|
277
|
+
continue;
|
|
278
|
+
if (edge.kind == "embed")
|
|
279
|
+
show(edge.to);
|
|
280
|
+
else
|
|
281
|
+
reach(edge.to);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// Shown inside something that can be reached, though not reached itself
|
|
285
|
+
for (const node of nodes) {
|
|
286
|
+
if (!node.reachable && shown.has(node.id))
|
|
287
|
+
node.embedded = true;
|
|
288
|
+
}
|
|
289
|
+
// ---- Dead ends ----
|
|
290
|
+
const masterIds = nodeById.has(sectionId(""))
|
|
291
|
+
? [sectionId(""), ...(passagesOf.get("") ?? []).map(p => p.id)]
|
|
292
|
+
: [];
|
|
293
|
+
for (const node of nodes) {
|
|
294
|
+
if (node.kind != "section")
|
|
295
|
+
continue;
|
|
296
|
+
const ending = endings.has(node.name);
|
|
297
|
+
if (ending)
|
|
298
|
+
node.ending = true;
|
|
299
|
+
// What's shown in this section: its own content, its passages', the master section's,
|
|
300
|
+
// and anything those embed
|
|
301
|
+
const seen = new Set();
|
|
302
|
+
const queue = [node.id, ...(passagesOf.get(node.name) ?? []).map(p => p.id), ...masterIds];
|
|
303
|
+
let wayOut = false;
|
|
304
|
+
let unknownExits = false;
|
|
305
|
+
while (queue.length) {
|
|
306
|
+
const id = queue.pop();
|
|
307
|
+
if (seen.has(id))
|
|
308
|
+
continue;
|
|
309
|
+
seen.add(id);
|
|
310
|
+
if (unknown.has(id))
|
|
311
|
+
unknownExits = true;
|
|
312
|
+
for (const edge of outgoing.get(id) ?? []) {
|
|
313
|
+
if (NAVIGATION.has(edge.kind))
|
|
314
|
+
wayOut = true;
|
|
315
|
+
else if (edge.kind == "embed" && edge.to)
|
|
316
|
+
queue.push(edge.to);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (unknownExits)
|
|
320
|
+
node.unknownExits = true;
|
|
321
|
+
const hasContent = source.sections.get(node.name)?.node !== undefined;
|
|
322
|
+
node.deadEnd = hasContent && node.name != "" && !ending && !wayOut && !unknownExits;
|
|
323
|
+
}
|
|
324
|
+
return { nodes, edges };
|
|
325
|
+
}
|
|
326
|
+
// "Unreachable section" and "dead end" warnings, for the language service's diagnostics
|
|
327
|
+
export function storyGraphDiagnostics(graph) {
|
|
328
|
+
const diagnostics = [];
|
|
329
|
+
const sections = graph.nodes.filter(n => n.kind == "section");
|
|
330
|
+
// If the story starts at a section that doesn't exist, or anything that can be reached
|
|
331
|
+
// navigates somewhere that can't be known, any section might be reachable
|
|
332
|
+
const checkReachable = sections.some(n => n.start) && !sections.some(n => n.reachable && n.unknownExits);
|
|
333
|
+
for (const node of sections) {
|
|
334
|
+
// The master section, which is part of every section
|
|
335
|
+
if (node.name == "")
|
|
336
|
+
continue;
|
|
337
|
+
if (!node.reachable) {
|
|
338
|
+
if (!checkReachable || node.embedded)
|
|
339
|
+
continue;
|
|
340
|
+
diagnostics.push({
|
|
341
|
+
file: node.location.file,
|
|
342
|
+
range: node.location.range,
|
|
343
|
+
severity: "warning",
|
|
344
|
+
code: "squiffy/unreachable-section",
|
|
345
|
+
message: "This section can't be reached from the start of the story, as nothing the player can reach links to it.",
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
else if (node.deadEnd) {
|
|
349
|
+
diagnostics.push({
|
|
350
|
+
file: node.location.file,
|
|
351
|
+
range: node.location.range,
|
|
352
|
+
severity: "warning",
|
|
353
|
+
code: "squiffy/dead-end",
|
|
354
|
+
message: "This section has no way out, as it has no links to another section. If it's one of the story's endings, add @end to say so.",
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return diagnostics;
|
|
359
|
+
}
|