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.
@@ -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
+ }
@@ -0,0 +1,150 @@
1
+ export interface Position {
2
+ line: number;
3
+ character: number;
4
+ }
5
+ export interface Range {
6
+ start: Position;
7
+ end: Position;
8
+ }
9
+ export type DiagnosticSeverity = "error" | "warning" | "hint";
10
+ export type DiagnosticCode = "squiffy/passage-without-section" | "squiffy/text-in-ui-block" | "squiffy/content-before-section" | "squiffy/v5-syntax" | "squiffy/external-files-unavailable" | "squiffy/no-next-section" | "squiffy/unknown-embed" | "squiffy/unknown-section-link" | "squiffy/unknown-passage-link" | "squiffy/duplicate-section" | "squiffy/duplicate-passage" | "squiffy/not-in-main-file" | "squiffy/redundant-import" | "squiffy/project-file" | "squiffy/unreachable-section" | "squiffy/dead-end";
11
+ export interface Diagnostic {
12
+ file: string;
13
+ range: Range;
14
+ severity: DiagnosticSeverity;
15
+ code: DiagnosticCode;
16
+ message: string;
17
+ }
18
+ export declare function formatDiagnostic(diagnostic: Diagnostic): string;
19
+ export interface SquiffyFile {
20
+ type: "file";
21
+ filename: string | undefined;
22
+ range: Range;
23
+ preamble: SectionNode;
24
+ sections: (SectionNode | SnippetNode)[];
25
+ }
26
+ export interface SectionNode {
27
+ type: "section";
28
+ kind: "named" | "continue" | "separator" | "preamble";
29
+ name?: string;
30
+ nameRange?: Range;
31
+ header?: SectionHeaderNode | ContinueNode | SeparatorNode;
32
+ range: Range;
33
+ body: StatementNode[];
34
+ passages: PassageNode[];
35
+ links: LinkNode[];
36
+ embeds: EmbedNode[];
37
+ }
38
+ export interface PassageNode {
39
+ type: "passage";
40
+ name: string;
41
+ nameRange: Range;
42
+ header: PassageHeaderNode;
43
+ range: Range;
44
+ body: StatementNode[];
45
+ links: LinkNode[];
46
+ embeds: EmbedNode[];
47
+ }
48
+ export interface SnippetNode {
49
+ type: "snippet";
50
+ name: string;
51
+ nameRange: Range;
52
+ header: SnippetHeaderNode;
53
+ range: Range;
54
+ content: string;
55
+ }
56
+ export interface SectionHeaderNode {
57
+ type: "section-header";
58
+ name: string;
59
+ range: Range;
60
+ }
61
+ export interface PassageHeaderNode {
62
+ type: "passage-header";
63
+ name: string;
64
+ range: Range;
65
+ }
66
+ export interface SnippetHeaderNode {
67
+ type: "snippet-header";
68
+ name: string;
69
+ range: Range;
70
+ }
71
+ export interface ContinueNode {
72
+ type: "continue";
73
+ text: string;
74
+ range: Range;
75
+ }
76
+ export interface SeparatorNode {
77
+ type: "separator";
78
+ range: Range;
79
+ }
80
+ export interface TitleNode {
81
+ type: "title";
82
+ value: string;
83
+ valueRange: Range;
84
+ range: Range;
85
+ }
86
+ export interface StartNode {
87
+ type: "start";
88
+ value: string;
89
+ valueRange: Range;
90
+ range: Range;
91
+ }
92
+ export interface ImportNode {
93
+ type: "import";
94
+ pattern: string;
95
+ patternRange: Range;
96
+ range: Range;
97
+ }
98
+ export interface UiBlockStartNode {
99
+ type: "ui-block-start";
100
+ range: Range;
101
+ }
102
+ export interface UiFileNode {
103
+ type: "ui-file";
104
+ path: string;
105
+ pathRange: Range;
106
+ range: Range;
107
+ }
108
+ export interface ClearNode {
109
+ type: "clear";
110
+ range: Range;
111
+ }
112
+ export interface EndNode {
113
+ type: "end";
114
+ range: Range;
115
+ }
116
+ export interface AttributeNode {
117
+ type: "attribute";
118
+ directive: "set" | "unset" | "inc" | "dec";
119
+ value: string;
120
+ valueRange: Range;
121
+ amount?: string;
122
+ range: Range;
123
+ }
124
+ export interface JsNode {
125
+ type: "js";
126
+ code: string;
127
+ codeRange: Range;
128
+ range: Range;
129
+ }
130
+ export interface TextNode {
131
+ type: "text";
132
+ text: string;
133
+ range: Range;
134
+ }
135
+ export type StatementNode = SeparatorNode | TitleNode | StartNode | ImportNode | UiBlockStartNode | UiFileNode | ClearNode | EndNode | AttributeNode | JsNode | TextNode;
136
+ export interface LinkNode {
137
+ type: "link";
138
+ linkType: "section" | "passage";
139
+ form: "named" | "unnamed" | "next";
140
+ text?: string;
141
+ target: string;
142
+ range: Range;
143
+ targetRange: Range;
144
+ }
145
+ export interface EmbedNode {
146
+ type: "embed";
147
+ name: string;
148
+ range: Range;
149
+ nameRange: Range;
150
+ }
package/dist/syntax.js ADDED
@@ -0,0 +1,8 @@
1
+ // The syntax tree that parse() returns for one .squiffy file, and the structured diagnostics
2
+ // that analyse() reports. Positions are zero-based and ranges are end-exclusive, following
3
+ // LSP conventions, so a language server can pass them straight through.
4
+ // Formats a diagnostic the way the compiler has always reported problems, e.g.
5
+ // `WARNING: story.squiffy line 12: In section 'start' there is a link to ...`
6
+ export function formatDiagnostic(diagnostic) {
7
+ return `${diagnostic.severity.toUpperCase()}: ${diagnostic.file} line ${diagnostic.range.start.line + 1}: ${diagnostic.message}`;
8
+ }
package/dist/text.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export interface TextLink {
2
+ linkType: "section" | "passage";
3
+ form: "named" | "unnamed" | "next";
4
+ text?: string;
5
+ target: string;
6
+ start: number;
7
+ end: number;
8
+ targetStart: number;
9
+ targetEnd: number;
10
+ }
11
+ export interface TextEmbed {
12
+ name: string;
13
+ start: number;
14
+ end: number;
15
+ nameStart: number;
16
+ nameEnd: number;
17
+ }
18
+ export interface NoNextSection {
19
+ display: string;
20
+ start: number;
21
+ end: number;
22
+ }
23
+ export interface TransformResult {
24
+ output: string;
25
+ links: TextLink[];
26
+ embeds: TextEmbed[];
27
+ noNextSection: NoNextSection[];
28
+ }
29
+ export declare function transformText(text: string, getNextSectionName: () => string | null): TransformResult;
30
+ export interface SourceLine {
31
+ line: number;
32
+ length: number;
33
+ }
34
+ export declare function positionMapper(lines: SourceLine[], lineLengths: number[]): (offset: number) => {
35
+ line: number;
36
+ character: number;
37
+ };