Skip to content

Commit 7455bd4

Browse files
committed
Plan XMD formatting edits in the prepared Rust module
1 parent 52a4161 commit 7455bd4

9 files changed

Lines changed: 241 additions & 62 deletions

File tree

‎packages/core/src/format-source.ts‎

Lines changed: 18 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,29 @@
11
import { Err, Ok, type Result } from "effection";
2+
import { indentationEdits } from "./markdown.ts";
3+
import type { SourceRange } from "./document-targets.ts";
24
import { scanSegments } from "./scanner.ts";
35
import type { ScanDiagnostic, SourceElement, SourceFence, UnfinishedConstruct } from "./scanner.ts";
46
import { envelopeBody } from "./source-inspection.ts";
57
import type { Segment } from "./types.ts";
68

7-
function afterLine(text: string, offset: number): number {
8-
const newline = text.indexOf("\n", offset);
9-
return newline === -1 ? text.length : newline + 1;
10-
}
11-
129
function startOfLine(text: string, offset: number): number {
1310
return offset === 0 ? 0 : text.lastIndexOf("\n", offset - 1) + 1;
1411
}
1512

16-
function proposeIndentation(text: string, elements: SourceElement[]): string {
17-
const depthChanges = new Map<number, number>();
18-
const headerLines = new Set<number>();
19-
for (const { opening, closing } of elements) {
20-
const bodyStart = afterLine(text, opening.end);
21-
for (
22-
let line = afterLine(text, opening.start);
23-
line < opening.end;
24-
line = afterLine(text, line)
25-
) {
26-
headerLines.add(line);
27-
}
28-
if (closing === undefined) {
29-
continue;
30-
}
31-
const beforeTag = text.slice(startOfLine(text, opening.start), opening.start);
32-
const afterTag = text.slice(opening.end, bodyStart);
33-
if (!/^[ \t]*$/.test(beforeTag) || !/^[ \t]*\n$/.test(afterTag)) {
34-
continue;
35-
}
36-
const closeLine = startOfLine(text, closing.start);
37-
const beforeClose = text.slice(closeLine, closing.start);
38-
const bodyEnd = /^[ \t]*$/.test(beforeClose) ? closeLine : afterLine(text, closing.end);
39-
if (bodyStart < bodyEnd) {
40-
depthChanges.set(bodyStart, (depthChanges.get(bodyStart) ?? 0) + 1);
41-
depthChanges.set(bodyEnd, (depthChanges.get(bodyEnd) ?? 0) - 1);
42-
}
43-
}
44-
let depth = 0;
45-
const lines = [];
46-
for (let start = 0; start < text.length; ) {
47-
depth += depthChanges.get(start) ?? 0;
48-
const end = afterLine(text, start);
49-
const line = text.slice(start, end);
50-
const prefix = " ".repeat(depth);
51-
if (headerLines.has(start)) {
52-
lines.push(line);
53-
} else if (line === prefix + "\n" || line === prefix + "\r\n") {
54-
lines.push(line.slice(prefix.length));
55-
} else {
56-
lines.push(
57-
line.startsWith(prefix) || line === "\n" || line === "\r\n" ? line : prefix + line,
58-
);
59-
}
60-
start = end;
13+
function applyEdits(text: string, edits: Uint32Array): string {
14+
const parts: string[] = [];
15+
let cursor = 0;
16+
for (let at = 0; at < edits.length; at += 3) {
17+
const start = edits[at]!;
18+
parts.push(text.slice(cursor, start), " ".repeat(edits[at + 2]!));
19+
cursor = start + edits[at + 1]!;
6120
}
62-
return lines.join("");
21+
return parts.join("") + text.slice(cursor);
6322
}
6423

6524
function scan(text: string, envelope: string) {
6625
const elements: SourceElement[] = [];
26+
const blocks: SourceRange[] = [];
6727
const unfinished: UnfinishedConstruct[] = [];
6828
const diagnostics: ScanDiagnostic[] = [];
6929
const fences: SourceFence[] = [];
@@ -81,14 +41,16 @@ function scan(text: string, envelope: string) {
8141
0,
8242
diagnostics,
8343
fences,
44+
blocks,
8445
);
8546
const openExecutableFences = new Set(
8647
fences
8748
.filter(({ executable, end }) => executable && end === "unfinished")
8849
.map(({ marker }) => startOfLine(text, marker)),
8950
);
9051
return {
91-
elements,
52+
headers: elements.map(({ opening }) => opening),
53+
blocks,
9254
segments,
9355
diagnostic: diagnostics[0],
9456
incomplete: unfinished.find(
@@ -129,17 +91,18 @@ export function formatSource(source: string): Result<string> {
12991
return Err(new Error(`Incomplete ${construct} at ${line}:${column}`));
13092
}
13193

132-
const formatted = proposeIndentation(text, before.elements);
133-
if (formatted === text) {
94+
const edits = indentationEdits(text, before.blocks, before.headers);
95+
if (edits.length === 0) {
13496
return Ok(source);
13597
}
98+
const formatted = applyEdits(text, edits);
13699
const after = scan(formatted, envelope);
137100
if (
138101
after.diagnostic !== undefined ||
139102
after.incomplete !== undefined ||
140103
JSON.stringify(withoutPositions(before.segments)) !==
141104
JSON.stringify(withoutPositions(after.segments)) ||
142-
proposeIndentation(formatted, after.elements) !== formatted
105+
indentationEdits(formatted, after.blocks, after.headers).length !== 0
143106
) {
144107
return Ok(source);
145108
}

‎packages/core/src/markdown.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,60 @@ const instance = new WebAssembly.Instance(
6565
const library = trackerExports(instance);
6666
const input = trackerInput(instance);
6767

68+
type Range = { readonly start: number; readonly end: number };
69+
70+
export function indentationEdits(
71+
source: string,
72+
blocks: readonly Range[],
73+
headers: readonly Range[],
74+
): Uint32Array {
75+
if (blocks.length === 0) {
76+
return new Uint32Array();
77+
}
78+
const {
79+
formatter_buffer_new: allocate,
80+
formatter_buffer_data: data,
81+
formatter_buffer_length: length,
82+
formatter_buffer_free: free,
83+
formatter_plan: plan,
84+
} = instance.exports;
85+
if (
86+
typeof allocate !== "function" ||
87+
typeof data !== "function" ||
88+
typeof length !== "function" ||
89+
typeof free !== "function" ||
90+
typeof plan !== "function"
91+
) {
92+
throw new Error("Invalid indentation formatter WASM exports");
93+
}
94+
const count = 1 + 2 * (blocks.length + headers.length);
95+
const text = library.tracker_input(source.length);
96+
try {
97+
const ranges = allocate(count);
98+
try {
99+
const units = new Uint16Array(library.memory.buffer, text, source.length);
100+
for (let at = 0; at < source.length; at++) {
101+
units[at] = source.charCodeAt(at);
102+
}
103+
const words = new Uint32Array(library.memory.buffer, data(ranges), count);
104+
words[0] = blocks.length;
105+
let at = 1;
106+
for (const list of [blocks, headers]) {
107+
for (const { start, end } of list) {
108+
words[at++] = start;
109+
words[at++] = end;
110+
}
111+
}
112+
plan(text, source.length, ranges);
113+
return new Uint32Array(library.memory.buffer, data(ranges), length(ranges)).slice();
114+
} finally {
115+
free(ranges);
116+
}
117+
} finally {
118+
library.tracker_input_free(text, source.length);
119+
}
120+
}
121+
68122
const NO_HEADER = 0xffffffff;
69123
function wasmTracker() {
70124
const state = library.tracker_new();

‎packages/core/src/scanner.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ export function scanSegments(
246246
depth = 0,
247247
diagnostics?: ScanDiagnostic[],
248248
fences?: SourceFence[],
249+
blocks?: SourceRange[],
249250
): Segment[] {
250251
const found: ScanDiagnostic[] = [];
251252
const lineStarts = computeLineStarts(text);
@@ -256,6 +257,7 @@ export function scanSegments(
256257
unfinished,
257258
diagnostics: found,
258259
fences,
260+
blocks,
259261
failedBodies: new Set(),
260262
proseTail: trailingInlineProse(text, lineStarts),
261263
unfinishedKeys: new Set(),
@@ -287,6 +289,7 @@ interface Walk {
287289
readonly unfinished?: UnfinishedConstruct[];
288290
readonly diagnostics?: ScanDiagnostic[];
289291
readonly fences?: SourceFence[];
292+
readonly blocks?: SourceRange[];
290293
readonly failedBodies?: Set<string>;
291294
readonly proseTail?: number;
292295
readonly unfinishedKeys?: Set<string>;
@@ -904,8 +907,10 @@ function parseComponentTag(
904907
}
905908
const children: Segment[] = [];
906909
const nestedFences: SourceFence[] | undefined = walk.fences === undefined ? undefined : [];
910+
const nestedBlocks: SourceRange[] | undefined = walk.blocks === undefined ? undefined : [];
911+
const closer = `</${name}>`;
907912
const childEnd = scanBody(
908-
{ ...walk, elements: nested, fences: nestedFences },
913+
{ ...walk, elements: nested, fences: nestedFences, blocks: nestedBlocks },
909914
block
910915
? {
911916
pos: opening.end,
@@ -914,7 +919,7 @@ function parseComponentTag(
914919
delimiterIndent: text.slice(text.lastIndexOf("\n", start - 1) + 1, start),
915920
}
916921
: { pos: openingEnd, depth, lineContent },
917-
`</${name}>`,
922+
closer,
918923
children,
919924
);
920925
if (childEnd === -1) {
@@ -938,11 +943,22 @@ function parseComponentTag(
938943
Object.freeze({
939944
name,
940945
opening: Object.freeze({ start, end: openingEnd }),
941-
closing: Object.freeze({ start: childEnd - `</${name}>`.length, end: childEnd }),
946+
closing: Object.freeze({ start: childEnd - closer.length, end: childEnd }),
942947
}),
943948
);
944949
elements.push(...nested);
945950
}
951+
if (walk.blocks !== undefined && nestedBlocks !== undefined) {
952+
if (block) {
953+
const closerStart = childEnd - closer.length;
954+
const line = text.lastIndexOf("\n", closerStart - 1) + 1;
955+
const end = beginsLine(text, line, closerStart)
956+
? line
957+
: Math.min(text.length, endOfLine(text, childEnd) + 1);
958+
walk.blocks.push({ start: opening.end, end });
959+
}
960+
walk.blocks.push(...nestedBlocks);
961+
}
946962
if (nestedFences !== undefined) {
947963
walk.fences?.push(...nestedFences);
948964
}

‎packages/core/tests/structural-indentation.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ import { useTempDirectory } from "@executablemd/test-support/temp";
2020
import { join } from "node:path";
2121
import { execute } from "../src/execute.ts";
2222
import { collect } from "../src/collect.ts";
23+
import { indentationEdits } from "../src/markdown.ts";
24+
import type { SourceRange } from "../src/document-targets.ts";
25+
import type { SourceElement } from "../src/scanner.ts";
2326
import { formatSource } from "../src/format-source.ts";
2427
import { scanSegments } from "../src/scanner.ts";
2528
import { asText } from "./helpers.ts";
@@ -385,6 +388,47 @@ describe("Formatter preservation", () => {
385388
expect(formatSource(passive)).toEqual({ ok: true, value: passive });
386389
});
387390

391+
it("plans exact UTF-16 edits without treating literal fence text as XMD", function* () {
392+
const lines = [
393+
"<Output>\n",
394+
"😀 body\n",
395+
" \r\n",
396+
"> ~~~xmd\n",
397+
"> <File />\n",
398+
"> 🌱 \n",
399+
"> ~~~\n",
400+
"</Output>",
401+
];
402+
const source = lines.join("");
403+
const elements: SourceElement[] = [];
404+
const blocks: SourceRange[] = [];
405+
scanSegments(
406+
source,
407+
undefined,
408+
undefined,
409+
elements,
410+
undefined,
411+
0,
412+
0,
413+
undefined,
414+
undefined,
415+
blocks,
416+
);
417+
expect(elements.map(({ name }) => name)).toEqual(["Output"]);
418+
expect(blocks).toEqual([{ start: 9, end: 54 }]);
419+
expect([
420+
...indentationEdits(
421+
source,
422+
blocks,
423+
elements.map(({ opening }) => opening),
424+
),
425+
]).toEqual([9, 0, 2, 17, 2, 0, 21, 0, 2, 30, 0, 2, 41, 0, 2, 48, 0, 2]);
426+
const expected =
427+
"<Output>\n 😀 body\n\r\n > ~~~xmd\n > <File />\n > 🌱 \n > ~~~\n</Output>";
428+
expect(formatSource(source)).toEqual({ ok: true, value: expected });
429+
expect(formatSource(expected)).toEqual({ ok: true, value: expected });
430+
});
431+
388432
it("keeps significant file whitespace and literal and executable fence payloads", function* () {
389433
const opening = '<File path="message.txt">\n';
390434
const closing = " </If>\n</File>";

‎packages/core/vendor/markdown-boundary/recipe.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22
"toolchain": "1.99.1",
33
"compilerCommit": "58cf8f9c35b355199727627d07ae34a4e2846d67",
44
"target": "wasm32-unknown-unknown",
5-
"wasmSha256": "303fa99c0173ea940d4a84cc078e8aff48fdb4b2a3a0acbb48cde4bde43e698e",
6-
"moduleSha256": "2e807d3c94ebdfa1813390c6055a3db33be447a88db4457aaccba61aaee6c9d9"
5+
"wasmSha256": "fb68d0695f2e75b1b799031d15e43de784a803c8eb218c757cfc9889dc2eeb55",
6+
"moduleSha256": "91a210cfaea38aaa96a72ade7df6102a55db670ddd87af86f4464ff126ab05ca"
77
}

0 commit comments

Comments
 (0)