@openrewrite/rewrite 8.97.1 → 8.97.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 (84) hide show
  1. package/README.md +42 -0
  2. package/dist/javascript/comparator.d.ts +16 -10
  3. package/dist/javascript/comparator.d.ts.map +1 -1
  4. package/dist/javascript/comparator.js +10 -8
  5. package/dist/javascript/comparator.js.map +1 -1
  6. package/dist/javascript/package-json-parser.d.ts +2 -0
  7. package/dist/javascript/package-json-parser.d.ts.map +1 -1
  8. package/dist/javascript/package-json-parser.js +27 -15
  9. package/dist/javascript/package-json-parser.js.map +1 -1
  10. package/dist/javascript/package-manager.d.ts +13 -4
  11. package/dist/javascript/package-manager.d.ts.map +1 -1
  12. package/dist/javascript/package-manager.js +134 -17
  13. package/dist/javascript/package-manager.js.map +1 -1
  14. package/dist/javascript/print.d.ts.map +1 -1
  15. package/dist/javascript/print.js +1 -1
  16. package/dist/javascript/print.js.map +1 -1
  17. package/dist/javascript/recipes/dependencies.d.ts +17 -0
  18. package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
  19. package/dist/javascript/recipes/dependencies.js +8 -0
  20. package/dist/javascript/recipes/dependencies.js.map +1 -1
  21. package/dist/javascript/templating/comparator.d.ts +32 -79
  22. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  23. package/dist/javascript/templating/comparator.js +35 -628
  24. package/dist/javascript/templating/comparator.js.map +1 -1
  25. package/dist/javascript/templating/debug.d.ts +143 -0
  26. package/dist/javascript/templating/debug.d.ts.map +1 -0
  27. package/dist/javascript/templating/debug.js +769 -0
  28. package/dist/javascript/templating/debug.js.map +1 -0
  29. package/dist/javascript/templating/index.d.ts +1 -1
  30. package/dist/javascript/templating/index.d.ts.map +1 -1
  31. package/dist/javascript/templating/index.js.map +1 -1
  32. package/dist/javascript/templating/pattern.d.ts +44 -35
  33. package/dist/javascript/templating/pattern.d.ts.map +1 -1
  34. package/dist/javascript/templating/pattern.js +224 -238
  35. package/dist/javascript/templating/pattern.js.map +1 -1
  36. package/dist/javascript/templating/rewrite.d.ts +4 -0
  37. package/dist/javascript/templating/rewrite.d.ts.map +1 -1
  38. package/dist/javascript/templating/rewrite.js +5 -1
  39. package/dist/javascript/templating/rewrite.js.map +1 -1
  40. package/dist/javascript/templating/types.d.ts +38 -35
  41. package/dist/javascript/templating/types.d.ts.map +1 -1
  42. package/dist/javascript/templating/utils.d.ts.map +1 -1
  43. package/dist/javascript/templating/utils.js +15 -0
  44. package/dist/javascript/templating/utils.js.map +1 -1
  45. package/dist/rewrite-javascript-version.txt +1 -1
  46. package/dist/rpc/request/install-recipes.d.ts +10 -0
  47. package/dist/rpc/request/install-recipes.d.ts.map +1 -1
  48. package/dist/rpc/request/install-recipes.js +51 -0
  49. package/dist/rpc/request/install-recipes.js.map +1 -1
  50. package/dist/rpc/request/prepare-recipe.d.ts +1 -0
  51. package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
  52. package/dist/rpc/request/prepare-recipe.js +13 -6
  53. package/dist/rpc/request/prepare-recipe.js.map +1 -1
  54. package/dist/test/rewrite-test.d.ts +1 -16
  55. package/dist/test/rewrite-test.d.ts.map +1 -1
  56. package/dist/test/rewrite-test.js +7 -58
  57. package/dist/test/rewrite-test.js.map +1 -1
  58. package/dist/util.d.ts +16 -0
  59. package/dist/util.d.ts.map +1 -1
  60. package/dist/util.js +53 -0
  61. package/dist/util.js.map +1 -1
  62. package/dist/yaml/parser.js +8 -5
  63. package/dist/yaml/parser.js.map +1 -1
  64. package/dist/yaml/print.js +9 -3
  65. package/dist/yaml/print.js.map +1 -1
  66. package/package.json +1 -1
  67. package/src/javascript/comparator.ts +66 -53
  68. package/src/javascript/package-json-parser.ts +25 -16
  69. package/src/javascript/package-manager.ts +121 -15
  70. package/src/javascript/print.ts +1 -2
  71. package/src/javascript/recipes/dependencies.ts +21 -0
  72. package/src/javascript/templating/comparator.ts +76 -766
  73. package/src/javascript/templating/debug.ts +806 -0
  74. package/src/javascript/templating/index.ts +1 -0
  75. package/src/javascript/templating/pattern.ts +267 -270
  76. package/src/javascript/templating/rewrite.ts +5 -1
  77. package/src/javascript/templating/types.ts +40 -37
  78. package/src/javascript/templating/utils.ts +0 -1
  79. package/src/rpc/request/install-recipes.ts +54 -0
  80. package/src/rpc/request/prepare-recipe.ts +18 -15
  81. package/src/test/rewrite-test.ts +2 -59
  82. package/src/util.ts +58 -0
  83. package/src/yaml/parser.ts +9 -5
  84. package/src/yaml/print.ts +9 -3
@@ -0,0 +1,806 @@
1
+ /*
2
+ * Copyright 2025 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Consolidated debug module containing all pattern debugging functionality:
19
+ * - Marker classes and utilities for highlighting mismatches
20
+ * - Custom marker printer for rendering debug markers
21
+ * - Debug-enabled pattern matching comparator with detailed logging
22
+ */
23
+
24
+ import * as path from 'path';
25
+ import {Cursor, isSourceFile, randomId, SourceFile, Tree} from '../..';
26
+ import {Marker, Markers, MarkersKind} from '../../markers';
27
+ import {MarkerPrinter, PrintOutputCapture, TreePrinters} from '../../print';
28
+ import {J, Type} from '../../java';
29
+ import {JavaScriptVisitor, JS} from '../index';
30
+ import {DebugCallbacks, Focus, MarkFocus, PatternMatchingComparator} from './comparator';
31
+ import {CaptureMarker, PlaceholderUtils} from './utils';
32
+ import {MatchExplanation} from './types';
33
+ import {JTree} from "../comparator";
34
+
35
+ // ============================================================================
36
+ // Marker Classes and Utilities
37
+ // ============================================================================
38
+
39
+ /**
40
+ * Custom marker for highlighting pattern mismatches in debug output.
41
+ * Contains before/after strings to render around the marked element.
42
+ */
43
+ export class PatternMismatchMarker implements Marker {
44
+ readonly kind = 'org.openrewrite.javascript.templating.PatternMismatchMarker';
45
+ readonly id: string;
46
+
47
+ constructor(
48
+ public readonly before: string,
49
+ public readonly after: string,
50
+ id?: string
51
+ ) {
52
+ this.id = id || randomId();
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Marks the code a capture holds in a successful match, with a circled letter for the capture's number.
58
+ */
59
+ export class CaptureHighlightMarker implements Marker {
60
+ readonly kind = 'org.openrewrite.javascript.templating.CaptureHighlightMarker';
61
+ readonly id: string;
62
+
63
+ constructor(
64
+ public readonly captureNumber: number,
65
+ id?: string
66
+ ) {
67
+ this.id = id || randomId();
68
+ }
69
+
70
+ /** Ⓐ for the first capture through Ⓩ for the 26th, and the number in brackets after that. */
71
+ symbol(): string {
72
+ return this.captureNumber >= 1 && this.captureNumber <= 26 ?
73
+ String.fromCodePoint(0x24B6 + this.captureNumber - 1) : `[${this.captureNumber}]`;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Whether debug output marks mismatches with 👉…👈 rather than colours and inverse video. FORCE_COLOR asks
79
+ * for colours, and otherwise NO_COLOR and a Claude Code session ask for markers. Then stderr decides where
80
+ * it is a terminal. A test runner's worker cannot see the terminal, so the terminal's own colour settings
81
+ * decide.
82
+ */
83
+ export function shouldUseEmoji(): boolean {
84
+ if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0') {
85
+ return false;
86
+ }
87
+ if (process.env.CLAUDECODE === '1' || process.env.NO_COLOR) {
88
+ return true;
89
+ }
90
+ if (process.stderr.isTTY) {
91
+ return false;
92
+ }
93
+ return !(process.env.COLORTERM || process.env.TERM?.includes('color'));
94
+ }
95
+
96
+ /**
97
+ * The first frame of `stack` outside this package, as `file:line:column (function)` with `file` relative
98
+ * to the working directory. The stack's own first frame names the package's root.
99
+ */
100
+ export function callSite(stack: string | undefined): string | undefined {
101
+ const frames = (stack ?? '').split('\n')
102
+ .map(line => /^\s*at (?:async )?(?:(.+?) \()?(?:file:\/\/)?(.+?):(\d+):(\d+)\)?$/.exec(line))
103
+ .filter((frame): frame is RegExpExecArray => frame !== null);
104
+ const own = frames[0]?.[2];
105
+ const rootEnd = own ? own.lastIndexOf('/javascript/templating/') : -1;
106
+ const root = rootEnd >= 0 ? own!.slice(0, rootEnd + 1) : undefined;
107
+ const caller = frames.find(([, , file]) => !(root && file.startsWith(root)) && !file.startsWith('node:'));
108
+ if (!caller) {
109
+ return undefined;
110
+ }
111
+ const [, fn, file, line, column] = caller;
112
+ return `${path.relative(process.cwd(), file)}:${line}:${column}${fn ? ` (${fn})` : ''}`;
113
+ }
114
+
115
+ /** What a mismatch mark prints before and after the node it is on. */
116
+ export function mismatchDelimiters(emoji: boolean = shouldUseEmoji()): [string, string] {
117
+ return emoji ? ['👉', '👈'] : ['\x1b[7m', '\x1b[27m'];
118
+ }
119
+
120
+ /** Marks where a tree starts, for {@link sourceLocation}. */
121
+ class PositionMarker implements Marker {
122
+ readonly kind = 'org.openrewrite.javascript.templating.PositionMarker';
123
+ readonly id = randomId();
124
+
125
+ constructor(readonly index: number) {
126
+ }
127
+ }
128
+
129
+ const positionsBySourceFile = new WeakMap<object, Map<Tree, { line: number, column: number }>>();
130
+
131
+ /** Where each tree of `sourceFile` starts, from one print of the file with every tree's start marked. */
132
+ async function positionsIn(sourceFile: SourceFile): Promise<Map<Tree, { line: number, column: number }>> {
133
+ let positions = positionsBySourceFile.get(sourceFile);
134
+ if (positions) {
135
+ return positions;
136
+ }
137
+ const trees: Tree[] = [];
138
+ const marked = await new class extends JavaScriptVisitor<undefined> {
139
+ override async visit<R extends J>(tree: Tree | null | undefined, p: undefined): Promise<R | undefined> {
140
+ if (!tree) {
141
+ return tree as R | undefined;
142
+ }
143
+ const index = trees.push(tree) - 1;
144
+ const visited = await super.visit(tree, p) as J | undefined;
145
+ return visited && {
146
+ ...visited,
147
+ markers: {...visited.markers, markers: [...visited.markers.markers, new PositionMarker(index)]}
148
+ } as R;
149
+ }
150
+ }().visit(sourceFile as unknown as J, undefined);
151
+ const printed = await TreePrinters.printer(sourceFile).print(marked!, new PrintOutputCapture({
152
+ beforeSyntax: marker => marker instanceof PositionMarker ? `\0${marker.index}\0` : '',
153
+ beforePrefix: () => '',
154
+ afterSyntax: () => ''
155
+ }));
156
+ positions = new Map();
157
+ let line = 1;
158
+ let column = 1;
159
+ for (let i = 0; i < printed.length; i++) {
160
+ if (printed[i] === '\0') {
161
+ const end = printed.indexOf('\0', i + 1);
162
+ positions.set(trees[Number(printed.slice(i + 1, end))], {line, column});
163
+ i = end;
164
+ } else if (printed[i] === '\n') {
165
+ line++;
166
+ column = 1;
167
+ } else {
168
+ column++;
169
+ }
170
+ }
171
+ positionsBySourceFile.set(sourceFile, positions);
172
+ return positions;
173
+ }
174
+
175
+ /**
176
+ * The source file `cursor` leads to, and where `tree` starts in it. A file that does not hold
177
+ * `tree` itself, as for a node a visitor built, gives its path alone.
178
+ */
179
+ export async function sourceLocation(tree: J, cursor: Cursor | undefined):
180
+ Promise<{ sourcePath: string, line?: number, column?: number } | undefined> {
181
+ const sourceFile = isSourceFile(tree) ? tree : cursor?.firstEnclosing(isSourceFile);
182
+ if (!sourceFile) {
183
+ return undefined;
184
+ }
185
+ return {sourcePath: sourceFile.sourcePath, ...(await positionsIn(sourceFile)).get(tree)};
186
+ }
187
+
188
+ /**
189
+ * `printed` with the mark around `element`'s code moved to `focus` within that code. It stays as it
190
+ * is where the mark does not hold exactly what `element` prints on its own.
191
+ */
192
+ export async function narrowMark(printed: string, element: J, focus: MarkFocus,
193
+ [before, after]: [string, string]): Promise<string> {
194
+ const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
195
+ const code = (await printer.print(element)).trim();
196
+ const at = printed.indexOf(before + code + after);
197
+ let range: [number, number] | undefined;
198
+ if (focus === 'start') {
199
+ range = [0, 0];
200
+ } else if (focus === 'operator') {
201
+ range = await operatorRange(element, code);
202
+ } else {
203
+ const child = (await printer.print(focus.after)).trim();
204
+ const end = code.indexOf(child) + child.length;
205
+ range = child && end >= child.length ? [end, end] : undefined;
206
+ }
207
+ if (at < 0 || !range) {
208
+ return printed;
209
+ }
210
+ const [start, end] = range;
211
+ return printed.slice(0, at) + code.slice(0, start) + before + code.slice(start, end) + after +
212
+ code.slice(end) + printed.slice(at + before.length + code.length + after.length);
213
+ }
214
+
215
+ /**
216
+ * The lines within one line of a mark, with `…` for each run of two or more lines left out. A mark
217
+ * over more than six lines keeps its first two and last two.
218
+ */
219
+ export function aroundMarks(lines: string[], [before, after]: [string, string]): string[] {
220
+ let open = 0;
221
+ const marked = lines.map(line => {
222
+ const inside = open > 0 || line.includes(before) || line.includes(after);
223
+ open += line.split(before).length - line.split(after).length;
224
+ return inside;
225
+ });
226
+ if (!marked.includes(true)) {
227
+ return lines;
228
+ }
229
+ const kept = lines.map((_, i) => marked[i] || marked[i - 1] === true || marked[i + 1] === true);
230
+ for (let start = 0; start < lines.length; start++) {
231
+ let end = start;
232
+ while (end < lines.length && marked[end]) {
233
+ end++;
234
+ }
235
+ if (end - start > 6) {
236
+ kept.fill(false, start + 2, end - 2);
237
+ }
238
+ start = end;
239
+ }
240
+ const result: string[] = [];
241
+ for (let i = 0; i < lines.length;) {
242
+ let j = i;
243
+ while (j < lines.length && kept[j] === kept[i]) {
244
+ j++;
245
+ }
246
+ result.push(...(!kept[i] && j - i >= 2 ? ['…'] : lines.slice(i, j)));
247
+ i = j;
248
+ }
249
+ return result;
250
+ }
251
+
252
+ // ============================================================================
253
+ // Marker Printer
254
+ // ============================================================================
255
+
256
+ /**
257
+ * Custom MarkerPrinter for pattern debugging that renders PatternMismatchMarker
258
+ * and CaptureHighlightMarker with custom before/after strings.
259
+ */
260
+ export const PATTERN_DEBUG_MARKER_PRINTER: MarkerPrinter = {
261
+ beforeSyntax(marker: Marker, cursor: Cursor, commentWrapper: (input: string) => string): string {
262
+ if (marker instanceof PatternMismatchMarker) {
263
+ return marker.before;
264
+ }
265
+ if (marker instanceof CaptureHighlightMarker) {
266
+ return marker.symbol();
267
+ }
268
+ return MarkerPrinter.DEFAULT.beforeSyntax(marker, cursor, commentWrapper);
269
+ },
270
+
271
+ beforePrefix(marker: Marker, cursor: Cursor, commentWrapper: (input: string) => string): string {
272
+ return MarkerPrinter.DEFAULT.beforePrefix(marker, cursor, commentWrapper);
273
+ },
274
+
275
+ afterSyntax(marker: Marker, cursor: Cursor, commentWrapper: (input: string) => string): string {
276
+ if (marker instanceof PatternMismatchMarker) {
277
+ return marker.after;
278
+ }
279
+ if (marker instanceof CaptureHighlightMarker) {
280
+ return marker.symbol();
281
+ }
282
+ return MarkerPrinter.DEFAULT.afterSyntax(marker, cursor, commentWrapper);
283
+ }
284
+ };
285
+
286
+ // ============================================================================
287
+ // ANSI-Aware Print Output Capture
288
+ // ============================================================================
289
+
290
+ /**
291
+ * A print output capture that closes active ANSI escape codes at each newline and resumes them at the
292
+ * next line's first non-blank character. Each line of debug output is then styled on its own, and its
293
+ * indentation stays unstyled so that it can be dedented.
294
+ */
295
+ export class AnsiAwarePrintOutputCapture extends PrintOutputCapture {
296
+ private activeAnsiCodes: string[] = [];
297
+ private resumePending = false;
298
+
299
+ override append(text: string | undefined): AnsiAwarePrintOutputCapture {
300
+ if (!text || text.length === 0) {
301
+ return this;
302
+ }
303
+ if (!this.resumePending && !text.includes('\x1b') && !text.includes('\n')) {
304
+ super.append(text);
305
+ return this;
306
+ }
307
+
308
+ // Process the text character by character to handle ANSI codes and newlines
309
+ let i = 0;
310
+ while (i < text.length) {
311
+ // Check for ANSI escape sequence
312
+ if (text[i] === '\x1b' && i + 1 < text.length && text[i + 1] === '[') {
313
+ // Find the end of the ANSI sequence (ends with a letter)
314
+ let j = i + 2;
315
+ while (j < text.length && !/[a-zA-Z]/.test(text[j])) {
316
+ j++;
317
+ }
318
+ if (j < text.length) {
319
+ j++; // Include the terminating letter
320
+ const ansiCode = text.substring(i, j);
321
+ super.append(ansiCode);
322
+
323
+ // Track state-changing codes
324
+ // \x1b[7m = inverted colors (start)
325
+ // \x1b[27m = normal colors (end inverted)
326
+ // \x1b[0m = reset all
327
+ if (ansiCode === '\x1b[7m') {
328
+ this.activeAnsiCodes.push(ansiCode);
329
+ } else if (ansiCode === '\x1b[27m') {
330
+ // Remove inverted colors from stack
331
+ this.activeAnsiCodes = this.activeAnsiCodes.filter(code => code !== '\x1b[7m');
332
+ } else if (ansiCode === '\x1b[0m' || ansiCode === '\x1b[m') {
333
+ // Reset clears all active codes
334
+ this.activeAnsiCodes = [];
335
+ }
336
+
337
+ i = j;
338
+ continue;
339
+ }
340
+ }
341
+
342
+ // Check for newline
343
+ if (text[i] === '\n') {
344
+ // First, close any active ANSI codes before the newline
345
+ for (let j = this.activeAnsiCodes.length - 1; j >= 0 && !this.resumePending; j--) {
346
+ if (this.activeAnsiCodes[j] === '\x1b[7m') {
347
+ super.append('\x1b[27m');
348
+ }
349
+ }
350
+
351
+ super.append('\n');
352
+ this.resumePending = this.activeAnsiCodes.length > 0;
353
+ i++;
354
+ continue;
355
+ }
356
+
357
+ if (this.resumePending && text[i] !== ' ' && text[i] !== '\t') {
358
+ for (const code of this.activeAnsiCodes) {
359
+ super.append(code);
360
+ }
361
+ this.resumePending = false;
362
+ }
363
+
364
+ // Regular character
365
+ super.append(text[i]);
366
+ i++;
367
+ }
368
+
369
+ return this;
370
+ }
371
+ }
372
+
373
+ // ============================================================================
374
+ // Element Marker Visitor
375
+ // ============================================================================
376
+
377
+ /**
378
+ * Visitor that marks elements with markers for highlighting in debug output.
379
+ * Uses referential equality to find target elements since nodes aren't mutated during matching.
380
+ *
381
+ * Can mark either:
382
+ * - A single element with PatternMismatchMarker (for failures)
383
+ * - Multiple elements with CaptureHighlightMarkers (for successes)
384
+ */
385
+ export class ElementMarkerVisitor extends JavaScriptVisitor<undefined> {
386
+ private readonly elementMarkers: Map<JTree, Marker>;
387
+
388
+ /**
389
+ * Create a visitor to mark a single element with a PatternMismatchMarker.
390
+ */
391
+ constructor(targetElement: JTree, emoji?: boolean);
392
+ /**
393
+ * Create a visitor to mark multiple captured elements with CaptureHighlightMarkers.
394
+ */
395
+ constructor(captures: Map<number, JTree | JTree[]>);
396
+ constructor(targetOrCaptures: JTree | Map<number, JTree | JTree[]>, emoji: boolean = shouldUseEmoji()) {
397
+ super();
398
+ this.elementMarkers = new Map();
399
+
400
+ if (targetOrCaptures instanceof Map) {
401
+ // Multiple captures - build map of element -> CaptureHighlightMarker
402
+ for (const [captureNum, captured] of targetOrCaptures.entries()) {
403
+ const marker = new CaptureHighlightMarker(captureNum);
404
+ if (Array.isArray(captured)) {
405
+ // For variadic captures, mark each element with the same number
406
+ for (const element of captured) {
407
+ this.elementMarkers.set(element, marker);
408
+ }
409
+ } else {
410
+ this.elementMarkers.set(captured, marker);
411
+ }
412
+ }
413
+ } else {
414
+ // Single element - create PatternMismatchMarker
415
+ const [before, after] = mismatchDelimiters(emoji);
416
+ this.elementMarkers.set(targetOrCaptures, new PatternMismatchMarker(before, after));
417
+ }
418
+ }
419
+
420
+ override async visit<R extends J>(tree: Tree | null | undefined, p: undefined): Promise<R | undefined> {
421
+ if (!tree) return tree as R | undefined;
422
+
423
+ // Check if this element should be marked
424
+ const marker = this.elementMarkers.get(tree as JTree);
425
+ if (marker) {
426
+ const updatedMarkers = [...(tree as J).markers.markers, marker];
427
+ const newMarkers: Markers = {
428
+ kind: MarkersKind.Markers,
429
+ id: (tree as J).markers.id,
430
+ markers: updatedMarkers
431
+ };
432
+ return {...(tree as J), markers: newMarkers} as R;
433
+ }
434
+
435
+ return await super.visit(tree, p);
436
+ }
437
+
438
+ override async visitContainer<T extends J>(container: J.Container<T>, p: undefined): Promise<J.Container<T>> {
439
+ // Check if this container should be marked
440
+ const marker = this.elementMarkers.get(container);
441
+ if (marker) {
442
+ const updatedMarkers = [...(container as any).markers.markers, marker];
443
+ const newMarkers: Markers = {
444
+ kind: MarkersKind.Markers,
445
+ id: (container as any).markers.id,
446
+ markers: updatedMarkers
447
+ };
448
+ return {...container, markers: newMarkers} as J.Container<T>;
449
+ }
450
+ return await super.visitContainer(container, p);
451
+ }
452
+ }
453
+
454
+ // ============================================================================
455
+ // Debug Pattern Matching Comparator
456
+ // ============================================================================
457
+
458
+ /** Whether {@link ElementMarkerVisitor} can mark `value`, which it does for the trees and containers it visits. */
459
+ function isMarkable(value: any): value is JTree {
460
+ return !!value?.markers && value.kind !== J.Kind.LeftPadded && value.kind !== J.Kind.RightPadded;
461
+ }
462
+
463
+ /** The value at a property path such as `lambda.parameters.parameters` or `statements[2]`. */
464
+ function at(node: any, path: string | undefined): any {
465
+ if (!path) {
466
+ return node;
467
+ }
468
+ return path.split(/\.|\[(\d+)]/).filter(Boolean).reduce((current, property) => current?.[property], node);
469
+ }
470
+
471
+ /** The code `value` stands for, as one line, or "none" where there is none. */
472
+ export async function describe(value: any): Promise<string> {
473
+ const elements = Array.isArray(value) ? value :
474
+ value?.kind === J.Kind.Container ? value.elements :
475
+ value === undefined || value === null ? [] : [value];
476
+ const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
477
+ const printed: string[] = [];
478
+ for (let element of elements) {
479
+ if (element?.kind === J.Kind.LeftPadded || element?.kind === J.Kind.RightPadded) {
480
+ element = element.element;
481
+ }
482
+ const text = isMarkable(element) ? (await printer.print(element as J)).trim() : String(element);
483
+ if (text) {
484
+ printed.push(text.split('\n')[0] + (text.includes('\n') ? ' …' : ''));
485
+ }
486
+ }
487
+ return printed.length > 0 ? printed.join(', ') : 'none';
488
+ }
489
+
490
+ /** A tree's kind in words, followed by its kind name, such as `arrow function (JS$ArrowFunction)`. */
491
+ export function describeKind(tree: any): string {
492
+ // A function written where an expression goes is held as a statement, which names its kind
493
+ const named = tree?.kind === JS.Kind.StatementExpression ? tree.statement : tree;
494
+ return `${kindInWords(tree)} (${shortKind(named)})`;
495
+ }
496
+
497
+ function shortKind(tree: any): string {
498
+ return tree?.kind ? tree.kind.substring(tree.kind.lastIndexOf('.') + 1) : 'unknown';
499
+ }
500
+
501
+ function kindInWords(tree: any): string {
502
+ // A function written where an expression goes is held as a statement
503
+ return tree?.kind === JS.Kind.StatementExpression && tree.statement?.kind === J.Kind.MethodDeclaration ?
504
+ 'function expression' : inWords(shortKind(tree).replace(/^[A-Za-z]+\$/, '').replace(/\$/g, ' '));
505
+ }
506
+
507
+ function inWords(name: string): string {
508
+ return name.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
509
+ }
510
+
511
+ /** Properties whose names say something other than what TypeScript calls them where they appear. */
512
+ const PROPERTY_WORDS: Record<string, string> = {
513
+ [`${J.Kind.MethodInvocation}.typeParameters`]: 'type arguments',
514
+ [`${JS.Kind.FunctionCall}.typeParameters`]: 'type arguments',
515
+ [`${J.Kind.NewClass}.typeParameters`]: 'type arguments',
516
+ [`${JS.Kind.ImportClause}.name`]: 'default import',
517
+ [`${JS.Kind.ImportClause}.namedBindings`]: 'named imports'
518
+ };
519
+
520
+ /**
521
+ * The code `tree` writes besides its operands, such as the `+` of a binary or the `!` of a unary.
522
+ * Each operand prints at the start or the end of its operation, so what remains is the operator.
523
+ */
524
+ async function operatorOf(tree: any): Promise<string | undefined> {
525
+ const code = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(tree)).trim();
526
+ const range = await operatorRange(tree, code);
527
+ return range ? code.slice(...range) : undefined;
528
+ }
529
+
530
+ /** Where the operator is in `code`, which is what `tree` prints. */
531
+ async function operatorRange(tree: any, code: string): Promise<[number, number] | undefined> {
532
+ const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
533
+ let start = 0;
534
+ let end = code.length;
535
+ const operands = [tree.left ?? tree.variable ?? tree.expression, tree.right ?? tree.assignment ?? tree.expression];
536
+ for (const operand of operands) {
537
+ const text = operand ? (await printer.print(operand)).trim() : '';
538
+ if (text && code.startsWith(text, start)) {
539
+ start += text.length;
540
+ } else if (text && code.slice(start, end).endsWith(text)) {
541
+ end -= text.length;
542
+ }
543
+ }
544
+ while (start < end && /\s/.test(code[start])) {
545
+ start++;
546
+ }
547
+ while (end > start && /\s/.test(code[end - 1])) {
548
+ end--;
549
+ }
550
+ return start < end ? [start, end] : undefined;
551
+ }
552
+
553
+ /** How the pattern's own text writes a capture, which the debug output shows as `🪝name`. */
554
+ function placeholder(marker: CaptureMarker): string {
555
+ return `${PlaceholderUtils.CAPTURE_PREFIX}${marker.captureName}__`;
556
+ }
557
+
558
+ /**
559
+ * Explains why a pattern does not match, and changes nothing about matching itself. It records
560
+ * what the base class reports through its mismatch methods and hooks, with the nodes to mark.
561
+ */
562
+ export class DebugPatternMatchingComparator extends PatternMatchingComparator {
563
+ private get debug(): DebugCallbacks {
564
+ return this.matcher.debug!;
565
+ }
566
+
567
+ /**
568
+ * Extracts the last segment of a kind string (after the last dot).
569
+ * For example: "org.openrewrite.java.tree.J.MethodInvocation" -> "MethodInvocation"
570
+ */
571
+ private formatKind(kind: string | undefined): string {
572
+ if (!kind) return 'unknown';
573
+ return kind.substring(kind.lastIndexOf('.') + 1);
574
+ }
575
+
576
+ /**
577
+ * Formats a value for display in error messages.
578
+ */
579
+ private formatValue(value: any): string {
580
+ if (value === null) return 'null';
581
+ if (value === undefined) return 'undefined';
582
+ if (typeof value === 'string') return `"${value}"`;
583
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
584
+
585
+ if (Type.isType(value)) {
586
+ return Type.isFullyQualified(value) ?
587
+ Type.FullyQualified.getFullyQualifiedName(value) :
588
+ this.formatKind((value as Type).kind);
589
+ }
590
+ if (value.kind === J.Kind.LeftPadded || value.kind === J.Kind.RightPadded) {
591
+ return this.formatValue(value.element);
592
+ }
593
+
594
+ // For objects with a kind property (LST nodes)
595
+ if (value && typeof value === 'object' && value.kind) {
596
+ const kind = this.formatKind(value.kind);
597
+
598
+ // Show key identifying properties for common node types
599
+ if (value.simpleName) return `${kind}("${value.simpleName}")`;
600
+ if (value.value !== undefined) return `${kind}(${this.formatValue(value.value)})`;
601
+
602
+ return kind;
603
+ }
604
+
605
+ return String(value);
606
+ }
607
+
608
+ /** A property's name and the code it holds, such as `modifiers: async`. */
609
+ private async describeProperty(propertyName: string | undefined, value: any): Promise<string> {
610
+ return propertyName ? `${this.propertyLabel(propertyName)}: ${await describe(value)}` : describe(value);
611
+ }
612
+
613
+ /**
614
+ * The property in words: the last name in its path, or for a container's `elements` or a padded
615
+ * value, the name its owner holds it under.
616
+ */
617
+ private propertyLabel(propertyName: string | undefined): string {
618
+ let owner = this.cursor?.value;
619
+ let name = propertyName?.replace(/\[\d+]$/, '').split('.').pop();
620
+ const wrapper = this.cursor?.value;
621
+ if (propertyName === undefined || propertyName === 'elements' && wrapper?.kind === J.Kind.Container) {
622
+ owner = this.cursor?.parent?.value;
623
+ name = owner ? Object.keys(owner).find(key => owner[key] === wrapper) : undefined;
624
+ } else if (name === 'statements' && wrapper?.kind === J.Kind.Block &&
625
+ this.cursor?.parent?.value?.kind === J.Kind.NewClass) {
626
+ // An object literal holds its properties as the statements of a block
627
+ return 'properties';
628
+ }
629
+ return name ? PROPERTY_WORDS[`${owner?.kind}.${name}`] ?? inWords(name) : 'value';
630
+ }
631
+
632
+ /**
633
+ * The node a mismatch is shown on. That is `element`, or the element a padding wrapper holds,
634
+ * where it can be marked, and otherwise the nearest node on `cursor` that can.
635
+ */
636
+ private markable(element: any, cursor: Cursor | undefined): JTree | undefined {
637
+ if (element?.kind === J.Kind.LeftPadded || element?.kind === J.Kind.RightPadded) {
638
+ element = element.element;
639
+ }
640
+ if (isMarkable(element)) {
641
+ return element;
642
+ }
643
+ for (let c = cursor; c; c = c.parent) {
644
+ if (isMarkable(c.value)) {
645
+ return c.value;
646
+ }
647
+ }
648
+ return undefined;
649
+ }
650
+
651
+ /** Records why matching failed, unless an earlier mismatch already did, and stops the match. */
652
+ private fail<T>(t: T, reason: MatchExplanation['reason'], expected: string | Promise<string>,
653
+ actual: string | Promise<string>, details: string | undefined, patternElement: any,
654
+ targetElement: any, focus?: Focus): T {
655
+ if (this.match) {
656
+ this.explain(reason, expected, actual, details, patternElement, targetElement, focus);
657
+ }
658
+ this.match = false;
659
+ return t;
660
+ }
661
+
662
+ private explain(reason: MatchExplanation['reason'], expected: string | Promise<string>,
663
+ actual: string | Promise<string>, details: string | undefined, patternElement: any,
664
+ targetElement: any, focus?: Focus): void {
665
+ this.debug.setExplanation(reason, expected, actual, details,
666
+ this.markable(patternElement, this.cursor), this.markable(targetElement, this.targetCursor), focus);
667
+ }
668
+
669
+ /** An abort that names no values leaves the explanation to the matcher's generic one. */
670
+ protected override abort<T>(t: T, reason?: string, propertyName?: string, expected?: any, actual?: any): T {
671
+ if (reason && (expected !== undefined || actual !== undefined)) {
672
+ return this.fail(t, reason as MatchExplanation['reason'],
673
+ this.formatValue(expected), this.formatValue(actual),
674
+ undefined, this.cursor?.value, this.targetCursor?.value);
675
+ }
676
+ return super.abort(t, reason, propertyName, expected, actual);
677
+ }
678
+
679
+ protected override kindMismatch<T extends JTree>(): T {
680
+ const pattern = this.cursor?.value as T;
681
+ const target = this.targetCursor?.value as any;
682
+ // Operations of one name in words, such as JavaScript's `===` and Java's `-`, differ in their operators
683
+ if (kindInWords(pattern) === kindInWords(target) && (pattern as any)?.operator && target?.operator) {
684
+ const describeOperator = async (tree: any) => `operator: ${await operatorOf(tree) ?? describeKind(tree)}`;
685
+ return this.fail(pattern, 'kind-mismatch', describeOperator(pattern), describeOperator(target), undefined,
686
+ pattern, target, {pattern: 'operator', target: 'operator'});
687
+ }
688
+ const names: string[] = [J.Kind.Identifier, J.Kind.FieldAccess];
689
+ const note = names.includes(pattern?.kind as string) && names.includes(target?.kind) ?
690
+ 'A pattern matches a name as it is written, not what it refers to. ' +
691
+ 'Write it as the source does, or put a capture in its place.' : undefined;
692
+ return this.fail(pattern, 'kind-mismatch', describeKind(pattern), describeKind(target), note,
693
+ pattern, target);
694
+ }
695
+
696
+ protected override structuralMismatch<T extends JTree>(propertyName?: string): T {
697
+ const pattern = this.cursor?.value as T;
698
+ const target = this.targetCursor?.value as any;
699
+ const expectedValue = propertyName ? at(pattern, propertyName) : pattern;
700
+ const actualValue = propertyName ? at(target, propertyName) : target;
701
+ const onlyOneSide = (expectedValue === undefined) !== (actualValue === undefined);
702
+ // The side without the property is marked where it would go
703
+ const missing = (node: any): MarkFocus | undefined =>
704
+ propertyName === 'typeParameters' && node?.name ? {after: node.name} :
705
+ propertyName === 'select' ? 'start' : undefined;
706
+ return this.fail(pattern, 'structural-mismatch',
707
+ this.describeProperty(propertyName, expectedValue), this.describeProperty(propertyName, actualValue),
708
+ undefined, onlyOneSide ? expectedValue ?? pattern : pattern, onlyOneSide ? actualValue ?? target : target,
709
+ onlyOneSide ? {
710
+ pattern: expectedValue === undefined ? missing(pattern) : undefined,
711
+ target: actualValue === undefined ? missing(target) : undefined
712
+ } : undefined);
713
+ }
714
+
715
+ protected override arrayLengthMismatch<T extends JTree>(propertyName: string): T {
716
+ const pattern = this.cursor?.value as T;
717
+ const target = this.targetCursor?.value as any;
718
+ const label = this.propertyLabel(propertyName);
719
+ const hint = label === 'arguments' || label === 'properties' ?
720
+ `A capture matches one ${label === 'arguments' ? 'argument' : 'property'}. ` +
721
+ 'capture({variadic: true}) matches any number of them.' : undefined;
722
+ const expected: any[] = at(pattern, propertyName) ?? [];
723
+ const actual: any[] = at(target, propertyName) ?? [];
724
+ // A modifier only one side has is marked, and the other side where it would go
725
+ const modifier = label === 'modifiers' && (expected.length === 0) !== (actual.length === 0);
726
+ return this.fail(pattern, 'array-length-mismatch',
727
+ this.describeProperty(propertyName, expected), this.describeProperty(propertyName, actual), hint,
728
+ modifier && expected.length > 0 ? expected[0] : pattern,
729
+ modifier && actual.length > 0 ? actual[0] : target,
730
+ modifier ? {
731
+ pattern: expected.length === 0 ? 'start' : undefined,
732
+ target: actual.length === 0 ? 'start' : undefined
733
+ } : undefined);
734
+ }
735
+
736
+ protected override valueMismatch<T extends JTree>(propertyName?: string, expected?: any, actual?: any): T {
737
+ const pattern = this.cursor?.value as any;
738
+ const target = this.targetCursor?.value as any;
739
+ const padded = pattern?.kind === J.Kind.LeftPadded || pattern?.kind === J.Kind.RightPadded;
740
+ if (!propertyName && padded && typeof expected === 'string') {
741
+ const label = this.propertyLabel(undefined);
742
+ const describeOperator = async (tree: any, value: string) => `${label}: ${await operatorOf(tree) ?? value}`;
743
+ const patternHolder = this.cursor?.parent?.value;
744
+ const targetHolder = this.targetCursor?.parent?.value;
745
+ return this.fail(pattern as T, 'value-mismatch', describeOperator(patternHolder, expected),
746
+ describeOperator(targetHolder, actual), undefined, patternHolder, targetHolder,
747
+ {pattern: 'operator', target: 'operator'});
748
+ }
749
+ const path = propertyName ? propertyName.split('.') : [];
750
+
751
+ // The mismatch shows on the node holding the property, and a call's method type on the call's name
752
+ const holder = pattern?.kind === J.Kind.MethodInvocation && path[0] === 'methodType' ?
753
+ 'name' : path.slice(0, -1).join('.');
754
+ const declared = path[path.length - 1] === 'declaringType';
755
+ const asWritten = (tree: any) => tree?.kind === J.Kind.Literal && (!propertyName || propertyName === 'value') ?
756
+ tree.valueSource : undefined;
757
+ const describeValue = (value: any, tree: any) => declared ? `declared in ${this.formatValue(value)}` :
758
+ asWritten(tree) ?? this.formatValue(value);
759
+ const note = declared ? 'A pattern matches a call only where it calls the same declaration. ' +
760
+ 'Its context option declares what its own calls refer to.' : undefined;
761
+ return this.fail(pattern as T, 'value-mismatch',
762
+ describeValue(expected !== undefined ? expected : at(pattern, propertyName), pattern),
763
+ describeValue(actual !== undefined ? actual : at(target, propertyName), target),
764
+ note, at(pattern, holder), at(target, holder));
765
+ }
766
+
767
+ protected override satisfiesConstraint(marker: CaptureMarker, patternElement: JTree, target: J | J[],
768
+ cursor: Cursor): boolean {
769
+ const capture = Array.isArray(target) ?
770
+ `variadic capture: ${marker.captureName} (${target.length} elements)` : `capture: ${marker.captureName}`;
771
+ this.debug.log('debug', 'constraint', `Evaluating constraint for ${capture}`);
772
+ let satisfied: boolean;
773
+ try {
774
+ satisfied = super.satisfiesConstraint(marker, patternElement, target, cursor);
775
+ } catch (e) {
776
+ const on = Array.isArray(target) ? `${target.length} elements` : describeKind(target);
777
+ const message = (e as Error)?.message ?? e;
778
+ throw new Error(`The constraint of capture ${marker.captureName} threw on ${on}: ${message}`);
779
+ }
780
+ if (satisfied) {
781
+ this.debug.log('debug', 'constraint', `Constraint passed for ${capture}`);
782
+ } else {
783
+ this.debug.log('info', 'constraint', `Constraint failed for ${capture}`);
784
+ if (this.match) {
785
+ const constraint = String(marker.constraint).split('\n')[0];
786
+ this.explain('constraint-failed', `${placeholder(marker)} satisfying ${constraint}`, describe(target),
787
+ undefined, patternElement,
788
+ Array.isArray(target) && target.length !== 1 ? this.targetCursor?.value : [target].flat()[0]);
789
+ }
790
+ }
791
+ return satisfied;
792
+ }
793
+
794
+ protected override explainCaptureConflict(marker: CaptureMarker, patternElement: JTree, targets: J[]): void {
795
+ const bound = marker.captureName ? this.matcher.getCapture(marker.captureName) : undefined;
796
+ if (bound === undefined || !this.match) {
797
+ return;
798
+ }
799
+ this.explain('value-mismatch',
800
+ describe(bound).then(code => `${code} (what ${placeholder(marker)} holds already)`),
801
+ describe(targets),
802
+ 'A capture the pattern names twice binds the same code at both places.',
803
+ patternElement,
804
+ targets.length === 1 ? targets[0] : this.targetCursor?.value);
805
+ }
806
+ }