@plannotator/sem-jiff 0.0.0-stage → 0.2.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE-APACHE +191 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +122 -2
  5. package/THIRD-PARTY-NOTICES +367 -0
  6. package/dist/candidate.d.ts +14 -0
  7. package/dist/candidate.js +1 -0
  8. package/dist/classifier.d.ts +25 -0
  9. package/dist/classifier.js +32 -0
  10. package/dist/copy-wasm-bin.d.ts +2 -0
  11. package/dist/copy-wasm-bin.js +11 -0
  12. package/dist/copy-wasm.d.ts +3 -0
  13. package/dist/copy-wasm.js +43 -0
  14. package/dist/coverage.d.ts +7 -0
  15. package/dist/coverage.js +43 -0
  16. package/dist/edits.d.ts +10 -0
  17. package/dist/edits.js +230 -0
  18. package/dist/extract.d.ts +5 -0
  19. package/dist/extract.js +24 -0
  20. package/dist/grammars.d.ts +22 -0
  21. package/dist/grammars.js +37 -0
  22. package/dist/index.d.ts +79 -0
  23. package/dist/index.js +581 -0
  24. package/dist/inline.d.ts +21 -0
  25. package/dist/inline.js +959 -0
  26. package/dist/languages.d.ts +2 -0
  27. package/dist/languages.js +28 -0
  28. package/dist/linediff.d.ts +28 -0
  29. package/dist/linediff.js +205 -0
  30. package/dist/opinions.d.ts +84 -0
  31. package/dist/opinions.js +201 -0
  32. package/dist/pairing.d.ts +10 -0
  33. package/dist/pairing.js +269 -0
  34. package/dist/parse.d.ts +119 -0
  35. package/dist/parse.js +1293 -0
  36. package/dist/pierre-types.d.ts +101 -0
  37. package/dist/pierre-types.js +5 -0
  38. package/dist/runtime.d.ts +48 -0
  39. package/dist/runtime.js +60 -0
  40. package/dist/structure.d.ts +23 -0
  41. package/dist/structure.js +1111 -0
  42. package/dist/summary.d.ts +19 -0
  43. package/dist/summary.js +15 -0
  44. package/dist/symbol-types.d.ts +18 -0
  45. package/dist/symbol-types.js +1 -0
  46. package/dist/symbols.d.ts +6 -0
  47. package/dist/symbols.js +458 -0
  48. package/dist/syntax.d.ts +69 -0
  49. package/dist/syntax.js +450 -0
  50. package/dist/textdiff.d.ts +15 -0
  51. package/dist/textdiff.js +64 -0
  52. package/dist/textmoves.d.ts +8 -0
  53. package/dist/textmoves.js +143 -0
  54. package/package.json +108 -4
  55. package/src/candidate.ts +10 -0
  56. package/src/grammars.ts +44 -0
  57. package/src/opinions.ts +271 -0
  58. package/wasm/SHA256SUMS +12 -0
  59. package/wasm/tree-sitter-c_sharp.wasm +0 -0
  60. package/wasm/tree-sitter-go.wasm +0 -0
  61. package/wasm/tree-sitter-java.wasm +0 -0
  62. package/wasm/tree-sitter-kotlin.wasm +0 -0
  63. package/wasm/tree-sitter-php.wasm +0 -0
  64. package/wasm/tree-sitter-python.wasm +0 -0
  65. package/wasm/tree-sitter-ruby.wasm +0 -0
  66. package/wasm/tree-sitter-rust.wasm +0 -0
  67. package/wasm/tree-sitter-swift.wasm +0 -0
  68. package/wasm/tree-sitter-tsx.wasm +0 -0
  69. package/wasm/tree-sitter-typescript.wasm +0 -0
  70. package/wasm/web-tree-sitter.wasm +0 -0
@@ -0,0 +1,1111 @@
1
+ import { brokenTree, isComment } from "./parse.js";
2
+ import { rule, trial } from "./runtime.js";
3
+ import { attachedAbove, codeLines, dice, endLine, keepWeights, longestInOrder, pairSameNamed, range, rangeOf, startLine } from "./syntax.js";
4
+ function leaves(n, cfg) {
5
+ const tokens = [];
6
+ const identifiers = [];
7
+ const comments = [];
8
+ // `seq` also records the tree's shape: equal tokens can still parse differently
9
+ // (`return x` vs `return` + newline + `x`, where an automatic semicolon or Go's
10
+ // newline rule changes the meaning), and formatting never changes the tree.
11
+ const seq = [];
12
+ // Iterative: very deep trees (generated or fuzzed code) would overflow the stack.
13
+ const stack = [n];
14
+ while (stack.length) {
15
+ const x = stack.pop();
16
+ if (x === null) {
17
+ seq.push('\u0003');
18
+ continue;
19
+ }
20
+ if (!x)
21
+ continue;
22
+ if (isComment(x)) {
23
+ comments.push(x.text.trim());
24
+ seq.push(x.text.trim());
25
+ continue;
26
+ }
27
+ const ts = cfg.id === 'typescript' || cfg.id === 'tsx';
28
+ if (ts && prettierOnly(x)) {
29
+ // Tokens a formatter adds or drops without changing the code: kept as tokens, left out of the shape.
30
+ if (x.childCount === 0)
31
+ tokens.push(x.text);
32
+ else
33
+ for (let i = x.childCount - 1; i >= 0; i--) {
34
+ const c = x.child(i);
35
+ if (c && c.isNamed)
36
+ stack.push(c);
37
+ else if (c)
38
+ tokens.push(c.text);
39
+ }
40
+ continue;
41
+ }
42
+ // A token the grammar calls missing on a correct tree is not part of the code.
43
+ if (x.isMissing && cfg.harmlessMissing?.has(x.type))
44
+ continue;
45
+ if (cfg.id === 'ruby' && rubyLayoutOnly(x))
46
+ continue;
47
+ if (x.childCount === 0) {
48
+ // A written `;` ending a JS/TS statement equals an inserted one; where the
49
+ // line break would split the statement differently, the tree shape differs.
50
+ const terminator = SAME_QUOTES.has(cfg.id) && cfg.id !== 'python' && x.type === ';' && x.parent?.lastChild?.startIndex === x.startIndex && /statement|declaration/.test(x.parent.type);
51
+ if (terminator)
52
+ tokens.push(x.text);
53
+ else if (x.text.length) {
54
+ tokens.push(x.text);
55
+ // Ruby's `{ ... }` block is `do ... end` (the tree already says which call each one belongs to).
56
+ if (cfg.id === 'ruby' && x.parent?.type === 'block' && (x.type === '{' || x.type === '}')) {
57
+ seq.push(x.type === '{' ? 'do' : 'end');
58
+ continue;
59
+ }
60
+ // 'a' and "a" are the same string where both quote styles mean the same (TS, Python), and in
61
+ // Ruby when the text holds no escape and no `#` (nothing a double quote would read differently).
62
+ seq.push((SAME_QUOTES.has(cfg.id) || (cfg.id === 'ruby' && rubyPlainString(x.parent))) && (x.text === "'" || x.text === '"') && x.parent?.type === 'string' ? '\u0004quote' : x.text);
63
+ }
64
+ else
65
+ seq.push(x.type === ';' ? ';' : `\u0001${x.type}`); // zero-width: an inserted semicolon equals a written one
66
+ if (cfg.identifierTypes.has(x.type) && !cfg.notAName?.(x))
67
+ identifiers.push(x);
68
+ // `return` (or `yield`, `break`, `continue`) and a line break ends the statement in
69
+ // JS/TS, whatever follows; the parser does not always show it (`return` + newline + JSX).
70
+ const next = x.nextSibling;
71
+ if ((cfg.id === 'typescript' || cfg.id === 'tsx') && /^(return|yield|break|continue)$/.test(x.type) && next && next.type !== ';' && next.startPosition.row > x.endPosition.row)
72
+ seq.push('\u0005break');
73
+ continue;
74
+ }
75
+ seq.push(`\u0002${cfg.id === 'ruby' ? (RUBY_SAME_NODE[x.type] ?? x.type) : x.type}`);
76
+ stack.push(null);
77
+ for (let i = x.childCount - 1; i >= 0; i--)
78
+ stack.push(x.child(i));
79
+ }
80
+ return { tokens, identifiers, comments, seq: withoutTrailingCommas(seq).join('\u0000') };
81
+ }
82
+ /**
83
+ * Formatter-only syntax in TypeScript/JavaScript, which Prettier adds or removes:
84
+ * - a leading `|` or `&` on a wrapped union or intersection type;
85
+ * - parentheses around a lone arrow parameter (`x => x` / `(x) => x`) and around JSX;
86
+ * - `;` or `,` separating interface, object-type and class members (a line break does the same).
87
+ * A wrapper node returns true to be walked through without its own marker or punctuation.
88
+ */
89
+ function prettierOnly(x) {
90
+ const p = x.parent;
91
+ if (x.childCount === 0) {
92
+ if ((x.type === '|' || x.type === '&') && p && /^(union_type|intersection_type)$/.test(p.type) && p.firstChild?.id === x.id)
93
+ return true;
94
+ if ((x.type === ';' || x.type === ',') && p && /^(object_type|interface_body|class_body)$/.test(p.type))
95
+ return true;
96
+ return false;
97
+ }
98
+ if (x.type === 'parenthesized_expression' && x.namedChildCount === 1 && /^jsx_/.test(x.namedChild(0)?.type ?? ''))
99
+ return true;
100
+ // `| 'a' | 'b'`: the leading bar wraps the first member in a union of its own.
101
+ if (/^(union_type|intersection_type)$/.test(x.type) && x.namedChildCount === 1 && /^[|&]$/.test(x.firstChild?.type ?? ''))
102
+ return true;
103
+ if (x.type === 'formal_parameters' && p?.type === 'arrow_function' && x.namedChildCount === 1) {
104
+ const only = x.namedChild(0);
105
+ if (only?.type === 'required_parameter' && only.namedChildCount === 1 && only.namedChild(0)?.type === 'identifier')
106
+ return true;
107
+ }
108
+ if (x.type === 'required_parameter' && p?.type === 'formal_parameters' && p.parent?.type === 'arrow_function' && p.namedChildCount === 1 && x.namedChildCount === 1 && x.namedChild(0)?.type === 'identifier')
109
+ return true;
110
+ return false;
111
+ }
112
+ /**
113
+ * Ruby syntax that only lays code out: `;` (a line break does the same), the optional `then` and
114
+ * loop `do` keywords, and the parentheses of an argument list when no block is attached
115
+ * (`log(message)` / `log message`). The tree's shape is still compared.
116
+ */
117
+ function rubyLayoutOnly(x) {
118
+ if (x.childCount !== 0 || x.isNamed)
119
+ return false;
120
+ const p = x.parent;
121
+ if (x.type === ';')
122
+ return true;
123
+ if (x.type === 'then' && p?.type === 'then')
124
+ return true;
125
+ if (x.type === 'do' && p?.type === 'do')
126
+ return true;
127
+ if ((x.type === '(' || x.type === ')') && p?.type === 'argument_list')
128
+ return !p.parent?.childForFieldName('block');
129
+ return false;
130
+ }
131
+ /** A Ruby string literal whose text reads the same in single and double quotes. */
132
+ const rubyPlainString = (s) => !!s && s.type === 'string' && s.namedChildren.every((c) => c?.type === 'string_content') && !/[\\#]/.test(s.text.slice(1, -1));
133
+ /** Ruby node types that mean the same: a `{ ... }` block and a `do ... end` block, with their bodies. */
134
+ const RUBY_SAME_NODE = { block: 'do_block', block_body: 'body_statement' };
135
+ /**
136
+ * A comma right before a closing bracket changes nothing (formatters add one when
137
+ * they wrap a list vertically). A Python one-element tuple `(a,)` still differs
138
+ * from `(a)`: it parses as a different node.
139
+ */
140
+ const SAME_QUOTES = new Set(['typescript', 'tsx', 'python']);
141
+ function withoutTrailingCommas(seq) {
142
+ return seq.filter((t, i) => {
143
+ if (t !== ',')
144
+ return true;
145
+ let j = i + 1;
146
+ while (seq[j] === '\u0003')
147
+ j++;
148
+ return !(seq[j] === ')' || seq[j] === ']' || seq[j] === '}' || seq[j] === '>');
149
+ });
150
+ }
151
+ /**
152
+ * The words no token holds: the text inside a node between its children (a Python string's content around an
153
+ * escape sequence, `"a \\n b"` holds only `\\n` as a token). Words only (letters, digits, `_`), so wrapping and
154
+ * spacing change nothing and any changed word does; symbols there are mostly layout the grammar leaves out of the
155
+ * tree (Swift's optional `;`, Rust's raw-string `#`). Comments are whole tokens already.
156
+ */
157
+ function gapWords(n) {
158
+ const out = [];
159
+ const stack = [n];
160
+ while (stack.length) {
161
+ const x = stack.pop();
162
+ if (x.childCount === 0 || isComment(x))
163
+ continue;
164
+ const text = x.text;
165
+ let at = x.startIndex;
166
+ const gap = (end) => {
167
+ if (end > at)
168
+ out.push(...(text.slice(at - x.startIndex, end - x.startIndex).match(/[\p{L}\p{N}_]+/gu) ?? []));
169
+ };
170
+ const kids = x.children.filter((c) => !!c);
171
+ for (const c of kids) {
172
+ gap(c.startIndex);
173
+ at = Math.max(at, c.endIndex);
174
+ }
175
+ gap(x.endIndex);
176
+ for (let i = kids.length - 1; i >= 0; i--)
177
+ stack.push(kids[i]);
178
+ }
179
+ return out.join('\u0000');
180
+ }
181
+ const declGapWords = (d) => gapWords(d.node) + (d.tail ? '\u0001' + gapWords(d.tail) : '');
182
+ /** A declaration's text, through its tail (a Ruby heredoc body after it). */
183
+ const declText = (d, source) => (d.tail ? source.slice(d.node.startIndex, d.tail.endIndex) : d.node.text);
184
+ /** Last line of a declaration, through its tail. */
185
+ const declEnd = (d) => endLine(d.tail ?? d.node);
186
+ function declLeaves(d, cfg) {
187
+ const a = leaves(d.node, cfg);
188
+ if (!d.tail)
189
+ return a;
190
+ const b = leaves(d.tail, cfg);
191
+ return { tokens: [...a.tokens, ...b.tokens], identifiers: [...a.identifiers, ...b.identifiers], comments: [...a.comments, ...b.comments], seq: a.seq + '\u0000' + b.seq };
192
+ }
193
+ const reopens = (cfg, d) => (cfg.id === 'ruby' && /^(class|module|singleton_class)$/.test(d.kind)) || !!cfg.typeOf?.(d);
194
+ function collect(root, cfg) {
195
+ const out = [];
196
+ const source = root.text;
197
+ const seen = new Map();
198
+ const visit = (container, parent, holder) => {
199
+ for (const decl of cfg.declarationsIn(container)) {
200
+ // Getters/setters share a name; so can overloads. Number repeats so keys stay unique.
201
+ const accessor = decl.node.children.find((c) => c?.type === 'get' || c?.type === 'set')?.type ?? '';
202
+ const base = `${parent}/${decl.kind}:${accessor}${decl.name}`;
203
+ const n = seen.get(base) ?? 0;
204
+ seen.set(base, n + 1);
205
+ const key = n ? `${base}#${n}` : base;
206
+ // A Ruby class reopened in the file (`class Foo` twice) is one class: its members share one scope.
207
+ // A Swift type and its extensions in the file are one type: their members share one scope.
208
+ const scope = cfg.typeOf?.(decl) ? `${parent}/type:${cfg.typeOf(decl)}` : reopens(cfg, decl) ? base : key;
209
+ const e = { decl, key, base: `${decl.kind}:${accessor}${decl.name}`, parent, text: declText(decl, source), ...declLeaves(decl, cfg), scope, holder };
210
+ out.push(e);
211
+ if (decl.members)
212
+ visit(decl.members, scope, e);
213
+ }
214
+ };
215
+ visit(root, '', null);
216
+ return out;
217
+ }
218
+ /**
219
+ * Trial EXT_BY_MEMBERS. For deciding which members crossed into another container, the containers of one type (Swift
220
+ * extensions) whose header pairing is missing or ambiguous pair by where their paired members went: an extension whose
221
+ * header changed (`_RopeElement` -> `RopeElement`, a conformance added), or two extensions with one header, are still
222
+ * the container their members stayed in. A container with a header found once on each side keeps its pairing, so a
223
+ * member moved from the type's body into a new extension still crossed. Among the open containers of one type and
224
+ * kind, the old and new ones holding the most paired members in common pair first, one to one (ties: the pairing by
225
+ * header, then file order); an open container left over keeps its pairing by header if that partner is still free.
226
+ * Only `holders` changes.
227
+ */
228
+ function pairContainersByMembers(pairs, olds, news, holders, cfg) {
229
+ const isContainer = (e) => !!cfg.typeOf(e.decl);
230
+ const oldC = olds.filter(isContainer);
231
+ const newC = news.filter(isContainer);
232
+ const count = (list) => {
233
+ const m = new Map();
234
+ for (const e of list)
235
+ m.set(`${e.parent}\u0000${e.base}`, (m.get(`${e.parent}\u0000${e.base}`) ?? 0) + 1);
236
+ return (e) => m.get(`${e.parent}\u0000${e.base}`) ?? 0;
237
+ };
238
+ const inOld = count(oldC);
239
+ const inNew = count(newC);
240
+ const byHeader = new Map(oldC.flatMap((e) => (holders.has(e) ? [[e, holders.get(e)]] : [])));
241
+ const pairedNew = new Set(byHeader.values());
242
+ const ambiguous = (e) => inOld(e) > 1 || inNew(e) > 1;
243
+ const openOld = new Set(oldC.filter((e) => !byHeader.has(e) || ambiguous(e) || ambiguous(byHeader.get(e))));
244
+ const openNew = new Set(newC.filter((e) => !pairedNew.has(e) || ambiguous(e)));
245
+ for (const [a, b] of byHeader)
246
+ if (openOld.has(a))
247
+ openNew.add(b);
248
+ const typeKey = (e) => `${e.parent}\u0000${e.decl.kind}\u0000${cfg.typeOf(e.decl)}`;
249
+ const flow = new Map();
250
+ for (const [a, b] of pairs) {
251
+ const ha = a.holder;
252
+ const hb = b.holder;
253
+ if (!ha || !hb || !openOld.has(ha) || !openNew.has(hb) || typeKey(ha) !== typeKey(hb))
254
+ continue;
255
+ const m = flow.get(ha) ?? new Map();
256
+ m.set(hb, (m.get(hb) ?? 0) + 1);
257
+ flow.set(ha, m);
258
+ }
259
+ if (!flow.size)
260
+ return;
261
+ const order = new Map([...olds, ...news].map((e, i) => [e, i]));
262
+ const cand = [];
263
+ for (const [ha, m] of flow)
264
+ for (const [hb, n] of m)
265
+ cand.push([n, byHeader.get(ha) === hb ? 1 : 0, ha, hb]);
266
+ cand.sort((x, y) => y[0] - x[0] || y[1] - x[1] || order.get(x[2]) - order.get(y[2]) || order.get(x[3]) - order.get(y[3]));
267
+ const usedNew = new Set();
268
+ const result = new Map();
269
+ for (const [, , ha, hb] of cand) {
270
+ if (result.has(ha) || usedNew.has(hb))
271
+ continue;
272
+ result.set(ha, hb);
273
+ usedNew.add(hb);
274
+ }
275
+ for (const ha of openOld) {
276
+ if (result.has(ha))
277
+ continue;
278
+ const hb = byHeader.get(ha);
279
+ if (hb && !usedNew.has(hb)) {
280
+ result.set(ha, hb);
281
+ usedNew.add(hb);
282
+ }
283
+ }
284
+ for (const ha of openOld) {
285
+ const hb = result.get(ha);
286
+ if (hb)
287
+ holders.set(ha, hb);
288
+ else
289
+ holders.delete(ha);
290
+ }
291
+ }
292
+ /**
293
+ * If `a` becomes `b` by consistently swapping identifiers (each old name maps to
294
+ * exactly one new name), return that mapping; otherwise null.
295
+ */
296
+ function identifierSubstitution(a, b) {
297
+ if (a.tokens.length !== b.tokens.length)
298
+ return null;
299
+ const ids = new Set(a.identifiers.map((n) => n.text));
300
+ const map = new Map();
301
+ for (let i = 0; i < a.tokens.length; i++) {
302
+ const x = a.tokens[i];
303
+ const y = b.tokens[i];
304
+ if (x === y)
305
+ continue;
306
+ if (!ids.has(x))
307
+ return null;
308
+ const prev = map.get(x);
309
+ if (prev !== undefined && prev !== y)
310
+ return null;
311
+ map.set(x, y);
312
+ }
313
+ return map;
314
+ }
315
+ /** The statements inside a declaration that hold no block of their own, in order, plus its first line. */
316
+ function simpleStatements(decl, cfg) {
317
+ const out = [];
318
+ const isBlock = (n) => /block|body|suite|^statements$/.test(n.type);
319
+ const walk = (n) => {
320
+ // Returns whether `n` holds a block; statements of a block that hold none are collected.
321
+ let holds = false;
322
+ for (const c of n.namedChildren) {
323
+ if (!c)
324
+ continue;
325
+ const inner = walk(c);
326
+ if (isBlock(n) && !inner && !isBlock(c) && !isComment(c))
327
+ out.push(c);
328
+ holds ||= inner || isBlock(c);
329
+ }
330
+ return holds;
331
+ };
332
+ walk(decl);
333
+ out.sort((x, y) => x.startIndex - y.startIndex);
334
+ return out.map((c) => ({ ...leaves(c, cfg), decl: { node: c, kind: 'statement', name: '' } }));
335
+ }
336
+ /** Whole lines of a declaration, from the start of its first line to the start of the line after it. */
337
+ const lineRange = (n) => range({ line: startLine(n), character: 0 }, { line: endLine(n) + 1, character: 0 });
338
+ /** Lines that differ between two texts once their common first and last lines are set aside (1-based, relative). */
339
+ function changedLines(a, b) {
340
+ const la = a.split('\n');
341
+ const lb = b.split('\n');
342
+ let head = 0;
343
+ while (head < la.length && head < lb.length && la[head] === lb[head])
344
+ head++;
345
+ let tail = 0;
346
+ while (tail < la.length - head && tail < lb.length - head && la[la.length - 1 - tail] === lb[lb.length - 1 - tail])
347
+ tail++;
348
+ return { old: { start: head + 1, end: la.length - tail }, new: { start: head + 1, end: lb.length - tail } };
349
+ }
350
+ /**
351
+ * `keptLines` (trial DUP_TIEBREAK): the line diff's unchanged lines, old line to new line. Equally similar same-named
352
+ * declarations pair first where the line diff keeps one unchanged in place.
353
+ */
354
+ export function detectStructure(oldRoot, newRoot, cfg, keptLines) {
355
+ const olds = collect(oldRoot, cfg);
356
+ const news = collect(newRoot, cfg);
357
+ const pairs = [];
358
+ const usedOld = new Set();
359
+ const usedNew = new Set();
360
+ // Pair level by level: top-level declarations, then the members of each paired
361
+ // class, so members pair only with members of the matching class.
362
+ const byParentKey = (list) => {
363
+ const m = new Map();
364
+ for (const e of list)
365
+ m.set(e.parent, [...(m.get(e.parent) ?? []), e]);
366
+ return m;
367
+ };
368
+ const oldKids = byParentKey(olds);
369
+ const newKids = byParentKey(news);
370
+ // Where one type spreads over several containers (Swift extensions), repeated containers pair by
371
+ // which members they hold, not by their code: a long method moved from one to the other would
372
+ // otherwise pull the pairing across.
373
+ const held = new Map();
374
+ for (const e of [...olds, ...news])
375
+ if (e.holder)
376
+ held.set(e.holder, [...(held.get(e.holder) ?? []), e.base]);
377
+ const similarBy = (e) => (cfg.typeOf?.(e.decl) ? (held.get(e) ?? []) : [...(attachedAbove(e.decl.node, cfg.attachedTypes).match(/\S+/g) ?? []), ...e.tokens]);
378
+ const levels = new Set();
379
+ const pairLevel = (oldParent, newParent) => {
380
+ // Reopenings of one Ruby class, or the containers of one Swift type, share a scope: its members pair once.
381
+ const level = `${oldParent}\u0000${newParent}`;
382
+ if (levels.has(level))
383
+ return;
384
+ levels.add(level);
385
+ const inPlace = keptLines ? (a, b) => keptLines.get(startLine(a.decl.node)) === startLine(b.decl.node) : undefined;
386
+ for (const [a, b] of pairSameNamed(oldKids.get(oldParent) ?? [], newKids.get(newParent) ?? [], (e) => e.base, similarBy, inPlace)) {
387
+ pairs.push([a, b]);
388
+ usedOld.add(a);
389
+ usedNew.add(b);
390
+ if (a.decl.members && b.decl.members)
391
+ pairLevel(a.scope, b.scope);
392
+ }
393
+ };
394
+ pairLevel('', '');
395
+ // Renamed declarations: same container and kind, identical apart from consistently swapped names.
396
+ for (const a of olds) {
397
+ if (usedOld.has(a))
398
+ continue;
399
+ // Trial IMPORT_NO_RENAME: an import names something else when its last segment changes
400
+ // (`runtime.ReadOnlyComposable` -> `runtime.currentComposer`): two imports are never one renamed declaration.
401
+ if (a.decl.kind === 'import' && trial('IMPORT_NO_RENAME'))
402
+ continue;
403
+ for (const b of news) {
404
+ if (usedNew.has(b) || b.parent !== a.parent || b.decl.kind !== a.decl.kind)
405
+ continue;
406
+ const sub = identifierSubstitution(a, b);
407
+ // The declared name changes, plus at most one other name: more than that is a different declaration.
408
+ // A short declaration (`type Path string`) has too little else to go on: only its name may change.
409
+ const limit = a.tokens.length >= 12 ? 2 : 1;
410
+ // The other name must be the declaration's own (a parameter or local renamed along);
411
+ // `getWidth` -> `getHeight` reading `r.width` -> `r.height` is a different function.
412
+ const own = (x) => a.identifiers.some((id) => id.text === x && isDeclarationName(id));
413
+ const declared = a.decl.name.split('.').at(-1);
414
+ if (sub && sub.get(declared) !== undefined && sub.size <= limit && [...sub.keys()].every((x) => x === declared || own(x))) {
415
+ pairs.push([a, b]);
416
+ usedOld.add(a);
417
+ usedNew.add(b);
418
+ break;
419
+ }
420
+ }
421
+ }
422
+ const operations = [];
423
+ const folds = [];
424
+ // Moves: within each container, keep the longest run that stayed in order.
425
+ const moved = new Set();
426
+ const byParent = new Map();
427
+ for (const p of pairs)
428
+ if (p[0].parent === p[1].parent)
429
+ byParent.set(p[0].parent, [...(byParent.get(p[0].parent) ?? []), p]);
430
+ const holders = new Map(pairs);
431
+ if (cfg.typeOf && trial('EXT_BY_MEMBERS'))
432
+ pairContainersByMembers(pairs, olds, news, holders, cfg);
433
+ for (const group of byParent.values()) {
434
+ const ordered = [...group].sort((p, q) => p[0].decl.node.startIndex - q[0].decl.node.startIndex);
435
+ // A member now in another reopening of its Ruby class, or another container of its Swift type, moved, whatever the order says.
436
+ const crossed = (p) => !!p[0].holder && reopens(cfg, p[0].holder.decl) && holders.get(p[0].holder) !== p[1].holder;
437
+ const stay = ordered.map((p, i) => i).filter((i) => !crossed(ordered[i]));
438
+ const starts = stay.map((i) => ordered[i][1].decl.node.startIndex);
439
+ const inOrder = longestInOrder(starts, keepWeights(starts, stay.map((i) => codeLines(ordered[i][0].decl, cfg)), cfg.moveEditedFirst ? stay.map((i) => ordered[i][0].text === ordered[i][1].text) : undefined));
440
+ const keep = new Set([...inOrder].map((k) => stay[k]));
441
+ ordered.forEach(([a, b], i) => {
442
+ if (keep.has(i))
443
+ return;
444
+ moved.add(a);
445
+ const na = a.decl.node;
446
+ const nb = b.decl.node;
447
+ if (cfg.marksOf && cfg.marksOf(na) !== cfg.marksOf(nb))
448
+ return;
449
+ // The doc comment directly above a declaration moves with it.
450
+ const da = docStart(na, cfg);
451
+ const db = docStart(nb, cfg);
452
+ const same = a.seq === b.seq && docText(na, da, cfg) === docText(nb, db, cfg);
453
+ const pair = { old: { start: da, end: declEnd(a.decl) }, new: { start: db, end: declEnd(b.decl) } };
454
+ const index = operations.push({
455
+ type: same ? 'moved' : 'movedWithEdit',
456
+ spans: [
457
+ {
458
+ role: 'root',
459
+ relation: 'moved',
460
+ old: [range({ line: da, character: 0 }, { line: declEnd(a.decl) + 1, character: 0 })],
461
+ new: [range({ line: db, character: 0 }, { line: declEnd(b.decl) + 1, character: 0 })],
462
+ linePairs: [pair],
463
+ },
464
+ ],
465
+ lines: { old: [{ ...pair.old, spanIndex: 0 }], new: [{ ...pair.new, spanIndex: 0 }] },
466
+ }) - 1;
467
+ if (same) {
468
+ const n = pair.old.end - pair.old.start + 1;
469
+ folds.push({ old: pair.old, operations: [index], counts: { moved: n, edited: 0, removed: 0 } });
470
+ }
471
+ });
472
+ }
473
+ // Renames: merge every consistent substitution; keep names that never conflict.
474
+ const renames = new Map();
475
+ const conflicted = new Set();
476
+ // Top-level statements that declare nothing (`test('...', () => { ... })`, `app.get(...)`)
477
+ // hold code too: pair them in order, when alike, as a source of renames only.
478
+ const loose = (root, list) => {
479
+ const declared = new Set(list.map((e) => e.decl.node.startIndex));
480
+ return root.namedChildren
481
+ .filter((c) => !!c && !isComment(c) && !declared.has(c.startIndex))
482
+ .map((c) => ({ ...leaves(c, cfg), decl: { node: c, kind: 'statement', name: '' } }));
483
+ };
484
+ const looseOld = loose(oldRoot, olds);
485
+ const looseNew = loose(newRoot, news);
486
+ const loosePairs = [];
487
+ let from = 0;
488
+ for (const a of looseOld) {
489
+ for (let j = from; j < Math.min(looseNew.length, from + 5); j++) {
490
+ const b = looseNew[j];
491
+ if (b.tokens.length === a.tokens.length && identifierSubstitution(a, b)) {
492
+ loosePairs.push([a, b]);
493
+ from = j + 1;
494
+ break;
495
+ }
496
+ }
497
+ }
498
+ // A paired declaration that was also edited (`rate` -> `taxRate` in a function whose discount
499
+ // changed too) does not read the same as a whole, but its statements still can: pair them in
500
+ // order, when alike, as a source of renames only. Which lines a rename may own is decided
501
+ // below, line by line; a line that changed in any other way stays an edit.
502
+ const innerPairs = [];
503
+ if (rule('INNER_RENAMES')) {
504
+ for (const [a, b] of pairs) {
505
+ if (a.decl.members || a.seq === b.seq || identifierSubstitution(a, b))
506
+ continue;
507
+ const sa = simpleStatements(a.decl.node, cfg);
508
+ const sb = simpleStatements(b.decl.node, cfg);
509
+ let at = 0;
510
+ for (const x of sa) {
511
+ for (let j = at; j < Math.min(sb.length, at + 5); j++) {
512
+ const y = sb[j];
513
+ if (y.tokens.length === x.tokens.length && identifierSubstitution(x, y)) {
514
+ innerPairs.push([x, y]);
515
+ at = j + 1;
516
+ break;
517
+ }
518
+ }
519
+ }
520
+ }
521
+ }
522
+ // Names whose only evidence is a statement inside an edited declaration.
523
+ const innerOnly = new Set();
524
+ const inner = new Set(innerPairs);
525
+ for (const pair of [...pairs, ...loosePairs, ...innerPairs]) {
526
+ const [a, b] = pair;
527
+ // Classes and interfaces are judged through their members, which are paired on their own.
528
+ if (a.decl.members)
529
+ continue;
530
+ const sub = identifierSubstitution(a, b);
531
+ if (!sub)
532
+ continue;
533
+ for (const [x, y] of sub) {
534
+ if (inner.has(pair)) {
535
+ // Never against what whole declarations say, and new names only.
536
+ if (renames.has(x))
537
+ continue;
538
+ innerOnly.add(x);
539
+ }
540
+ if (renames.has(x) && renames.get(x) !== y)
541
+ conflicted.add(x);
542
+ renames.set(x, y);
543
+ }
544
+ }
545
+ const oldIndex = renames.size ? identifierIndex(oldRoot, cfg) : new Map();
546
+ const newIndex = renames.size ? identifierIndex(newRoot, cfg) : new Map();
547
+ // Each use must stay inside the same declaration: a use in a deleted function
548
+ // and one in an unrelated new function only look alike by position.
549
+ const partner = new Map(pairs);
550
+ const innermost = (list, n) => {
551
+ let best = null;
552
+ for (const e of list) {
553
+ const d = e.decl.node;
554
+ if (d.startIndex <= n.startIndex && n.endIndex <= d.endIndex && (!best || d.startIndex >= best.decl.node.startIndex))
555
+ best = e;
556
+ }
557
+ return best;
558
+ };
559
+ const accepted = new Map();
560
+ const guards = trial('RENAME_GUARDS');
561
+ for (const [from, to] of renames) {
562
+ if (conflicted.has(from))
563
+ continue;
564
+ // A renamed name is gone afterwards and its new name was not there before.
565
+ // Otherwise names only shifted against each other (one item deleted from
566
+ // a list and another added further down pairs every name in between).
567
+ // A variable and a property spelled the same are different things: renaming a
568
+ // local `name` does not rename `user.name`. Only uses of the declared kind count.
569
+ const declKinds = new Set((oldIndex.get(from) ?? []).filter(isDeclarationName).map(kindOf));
570
+ const sameKind = (ids) => (ids ?? []).filter((n) => declKinds.has(kindOf(n)));
571
+ if (sameKind(newIndex.get(from)).length || sameKind(oldIndex.get(to)).length)
572
+ continue;
573
+ // A field's uses are those reached through its own type (`this.value`, `opts.headers`
574
+ // with `opts: RequestOptions`), not the same-named property of another object
575
+ // (`input.value`, `document.title`, a `{ headers }` key passed to fetch).
576
+ const ownUses = (ids, index) => {
577
+ const decl = ids.find(isDeclarationName);
578
+ const owner = decl ? ownerTypeName(decl) : null;
579
+ return owner === null ? ids : ids.filter((n) => isDeclarationName(n) || reachedThrough(n, owner, index));
580
+ };
581
+ const oldIds = ownUses(sameKind(oldIndex.get(from)), oldIndex);
582
+ const newIds = ownUses(sameKind(newIndex.get(to)), newIndex);
583
+ if (guards) {
584
+ // Trial RENAME_GUARDS, targeted: renames where the name now stands for something else.
585
+ // A Ruby global (`$stdout` -> `$stderr`) is never declared here: switching it switches what the code talks to.
586
+ if (cfg.id === 'ruby' && from.startsWith('$'))
587
+ continue;
588
+ }
589
+ // Every occurrence must have a counterpart, or this is not a clean rename.
590
+ if (!oldIds.length || oldIds.length !== newIds.length)
591
+ continue;
592
+ // A name used once (`Once` -> `OnceExit`) is a different thing, not a rename.
593
+ if (oldIds.length < 2)
594
+ continue;
595
+ // A rename changes a name declared in this file; swapping one property access
596
+ // (`user.email` -> `user.mail`) is an edit, not a rename.
597
+ if (!oldIds.some(isDeclarationName))
598
+ continue;
599
+ // A field or parameter that also changed type was replaced, not renamed
600
+ // (`toPath func(string) Path` -> `caseSensitivity CaseSensitivity`).
601
+ if (oldIds.some((o, i) => isDeclarationName(o) && declaredTypeChanged(o, newIds[i], from, to)))
602
+ continue;
603
+ if (guards) {
604
+ // A parameter that changed place in its list is another parameter (`{ (a, b) in }` -> `{ (b, a) in }`).
605
+ if (oldIds.some((o, i) => { if (!isDeclarationName(o))
606
+ return false; const a = parameterIndex(o); const b = parameterIndex(newIds[i]); return a !== null && b !== null && a !== b; }))
607
+ continue;
608
+ // A value built from another class (`networkObserver = NetworkObserver(...)` -> `systemCallbacks = SystemCallbacks(...)`)
609
+ // was replaced, unless that class was renamed too.
610
+ if (oldIds.some((o, i) => isDeclarationName(o) && constructedTypeChanged(o, newIds[i], renames, cfg)))
611
+ continue;
612
+ }
613
+ // A declaration renamed and also edited is not paired, but is still this rename's own declaration.
614
+ const counterpartOf = (e) => partner.get(e) ?? (e.decl.name.split('.').at(-1) === from ? news.find((x) => x.parent === e.parent && x.decl.kind === e.decl.kind && x.decl.name === e.decl.name.replace(new RegExp(`${from}$`), to)) : undefined);
615
+ if (oldIds.some((o, i) => { const e = innermost(olds, o); const f = innermost(news, newIds[i]); return e ? counterpartOf(e) !== f : f !== null; }))
616
+ continue;
617
+ accepted.set(from, { oldIds, newIds });
618
+ }
619
+ // A name found only inside an edited declaration is a rename when the thing named is plainly the
620
+ // same: a variable or parameter whose own declaration reads the same apart from renames. A new
621
+ // name bound to something else (`typeChecker` -> `typeCheckerUtils`, another service; `entityTasks`
622
+ // -> `openTasks`, now a count) is a replacement; so is a function whose body also changed.
623
+ const declarationOf = (id) => {
624
+ let p = id.parent;
625
+ while (p.parent && /pattern$|_list$/.test(p.type))
626
+ p = p.parent;
627
+ return p;
628
+ };
629
+ // Only a rename's own uses may differ: `logDirs = config.logDirs()` -> `absoluteLogDirs =
630
+ // config.absoluteLogDirs()` also calls another method, spelled like the variable.
631
+ const sameDeclaration = (o, n) => {
632
+ const d = declarationOf(o);
633
+ const a = leaves(d, cfg).tokens;
634
+ const b = leaves(declarationOf(n), cfg).tokens;
635
+ if (a.length !== b.length)
636
+ return false;
637
+ const swapped = new Map();
638
+ for (let i = 0; i < a.length; i++) {
639
+ const t = a[i];
640
+ if (t === b[i])
641
+ continue;
642
+ if (!accepted.has(t) || renames.get(t) !== b[i])
643
+ return false;
644
+ // A name after a dot is another object's member, whatever the grammar calls it.
645
+ if (i > 0 && /^(\.|->|::|\?\.|&\.)$/.test(a[i - 1]))
646
+ return false;
647
+ swapped.set(t, (swapped.get(t) ?? 0) + 1);
648
+ }
649
+ for (const [t, count] of swapped) {
650
+ const own = accepted.get(t).oldIds.filter((id) => d.startIndex <= id.startIndex && id.endIndex <= d.endIndex).length;
651
+ if (own !== count)
652
+ return false;
653
+ }
654
+ return true;
655
+ };
656
+ const NOT_A_VARIABLE = /function|method|class|interface|struct|enum|trait|constructor|type_alias|impl/;
657
+ // Until nothing more is dropped: a declaration may lean on another rename that is dropped later.
658
+ for (let dropped = true; dropped;) {
659
+ dropped = false;
660
+ for (const [from, { oldIds, newIds }] of [...accepted]) {
661
+ if (!innerOnly.has(from))
662
+ continue;
663
+ if (oldIds.some((o, i) => isDeclarationName(o) && (NOT_A_VARIABLE.test(o.parent.type) || !sameDeclaration(o, newIds[i])))) {
664
+ accepted.delete(from);
665
+ dropped = true;
666
+ }
667
+ }
668
+ }
669
+ // A line belongs to a rename only when renaming is its only change; a line
670
+ // that also changed behaviour (`n < LIMIT` -> `n <= MAX`) stays a plain edit.
671
+ // A shorthand key (`{ timeout }` -> `{ delay }`) also renames an object key.
672
+ const oldText = oldRoot.text.split('\n');
673
+ const newText = newRoot.text.split('\n');
674
+ const words = (l) => l.match(/[\p{L}\p{N}_$]+|\S/gu) ?? [];
675
+ // The check swaps exactly the rename's own uses on the line, not every word spelled the same.
676
+ const usesOnLine = new Map();
677
+ for (const [from, { oldIds }] of accepted) {
678
+ for (const o of oldIds) {
679
+ if (o.startPosition.row !== o.endPosition.row)
680
+ continue;
681
+ const l = startLine(o);
682
+ usesOnLine.set(l, [...(usesOnLine.get(l) ?? []), { col: o.startPosition.column, len: o.endPosition.column - o.startPosition.column, to: renames.get(from) }]);
683
+ }
684
+ }
685
+ const swapped = (l) => {
686
+ let line = oldText[l - 1] ?? '';
687
+ for (const u of [...(usesOnLine.get(l) ?? [])].sort((x, y) => y.col - x.col))
688
+ line = line.slice(0, u.col) + u.to + line.slice(u.col + u.len);
689
+ return line;
690
+ };
691
+ const clean = (o, n) => !SHORTHAND.has(o.type) && words(swapped(startLine(o))).join(' ') === words(newText[startLine(n) - 1] ?? '').join(' ');
692
+ // An import alias stands for what it imports: when the import itself changed
693
+ // (`debounce as d` -> `throttle as t`), its uses call something else.
694
+ for (const [from, { oldIds, newIds }] of [...accepted]) {
695
+ if (oldIds.some((o, i) => /import|use_/.test(o.parent?.type ?? '') && isDeclarationName(o) && !clean(o, newIds[i])))
696
+ accepted.delete(from);
697
+ }
698
+ // Renames that share a line are one operation, one span per name, so none of them loses its lines to another.
699
+ const group = new Map();
700
+ const root = (k) => (group.get(k) === k ? k : root(group.get(k)));
701
+ const lineOwner = new Map();
702
+ const kept = new Map();
703
+ // Trial RENAME_GUARDS: a function renamed whose body is mostly new (the old helper deleted, a different one called
704
+ // instead) was replaced, not renamed: fewer than half the names in its body alike, renames applied.
705
+ if (guards) {
706
+ for (const [from, { oldIds, newIds }] of [...accepted]) {
707
+ if (innerOnly.has(from))
708
+ continue;
709
+ if (oldIds.some((o, i) => {
710
+ if (!isDeclarationName(o) || !/function|method|constructor/.test(o.parent.type))
711
+ return false;
712
+ const ba = cfg.bodyOf(o.parent);
713
+ const bb = cfg.bodyOf(newIds[i].parent);
714
+ if (!ba || !bb)
715
+ return false;
716
+ const names = (n) => leaves(n, cfg).tokens.filter((t) => /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(t));
717
+ return dice(names(ba).map((t) => renames.get(t) ?? t), names(bb)) < 0.5;
718
+ }))
719
+ accepted.delete(from);
720
+ }
721
+ }
722
+ // Trial RENAME_GUARDS: a use whose only other change is a negation (`hasRowID = !x` -> `isWithoutRowID = x`,
723
+ // `.hasRowID` -> `.isWithoutRowID == false`) shows the name now means the opposite: no rename at all.
724
+ if (guards) {
725
+ for (const [from, { oldIds, newIds }] of [...accepted]) {
726
+ if (oldIds.some((o, i) => negatedOnly(words(swapped(startLine(o))), words(newText[startLine(newIds[i]) - 1] ?? ''))))
727
+ accepted.delete(from);
728
+ }
729
+ }
730
+ for (const [from, { oldIds, newIds }] of accepted) {
731
+ const occ = oldIds.map((o, i) => [o, newIds[i]]).filter(([o, n]) => clean(o, n));
732
+ if (!occ.length)
733
+ continue;
734
+ kept.set(from, occ);
735
+ group.set(from, from);
736
+ for (const [o] of occ) {
737
+ const other = lineOwner.get(startLine(o));
738
+ if (other)
739
+ group.set(root(from), root(other));
740
+ else
741
+ lineOwner.set(startLine(o), from);
742
+ }
743
+ }
744
+ const groups = new Map();
745
+ for (const k of kept.keys())
746
+ groups.set(root(k), [...(groups.get(root(k)) ?? []), k]);
747
+ for (const names of groups.values()) {
748
+ const spans = [];
749
+ const lines = { old: [], new: [] };
750
+ const seen = new Set();
751
+ for (const from of names) {
752
+ const occ = kept.get(from);
753
+ const linePairs = [];
754
+ for (const [o, n] of occ) {
755
+ const k = `${startLine(o)}:${startLine(n)}`;
756
+ if (seen.has(k))
757
+ continue;
758
+ seen.add(k);
759
+ linePairs.push({ old: { start: startLine(o), end: startLine(o) }, new: { start: startLine(n), end: startLine(n) } });
760
+ }
761
+ const spanIndex = spans.push({ role: 'focus', relation: 'replaced', old: occ.map(([o]) => rangeOf(o)), new: occ.map(([, n]) => rangeOf(n)), linePairs }) - 1;
762
+ for (const p of linePairs) {
763
+ lines.old.push({ ...p.old, spanIndex });
764
+ lines.new.push({ ...p.new, spanIndex });
765
+ }
766
+ }
767
+ lines.old.sort((x, y) => x.start - y.start);
768
+ lines.new.sort((x, y) => x.start - y.start);
769
+ operations.push({ type: 'renamed', spans, lines });
770
+ }
771
+ // Formatting only: same tokens, same comments, different text.
772
+ // A class or interface whose whole shape is unchanged (`interface P { a: string }` wrapped
773
+ // onto lines) is reformatted as a whole; otherwise its changed members are reported.
774
+ const whole = pairs.filter(([a, b]) => a.decl.members && !moved.has(a) && a.text !== b.text && a.seq === b.seq && !brokenTree(a.decl.node, cfg) && !brokenTree(b.decl.node, cfg) && invisibles(a.text) === invisibles(b.text)).map(([a]) => a.decl.node);
775
+ const wordsChanged = new Set();
776
+ const insideWhole = (a) => whole.some((w) => w.id !== a.decl.node.id && w.startIndex <= a.decl.node.startIndex && a.decl.node.endIndex <= w.endIndex);
777
+ for (const [a, b] of pairs) {
778
+ if (moved.has(a) || a.text === b.text || insideWhole(a))
779
+ continue;
780
+ // A comment that changed places changes what it describes: not formatting.
781
+ if (a.seq !== b.seq)
782
+ continue;
783
+ // Invisible characters (zero-width space, line separators) can change how code
784
+ // parses or reads, so a change involving them is never called formatting.
785
+ if (invisibles(a.text) !== invisibles(b.text))
786
+ continue;
787
+ // Code that does not parse has no reliable shape to compare.
788
+ if (brokenTree(a.decl.node, cfg) || brokenTree(b.decl.node, cfg))
789
+ continue;
790
+ // Rust macro arguments are raw tokens: spacing can be the macro's input (`stringify!`).
791
+ if (macroArgs(a.decl.node) !== macroArgs(b.decl.node))
792
+ continue;
793
+ if (a.decl.members && !whole.includes(a.decl.node))
794
+ continue; // report the changed members, not the whole class
795
+ const rel = changedLines(a.text, b.text);
796
+ // Formatting changes lines on both sides; a declaration that only grew or shrank
797
+ // at its edge (a `;` attached from the next line) did not get reformatted.
798
+ if (rel.old.start > rel.old.end || rel.new.start > rel.new.end)
799
+ continue;
800
+ const oldStart = startLine(a.decl.node) + rel.old.start - 1;
801
+ const newStart = startLine(b.decl.node) + rel.new.start - 1;
802
+ const pair = {
803
+ old: { start: oldStart, end: startLine(a.decl.node) + rel.old.end - 1 },
804
+ new: { start: newStart, end: startLine(b.decl.node) + rel.new.end - 1 },
805
+ };
806
+ // The words must be the same too, inside strings and docstrings: rewrapping a docstring is formatting, changing
807
+ // its words is an edit (held4: Python docstrings with an escape sequence read only the escape as a token).
808
+ if (declGapWords(a.decl) !== declGapWords(b.decl))
809
+ wordsChanged.add(operations.length);
810
+ operations.push({
811
+ type: 'reformatted',
812
+ spans: [
813
+ {
814
+ role: 'root',
815
+ relation: 'mapped',
816
+ old: [range({ line: pair.old.start, character: 0 }, { line: pair.old.end + 1, character: 0 })],
817
+ new: [range({ line: pair.new.start, character: 0 }, { line: pair.new.end + 1, character: 0 })],
818
+ linePairs: [pair],
819
+ },
820
+ ],
821
+ lines: { old: [{ ...pair.old, spanIndex: 0 }], new: [{ ...pair.new, spanIndex: 0 }] },
822
+ });
823
+ }
824
+ const paired = pairs.map(([a]) => ({ start: docStart(a.decl.node, cfg), end: declEnd(a.decl) }));
825
+ return { operations, folds, paired, wordsChanged };
826
+ }
827
+ const invisibles = (t) => (t.match(/[\u200b-\u200f\u2028\u2029\u2060\ufeff\u00ad]/g) ?? []).join('');
828
+ const macroArgs = (n) => n.descendantsOfType('token_tree').map((t) => t?.text ?? '').join('\u0000');
829
+ /** The class, interface or type a field is declared in (null for anything else). */
830
+ function ownerTypeName(decl) {
831
+ if (kindOf(decl) !== 'member')
832
+ return null;
833
+ for (let p = decl.parent; p; p = p.parent) {
834
+ if (/^(class_declaration|abstract_class_declaration|interface_declaration|type_alias_declaration|class|struct_item|type_spec|class_definition)$/.test(p.type))
835
+ return p.childForFieldName('name')?.text ?? null;
836
+ if (/^(object|statement_block|program|source_file|module)$/.test(p.type))
837
+ return null;
838
+ }
839
+ return null;
840
+ }
841
+ /** Whether a use of a field declared in `owner` is reached through that type. */
842
+ function reachedThrough(n, owner, index) {
843
+ const p = n.parent;
844
+ if (!p)
845
+ return true;
846
+ // An object-literal key belongs to whatever type the literal has, which is unknown.
847
+ if (p.type === 'pair' && p.childForFieldName('key')?.id === n.id)
848
+ return false;
849
+ if (kindOf(n) !== 'member' || p.namedChildren.at(-1)?.id !== n.id)
850
+ return true;
851
+ const obj = p.childForFieldName('object') ?? p.childForFieldName('operand') ?? p.childForFieldName('value') ?? p.namedChild(0);
852
+ if (!obj || obj.type === 'this' || /^(this|self|base|super)$/.test(obj.text))
853
+ return true;
854
+ if (obj.type !== 'identifier')
855
+ return true; // a longer chain: unknown
856
+ const decls = (index.get(obj.text) ?? []).filter(isDeclarationName);
857
+ if (!decls.length)
858
+ return false; // a global (`document`, `window`): not this type
859
+ return decls.some((d) => {
860
+ const t = d.parent?.childForFieldName('type');
861
+ return !t || new RegExp(`\\b${owner}\\b`).test(t.text);
862
+ });
863
+ }
864
+ /** What a name refers to: a variable or function (`binding`), a property or field reached through an object (`member`), or a type. */
865
+ function kindOf(n) {
866
+ if (n.type === 'type_identifier')
867
+ return 'type';
868
+ if (SHORTHAND.has(n.type))
869
+ return 'binding';
870
+ const p = n.parent;
871
+ // A PHP property is declared as `$count` and used as `$this->count`.
872
+ if (p?.type === 'variable_name' && p.parent?.type === 'property_element')
873
+ return 'member';
874
+ // Ruby `user.name` is a call of the method `name` on `user`.
875
+ if (p?.type === 'call' && p.childForFieldName('receiver') && p.childForFieldName('method')?.id === n.id)
876
+ return 'member';
877
+ // `user.name`, `self.name`, `x.Name`, `obj->name`: the name after the dot.
878
+ // Swift: `self.count` is the same name as a bare `count`; `other.count` is another object's member.
879
+ if (p?.type === 'navigation_suffix')
880
+ return p.parent?.childForFieldName('target')?.type === 'self_expression' ? 'binding' : 'member';
881
+ // Kotlin's `this.count` is the property a bare `count` also names.
882
+ if (p?.type === 'navigation_expression' && p.namedChild(0)?.type === 'this_expression' && p.namedChildren.length === 2 && p.namedChildren.at(-1)?.id === n.id)
883
+ return 'binding';
884
+ if (p && /^(member_expression|attribute|field_expression|selector_expression|field_access|member_access_expression|navigation_expression)$/.test(p.type) && p.namedChildren.length > 1 && p.namedChildren.at(-1)?.id === n.id)
885
+ return 'member';
886
+ if (/property_identifier|field_identifier/.test(n.type))
887
+ return 'member';
888
+ return 'binding';
889
+ }
890
+ /** Identifiers that are both a variable and an object key. */
891
+ const SHORTHAND = new Set(['shorthand_property_identifier', 'shorthand_property_identifier_pattern', 'shorthand_field_identifier']);
892
+ /** The identifier is the name being declared (a variable, parameter, function, field, type...). */
893
+ const DECLARING_PARENT = /(declaration|declarator|definition|parameter|specifier|signature|_spec|_clause|_item|_variant|enum_assignment)$/;
894
+ /** The declared type next to a name, compared with this rename applied (a type can be the thing renamed). */
895
+ /**
896
+ * Swift writes the type with no `type` field: a parameter's type is its second `name` child, and a
897
+ * property's type is the `type_annotation` beside its pattern.
898
+ */
899
+ function declaredType(id) {
900
+ const p = id.parent;
901
+ if (!p || id.type !== 'simple_identifier')
902
+ return null;
903
+ if (p.type === 'parameter' || p.type === 'lambda_parameter')
904
+ return p.childrenForFieldName('name').find((c) => c && c.id !== id.id && c.type !== 'simple_identifier') ?? null;
905
+ if (p.type === 'pattern' && p.parent?.type === 'property_declaration')
906
+ return p.parent.namedChildren.find((c) => c?.type === 'type_annotation') ?? null;
907
+ return null;
908
+ }
909
+ /** Position of a parameter in its list (function, closure or block parameters), or null. */
910
+ function parameterIndex(id) {
911
+ let q = id;
912
+ for (let depth = 0; q?.parent && depth < 4; depth++, q = q.parent) {
913
+ const list = q.parent;
914
+ if (/(^|_)parameters$|parameter_list|lambda_function_type_parameters|closure_parameters|block_parameters/.test(list.type)) {
915
+ const items = list.namedChildren.filter((c) => !!c && !isComment(c) && c.type === q.type);
916
+ const i = items.findIndex((c) => c.id === q.id);
917
+ return i < 0 ? null : i;
918
+ }
919
+ }
920
+ return null;
921
+ }
922
+ /** The class a declaration's value is built from (`= Foo(...)`, `= Foo.new(...)`), when it is one. */
923
+ function constructedType(id, cfg) {
924
+ let d = id.parent;
925
+ for (let depth = 0; d && depth < 3 && !/property_declaration|variable_declaration|assignment|lexical_declaration|local_variable_declaration|field_declaration|variable_declarator/.test(d.type); depth++)
926
+ d = d.parent;
927
+ if (d?.type === 'variable_declaration' && d.parent?.type === 'property_declaration')
928
+ d = d.parent; // Kotlin
929
+ if (!d)
930
+ return null;
931
+ const value = d.childForFieldName('value') ?? d.childForFieldName('right') ?? d.namedChildren.filter((c) => !!c && !isComment(c)).at(-1) ?? null;
932
+ if (!value || value.startIndex <= id.startIndex || !cfg.callTypes.has(value.type))
933
+ return null;
934
+ let name = cfg.calleeOf(value);
935
+ if (name === 'new')
936
+ name = (value.childForFieldName('receiver') ?? null)?.text ?? null;
937
+ return name && /^[A-Z]/.test(name) ? name : null;
938
+ }
939
+ function constructedTypeChanged(o, n, renames, cfg) {
940
+ const a = constructedType(o, cfg);
941
+ const b = constructedType(n, cfg);
942
+ return !!a && !!b && a !== b && renames.get(a) !== b;
943
+ }
944
+ /** The two lines differ only by a negation: `!` or `not` added or dropped, or `== false` / `!= true` appended. */
945
+ function negatedOnly(a, b) {
946
+ if (a.join(' ') === b.join(' '))
947
+ return false;
948
+ const count = (xs) => xs.reduce((m, x) => m.set(x, (m.get(x) ?? 0) + 1), new Map());
949
+ const ca = count(a);
950
+ const cb = count(b);
951
+ const diff = [];
952
+ for (const k of new Set([...ca.keys(), ...cb.keys()]))
953
+ for (let i = Math.abs((ca.get(k) ?? 0) - (cb.get(k) ?? 0)); i > 0; i--)
954
+ diff.push(k);
955
+ if (!diff.length || !diff.every((x) => /^(!|=|not|false|true)$/.test(x)))
956
+ return false;
957
+ const n = (re) => diff.filter((x) => re.test(x)).length;
958
+ // `!x` / `not x`, or a comparison appended (`== false`): never a default value (`flag: Boolean = false`).
959
+ return n(/^(!|not)$/) > 0 || (n(/^=$/) === 2 && n(/^(false|true)$/) === 1);
960
+ }
961
+ function declaredTypeChanged(o, n, from, to) {
962
+ // Kotlin writes the type after the name with no field: `val x: Int`, `(by: Double)`.
963
+ const typeOf = (d) => d?.childForFieldName('type') ?? (d && /^(variable_declaration|parameter|class_parameter)$/.test(d.type) ? d.namedChildren.find((c) => !!c && /^(user_type|nullable_type|function_type|parenthesized_type|not_nullable_type)$/.test(c.type)) : null) ?? null;
964
+ const ta = declaredType(o) ?? typeOf(o.parent);
965
+ const tb = declaredType(n) ?? typeOf(n.parent);
966
+ if (!ta && !tb)
967
+ return false;
968
+ if (!ta || !tb)
969
+ return true;
970
+ const swap = (t) => t.replace(/\w+/g, (w) => (w === from ? to : w)).replace(/\s+/g, '');
971
+ return swap(ta.text) !== tb.text.replace(/\s+/g, '');
972
+ }
973
+ function isDeclarationName(id) {
974
+ const p = id.parent;
975
+ // Only declaring constructs: a qualified reference such as `Anthropic.X` or
976
+ // `user.email` also has a `name` field, but declares nothing.
977
+ if (!p)
978
+ return false;
979
+ // Python: plain parameters sit directly in the list; `x = ...` declares x.
980
+ if (p.type === 'parameters' || p.type === 'lambda_parameters')
981
+ return true;
982
+ if (p.type === 'typed_parameter')
983
+ return p.namedChild(0)?.startIndex === id.startIndex;
984
+ if (p.type === 'assignment')
985
+ return p.childForFieldName('left')?.startIndex === id.startIndex;
986
+ // Go: `x := ...` and `for k, v := range` declare through their left-hand list.
987
+ if (p.type === 'expression_list' && (p.parent?.type === 'short_var_declaration' || p.parent?.type === 'range_clause'))
988
+ return p.parent.childForFieldName('left')?.startIndex === p.startIndex;
989
+ // Swift binds names through `bound_identifier` (`if let x`, `guard let x`, `catch let e`, `let x = ...`),
990
+ // bare names in tuple patterns (`for (i, c) in ...`), and enum cases. In `case .some(let z)` the case
991
+ // name `some` declares nothing.
992
+ if (id.type === 'simple_identifier') {
993
+ if (p.childrenForFieldName('bound_identifier').some((c) => c?.id === id.id))
994
+ return true;
995
+ if (p.type === 'pattern')
996
+ return p.namedChildCount === 1 && p.childCount === 1;
997
+ if (p.type === 'enum_entry')
998
+ return p.childrenForFieldName('name').some((c) => c?.id === id.id);
999
+ }
1000
+ // Names bound by patterns (`Some(byte) =>`, `let (a, b)`, `[x, y] = ...`) and
1001
+ // closure parameters (`|a, b|`). In `{ key: value }` patterns only the value is bound.
1002
+ if (/pattern$/.test(p.type) || p.type === 'closure_parameters') {
1003
+ const bound = p.childForFieldName('value') ?? p.childForFieldName('pattern');
1004
+ return !bound || bound.startIndex === id.startIndex;
1005
+ }
1006
+ // Java lambda parameters without types (`(key, value) -> ...`) and Python's
1007
+ // `except E as exc` / `with f() as x` targets.
1008
+ if (p.type === 'inferred_parameters' || p.type === 'as_pattern_target')
1009
+ return true;
1010
+ // TypeScript enum members without a value: `enum E { A, B }`.
1011
+ if (p.type === 'enum_body')
1012
+ return true;
1013
+ // PHP: `$x` is a `variable_name` holding the name. It is declared by a parameter, a property, an
1014
+ // assignment (also `[$a, $b] = ...`), a `static` or `global` line, a closure's `use (...)`, a catch
1015
+ // clause or a foreach target.
1016
+ if (p.type === 'variable_name') {
1017
+ const q = p.parent;
1018
+ if (!q)
1019
+ return false;
1020
+ if (q.type === 'assignment_expression' || q.type === 'reference_assignment_expression')
1021
+ return q.childForFieldName('left')?.id === p.id;
1022
+ if (/parameter$|^property_element$|^static_variable_declaration$/.test(q.type))
1023
+ return q.childForFieldName('name')?.id === p.id;
1024
+ if (q.type === 'global_declaration' || q.type === 'anonymous_function_use_clause')
1025
+ return true;
1026
+ if (q.type === 'catch_clause')
1027
+ return q.childForFieldName('name')?.id === p.id;
1028
+ if (q.type === 'list_literal')
1029
+ return true;
1030
+ if (q.type === 'foreach_statement' || (q.type === 'pair' && q.parent?.type === 'foreach_statement'))
1031
+ return q.namedChildren[0]?.id !== p.id || q.type === 'pair';
1032
+ return false;
1033
+ }
1034
+ if (p.type === 'const_element' || p.type === 'enum_case')
1035
+ return p.namedChildren.find((c) => c?.type === 'name')?.id === id.id;
1036
+ // Ruby: parameter lists, `a, b = ...`, `x ||= ...`, `for x in`, `rescue => e`, and a method's, class's or module's name.
1037
+ if (/^(method_parameters|block_parameters|left_assignment_list|destructured_left_assignment|destructured_parameter|exception_variable)$/.test(p.type))
1038
+ return true;
1039
+ if (p.type === 'operator_assignment')
1040
+ return p.childForFieldName('left')?.id === id.id;
1041
+ if (p.type === 'for')
1042
+ return p.childForFieldName('pattern')?.id === id.id;
1043
+ if (p.type === 'method' || p.type === 'singleton_method' || (id.type === 'constant' && (p.type === 'class' || p.type === 'module')))
1044
+ return p.childForFieldName('name')?.id === id.id;
1045
+ // Kotlin names its declarations by position, not by field: `val x`, `(a: Int)`, `class P(val x: Int)`,
1046
+ // `enum class E { A }`, `catch (e: E)`, `<T>`, `import a.B as C` (the alias); `typealias S = ...` uses `type`.
1047
+ if (/^(variable_declaration|parameter|class_parameter|enum_entry|catch_block|type_parameter)$/.test(p.type) && !p.childForFieldName('name'))
1048
+ return p.namedChildren.find((c) => c?.type === 'identifier')?.id === id.id;
1049
+ if (p.type === 'import')
1050
+ return p.namedChildren.some((c) => c?.type === 'qualified_identifier') && p.namedChildren.find((c) => c?.type === 'identifier')?.id === id.id;
1051
+ if (p.type === 'type_alias')
1052
+ return p.childForFieldName('type')?.id === id.id;
1053
+ if (!DECLARING_PARENT.test(p.type))
1054
+ return false;
1055
+ // `import { A }` -> `import { B }` brings in a different thing; only a local
1056
+ // alias (`import { A as b }`) is a name this file owns.
1057
+ if (p.type === 'import_specifier') {
1058
+ const alias = p.childForFieldName('alias');
1059
+ return !!alias && alias.startIndex === id.startIndex;
1060
+ }
1061
+ // Every name, not just the first: Go declares several at once (`dirs, names []string`).
1062
+ for (const field of ['name', 'pattern']) {
1063
+ for (const n of p.childrenForFieldName(field))
1064
+ if (n && n.startIndex === id.startIndex && n.endIndex === id.endIndex)
1065
+ return true;
1066
+ }
1067
+ return false;
1068
+ }
1069
+ /** First line of the comments directly above a declaration (no blank line between), else its own first line. */
1070
+ function docStart(n, cfg) {
1071
+ let line = startLine(n);
1072
+ // Rust line comments end at the start of the next line, so compare start lines.
1073
+ for (let c = n.previousSibling; c && cfg.attachedTypes.has(c.type) && commentEnd(c) === line - 1; c = c.previousSibling)
1074
+ line = startLine(c);
1075
+ return line;
1076
+ }
1077
+ /** Last line a node really covers (a node ending in a newline ends on the line before). */
1078
+ const commentEnd = (c) => (c.endPosition.column === 0 && c.endPosition.row > c.startPosition.row ? c.endPosition.row : c.endPosition.row + 1);
1079
+ function docText(n, from, cfg) {
1080
+ const out = [];
1081
+ for (let c = n.previousSibling; c && cfg.attachedTypes.has(c.type) && startLine(c) >= from; c = c.previousSibling)
1082
+ out.push(c.text.trim());
1083
+ return out.join('\n');
1084
+ }
1085
+ /** Every identifier in the tree, by name. */
1086
+ function identifierIndex(root, cfg) {
1087
+ const out = new Map();
1088
+ const stack = [root];
1089
+ while (stack.length) {
1090
+ const x = stack.pop();
1091
+ if (x.childCount === 0) {
1092
+ if (cfg.identifierTypes.has(x.type) && !cfg.notAName?.(x)) {
1093
+ const list = out.get(x.text);
1094
+ if (list)
1095
+ list.push(x);
1096
+ else
1097
+ out.set(x.text, [x]);
1098
+ }
1099
+ continue;
1100
+ }
1101
+ for (let i = x.childCount - 1; i >= 0; i--) {
1102
+ const c = x.child(i);
1103
+ if (c)
1104
+ stack.push(c);
1105
+ }
1106
+ }
1107
+ // Source order, as the recursive walk gave.
1108
+ for (const list of out.values())
1109
+ list.sort((a, b) => a.startIndex - b.startIndex);
1110
+ return out;
1111
+ }