@plannotator/sem-jiff 0.2.0 → 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.
package/dist/inline.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isComment } from "./parse.js";
2
2
  import { likelyMoved, probabilityMoved } from "./classifier.js";
3
- import { currentSetup, flags, rule } from "./runtime.js";
3
+ import { currentSetup, flags, rule, trial } from "./runtime.js";
4
4
  import { pairFunctions } from "./pairing.js";
5
5
  import { allStatements, callsTo, dice, endLine, functionsIn, nodesWithTokens, pos, range, rangeOf, startLine, tokens, } from "./syntax.js";
6
6
  export const DEFAULT_INLINE_OPTIONS = { statementSimilarity: 0.7, coverage: 0.5 };
@@ -54,6 +54,125 @@ function boilerplate(roots, cfg) {
54
54
  }
55
55
  return out;
56
56
  }
57
+ /** Statements of a tree by shape (short ones only, as in boilerplate). */
58
+ function statementsByShape(root, cfg) {
59
+ const out = new Map();
60
+ for (const st of allStatements(root, cfg)) {
61
+ const k = shape(st);
62
+ if (k !== null)
63
+ out.set(k, [...(out.get(k) ?? []), st]);
64
+ }
65
+ return out;
66
+ }
67
+ const inside = (n, outer) => outer.startIndex <= n.startIndex && n.endIndex <= outer.endIndex;
68
+ /**
69
+ * Trial RUBY_SHAPES: a helper pulled out of several callers left one copy of each of its statements per caller, which
70
+ * reads as repetition. Such a statement is evidence after all for this helper when, on the helper's side, every
71
+ * copy is inside the helper, and on the other side every copy is inside a caller of it.
72
+ */
73
+ function repeatedFor(helper, fns, counterpart, common, [here, there], cfg) {
74
+ const callers = fns.flatMap((f) => {
75
+ const other = f !== helper ? counterpart(f) : null;
76
+ return other && callsTo(f.node, helper.name, cfg, helper.node).some((c) => !inside(c, helper.node)) ? [other.node] : [];
77
+ });
78
+ if (!callers.length)
79
+ return common;
80
+ const out = new Set(common);
81
+ for (const st of allStatements(helper.body, cfg)) {
82
+ const k = shape(st);
83
+ if (k === null || !common.has(k))
84
+ continue;
85
+ const mine = here.get(k) ?? [];
86
+ const theirs = there.get(k) ?? [];
87
+ if (mine.every((n) => inside(n, helper.node)) && theirs.length >= 2 && theirs.every((n) => callers.some((c) => inside(n, c))))
88
+ out.delete(k);
89
+ }
90
+ return out;
91
+ }
92
+ /** Leaf tokens with their offsets, as tokens() reads them. */
93
+ function leaves(n) {
94
+ const out = [];
95
+ const stack = [n];
96
+ while (stack.length) {
97
+ const x = stack.pop();
98
+ if (isComment(x))
99
+ continue;
100
+ if (x.childCount === 0) {
101
+ if (x.text.length)
102
+ out.push({ text: x.text, start: x.startIndex, end: x.endIndex });
103
+ continue;
104
+ }
105
+ for (let i = x.childCount - 1; i >= 0; i--) {
106
+ const c = x.child(i);
107
+ if (c)
108
+ stack.push(c);
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Trial RUBY_SHAPES: the call replaced one expression of a statement and nothing else in it changed (`params:
115
+ * env[Q].merge(env[F] || Hash[])` became `params: extract_params(env)`). That place anchors the old expression,
116
+ * so it is the helper's value when it is similar enough (half its tokens, the same calls, no other literals).
117
+ */
118
+ function inPlace(call, value, body, fresh, cfg) {
119
+ let st = call;
120
+ while (st.parent && st.parent.id !== body.id && !(cfg.blockTypes.has(st.parent.type) && cfg.statementsOf(st.parent).some((x) => x.id === st.id)))
121
+ st = st.parent;
122
+ if (st.id === call.id)
123
+ return null;
124
+ const ls = leaves(st);
125
+ const before = ls.filter((l) => l.end <= call.startIndex).map((l) => l.text);
126
+ const after = ls.filter((l) => l.start >= call.endIndex).map((l) => l.text);
127
+ if (before.length + after.length < 2)
128
+ return null;
129
+ const want = tokens(value);
130
+ if (want.length < 3)
131
+ return null;
132
+ const wantCalls = methodsCalled(value);
133
+ for (const f of outermost(fresh)) {
134
+ const lf = leaves(f);
135
+ const n = lf.length - before.length - after.length;
136
+ if (n < 3 || lf.slice(0, before.length).some((l, i) => l.text !== before[i]) || lf.slice(lf.length - after.length).some((l, i) => l.text !== after[i]))
137
+ continue;
138
+ const mid = lf.slice(before.length, before.length + n);
139
+ if (dice(mid.map((l) => l.text), want) < 0.5)
140
+ continue;
141
+ const node = f.descendantForIndex(mid[0].start, mid.at(-1).end);
142
+ if (!node || disjointLiterals(literals(node), literals(value)))
143
+ continue;
144
+ const calls = methodsCalled(node);
145
+ if (wantCalls.size && ![...calls].some((x) => wantCalls.has(x)))
146
+ continue;
147
+ return node;
148
+ }
149
+ return null;
150
+ }
151
+ /** Ruby: the names of the methods a node calls (`a.b.c(d)` calls b and c). */
152
+ function methodsCalled(n) {
153
+ const out = new Set();
154
+ const stack = [n];
155
+ while (stack.length) {
156
+ const x = stack.pop();
157
+ if (x.type === 'call') {
158
+ const m = x.childForFieldName('method')?.text;
159
+ if (m)
160
+ out.add(m);
161
+ }
162
+ for (const c of x.namedChildren)
163
+ if (c)
164
+ stack.push(c);
165
+ }
166
+ return out;
167
+ }
168
+ /** Ruby: the call is a statement of its own (also as the body of a modifier `if`), so its value is not used. */
169
+ function valueDropped(call, cfg) {
170
+ let x = call;
171
+ while (x.parent && /^(if|unless|while|until)_modifier$/.test(x.parent.type) && x.parent.childForFieldName('body')?.id === x.id)
172
+ x = x.parent;
173
+ const block = x.parent;
174
+ return !!block && cfg.blockTypes.has(block.type) && cfg.statementsOf(block).some((s) => s.id === x.id);
175
+ }
57
176
  const why = (helper, reason) => { if (flags.reasons())
58
177
  console.error(`[inline] ${helper}: ${reason}`); };
59
178
  /** `const x = helper(...)` where the helper returns the identifier `x`. */
@@ -69,12 +188,44 @@ function assignsToSameName(call, value) {
69
188
  }
70
189
  return false;
71
190
  }
191
+ /** The literal text in a node: string pieces around any code inside, and symbols (`"msg"`, `:no_session`). */
192
+ function literals(n) {
193
+ const out = new Set();
194
+ const walk = (x) => {
195
+ if (isComment(x))
196
+ return;
197
+ if ((/string|template/.test(x.type) && !/content|fragment/.test(x.type)) || /^(simple_symbol|delimited_symbol|hash_key_symbol|symbol_literal)$/.test(x.type)) {
198
+ // The code inside a string (`"${a.line}:"`) is not literal: only the text around it counts.
199
+ let text = x.text;
200
+ for (const c of [...x.namedChildren].reverse())
201
+ if (c && /interpolation|substitution|template_|expression/.test(c.type))
202
+ text = text.slice(0, c.startIndex - x.startIndex) + '\u0000' + text.slice(c.endIndex - x.startIndex);
203
+ // Pieces with a letter or digit: quotes and separators say nothing.
204
+ for (const piece of text.split('\u0000'))
205
+ if (/[\p{L}\p{N}]/u.test(piece))
206
+ out.add(piece);
207
+ return;
208
+ }
209
+ for (const c of x.namedChildren)
210
+ if (c)
211
+ walk(c);
212
+ };
213
+ walk(n);
214
+ return out;
215
+ }
216
+ /** Both have literals and share none. */
217
+ const disjointLiterals = (a, b) => a.size > 0 && b.size > 0 && ![...a].some((x) => b.has(x));
72
218
  /** Best one-to-one pairing of two statement lists by similarity, greedy and deterministic. */
73
219
  /** Statements this long (in tokens) rarely look alike by chance. */
74
220
  const LONG_STATEMENT = 25;
75
221
  function pairStatements(a, b, min, common = new Set()) {
76
222
  const ta = a.map(tokens);
77
223
  const tb = b.map(tokens);
224
+ // Trial XI_EVIDENCE: lookalikes that differ only in their literals are different code
225
+ // (`emit(offset, "Missing comma")` is not `emit(offset, "Unnecessary comma")`, `fetch :error` is not `fetch :no_session`).
226
+ const literalAware = trial('XI_EVIDENCE');
227
+ const la = literalAware ? a.map(literals) : [];
228
+ const lb = literalAware ? b.map(literals) : [];
78
229
  const wa = a.map(words);
79
230
  const wb = b.map(words);
80
231
  const ca = ta.map((t) => new Set(calledNames(t)));
@@ -92,7 +243,7 @@ function pairStatements(a, b, min, common = new Set()) {
92
243
  // Same punctuation and keywords is not enough: `db, err := openDB(cfg.DSN)` is
93
244
  // not `exp, err := newExporter(cfg.TraceURL)`. In a short statement, where shapes repeat
94
245
  // by chance, most names and values must match too (60%); a long one is evidence by its length.
95
- if (s >= min && sameAction(i, j) && (x.length >= LONG_STATEMENT || !wa[i].length || dice(wa[i], wb[j]) >= 0.6))
246
+ if (s >= min && sameAction(i, j) && (x.length >= LONG_STATEMENT || !wa[i].length || dice(wa[i], wb[j]) >= 0.6) && (!literalAware || !disjointLiterals(la[i], lb[j])))
96
247
  candidates.push([s, i, j]);
97
248
  });
98
249
  });
@@ -155,7 +306,8 @@ function findReplacementAnywhere(body, value, after, inFresh, minSimilarity, che
155
306
  return hit;
156
307
  }
157
308
  const want = tokens(value);
158
- const names = check === 'keepNames' ? want.filter((t) => /^[A-Za-z_$][\w$]*$/.test(t)) : [];
309
+ // Trial XI_EVIDENCE: a Ruby symbol names what it fetches or sends (`fetch :no_session` is not `fetch :error`): kept too.
310
+ const names = check === 'keepNames' ? want.filter((t) => /^[A-Za-z_$][\w$]*$/.test(t) || (trial('XI_EVIDENCE') && /^:[A-Za-z_]\w*[?!=]?$/.test(t))) : [];
159
311
  // Calls in the arguments at the call site stand in for the helper's parameters.
160
312
  const wantCalls = new Set([...calledNames(want), ...(passedIn ? calledNames(tokens(passedIn)) : [])]);
161
313
  // The older code may not call anything the newer value does not (`Config.FileNames()` is not `Config.BaseDirectory()`).
@@ -165,12 +317,13 @@ function findReplacementAnywhere(body, value, after, inFresh, minSimilarity, che
165
317
  const callsOk = (t) => (check !== 'sameCalls' || calledNames(t).every((c) => wantCalls.has(c))) && valueCalls.every((c) => calledNames(t).includes(c));
166
318
  let best = null;
167
319
  let bestScore = minSimilarity;
320
+ const wantLiterals = trial('XI_EVIDENCE') ? literals(value) : null;
168
321
  const walk = (n) => {
169
322
  if (n.startIndex >= after && inFresh(n) && n.namedChildCount > 0) {
170
323
  const t = tokens(n);
171
324
  if (t.length >= want.length / 2 && t.length <= want.length * 2) {
172
325
  const s = dice(want, t);
173
- if (s > bestScore && names.every((x) => t.includes(x)) && callsOk(t) && (params === null || sameOrder(want, t, params, VALUE_ORDER))) {
326
+ if (s > bestScore && names.every((x) => t.includes(x)) && callsOk(t) && (params === null || sameOrder(want, t, params, VALUE_ORDER)) && !(wantLiterals && disjointLiterals(wantLiterals, literals(n)))) {
174
327
  bestScore = s;
175
328
  best = n;
176
329
  }
@@ -318,6 +471,12 @@ export function detectInlined(oldRoot, newRoot, oldText, cfg, options = DEFAULT_
318
471
  const oldLines = oldText.split('\n');
319
472
  const ops = [];
320
473
  const common = boilerplate([oldRoot, newRoot], cfg);
474
+ // Trial XI_EVIDENCE: every candidate is scored first, then assigned one to one (see assignEvidence).
475
+ const oneToOne = trial('XI_EVIDENCE');
476
+ const accepted = [];
477
+ // Trial RUBY_SHAPES (Ruby): see repeatedFor and tailIsValue.
478
+ const rubyShapes = trial('RUBY_SHAPES') && cfg.id === 'ruby';
479
+ const copies = rubyShapes ? [statementsByShape(oldRoot, cfg), statementsByShape(newRoot, cfg)] : null;
321
480
  for (const helper of oldFns.filter((f) => {
322
481
  if (counterpart(f)) {
323
482
  why(f.name, 'not a candidate: it still exists on the other side');
@@ -331,6 +490,7 @@ export function detectInlined(oldRoot, newRoot, oldText, cfg, options = DEFAULT_
331
490
  })) {
332
491
  // Debug only: why a helper never became a candidate with any caller.
333
492
  const seen = flags.reasons() ? { calledByUnpaired: 0, stillCalled: 0, candidates: 0 } : null;
493
+ const helperCommon = copies ? repeatedFor(helper, oldFns, counterpart, common, copies, cfg) : common;
334
494
  for (const caller of oldFns) {
335
495
  if (caller === helper)
336
496
  continue;
@@ -351,11 +511,22 @@ export function detectInlined(oldRoot, newRoot, oldText, cfg, options = DEFAULT_
351
511
  }
352
512
  if (seen)
353
513
  seen.candidates++;
354
- const c = makeCase({ helper, caller, callerNew, calls, oldFns, newFns, cfg, common, options });
514
+ // Trial XI_EVIDENCE: code inside a parse error is no evidence of anything.
515
+ if (oneToOne && [helper, caller, callerNew].some((f) => unreadable(f.node))) {
516
+ why(helper.name, 'not a candidate: its helper or caller sits inside a parse error');
517
+ continue;
518
+ }
519
+ let c = makeCase({ helper, caller, callerNew, calls, oldFns, newFns, cfg, common: helperCommon, options });
355
520
  // Evidence 1: the helper's statements reappear one by one. Evidence 2, when statements changed
356
521
  // shape on the way (`x = A` in an if/else chain became `return A`): the helper's tokens line up,
357
522
  // in order, with the code the caller lost.
358
523
  let found = byStatements(c) ?? alignedTokens(c.stmts, c.fresh, helper.name, callerNew.body, caller.body, helper.node);
524
+ // Trial RUBY_SHAPES: the tail read as a statement did not pair; read it as the value, as by default.
525
+ if (!found && c.tailDropped) {
526
+ why(helper.name, 'tail as a statement found nothing: read as the value');
527
+ c = makeCase({ helper, caller, callerNew, calls, oldFns, newFns, cfg, common: helperCommon, options, tailAsValue: true });
528
+ found = byStatements(c) ?? alignedTokens(c.stmts, c.fresh, helper.name, callerNew.body, caller.body, helper.node);
529
+ }
359
530
  // The rules above are strict on purpose. A candidate they reject can still be accepted by the
360
531
  // learned check (`classifier.ts`) or a second opinion (a decision model), each with its own guards.
361
532
  const secondOpinion = options.secondOpinion ?? currentSetup().secondOpinion;
@@ -371,18 +542,76 @@ export function detectInlined(oldRoot, newRoot, oldText, cfg, options = DEFAULT_
371
542
  if (!found)
372
543
  continue;
373
544
  const { pairs, replacement } = found;
374
- ops.push(buildOperation({ helper, calls, ret: c.ret, pairs, replacement, oldLines }));
545
+ if (oneToOne)
546
+ accepted.push({ c, pairs, replacement, order: accepted.length });
547
+ else
548
+ ops.push(buildOperation({ helper, calls, ret: c.ret, pairs, replacement, oldLines }));
375
549
  }
376
550
  if (seen && !seen.candidates)
377
551
  why(helper.name, seen.stillCalled ? 'not a candidate: callers still call it' : seen.calledByUnpaired ? "not a candidate: its callers have no counterpart on the other side" : 'not a candidate: no call to it found');
378
552
  }
553
+ if (oneToOne)
554
+ for (const a of assignEvidence(accepted))
555
+ ops.push(buildOperation({ helper: a.c.helper, calls: a.c.calls, ret: a.c.ret, pairs: a.pairs, replacement: a.replacement, oldLines }));
379
556
  return ops;
380
557
  }
558
+ /**
559
+ * The function sits inside a parse error: the parser lost the code around it (a class header it could not read
560
+ * turns the members into top-level functions). An error inside a function (newer syntax the grammar lacks) is
561
+ * not enough: the function is still where it was.
562
+ */
563
+ function unreadable(n) {
564
+ for (let p = n.parent; p; p = p.parent)
565
+ if (p.isError)
566
+ return true;
567
+ return false;
568
+ }
569
+ /**
570
+ * Trial XI_EVIDENCE: one piece of evidence backs one operation. A statement of the caller's other version, the
571
+ * expression that replaced a call, and a call site belong to the candidate that explains the most of its helper
572
+ * (helper tokens matched, weighted by similarity; then the share of its helper); a helper may still go to several callers. A candidate that
573
+ * shares a call site loses; one that shares moved code keeps what is left only if that still covers enough of its
574
+ * helper. Candidates are not handed leftover lines: a loser is rebuilt from its own evidence or dropped.
575
+ */
576
+ function assignEvidence(cands) {
577
+ const helperTokens = (c) => c.stmts.reduce((n, s) => n + tokens(s).length, 0) || 1;
578
+ const valueTokens = (a) => (a.replacement ? tokens(a.replacement).length : 0);
579
+ const score = (a, pairs) => pairs.reduce((n, p) => n + tokens(p.a).length * p.similarity, 0) + valueTokens(a);
580
+ // The same node, not merely nested: two helpers can come out of one large statement.
581
+ const overlaps = (x, y) => x.startIndex === y.startIndex && x.endIndex === y.endIndex;
582
+ const order = [...cands].sort((x, y) => score(y, y.pairs) - score(x, x.pairs) || score(y, y.pairs) / helperTokens(y.c) - score(x, x.pairs) / helperTokens(x.c) || x.order - y.order);
583
+ const usedBodies = [];
584
+ const usedCalls = new Set();
585
+ const out = [];
586
+ for (const a of order) {
587
+ if (a.c.calls.some((call) => usedCalls.has(call.startIndex))) {
588
+ why(a.c.helper.name, `one to one: its call site went to another candidate`);
589
+ continue;
590
+ }
591
+ const pairs = a.pairs.filter((p) => !usedBodies.some((u) => overlaps(u, p.b)));
592
+ const replacement = a.replacement && !usedBodies.some((u) => overlaps(u, a.replacement)) ? a.replacement : null;
593
+ if (pairs.length < a.pairs.length || replacement !== a.replacement) {
594
+ const left = score({ ...a, replacement }, pairs) / helperTokens(a.c);
595
+ if ((!pairs.length && !replacement) || left < a.c.options.coverage) {
596
+ why(a.c.helper.name, `one to one: its evidence went to another candidate (${left.toFixed(2)} left)`);
597
+ continue;
598
+ }
599
+ }
600
+ out.push({ ...a, pairs, replacement });
601
+ usedBodies.push(...pairs.map((p) => p.b), ...(replacement ? [replacement] : []));
602
+ for (const call of a.c.calls)
603
+ usedCalls.add(call.startIndex);
604
+ }
605
+ return out.sort((x, y) => x.order - y.order);
606
+ }
381
607
  function makeCase(a) {
382
608
  const { helper, caller, callerNew, calls, oldFns, newFns, cfg, common, options } = a;
383
609
  const stmts = helper.statements;
384
610
  const last = stmts.at(-1);
385
- const ret = last && cfg.isReturn(last, true) ? last : null;
611
+ // Trial RUBY_SHAPES: an implicit return is no value when every call drops it.
612
+ const tailIsValue = !!a.tailAsValue || !(trial('RUBY_SHAPES') && cfg.id === 'ruby' && last?.type !== 'return' && calls.every((c) => valueDropped(c, cfg)));
613
+ const ret = last && tailIsValue && cfg.isReturn(last, true) ? last : null;
614
+ const tailDropped = !tailIsValue && !!last && cfg.isReturn(last, true);
386
615
  const moved = ret ? stmts.slice(0, -1) : stmts;
387
616
  const call = calls[0];
388
617
  // Statements that are new in the caller (not already present before).
@@ -398,7 +627,7 @@ function makeCase(a) {
398
627
  const declares = (s, f) => !known.has(f.name) && f.node.startIndex >= s.startIndex && f.node.endIndex <= s.endIndex &&
399
628
  (f.node.parent?.id === s.id || (f.node.parent?.parent?.id === s.id && /declarator/.test(f.node.parent.type)));
400
629
  const fresh = allStatements(callerNew.body, cfg).filter((s) => !before.has(key(s)) && !nested.some((f) => declares(s, f) || (f.node.startIndex <= s.startIndex && s.endIndex <= f.node.endIndex)));
401
- return { helper, caller, callerNew, calls, call, stmts, ret, moved, fresh, cfg, common, options };
630
+ return { helper, caller, callerNew, calls, call, stmts, ret, moved, fresh, cfg, common, options, tailDropped };
402
631
  }
403
632
  /** The rule: the helper's statements reappear, one by one, in code new to the caller (and its value at the call's place). */
404
633
  function byStatements(c) {
@@ -427,12 +656,19 @@ function byStatements(c) {
427
656
  const check = pairs.length ? 'none' : options.mirrored ? 'sameCalls' : 'keepNames';
428
657
  // `const x = helper()` + `return x`: the helper's own `x` took over, so no expression replaced the
429
658
  // call. Looking for one anyway would land on some later use of `x` and claim that line.
430
- const replacement = value && calls.length === 1 && !assignsToSameName(call, value) ? findReplacement(callerNew.body, value, afterMoved, inFresh, pairs.length ? 0.6 : 0.8, check, call.childForFieldName('arguments'), !pairs.length && helper.body.type !== 'statement_block' && helper.body.parent?.type === 'arrow_function' ? parameterNames(helper) : null, substitutedValue(helper, value, call), !pairs.length && stmts.length === 1 ? caller.body : null, caller.body) : null;
659
+ const found = value && calls.length === 1 && !assignsToSameName(call, value) ? findReplacement(callerNew.body, value, afterMoved, inFresh, pairs.length ? 0.6 : 0.8, check, call.childForFieldName('arguments'), !pairs.length && helper.body.type !== 'statement_block' && helper.body.parent?.type === 'arrow_function' ? parameterNames(helper) : null, substitutedValue(helper, value, call), !pairs.length && stmts.length === 1 ? caller.body : null, caller.body) : null;
660
+ // Trial RUBY_SHAPES: an edited value is still found where the call took its place in an otherwise unchanged statement.
661
+ const replacement = found ?? (value && calls.length === 1 && trial('RUBY_SHAPES') && cfg.id === 'ruby' ? inPlace(call, value, caller.body, fresh, cfg) : null);
431
662
  // No replacement expression: accept only when the call's result was stored in a
432
663
  // variable of the same name the helper returned (`const x = helper()` + `return x`),
433
664
  // so the helper's own `x` simply took over.
434
665
  // Boilerplate statements still count in the total: they cannot be evidence, but the helper is made of them.
435
666
  const helperTokens = stmts.reduce((n, s) => n + tokens(s).length, 0) || 1;
667
+ // The tiny-value rule below, for a tail read as a statement: `def finish; close; end` is no evidence.
668
+ if (c.tailDropped && helperTokens < 3) {
669
+ why(helper.name, 'only a tiny statement reappears');
670
+ return null;
671
+ }
436
672
  // When most of the helper's statements came from the caller, its return value
437
673
  // may be new (`return true`, `return nil`): the moved code is evidence enough.
438
674
  const movedShare = pairs.reduce((n, p) => n + tokens(p.a).length * p.similarity, 0) / helperTokens;
@@ -21,7 +21,8 @@ export interface ChangeBlock {
21
21
  */
22
22
  export declare const NO_FINAL_NEWLINE = "\0no-newline";
23
23
  export declare function diffLines(text: string): string[];
24
- /** Lines as `diffLines` gives them (see there). */
25
24
  export declare function alignedLineDiff(oldRoot: Node, newRoot: Node, cfg: LanguageConfig, oldLines: string[], newLines: string[]): ChangeBlock[];
26
25
  /** Unified diff text for the blocks (standard unified diff format). */
27
26
  export declare function toPatch(name: string, blocks: ChangeBlock[], oldLines: string[], newLines: string[], context?: number): string;
27
+ /** The lines `blocks` leave unchanged, old line to new line (1-based). */
28
+ export declare function unchangedLinePairs(blocks: ChangeBlock[], oldCount: number): Map<number, number>;
package/dist/linediff.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // recursively through class members, and only the gaps between anchors are
7
7
  // diffed freely.
8
8
  import { diffArrays } from 'diff';
9
+ import { trial } from "./runtime.js";
9
10
  import { attachedAbove, codeLines, endLine, keepWeights, longestInOrder, pairSameNamed, startLine, tokens } from "./syntax.js";
10
11
  function anchors(oldContainer, newContainer, cfg) {
11
12
  const keyed = (container) => {
@@ -50,6 +51,18 @@ export function diffLines(text) {
50
51
  return lines;
51
52
  }
52
53
  /** Lines as `diffLines` gives them (see there). */
54
+ /** First line of the comments and attributes directly above a declaration (no blank line between), else its own first line. */
55
+ function commentStart(n, cfg) {
56
+ let line = startLine(n);
57
+ for (let c = n.previousSibling; c && cfg.attachedTypes.has(c.type); c = c.previousSibling) {
58
+ // A comment node can end at the start of the next line (Rust line comments): compare where it really ends.
59
+ const end = c.endPosition.column === 0 && c.endPosition.row > c.startPosition.row ? c.endPosition.row : c.endPosition.row + 1;
60
+ if (end !== line - 1)
61
+ break;
62
+ line = startLine(c);
63
+ }
64
+ return line;
65
+ }
53
66
  export function alignedLineDiff(oldRoot, newRoot, cfg, oldLines, newLines) {
54
67
  const blocks = [];
55
68
  /** Free diff of a region (1-based inclusive lines; may be empty). */
@@ -90,10 +103,24 @@ export function alignedLineDiff(oldRoot, newRoot, cfg, oldLines, newLines) {
90
103
  let n = r.newStart;
91
104
  for (const p of pairs) {
92
105
  // Half-written code can end past the last line (the parser supplies a missing `}`).
106
+ // Trial ATTACH_DOC: a declaration's anchor starts at the comments directly above it, so its doc comment lines
107
+ // up with its own counterpart, not with a lookalike `/**` of a neighbour. Only when those comments are the same
108
+ // lines on both sides: a comment that changed (reindented with its code) stays a change block of its own, as before.
109
+ let docOld = startLine(p.a);
110
+ let docNew = startLine(p.b);
111
+ if (trial('ATTACH_DOC')) {
112
+ const ca = commentStart(p.a, cfg);
113
+ const cb = commentStart(p.b, cfg);
114
+ const same = startLine(p.a) - ca === startLine(p.b) - cb && oldLines.slice(ca - 1, startLine(p.a) - 1).every((l, i) => l === newLines[cb - 1 + i]);
115
+ if (same) {
116
+ docOld = ca;
117
+ docNew = cb;
118
+ }
119
+ }
93
120
  const ps = {
94
- oldStart: startLine(p.a),
121
+ oldStart: docOld,
95
122
  oldEnd: Math.min(endLine(p.a), oldLines.length),
96
- newStart: startLine(p.b),
123
+ newStart: docNew,
97
124
  newEnd: Math.min(endLine(p.b), newLines.length),
98
125
  };
99
126
  if (ps.oldStart > oldLines.length || ps.newStart > newLines.length)
@@ -161,3 +188,18 @@ export function toPatch(name, blocks, oldLines, newLines, context = 3) {
161
188
  // git's marker for a last line without a newline, right after that line.
162
189
  return out.flatMap((l) => (l.endsWith(NO_FINAL_NEWLINE) ? [l.slice(0, -NO_FINAL_NEWLINE.length), '\'] : [l])).join('\n') + '\n';
163
190
  }
191
+ /** The lines `blocks` leave unchanged, old line to new line (1-based). */
192
+ export function unchangedLinePairs(blocks, oldCount) {
193
+ const out = new Map();
194
+ let o = 1;
195
+ let n = 1;
196
+ for (const b of [...blocks].sort((x, y) => x.oldAt - y.oldAt || x.newAt - y.newAt)) {
197
+ while (o < b.oldAt && n < b.newAt)
198
+ out.set(o++, n++);
199
+ o = b.old ? b.old.end + 1 : b.oldAt;
200
+ n = b.new ? b.new.end + 1 : b.newAt;
201
+ }
202
+ while (o <= oldCount)
203
+ out.set(o++, n++);
204
+ return out;
205
+ }
package/dist/pairing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Node } from 'web-tree-sitter';
2
- import type { LanguageConfig } from './parse.js';
2
+ import { type LanguageConfig } from './parse.js';
3
3
  import { type FunctionInfo } from './syntax.js';
4
4
  export interface Pairing {
5
5
  /** The same function on the other side, if it still exists there. */
package/dist/pairing.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Which function on one side is the same function on the other: the pairing the extract/inline
2
2
  // check builds on. A function with a counterpart still exists (it was not inlined or extracted);
3
3
  // one with a twin moved or was renamed. Each rule below is one way the same function shows up.
4
- import { rule } from "./runtime.js";
5
- import { callsTo, dice, pairSameNamed, tokens } from "./syntax.js";
4
+ import { rule, trial } from "./runtime.js";
5
+ import { swiftParams } from "./parse.js";
6
+ import { callsParent, callsTo, dice, pairSameNamed, tokens } from "./syntax.js";
6
7
  export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
7
8
  // Same function in both versions: same class (or receiver) and name, or, when the
8
9
  // class itself was renamed, the only function of that name on each side.
@@ -10,8 +11,15 @@ export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
10
11
  // The overload that kept the old parameter list is the old function: when code moves
11
12
  // into a new, longer overload (`readFrom(in, funnel)` -> `readFrom(in, funnel, max)`),
12
13
  // body similarity alone would pair the old one with the overload now holding its code.
14
+ // Trial FN_PAIRING: Swift has no `parameters` field. Its signature is the declaration's header before the
15
+ // body (parameter labels and types, `async`, `throws`, the result type), so overloads are told apart by what
16
+ // they take and give, not by their bodies alone.
17
+ const fnPairing = trial('FN_PAIRING');
18
+ const swiftSig = (f) => fnPairing && cfg.id === 'swift' && SWIFT_SIGNED.has(f.node.type);
13
19
  const signature = (f) => {
14
- const p = tokens(f.node.childForFieldName('parameters') ?? f.node.childForFieldName('value')?.childForFieldName('parameters') ?? f.body).slice(0, 60);
20
+ const p = swiftSig(f)
21
+ ? f.node.children.filter((c) => !!c && c.endIndex <= f.body.startIndex && c.type !== 'modifiers').flatMap(tokens).slice(0, 60)
22
+ : tokens(f.node.childForFieldName('parameters') ?? f.node.childForFieldName('value')?.childForFieldName('parameters') ?? f.body).slice(0, 60);
15
23
  return [...p, ...p, ...p, ...tokens(f.body)];
16
24
  };
17
25
  // An overload that kept the old parameter list exactly is the old function, however
@@ -22,6 +30,8 @@ export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
22
30
  const p = f.node.childForFieldName('parameters') ?? f.node.childForFieldName('value')?.childForFieldName('parameters');
23
31
  return p ? tokens(p).join(' ') : null;
24
32
  };
33
+ // A tie-break, not a key: only huge same-name groups (which otherwise pair in order) pair an exact parameter list first.
34
+ const exactSignature = (f) => (swiftSig(f) ? swiftParams(f.node) : params(f));
25
35
  const samePlace = (fs, f) => fs.filter((g) => base(g) === base(f));
26
36
  const pinned = [];
27
37
  // Either way round: one function became several overloads, or several became one.
@@ -77,17 +87,21 @@ export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
77
87
  pinned.push([f, g]);
78
88
  taken.add(f).add(g);
79
89
  }
90
+ if (fnPairing)
91
+ pinned.push(...renameChains(oldFns, newFns, oldRoot, newRoot, cfg, base, taken));
80
92
  }
81
93
  const pinnedOld = new Set(pinned.map(([a]) => a));
82
94
  const pinnedNew = new Set(pinned.map(([, b]) => b));
83
95
  const byKey = new Map([
84
96
  ...pinned,
85
- ...pairSameNamed(oldFns.filter((f) => !pinnedOld.has(f)), newFns.filter((f) => !pinnedNew.has(f)), base, signature),
97
+ ...pairSameNamed(oldFns.filter((f) => !pinnedOld.has(f)), newFns.filter((f) => !pinnedNew.has(f)), base, signature, undefined, fnPairing ? exactSignature : undefined),
86
98
  ]);
87
99
  const count = (fs) => fs.reduce((m, f) => m.set(f.name, (m.get(f.name) ?? 0) + 1), new Map());
88
100
  const oldCount = count(oldFns);
89
101
  const newCount = count(newFns);
90
- const newOnlyByName = new Map(newFns.filter((f) => newCount.get(f.name) === 1).map((f) => [f.name, f]));
102
+ // With FN_PAIRING, a function already paired (a rename chain took it) is no one else's counterpart by name.
103
+ const pairedNew = fnPairing ? new Set(byKey.values()) : new Set();
104
+ const newOnlyByName = new Map(newFns.filter((f) => newCount.get(f.name) === 1 && !pairedNew.has(f)).map((f) => [f.name, f]));
91
105
  const counterpart = (f) => byKey.get(f) ?? (oldCount.get(f.name) === 1 ? newOnlyByName.get(f.name) : undefined);
92
106
  // A function whose twin (same name, same body) is on the other side was moved or
93
107
  // had its class renamed; it was not inlined or extracted.
@@ -118,6 +132,124 @@ export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
118
132
  };
119
133
  return { counterpart, hasTwin };
120
134
  }
135
+ /**
136
+ * Trial FN_PAIRING: renames where a new function took the old name, which name-only pairing reads as an
137
+ * extract or inline. `f` (old) and `g` (new) under different names
138
+ * in one class are one function when their bodies are near-identical (dice >= 0.9, 12+ tokens), or identical and short
139
+ * with the references to the name moved over (`schema` -> `__schema__`, callers updated); one to one, and
140
+ * only when a namesake took a name. A namesake that calls the other one took its body (an inline or an
141
+ * extract), unless it is itself one link of the chain: its body reappears in another new (old) function,
142
+ * with the call renamed (`clearDiskCache()` -> `clearDiskCache_()` while `clearDiskCacheWith...(_:)` ->
143
+ * `clearDiskCache(with:)`); a call to the parent's version (`super.f`, `superclass&.__schema__`) never counts.
144
+ */
145
+ function renameChains(oldFns, newFns, oldRoot, newRoot, cfg, base, taken) {
146
+ const out = [];
147
+ const toks = new Map();
148
+ const t = (f) => toks.get(f) ?? (toks.set(f, tokens(f.body)), toks.get(f));
149
+ const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
150
+ let refs = null;
151
+ const moved = (from, to) => {
152
+ refs ??= [leafCounts(oldRoot), leafCounts(newRoot)];
153
+ const [o, n] = refs;
154
+ return (o.get(from) ?? 0) > (n.get(from) ?? 0) && (n.get(to) ?? 0) > (o.get(to) ?? 0);
155
+ };
156
+ const alike = (f, g) => {
157
+ const a = t(f);
158
+ const b = t(g);
159
+ if (a.length >= 12 && b.length >= 12)
160
+ return dice(a, b);
161
+ return a.length >= 4 && same(a, b) && f.name !== g.name && moved(f.name, g.name) ? 1 : 0;
162
+ };
163
+ const scope = (f) => base(f).slice(0, base(f).lastIndexOf('/'));
164
+ const ownCalls = (x, name) => callsTo(x.node, name, cfg).filter((c) => !callsParent(c));
165
+ // `x` (on one side) calls `name`; its own twin `y` on the other side calls `to` and reads the same with the call renamed.
166
+ // `y` is new to its side: no function of its name on `x`'s side.
167
+ const chainTwin = (x, name, to, others, xSide) => {
168
+ const want = t(x).map((k) => (k === name ? to : k));
169
+ return others.find((y) => !taken.has(y) && y.name !== x.name && !xSide.some((z) => base(z) === base(y)) && ownCalls(y, to).length && dice(want, t(y)) >= 0.8);
170
+ };
171
+ const best = (pool, skip, score1) => {
172
+ let top = null;
173
+ let score = 0;
174
+ let tie = false;
175
+ for (const g of pool) {
176
+ if (taken.has(g) || skip(g))
177
+ continue;
178
+ const s = score1(g);
179
+ if (s > score) {
180
+ top = g;
181
+ score = s;
182
+ tie = false;
183
+ }
184
+ else if (s === score && s > 0)
185
+ tie = true;
186
+ }
187
+ return score >= 0.9 && !tie ? { g: top, score } : null;
188
+ };
189
+ for (const f of oldFns) {
190
+ if (taken.has(f))
191
+ continue;
192
+ const m = best(newFns, (g) => g.name === f.name || scope(g) !== scope(f), (g) => alike(f, g));
193
+ if (!m)
194
+ continue;
195
+ const { g, score } = m;
196
+ const back = best(oldFns, (x) => x.name === g.name || scope(x) !== scope(g), (x) => alike(x, g));
197
+ if (back?.g !== f)
198
+ continue;
199
+ const sameNameNew = newFns.filter((x) => base(x) === base(f));
200
+ const sameNameOld = oldFns.filter((x) => base(x) === base(g));
201
+ if (!sameNameNew.length && !sameNameOld.length)
202
+ continue; // a plain rename: hasTwin handles it
203
+ // A same-name partner just as alike: a copy, not a rename.
204
+ if (sameNameNew.some((x) => alike(f, x) >= score) || sameNameOld.some((x) => alike(x, g) >= score))
205
+ continue;
206
+ const links = [];
207
+ let namesakeTookIt = false;
208
+ for (const x of sameNameOld) {
209
+ if (!ownCalls(x, f.name).length)
210
+ continue;
211
+ const y = chainTwin(x, f.name, g.name, newFns.filter((y) => y !== g), oldFns);
212
+ if (y)
213
+ links.push([x, y]);
214
+ else
215
+ namesakeTookIt = true;
216
+ }
217
+ for (const x of sameNameNew) {
218
+ if (!ownCalls(x, g.name).length)
219
+ continue;
220
+ const y = chainTwin(x, g.name, f.name, oldFns.filter((y) => y !== f), newFns);
221
+ if (y)
222
+ links.push([y, x]);
223
+ else
224
+ namesakeTookIt = true;
225
+ }
226
+ if (namesakeTookIt)
227
+ continue;
228
+ out.push([f, g], ...links);
229
+ taken.add(f).add(g);
230
+ for (const [a, b] of links)
231
+ taken.add(a).add(b);
232
+ }
233
+ return out;
234
+ }
235
+ /** How often each leaf text occurs in the tree (declarations and references alike). */
236
+ function leafCounts(root) {
237
+ const out = new Map();
238
+ const stack = [root];
239
+ while (stack.length) {
240
+ const n = stack.pop();
241
+ if (n.childCount === 0) {
242
+ out.set(n.text, (out.get(n.text) ?? 0) + 1);
243
+ continue;
244
+ }
245
+ for (const c of n.children)
246
+ if (c)
247
+ stack.push(c);
248
+ }
249
+ return out;
250
+ }
251
+ /** Swift declarations with a parameter list (a computed property has none). */
252
+ const SWIFT_SIGNED = new Set(['function_declaration', 'init_declaration', 'subscript_declaration']);
121
253
  /** How often the tree declares each name (a leaf that is its parent's `name` field). */
122
254
  function namesIn(root) {
123
255
  const out = new Map();