@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
package/dist/syntax.js ADDED
@@ -0,0 +1,450 @@
1
+ // Small helpers over tree-sitter nodes: positions, tokens, similarity, and
2
+ // finding functions, statements and calls with a language config.
3
+ import { rule } from "./runtime.js";
4
+ import { isComment, kotlinReceiver } from "./parse.js";
5
+ export const pos = (p) => ({
6
+ line: p.row + 1,
7
+ character: p.column,
8
+ });
9
+ export const rangeOf = (n) => ({ start: pos(n.startPosition), end: pos(n.endPosition) });
10
+ export const range = (start, end) => ({
11
+ start,
12
+ end,
13
+ });
14
+ export const startLine = (n) => n.startPosition.row + 1;
15
+ export const endLine = (n) => n.endPosition.row + 1;
16
+ /** Leaf tokens of a node, comments excluded. Whitespace never appears in tokens. */
17
+ export function tokens(n) {
18
+ const out = [];
19
+ // Iterative: very deep trees would overflow the stack.
20
+ const stack = [n];
21
+ while (stack.length) {
22
+ const x = stack.pop();
23
+ if (isComment(x))
24
+ continue;
25
+ if (x.childCount === 0) {
26
+ if (x.text.length)
27
+ out.push(x.text);
28
+ continue;
29
+ }
30
+ for (let i = x.childCount - 1; i >= 0; i--) {
31
+ const c = x.child(i);
32
+ if (c)
33
+ stack.push(c);
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ /** Dice similarity of two token multisets: 1 = same tokens, 0 = nothing shared. */
39
+ export function dice(a, b) {
40
+ if (!a.length && !b.length)
41
+ return 1;
42
+ const counts = new Map();
43
+ for (const t of a)
44
+ counts.set(t, (counts.get(t) ?? 0) + 1);
45
+ let shared = 0;
46
+ for (const t of b) {
47
+ const c = counts.get(t);
48
+ if (c) {
49
+ shared++;
50
+ counts.set(t, c - 1);
51
+ }
52
+ }
53
+ return (2 * shared) / (a.length + b.length);
54
+ }
55
+ /**
56
+ * The name an object literal is held under: `const actionWrap = register({ perform() {} })`
57
+ * makes its functions `actionWrap.perform`, so several objects' `perform`s stay apart.
58
+ */
59
+ function holderOf(obj) {
60
+ for (let p = obj.parent, depth = 0; p && depth < 6; p = p.parent, depth++) {
61
+ if (p.type === 'variable_declarator' || p.type === 'public_field_definition')
62
+ return p.childForFieldName('name')?.text;
63
+ if (p.type === 'pair')
64
+ return p.childForFieldName('key')?.text;
65
+ if (p.type === 'assignment_expression')
66
+ return p.childForFieldName('left')?.text;
67
+ if (!/^(arguments|call_expression|parenthesized_expression|as_expression|satisfies_expression|export_statement)$/.test(p.type))
68
+ return undefined;
69
+ }
70
+ return undefined;
71
+ }
72
+ /** The class, interface or object a function belongs to (TS), or its receiver type (Go). */
73
+ function scopeOf(n) {
74
+ const recv = n.childForFieldName('receiver');
75
+ if (recv)
76
+ return (recv.text.match(/\*?\s*([A-Za-z_]\w*)\s*(\[[^\]]*\])?\s*\)\s*$/) ?? [])[1] ?? '';
77
+ const names = [];
78
+ for (let p = n.parent; p; p = p.parent) {
79
+ if (/class|interface|object|function|method|trait|impl|mod_item/.test(p.type)) {
80
+ // A Rust `impl` is named by its type: methods of `impl Foo` belong to Foo.
81
+ const name = p.type === 'impl_item' ? p.childForFieldName('type')?.text.replace(/<.*$/s, '') : p.type === 'object' ? holderOf(p) : p.childForFieldName('name')?.text;
82
+ if (name)
83
+ names.unshift(name);
84
+ }
85
+ }
86
+ return names.join('.');
87
+ }
88
+ export function functionsIn(root, cfg) {
89
+ const out = [];
90
+ const seen = new Map();
91
+ const walk = (n) => {
92
+ if (cfg.functionTypes.has(n.type)) {
93
+ const name = cfg.nameOf(n);
94
+ const body = cfg.bodyOf(n);
95
+ if (name && body) {
96
+ const base = `${scopeOf(n)}/${name}`;
97
+ const k = seen.get(base) ?? 0;
98
+ seen.set(base, k + 1);
99
+ out.push({ name, key: k ? `${base}#${k}` : base, node: n, body, statements: cfg.statementsOf(body) });
100
+ }
101
+ }
102
+ for (const c of n.namedChildren)
103
+ if (c)
104
+ walk(c);
105
+ };
106
+ walk(root);
107
+ return out;
108
+ }
109
+ /** Every statement at any depth inside `n` (statements of nested blocks included). */
110
+ export function allStatements(n, cfg) {
111
+ const out = [];
112
+ const walk = (x) => {
113
+ if (cfg.blockTypes.has(x.type))
114
+ out.push(...cfg.statementsOf(x));
115
+ for (const c of x.namedChildren)
116
+ if (c)
117
+ walk(c);
118
+ };
119
+ walk(n);
120
+ return out;
121
+ }
122
+ /**
123
+ * Calls to `name` inside `n`. With `fn`, a call passing more arguments than the
124
+ * function takes is a different function of the same name (`caseSensitivity.PathKey(p)`
125
+ * is not `(t *parseTask) PathKey()`).
126
+ */
127
+ export function callsTo(n, name, cfg, fn) {
128
+ const max = fn ? maxArguments(fn) : Infinity;
129
+ const min = fn && rule('ARITY_MIN') && cfg.id === 'java' ? requiredArguments(fn) : 0;
130
+ const out = [];
131
+ const walk = (x) => {
132
+ // A free function is never called through an object: `JSON.parse(t)` does not call a local `parse`.
133
+ // A call that is a single token (Ruby's bare `total`) can only call its own text: checked first, as it is cheap.
134
+ if (cfg.callTypes.has(x.type) && (x.childCount > 0 || x.text === name) && cfg.calleeOf(x) === name && argumentCount(x) <= max && argumentCount(x) >= min && !(fn && !isMethod(fn) && memberCall(x)) && !(fn?.type === 'pair' && memberCall(x) && !thisCall(x)))
135
+ out.push(x);
136
+ // JSX renders a component by calling it: `<OrderRow order={o} />` calls `OrderRow`.
137
+ // Effect runs a defined effect with `yield* load` or `yield* load.pipe(...)`: no call, but the same use.
138
+ else if (x.type === 'yield_expression' && x.child(1)?.type === '*' && yieldsEffect(x.namedChild(0), name))
139
+ out.push(x);
140
+ else if ((x.type === 'jsx_self_closing_element' || x.type === 'jsx_opening_element') && /^[A-Z]/.test(name) && x.childForFieldName('name')?.text === name)
141
+ out.push(x.type === 'jsx_opening_element' && x.parent ? x.parent : x);
142
+ // A Java constructor runs another of its class with `this(...)` (only with the right argument count).
143
+ else if (rule('CONSTRUCTOR_CHAINS') && fn?.type === 'constructor_declaration' && x.type === 'explicit_constructor_invocation' && x.childForFieldName('constructor')?.type === 'this' && argumentCount(x) <= max && argumentCount(x) >= min)
144
+ out.push(x);
145
+ // `new Internals(def)` runs a constructor function.
146
+ else if (rule('VALUE_REFS') && x.type === 'new_expression' && x.childForFieldName('constructor')?.text === name)
147
+ out.push(x);
148
+ // A function handed over as a value is used all the same: `Effect.catch(failSearch)`,
149
+ // `items.map(toRow)`, `atom(resolveLoad)`. Only bare names in argument lists, and never a
150
+ // function of an object literal (those are reached through `this` only).
151
+ else if (rule('VALUE_REFS') && x.parent?.type === 'arguments' && cfg.identifierTypes.has(x.type) && x.text === name && fn?.type !== 'pair' && !!x.parent.parent && cfg.callTypes.has(x.parent.parent.type) && cfg.calleeOf(x.parent.parent) !== name)
152
+ out.push(x);
153
+ for (const c of x.namedChildren)
154
+ if (c)
155
+ walk(c);
156
+ };
157
+ walk(n);
158
+ return out;
159
+ }
160
+ /** All descendants of `n` (including `n`) whose token sequence equals `want`. */
161
+ export function nodesWithTokens(n, want) {
162
+ const key = want.join('\u0000');
163
+ const out = [];
164
+ const walk = (x) => {
165
+ if (tokens(x).join('\u0000') === key)
166
+ out.push(x);
167
+ for (const c of x.namedChildren)
168
+ if (c)
169
+ walk(c);
170
+ };
171
+ walk(n);
172
+ return out;
173
+ }
174
+ function argumentCount(call) {
175
+ // Swift: `f(a, b)` keeps its arguments in a call suffix; a trailing closure `f(a) { ... }` is one more.
176
+ const suffix = call.namedChildren.find((c) => c?.type === 'call_suffix');
177
+ if (suffix)
178
+ return (suffix.namedChildren.find((c) => c?.type === 'value_arguments')?.namedChildren.filter((c) => c?.type === 'value_argument').length ?? 0) + suffix.namedChildren.filter((c) => c?.type === 'lambda_literal' || c?.type === 'annotated_lambda').length;
179
+ // Kotlin: `f(a) { ... }` passes the trailing lambda as one more argument.
180
+ const args = call.childForFieldName('arguments') ?? call.namedChildren.find((c) => c?.type === 'value_arguments');
181
+ const lambda = call.namedChildren.some((c) => c?.type === 'annotated_lambda') ? 1 : 0;
182
+ return (args ? args.namedChildren.filter((c) => c !== null && !isComment(c)).length : 0) + lambda;
183
+ }
184
+ /**
185
+ * Java has no optional parameters: a call passing fewer arguments than a method takes calls another
186
+ * method of that name (`this.reader.read()` is not `read(boolean readEscaped)`). Varargs may be empty.
187
+ */
188
+ function requiredArguments(fn) {
189
+ const params = fn.childForFieldName('parameters');
190
+ if (!params)
191
+ return 0;
192
+ let n = 0;
193
+ for (const p of params.namedChildren) {
194
+ if (!p || isComment(p) || p.type === 'receiver_parameter')
195
+ continue;
196
+ if (p.type === 'spread_parameter')
197
+ return n;
198
+ n++;
199
+ }
200
+ return n;
201
+ }
202
+ /** Most arguments a function accepts; Infinity with a rest/variadic parameter. */
203
+ function maxArguments(fn) {
204
+ // Arrow functions and function expressions keep their parameters in the value; `x => ...` has one.
205
+ const value = fn.childForFieldName('value');
206
+ if (value?.childForFieldName('parameter'))
207
+ return 1;
208
+ const params = fn.childForFieldName('parameters') ?? value?.childForFieldName('parameters') ?? fn.namedChildren.find((c) => c?.type === 'function_value_parameters');
209
+ // Swift parameters sit directly in the declaration; `xs: Int...` takes any number.
210
+ const swiftParams = params ? [] : fn.namedChildren.filter((c) => c?.type === 'parameter');
211
+ if (swiftParams.length || (!params && fn.type === 'function_declaration' && fn.childForFieldName('body')?.type === 'function_body'))
212
+ return swiftParams.some((p) => p?.children.some((c) => c?.type === '...')) ? Infinity : swiftParams.length;
213
+ if (!params)
214
+ return Infinity;
215
+ // Kotlin lists `vararg` and default values next to each parameter, not inside it.
216
+ if (params.type === 'function_value_parameters')
217
+ return /\bvararg\b/.test(params.text) ? Infinity : params.namedChildren.filter((c) => c?.type === 'parameter').length;
218
+ let n = 0;
219
+ for (const p of params.namedChildren) {
220
+ if (!p || isComment(p))
221
+ continue;
222
+ // Rest parameters: `...xs` (TS), `xs ...T` (Go), `*args`/`**kw` (Python), `params T[] xs` (C#).
223
+ if (p.text.includes('...') || /^\*|^params\s/.test(p.text) || p.type.includes('splat'))
224
+ return Infinity;
225
+ // Go groups names that share a type: `a, b int`.
226
+ const names = p.childrenForFieldName?.('name')?.filter(Boolean).length ?? 0;
227
+ n += Math.max(1, names);
228
+ }
229
+ return n;
230
+ }
231
+ /**
232
+ * Indexes (into `seq`) of the strictly increasing subsequence with the most
233
+ * total `weight`: the declarations that stay in place, so the rest are the moves.
234
+ * Callers weight by size in lines, so the fewest lines are shown as moved (a long
235
+ * import stays and the short ones around it move, as a line diff would have it),
236
+ * with a small bonus for staying at the same position to settle ties (a re-sort
237
+ * that leaves an import where it was does not report it). O(n log n).
238
+ */
239
+ export function longestInOrder(seq, weight = seq.map(() => 1)) {
240
+ const n = seq.length;
241
+ // Fenwick tree over the ranks of `seq`, holding the best chain ending below each rank.
242
+ const ranks = [...new Set(seq)].sort((a, b) => a - b);
243
+ const rank = new Map(ranks.map((v, i) => [v, i + 1]));
244
+ const treeBest = new Array(ranks.length + 1).fill(0);
245
+ const treeAt = new Array(ranks.length + 1).fill(-1);
246
+ const best = new Array(n).fill(0);
247
+ const prev = new Array(n).fill(-1);
248
+ for (let i = 0; i < n; i++) {
249
+ const r = rank.get(seq[i]);
250
+ let b = 0;
251
+ let at = -1;
252
+ for (let k = r - 1; k > 0; k -= k & -k)
253
+ if (treeBest[k] > b) {
254
+ b = treeBest[k];
255
+ at = treeAt[k];
256
+ }
257
+ best[i] = b + weight[i];
258
+ prev[i] = at;
259
+ for (let k = r; k <= ranks.length; k += k & -k)
260
+ if (best[i] > treeBest[k]) {
261
+ treeBest[k] = best[i];
262
+ treeAt[k] = i;
263
+ }
264
+ }
265
+ let end = -1;
266
+ for (let i = 0; i < n; i++)
267
+ if (end < 0 || best[i] > best[end])
268
+ end = i;
269
+ const keep = new Set();
270
+ for (let i = end; i >= 0; i = prev[i])
271
+ keep.add(i);
272
+ return keep;
273
+ }
274
+ /**
275
+ * Lines of code a declaration spans (through its tail), for choosing which declarations stayed in
276
+ * place. In Ruby the text lines of a heredoc are a string, not code: a method holding a long SQL
277
+ * heredoc does not outweigh the methods it swapped places with.
278
+ */
279
+ export function codeLines(d, cfg) {
280
+ const lines = endLine(d.tail ?? d.node) - startLine(d.node) + 1;
281
+ if (cfg.id !== 'ruby')
282
+ return lines;
283
+ const text = new Set();
284
+ for (const n of [d.node, ...(d.tail ? [d.tail] : [])]) {
285
+ for (const h of n.type === 'heredoc_body' ? [n] : n.descendantsOfType('heredoc_body')) {
286
+ if (h)
287
+ for (let l = startLine(h) + 1; l <= endLine(h); l++)
288
+ text.add(l);
289
+ }
290
+ }
291
+ return Math.max(1, lines - text.size);
292
+ }
293
+ /**
294
+ * Weights for `longestInOrder`, for pairs listed in old order: size in lines,
295
+ * plus a tie-breaking bonus for staying at the same position among the pairs.
296
+ * With `unchanged`, an unchanged pair also wins a tie over an edited one, so of two
297
+ * swapped declarations the edited one is called moved (see LanguageConfig.moveEditedFirst).
298
+ */
299
+ export function keepWeights(newStarts, lines, unchanged) {
300
+ const rank = new Map([...newStarts].sort((a, b) => a - b).map((v, i) => [v, i]));
301
+ // Scaled so that all the bonuses together never outweigh one line.
302
+ const scale = newStarts.length + 1;
303
+ if (unchanged)
304
+ return newStarts.map((v, i) => lines[i] * scale * scale + (unchanged[i] ? scale : 0) + (rank.get(v) === i ? 1 : 0));
305
+ return newStarts.map((v, i) => lines[i] * scale + (rank.get(v) === i ? 1 : 0));
306
+ }
307
+ /**
308
+ * Pair items that share a base key (kind + name). A name used once on each side
309
+ * pairs directly; repeated names (overloads, `#[cfg]` twins, Go `init()`, two
310
+ * imports from one module) pair by similarity, not position, so inserting one
311
+ * overload first does not shift every pairing by one.
312
+ */
313
+ export function pairSameNamed(olds, news, base, toks, kept, exact) {
314
+ const group = (xs) => {
315
+ const m = new Map();
316
+ for (const x of xs)
317
+ m.set(base(x), [...(m.get(base(x)) ?? []), x]);
318
+ return m;
319
+ };
320
+ const go = group(olds);
321
+ const gn = group(news);
322
+ const out = [];
323
+ for (const [k, as] of go) {
324
+ const bs = gn.get(k);
325
+ if (!bs)
326
+ continue;
327
+ // Huge groups (generated code repeating one name thousands of times) pair in
328
+ // order: comparing every pair would take time and memory in the square of the size.
329
+ if ((as.length === 1 && bs.length === 1) || as.length * bs.length > 2500) {
330
+ if (exact && as.length * bs.length > 2500) {
331
+ // With `exact` (trial FN_PAIRING): a key found once on each side pairs first; the rest pair in order,
332
+ // so one deleted overload among hundreds does not shift every pair after it.
333
+ const once = (xs) => {
334
+ const m = new Map();
335
+ for (const x of xs) {
336
+ const e = exact(x);
337
+ if (e !== null)
338
+ m.set(e, [...(m.get(e) ?? []), x]);
339
+ }
340
+ return m;
341
+ };
342
+ const ea = once(as);
343
+ const eb = once(bs);
344
+ const done = new Set();
345
+ for (const [e, xs] of ea) {
346
+ const ys = eb.get(e);
347
+ if (xs.length === 1 && ys?.length === 1) {
348
+ out.push([xs[0], ys[0]]);
349
+ done.add(xs[0]).add(ys[0]);
350
+ }
351
+ }
352
+ const ra = as.filter((x) => !done.has(x));
353
+ const rb = bs.filter((x) => !done.has(x));
354
+ for (let i = 0; i < Math.min(ra.length, rb.length); i++)
355
+ out.push([ra[i], rb[i]]);
356
+ continue;
357
+ }
358
+ for (let i = 0; i < Math.min(as.length, bs.length); i++)
359
+ out.push([as[i], bs[i]]);
360
+ continue;
361
+ }
362
+ const ta = as.map(toks);
363
+ const tb = bs.map(toks);
364
+ const cand = [];
365
+ as.forEach((a, i) => bs.forEach((b, j) => cand.push([dice(ta[i], tb[j]), i, j, kept?.(a, b) ? 1 : 0])));
366
+ // Most similar first; ties keep their order (the i-th old with the i-th new). With `kept` (trial DUP_TIEBREAK),
367
+ // equally similar copies go first to the pair the line diff keeps unchanged in place (the original of a
368
+ // duplicated `require`, not the copy added above it).
369
+ cand.sort((x, y) => y[0] - x[0] || y[3] - x[3] || Math.abs(x[1] - x[2]) - Math.abs(y[1] - y[2]) || x[1] - y[1]);
370
+ const ua = new Set();
371
+ const ub = new Set();
372
+ for (const [sim, i, j] of cand) {
373
+ if (ua.has(i) || ub.has(j))
374
+ continue;
375
+ // Leftovers that share little are not the same declaration (one overload became
376
+ // another function; a new one was added): leave them unpaired.
377
+ if (sim < 0.3)
378
+ continue;
379
+ ua.add(i);
380
+ ub.add(j);
381
+ out.push([as[i], bs[j]]);
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+ /** The function is a method (of a class, impl, receiver type), so `x.name()` can call it. */
387
+ export function isMethod(fn) {
388
+ if (fn.childForFieldName('receiver'))
389
+ return true;
390
+ // Every Ruby `def` defines a method, in a class, a module or at the top (on Object).
391
+ if (fn.type === 'method' || fn.type === 'singleton_method')
392
+ return true;
393
+ // A Kotlin extension function (`fun String.shout()`) is called on its receiver.
394
+ if (fn.type === 'function_declaration' && kotlinReceiver(fn))
395
+ return true;
396
+ for (let p = fn.parent; p; p = p.parent) {
397
+ if (/class|interface|impl_item|trait_item|object|struct_declaration|record_declaration|enum_declaration/.test(p.type))
398
+ return true;
399
+ if (/function|method/.test(p.type) && p !== fn)
400
+ return false;
401
+ }
402
+ return false;
403
+ }
404
+ /** The call names its function through an object (`a.f()`, `pkg.F()`, `self.f()`), not bare (`f()`). */
405
+ /** `load` or `load.pipe(...)`: the effect named `name`, run as is or piped through operators. */
406
+ function yieldsEffect(n, name) {
407
+ if (n?.type === 'identifier')
408
+ return n.text === name;
409
+ const f = n?.type === 'call_expression' ? n.childForFieldName('function') : null;
410
+ return f?.type === 'member_expression' && f.childForFieldName('property')?.text === 'pipe' && f.childForFieldName('object')?.type === 'identifier' && f.childForFieldName('object')?.text === name;
411
+ }
412
+ /**
413
+ * `this.f()`: a call on the object itself. A function stored in an object literal
414
+ * (`{ run: () => ... }`) is reached this way from its siblings; `options.run()` elsewhere
415
+ * calls whatever `options` holds, not necessarily this literal's `run`.
416
+ */
417
+ function thisCall(call) {
418
+ if (call.namedChild(0)?.type === 'navigation_expression')
419
+ return call.namedChild(0).childForFieldName('target')?.type === 'self_expression';
420
+ return call.childForFieldName('function')?.childForFieldName('object')?.type === 'this';
421
+ }
422
+ /** The call reaches the parent class's version: `super.f()`, `super.init(...)`, Ruby `superclass.f` / `superclass&.f`. */
423
+ export function callsParent(call) {
424
+ if (!memberCall(call))
425
+ return false;
426
+ const f = call.childForFieldName('function') ?? (call.type === 'call_expression' ? call.namedChild(0) : null);
427
+ const r = call.childForFieldName('receiver') ?? call.childForFieldName('object') ?? f?.childForFieldName('target') ?? f?.childForFieldName('object') ?? f?.namedChild(0);
428
+ return !!r && (/^super/.test(r.type) || /^(super|superclass)$/.test(r.text));
429
+ }
430
+ function memberCall(call) {
431
+ if (call.childForFieldName('object'))
432
+ return true; // Java
433
+ if (call.childForFieldName('receiver'))
434
+ return true; // Ruby
435
+ const f = call.childForFieldName('function') ?? (call.type === 'call_expression' ? call.namedChild(0) : null);
436
+ return !!f && /member_expression|selector_expression|field_expression|attribute|member_access_expression|navigation_expression/.test(f.type);
437
+ }
438
+ /** Text of the comments and attributes directly above a declaration (they belong to it). */
439
+ export function attachedAbove(n, attached) {
440
+ const out = [];
441
+ let line = n.startPosition.row;
442
+ for (let c = n.previousSibling; c && attached.has(c.type); c = c.previousSibling) {
443
+ const end = c.endPosition.column === 0 && c.endPosition.row > c.startPosition.row ? c.endPosition.row - 1 : c.endPosition.row;
444
+ if (end !== line - 1)
445
+ break;
446
+ out.unshift(c.text.trim());
447
+ line = c.startPosition.row;
448
+ }
449
+ return out.join('\n');
450
+ }
@@ -0,0 +1,15 @@
1
+ import type { SemanticDiffTextPosition } from './pierre-types.js';
2
+ /** Above this many lines, skip move detection (it is the costly part). */
3
+ export declare const MAX_TEXT_MOVE_LINES = 20000;
4
+ declare const computer: import("@vscode/diff/core").IDiffComputer;
5
+ export type TextDiff = ReturnType<typeof computer.computeDiff>;
6
+ /** Roughly one second of diffing on a 2024 laptop (measured: 50M to 250M, median 90M). */
7
+ export declare const WORK_PER_SECOND = 75000000;
8
+ /** Work used by the most recent `computeTextDiff`. */
9
+ export declare let lastWork: number;
10
+ /** Work used by every `computeTextDiff` so far, for tests that bound the engine by work instead of time. */
11
+ export declare let totalWork: number;
12
+ /** `maxWork` bounds the diff by work done, not by time, so the result is repeatable. */
13
+ export declare function computeTextDiff(oldText: string, newText: string, maxWork?: number): TextDiff;
14
+ export declare function positions(text: string): (offset: number) => SemanticDiffTextPosition;
15
+ export {};
@@ -0,0 +1,64 @@
1
+ // One VS Code diff (`@vscode/diff`, MIT) per file, shared by the passes that
2
+ // need text-level changes, plus offset -> (line, character) conversion.
3
+ import { createTsDiffComputer } from '@vscode/diff/core';
4
+ /** Above this many lines, skip move detection (it is the costly part). */
5
+ export const MAX_TEXT_MOVE_LINES = 20_000;
6
+ const computer = createTsDiffComputer();
7
+ const impl = computer._impl;
8
+ const myers = impl?._myersDiffingAlgorithm;
9
+ if (!myers)
10
+ throw new Error('@vscode/diff changed shape: the work count in textdiff.ts needs updating');
11
+ let work = 0;
12
+ let round = -1; // >= 0 while inside the O(ND) algorithm
13
+ const compute = myers.compute.bind(myers);
14
+ myers.compute = (...args) => {
15
+ const outer = round;
16
+ round = 0;
17
+ try {
18
+ return compute(...args);
19
+ }
20
+ finally {
21
+ round = outer;
22
+ }
23
+ };
24
+ const workClock = () => (work += round < 0 ? 1 : ++round);
25
+ /** Roughly one second of diffing on a 2024 laptop (measured: 50M to 250M, median 90M). */
26
+ export const WORK_PER_SECOND = 75_000_000;
27
+ /** Work used by the most recent `computeTextDiff`. */
28
+ export let lastWork = 0;
29
+ /** Work used by every `computeTextDiff` so far, for tests that bound the engine by work instead of time. */
30
+ export let totalWork = 0;
31
+ /** `maxWork` bounds the diff by work done, not by time, so the result is repeatable. */
32
+ export function computeTextDiff(oldText, newText, maxWork = WORK_PER_SECOND) {
33
+ const computeMoves = oldText.split('\n').length <= MAX_TEXT_MOVE_LINES;
34
+ const clock = Date.now;
35
+ work = 0;
36
+ round = -1;
37
+ Date.now = workClock;
38
+ try {
39
+ return computer.computeDiff(oldText, newText, { computeMoves, maxComputationTimeMs: Math.max(1, Math.floor(maxWork)) });
40
+ }
41
+ finally {
42
+ Date.now = clock;
43
+ lastWork = work;
44
+ totalWork += work;
45
+ }
46
+ }
47
+ export function positions(text) {
48
+ const starts = [0];
49
+ for (let i = 0; i < text.length; i++)
50
+ if (text.charCodeAt(i) === 10)
51
+ starts.push(i + 1);
52
+ return (offset) => {
53
+ let lo = 0;
54
+ let hi = starts.length - 1;
55
+ while (lo < hi) {
56
+ const mid = (lo + hi + 1) >> 1;
57
+ if (starts[mid] <= offset)
58
+ lo = mid;
59
+ else
60
+ hi = mid - 1;
61
+ }
62
+ return { line: lo + 1, character: offset - starts[lo] };
63
+ };
64
+ }
@@ -0,0 +1,8 @@
1
+ import type { SemanticDiffFold, SemanticDiffOperation } from './pierre-types.js';
2
+ import { type TextDiff } from './textdiff.js';
3
+ /** A moved block may differ by at most this share of its characters; beyond that it reads as rewritten. */
4
+ export declare const MAX_MOVED_EDIT_RATIO = 0.2;
5
+ export declare function detectTextMoves(result: TextDiff, oldText: string, newText: string): {
6
+ operations: SemanticDiffOperation[];
7
+ folds: SemanticDiffFold[];
8
+ };