@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,19 @@
1
+ import type { SemanticDiffOperation, SemanticDiffOperationType } from './pierre-types.js';
2
+ /** Kinds of change that alter what the code does (or may): always shown. */
3
+ export declare const READ_KINDS: readonly SemanticDiffOperationType[];
4
+ /** Kinds that leave the code's meaning alone: safe to collapse, never to remove from view. */
5
+ export declare const SKIM_KINDS: readonly SemanticDiffOperationType[];
6
+ export interface ReviewSummary {
7
+ /** Operations to read, in the engine's order. */
8
+ read: SemanticDiffOperation[];
9
+ /** Operations that can be collapsed to one row each. */
10
+ skim: SemanticDiffOperation[];
11
+ /** How many operations of each kind. */
12
+ counts: Partial<Record<SemanticDiffOperationType, number>>;
13
+ /** Changed lines (old side + new side) owned by each group. */
14
+ lines: {
15
+ read: number;
16
+ skim: number;
17
+ };
18
+ }
19
+ export declare function reviewSummary(operations: SemanticDiffOperation[]): ReviewSummary;
@@ -0,0 +1,15 @@
1
+ /** Kinds of change that alter what the code does (or may): always shown. */
2
+ export const READ_KINDS = ['edited', 'added', 'deleted', 'movedWithEdit'];
3
+ /** Kinds that leave the code's meaning alone: safe to collapse, never to remove from view. */
4
+ export const SKIM_KINDS = ['moved', 'renamed', 'reordered', 'reformatted', 'extractedFunction', 'inlinedFunction'];
5
+ const lineCount = (op) => [...op.lines.old, ...op.lines.new].reduce((n, r) => n + (r.end - r.start + 1), 0);
6
+ export function reviewSummary(operations) {
7
+ const out = { read: [], skim: [], counts: {}, lines: { read: 0, skim: 0 } };
8
+ for (const op of operations) {
9
+ out.counts[op.type] = (out.counts[op.type] ?? 0) + 1;
10
+ const group = SKIM_KINDS.includes(op.type) ? 'skim' : 'read'; // an unknown kind is read, not hidden
11
+ out[group].push(op);
12
+ out.lines[group] += lineCount(op);
13
+ }
14
+ return out;
15
+ }
@@ -0,0 +1,18 @@
1
+ import type { SemanticDiffOperation } from './pierre-types.js';
2
+ export type SymbolKind = 'function' | 'method' | 'constructor' | 'class' | 'interface' | 'enum' | 'struct' | 'property' | 'field' | 'variable' | 'type' | 'module' | 'namespace' | 'import' | 'other';
3
+ export interface OperationSymbol {
4
+ /** The declaration's own name as written, without class, receiver or namespace: "greet", not "Greeter.greet". */
5
+ name: string;
6
+ kind: SymbolKind;
7
+ /** renamed only: the name before (`name` is the name after). */
8
+ oldName?: string;
9
+ /**
10
+ * The enclosing declarations, outermost first, joined with "." ("Greeter", "User.Companion"). For a Kotlin
11
+ * extension function or property it is the receiver type; inside a Swift extension, the extended type.
12
+ */
13
+ container?: string;
14
+ }
15
+ /** An operation as semanticDiffFile returns it: Pierre's operation plus the optional symbol. */
16
+ export type SemDiffOperation = SemanticDiffOperation & {
17
+ symbol?: OperationSymbol;
18
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import type { Node } from 'web-tree-sitter';
2
+ import type { LanguageConfig } from './parse.js';
3
+ import type { SemDiffOperation } from './symbol-types.js';
4
+ export type { OperationSymbol, SemDiffOperation, SymbolKind } from './symbol-types.js';
5
+ /** Set `symbol` on every operation the rules name a declaration for (docs/symbols.md); never changes anything else. */
6
+ export declare function attachSymbols(ops: SemDiffOperation[], oldRoot: Node, newRoot: Node, oldText: string, newText: string, cfg: LanguageConfig): void;
@@ -0,0 +1,458 @@
1
+ import { functionsIn } from "./syntax.js";
2
+ const FUNCTION_KINDS = new Set(['function', 'method', 'constructor']);
3
+ const line = (n) => n.startPosition.row + 1;
4
+ const lastLine = (n) => n.endPosition.row + 1;
5
+ /** First line of the comments and attributes directly above a declaration (no blank line between). */
6
+ function attachedStart(n, cfg) {
7
+ let at = line(n);
8
+ for (let c = n.previousSibling; c && cfg.attachedTypes.has(c.type); c = c.previousSibling) {
9
+ const end = c.endPosition.column === 0 && c.endPosition.row > c.startPosition.row ? c.endPosition.row : c.endPosition.row + 1;
10
+ if (end !== at - 1)
11
+ break;
12
+ at = line(c);
13
+ }
14
+ return at;
15
+ }
16
+ const bareType = (t) => (t.match(/[A-Za-z_][\w]*/g) ?? []).filter((w) => !/^(where|extension|impl|for)$/.test(w))[0] ?? t;
17
+ /** Name and container prefix of a declaration, per language: receivers, namespaces and `self.` are taken off the name. */
18
+ function nameOf(d, cfg) {
19
+ const raw = d.name;
20
+ if (d.kind === 'import' || d.kind === 'export-from') {
21
+ const key = raw.slice(raw.lastIndexOf(' ') + 1);
22
+ return key ? { name: key } : null;
23
+ }
24
+ switch (cfg.id) {
25
+ case 'kotlin': {
26
+ if (d.kind === 'companion')
27
+ return { name: raw === 'companion' ? 'Companion' : raw.slice('companion '.length) };
28
+ const dot = d.kind.startsWith('function') || d.kind === 'property' ? raw.lastIndexOf('.') : -1;
29
+ return dot > 0 ? { name: raw.slice(dot + 1), receiver: raw.slice(0, dot) } : { name: raw };
30
+ }
31
+ case 'go': {
32
+ const m = raw.match(/^\(\s*\*?\s*([A-Za-z_]\w*)[^)]*\)\.(.+)$/);
33
+ return m ? { name: m[2], receiver: m[1] } : { name: raw };
34
+ }
35
+ case 'php':
36
+ return { name: raw.slice(raw.lastIndexOf('\\') + 1) };
37
+ case 'ruby':
38
+ return { name: raw.replace(/^self\./, '') };
39
+ default:
40
+ return { name: raw };
41
+ }
42
+ }
43
+ /** The kind of a declaration (null: give no symbol), from its config kind and node type. */
44
+ function kindOf(d, parent, cfg) {
45
+ const k = d.kind;
46
+ const t = d.node.type;
47
+ if (k === 'import' || k === 'export-from')
48
+ return 'import';
49
+ const inType = !!parent && parent.kind !== null && ['class', 'interface', 'enum', 'struct', 'other'].includes(parent.kind);
50
+ const fn = () => (inType ? 'method' : 'function');
51
+ switch (cfg.id) {
52
+ case 'typescript':
53
+ case 'tsx': {
54
+ const decl = t === 'export_statement' ? (d.node.childForFieldName('declaration') ?? d.node) : d.node;
55
+ const dt = decl.type;
56
+ if (/^(function_declaration|generator_function_declaration|function_signature)$/.test(dt))
57
+ return 'function';
58
+ if (dt === 'method_definition' || dt === 'method_signature' || dt === 'abstract_method_signature')
59
+ return d.name === 'constructor' ? 'constructor' : 'method';
60
+ if (dt === 'class_declaration' || dt === 'abstract_class_declaration')
61
+ return 'class';
62
+ if (dt === 'interface_declaration')
63
+ return 'interface';
64
+ if (dt === 'enum_declaration')
65
+ return 'enum';
66
+ if (dt === 'type_alias_declaration')
67
+ return 'type';
68
+ if (dt === 'internal_module' || dt === 'module')
69
+ return 'namespace';
70
+ if (dt === 'lexical_declaration' || dt === 'variable_declaration') {
71
+ const value = decl.namedChildren.find((c) => c?.type === 'variable_declarator')?.childForFieldName('value');
72
+ return value && /^(arrow_function|function_expression|function|generator_function)$/.test(value.type) ? 'function' : 'variable';
73
+ }
74
+ if (dt === 'public_field_definition') {
75
+ const value = decl.childForFieldName('value');
76
+ return value && /^(arrow_function|function_expression)$/.test(value.type) ? 'method' : 'field';
77
+ }
78
+ return null;
79
+ }
80
+ case 'python': {
81
+ const def = t === 'decorated_definition' ? d.node.childForFieldName('definition') : d.node;
82
+ if (def?.type === 'function_definition')
83
+ return inType ? (d.name === '__init__' ? 'constructor' : 'method') : 'function';
84
+ if (def?.type === 'class_definition')
85
+ return 'class';
86
+ if (k === 'assignment')
87
+ return inType ? 'field' : 'variable';
88
+ return null;
89
+ }
90
+ case 'go': {
91
+ if (t === 'function_declaration')
92
+ return 'function';
93
+ if (t === 'method_declaration')
94
+ return 'method';
95
+ if (t === 'type_declaration') {
96
+ const spec = d.node.namedChildren.find((c) => c?.type === 'type_spec' || c?.type === 'type_alias');
97
+ const ty = spec?.childForFieldName('type')?.type;
98
+ return ty === 'struct_type' ? 'struct' : ty === 'interface_type' ? 'interface' : 'type';
99
+ }
100
+ if (t === 'const_declaration' || t === 'var_declaration')
101
+ return 'variable';
102
+ return null;
103
+ }
104
+ case 'rust': {
105
+ if (t === 'function_item' || t === 'function_signature_item')
106
+ return parent && (parent.node.type === 'impl_item' || parent.node.type === 'trait_item') ? 'method' : 'function';
107
+ if (t === 'struct_item' || t === 'union_item')
108
+ return 'struct';
109
+ if (t === 'enum_item')
110
+ return 'enum';
111
+ if (t === 'trait_item')
112
+ return 'interface';
113
+ if (t === 'mod_item')
114
+ return 'module';
115
+ if (t === 'const_item' || t === 'static_item')
116
+ return 'variable';
117
+ if (t === 'type_item')
118
+ return 'type';
119
+ return null; // impl blocks, macros, extern crates
120
+ }
121
+ case 'java': {
122
+ if (t === 'method_declaration')
123
+ return 'method';
124
+ if (t === 'constructor_declaration' || t === 'compact_constructor_declaration')
125
+ return 'constructor';
126
+ if (t === 'class_declaration' || t === 'record_declaration')
127
+ return 'class';
128
+ if (t === 'interface_declaration' || t === 'annotation_type_declaration')
129
+ return 'interface';
130
+ if (t === 'enum_declaration')
131
+ return 'enum';
132
+ if (k === 'field_declaration')
133
+ return 'field';
134
+ return null;
135
+ }
136
+ case 'csharp': {
137
+ if (t === 'method_declaration' || t === 'local_function_statement')
138
+ return t === 'method_declaration' ? 'method' : 'function';
139
+ if (t === 'constructor_declaration')
140
+ return 'constructor';
141
+ if (t === 'class_declaration' || t === 'record_declaration')
142
+ return 'class';
143
+ if (t === 'struct_declaration' || t === 'record_struct_declaration')
144
+ return 'struct';
145
+ if (t === 'interface_declaration')
146
+ return 'interface';
147
+ if (t === 'enum_declaration')
148
+ return 'enum';
149
+ if (t === 'property_declaration')
150
+ return 'property';
151
+ if (k === 'field_declaration')
152
+ return 'field';
153
+ if (t === 'delegate_declaration')
154
+ return 'type';
155
+ if (t === 'namespace_declaration')
156
+ return 'namespace';
157
+ return null;
158
+ }
159
+ case 'php': {
160
+ if (t === 'function_definition')
161
+ return 'function';
162
+ if (t === 'method_declaration')
163
+ return d.name === '__construct' ? 'constructor' : 'method';
164
+ if (t === 'class_declaration' || t === 'trait_declaration')
165
+ return 'class';
166
+ if (t === 'interface_declaration')
167
+ return 'interface';
168
+ if (t === 'enum_declaration')
169
+ return 'enum';
170
+ if (t === 'enum_case')
171
+ return 'field';
172
+ if (t === 'property_declaration')
173
+ return 'property';
174
+ if (t === 'const_declaration')
175
+ return inType ? 'field' : 'variable';
176
+ if (k === 'namespace')
177
+ return 'namespace';
178
+ if (k === 'use_declaration')
179
+ return 'other';
180
+ return null;
181
+ }
182
+ case 'ruby': {
183
+ if (k === 'method' || k === 'define_method')
184
+ return fn();
185
+ if (k === 'class')
186
+ return 'class';
187
+ if (k === 'module')
188
+ return 'module';
189
+ if (k === 'constant')
190
+ return 'variable';
191
+ if (/^attr(_reader|_writer|_accessor)?$/.test(k))
192
+ return d.name.includes(',') ? null : 'property';
193
+ return null; // `class << self`, visibility lines
194
+ }
195
+ case 'kotlin': {
196
+ if (k.startsWith('function('))
197
+ return fn();
198
+ if (k.startsWith('constructor('))
199
+ return 'constructor';
200
+ if (k === 'class' || k === 'object' || k === 'companion')
201
+ return 'class';
202
+ if (k === 'interface')
203
+ return 'interface';
204
+ if (k === 'enum class')
205
+ return 'enum';
206
+ if (k === 'property')
207
+ return d.name.startsWith('(') ? null : 'property';
208
+ if (k === 'type_alias')
209
+ return 'type';
210
+ if (k === 'enum_entry')
211
+ return 'field';
212
+ if (k === 'init')
213
+ return 'other';
214
+ return null;
215
+ }
216
+ case 'swift': {
217
+ if (k.startsWith('func(') || k.startsWith('requirement func(')) {
218
+ if (t === 'init_declaration')
219
+ return 'constructor';
220
+ if (t === 'subscript_declaration')
221
+ return null;
222
+ return fn();
223
+ }
224
+ if (k === 'class' || k === 'actor')
225
+ return 'class';
226
+ if (k === 'struct')
227
+ return 'struct';
228
+ if (k === 'enum')
229
+ return 'enum';
230
+ if (t === 'protocol_declaration' || k === 'protocol')
231
+ return 'interface';
232
+ if (k === 'extension')
233
+ return 'other';
234
+ if (k === 'property' || k === 'requirement property')
235
+ return inType ? 'property' : 'variable';
236
+ if (k === 'case')
237
+ return d.name.includes(',') ? null : 'field';
238
+ if (t === 'typealias_declaration' || t === 'associatedtype_declaration')
239
+ return 'type';
240
+ return null;
241
+ }
242
+ }
243
+ return null;
244
+ }
245
+ /** Every declaration in a tree, as the engine's config sees them, with its kind, container and children. */
246
+ function declarations(root, cfg) {
247
+ const all = [];
248
+ const visit = (container, parent) => {
249
+ for (const d of cfg.declarationsIn(container)) {
250
+ const named = nameOf(d, cfg);
251
+ const kind = named ? kindOf(d, parent, cfg) : null;
252
+ const outer = parent?.scope;
253
+ const container_ = named?.receiver ? (outer ? `${outer}.${bareType(named.receiver)}` : bareType(named.receiver)) : outer;
254
+ const node = d.node;
255
+ const end = lastLine(d.tail ?? node);
256
+ const decl = { node, start: attachedStart(node, cfg), bodyStart: line(node), end, name: named?.name ?? d.name, kind, container: container_, parent, children: [] };
257
+ // Members of an extension or impl belong to the type it extends or implements.
258
+ const own = cfg.id === 'swift' && d.kind === 'extension' ? bareType(d.name) : node.type === 'impl_item' ? bareType((node.childForFieldName('type')?.text ?? d.name).replace(/<.*$/s, '')) : decl.name;
259
+ decl.scope = cfg.id === 'swift' && d.kind === 'extension' ? own : outer ? `${outer}.${own}` : own;
260
+ parent?.children.push(decl);
261
+ all.push(decl);
262
+ if (d.members)
263
+ visit(d.members, decl);
264
+ }
265
+ };
266
+ visit(root, undefined);
267
+ return all;
268
+ }
269
+ const symbolOf = (d) => d.kind === null || !d.name ? null : { name: d.name, kind: d.kind, ...(d.container ? { container: d.container } : {}) };
270
+ /** Lines of a side's ranges, blank lines dropped. */
271
+ const nonBlank = (ranges, lines) => {
272
+ const out = [];
273
+ for (const r of ranges)
274
+ for (let l = r.start; l <= r.end; l++)
275
+ if ((lines[l - 1] ?? '').trim())
276
+ out.push(l);
277
+ return out;
278
+ };
279
+ /** The one declaration a single range is exactly (from its first or attached line to its last). */
280
+ function whole(ranges, decls, lines) {
281
+ const ls = nonBlank(ranges, lines);
282
+ if (!ls.length)
283
+ return null;
284
+ const lo = ls[0];
285
+ const hi = ls.at(-1);
286
+ const hits = decls.filter((d) => (d.start === lo || d.bodyStart === lo) && d.end === hi);
287
+ if (hits.length === 1)
288
+ return hits[0];
289
+ // A declaration and its only member on the same lines: the outer one is what the lines are.
290
+ const outer = hits.filter((d) => !hits.some((o) => o !== d && o === d.parent));
291
+ return hits.length && outer.length === 1 ? outer[0] : null;
292
+ }
293
+ /** The innermost declaration holding every line, unless the lines also reach into more than one of its members. */
294
+ function holder(ranges, decls, lines) {
295
+ const ls = nonBlank(ranges, lines);
296
+ if (!ls.length)
297
+ return null;
298
+ const lo = ls[0];
299
+ const hi = ls.at(-1);
300
+ const holding = decls.filter((d) => d.start <= lo && hi <= d.end);
301
+ if (!holding.length)
302
+ return null;
303
+ // The smallest holder; when a declaration and its member cover the same lines (`object A { val x = 1 }`), the outer one.
304
+ const inner = holding.reduce((a, b) => (b.end - b.start < a.end - a.start || (b.end - b.start === a.end - a.start && a.parent === b) ? b : a));
305
+ // Lines in the holder that also reach into one of its members (and not only that member) are about more than one thing.
306
+ if (ls.some((l) => inner.children.some((c) => c.start <= l && l <= c.end)) && !(lo <= inner.start && inner.end <= hi))
307
+ return null;
308
+ return inner;
309
+ }
310
+ const same = (a, b) => !!a && !!b && a.name === b.name && a.kind === b.kind && a.container === b.container;
311
+ const agree = (a, b) => (a === undefined ? b ?? null : b === undefined ? a : same(a, b) ? a : null);
312
+ /** The text a span range covers, on one line. */
313
+ function textAt(lines, r) {
314
+ if (r.start.line !== r.end.line)
315
+ return null;
316
+ return (lines[r.start.line - 1] ?? '').slice(r.start.character, r.end.character) || null;
317
+ }
318
+ const VARIABLE_PARENT = /parameter|variable_declarator|variable_declaration|let_declaration|short_var_declaration|assignment|pattern|catch|for_statement|for_in|range_clause|lambda|closure_parameters|block_parameters|method_parameters|value_binding|property_declaration|multi_variable/;
319
+ /** The kind of a renamed name, from where it is declared (on the old side): a declaration, or a local or parameter. */
320
+ function renamedSymbol(op, oldDecls, newDecls, oldRoot, oldLines, newLines, cfg) {
321
+ if (op.spans.length !== 1)
322
+ return null;
323
+ const span = op.spans[0];
324
+ const olds = 'old' in span ? (span.old ?? []) : [];
325
+ const news = 'new' in span ? (span.new ?? []) : [];
326
+ const oldNames = new Set(olds.map((r) => textAt(oldLines, r)));
327
+ const newNames = new Set(news.map((r) => textAt(newLines, r)));
328
+ if (oldNames.size !== 1 || newNames.size !== 1)
329
+ return null;
330
+ const oldName = [...oldNames][0];
331
+ const newName = [...newNames][0];
332
+ if (!oldName || !newName || oldName === newName)
333
+ return null;
334
+ const declared = oldDecls.filter((d) => d.name === oldName && d.kind !== null && d.kind !== 'import');
335
+ if (declared.length) {
336
+ const kinds = new Set(declared.map((d) => `${d.kind}\u0000${d.container ?? ''}`));
337
+ if (kinds.size !== 1)
338
+ return null;
339
+ const d = declared[0];
340
+ const after = newDecls.filter((x) => x.name === newName && x.kind === d.kind && x.container === d.container);
341
+ if (!after.length)
342
+ return null;
343
+ return { name: newName, kind: d.kind, oldName, ...(d.container ? { container: d.container } : {}) };
344
+ }
345
+ // Not a declaration the config lists: a local or a parameter, when one of the old name's uses declares it.
346
+ let local = false;
347
+ let other = false;
348
+ const walk = (n) => {
349
+ if (n.childCount === 0) {
350
+ if (cfg.identifierTypes.has(n.type) && n.text === oldName && n.parent) {
351
+ const p = n.parent;
352
+ if (/type_parameter/.test(p.type))
353
+ other = true;
354
+ else if (VARIABLE_PARENT.test(p.type) || VARIABLE_PARENT.test(p.parent?.type ?? ''))
355
+ local = true;
356
+ }
357
+ return;
358
+ }
359
+ for (const c of n.children)
360
+ if (c)
361
+ walk(c);
362
+ };
363
+ walk(oldRoot);
364
+ if (!local || other)
365
+ return null;
366
+ const holderFn = holder(op.lines.old, oldDecls, oldLines);
367
+ const container = holderFn && FUNCTION_KINDS.has(holderFn.kind ?? 'other') ? [holderFn.container, holderFn.name].filter(Boolean).join('.') : undefined;
368
+ return { name: newName, kind: 'variable', oldName, ...(container ? { container } : {}) };
369
+ }
370
+ /** Functions on one side lying wholly inside an operation's ranges. */
371
+ function functionsWithin(ranges, decls) {
372
+ const covered = new Set();
373
+ for (const r of ranges)
374
+ for (let l = r.start; l <= r.end; l++)
375
+ covered.add(l);
376
+ return decls.filter((d) => {
377
+ if (d.kind === null || !FUNCTION_KINDS.has(d.kind))
378
+ return false;
379
+ for (let l = d.bodyStart; l <= d.end; l++)
380
+ if (!covered.has(l))
381
+ return false;
382
+ return true;
383
+ });
384
+ }
385
+ /** Set `symbol` on every operation the rules name a declaration for (docs/symbols.md); never changes anything else. */
386
+ export function attachSymbols(ops, oldRoot, newRoot, oldText, newText, cfg) {
387
+ const oldDecls = declarations(oldRoot, cfg);
388
+ const newDecls = declarations(newRoot, cfg);
389
+ // Functions the config does not list as declarations (nested ones): known only by name, as functions.
390
+ const nested = (root, decls) => {
391
+ const out = [];
392
+ // A function the config already lists (perhaps under an `export` or a decorator) is not a nested one.
393
+ const listed = (f) => decls.some((d) => d.node.startIndex <= f.startIndex && f.endIndex <= d.node.endIndex && d.bodyStart <= line(f) && lastLine(f) === d.end && (d.node.startIndex === f.startIndex || d.node.endIndex === f.endIndex));
394
+ for (const f of functionsIn(root, cfg)) {
395
+ if (listed(f.node) || f.node.type === 'pair' || f.node.type === 'variable_declarator' || f.node.type === 'public_field_definition')
396
+ continue;
397
+ const outer = decls.filter((d) => d.start <= line(f.node) && lastLine(f.node) <= d.end).sort((a, b) => b.start - a.start || a.end - b.end)[0];
398
+ if (!outer || !FUNCTION_KINDS.has(outer.kind ?? 'other'))
399
+ continue;
400
+ const d = { node: f.node, start: line(f.node), bodyStart: line(f.node), end: lastLine(f.node), name: f.name, kind: 'function', container: [outer.container, outer.name].filter(Boolean).join('.'), parent: outer, children: [] };
401
+ outer.children.push(d);
402
+ out.push(d);
403
+ }
404
+ return out;
405
+ };
406
+ oldDecls.push(...nested(oldRoot, oldDecls));
407
+ newDecls.push(...nested(newRoot, newDecls));
408
+ const oldLines = oldText.split('\n');
409
+ const newLines = newText.split('\n');
410
+ const sideSymbol = (ranges, decls, lines, pick) => {
411
+ if (!ranges.length)
412
+ return undefined;
413
+ if (pick === 'whole') {
414
+ const d = whole(ranges, decls, lines);
415
+ return d ? symbolOf(d) : null;
416
+ }
417
+ if (pick === 'holder') {
418
+ const d = holder(ranges, decls, lines);
419
+ return d ? symbolOf(d) : null;
420
+ }
421
+ const w = whole(ranges, decls, lines);
422
+ if (w)
423
+ return symbolOf(w);
424
+ const h = holder(ranges, decls, lines);
425
+ return h && FUNCTION_KINDS.has(h.kind ?? 'other') ? symbolOf(h) : null;
426
+ };
427
+ for (const op of ops) {
428
+ let s = null;
429
+ switch (op.type) {
430
+ case 'moved':
431
+ case 'movedWithEdit':
432
+ s = agree(sideSymbol(op.lines.old, oldDecls, oldLines, 'moved'), sideSymbol(op.lines.new, newDecls, newLines, 'moved'));
433
+ break;
434
+ case 'reformatted':
435
+ case 'edited':
436
+ s = agree(sideSymbol(op.lines.old, oldDecls, oldLines, 'holder'), sideSymbol(op.lines.new, newDecls, newLines, 'holder'));
437
+ break;
438
+ case 'added':
439
+ s = op.lines.old.length ? null : sideSymbol(op.lines.new, newDecls, newLines, 'whole');
440
+ break;
441
+ case 'deleted':
442
+ s = op.lines.new.length ? null : sideSymbol(op.lines.old, oldDecls, oldLines, 'whole');
443
+ break;
444
+ case 'extractedFunction':
445
+ case 'inlinedFunction': {
446
+ const [ranges, decls] = op.type === 'extractedFunction' ? [op.lines.new, newDecls] : [op.lines.old, oldDecls];
447
+ const fns = functionsWithin(ranges, decls).filter((f) => !functionsWithin(ranges, decls).some((g) => g !== f && g.start <= f.start && f.end <= g.end));
448
+ s = fns.length === 1 ? symbolOf(fns[0]) : null;
449
+ break;
450
+ }
451
+ case 'renamed':
452
+ s = renamedSymbol(op, oldDecls, newDecls, oldRoot, oldLines, newLines, cfg);
453
+ break;
454
+ }
455
+ if (s)
456
+ op.symbol = s;
457
+ }
458
+ }
@@ -0,0 +1,69 @@
1
+ import type { Node } from 'web-tree-sitter';
2
+ import { type Declaration, type LanguageConfig } from './parse.js';
3
+ import type { SemanticDiffTextPosition, SemanticDiffTextRange } from './pierre-types.js';
4
+ export declare const pos: (p: {
5
+ row: number;
6
+ column: number;
7
+ }) => SemanticDiffTextPosition;
8
+ export declare const rangeOf: (n: Node) => SemanticDiffTextRange;
9
+ export declare const range: (start: SemanticDiffTextPosition, end: SemanticDiffTextPosition) => SemanticDiffTextRange;
10
+ export declare const startLine: (n: Node) => number;
11
+ export declare const endLine: (n: Node) => number;
12
+ /** Leaf tokens of a node, comments excluded. Whitespace never appears in tokens. */
13
+ export declare function tokens(n: Node): string[];
14
+ /** Dice similarity of two token multisets: 1 = same tokens, 0 = nothing shared. */
15
+ export declare function dice(a: string[], b: string[]): number;
16
+ export interface FunctionInfo {
17
+ name: string;
18
+ /** Unique within the file: enclosing class or receiver type, name, and `#n` for repeats. */
19
+ key: string;
20
+ node: Node;
21
+ body: Node;
22
+ statements: Node[];
23
+ }
24
+ export declare function functionsIn(root: Node, cfg: LanguageConfig): FunctionInfo[];
25
+ /** Every statement at any depth inside `n` (statements of nested blocks included). */
26
+ export declare function allStatements(n: Node, cfg: LanguageConfig): Node[];
27
+ /**
28
+ * Calls to `name` inside `n`. With `fn`, a call passing more arguments than the
29
+ * function takes is a different function of the same name (`caseSensitivity.PathKey(p)`
30
+ * is not `(t *parseTask) PathKey()`).
31
+ */
32
+ export declare function callsTo(n: Node, name: string, cfg: LanguageConfig, fn?: Node): Node[];
33
+ /** All descendants of `n` (including `n`) whose token sequence equals `want`. */
34
+ export declare function nodesWithTokens(n: Node, want: string[]): Node[];
35
+ /**
36
+ * Indexes (into `seq`) of the strictly increasing subsequence with the most
37
+ * total `weight`: the declarations that stay in place, so the rest are the moves.
38
+ * Callers weight by size in lines, so the fewest lines are shown as moved (a long
39
+ * import stays and the short ones around it move, as a line diff would have it),
40
+ * with a small bonus for staying at the same position to settle ties (a re-sort
41
+ * that leaves an import where it was does not report it). O(n log n).
42
+ */
43
+ export declare function longestInOrder(seq: number[], weight?: number[]): Set<number>;
44
+ /**
45
+ * Lines of code a declaration spans (through its tail), for choosing which declarations stayed in
46
+ * place. In Ruby the text lines of a heredoc are a string, not code: a method holding a long SQL
47
+ * heredoc does not outweigh the methods it swapped places with.
48
+ */
49
+ export declare function codeLines(d: Declaration, cfg: LanguageConfig): number;
50
+ /**
51
+ * Weights for `longestInOrder`, for pairs listed in old order: size in lines,
52
+ * plus a tie-breaking bonus for staying at the same position among the pairs.
53
+ * With `unchanged`, an unchanged pair also wins a tie over an edited one, so of two
54
+ * swapped declarations the edited one is called moved (see LanguageConfig.moveEditedFirst).
55
+ */
56
+ export declare function keepWeights(newStarts: number[], lines: number[], unchanged?: boolean[]): number[];
57
+ /**
58
+ * Pair items that share a base key (kind + name). A name used once on each side
59
+ * pairs directly; repeated names (overloads, `#[cfg]` twins, Go `init()`, two
60
+ * imports from one module) pair by similarity, not position, so inserting one
61
+ * overload first does not shift every pairing by one.
62
+ */
63
+ export declare function pairSameNamed<T>(olds: T[], news: T[], base: (t: T) => string, toks: (t: T) => string[], kept?: (a: T, b: T) => boolean, exact?: (t: T) => string | null): Array<[T, T]>;
64
+ /** The function is a method (of a class, impl, receiver type), so `x.name()` can call it. */
65
+ export declare function isMethod(fn: Node): boolean;
66
+ /** The call reaches the parent class's version: `super.f()`, `super.init(...)`, Ruby `superclass.f` / `superclass&.f`. */
67
+ export declare function callsParent(call: Node): boolean;
68
+ /** Text of the comments and attributes directly above a declaration (they belong to it). */
69
+ export declare function attachedAbove(n: Node, attached: ReadonlySet<string>): string;