@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
@@ -27,7 +27,14 @@ import {
27
27
  PatternOptions
28
28
  } from './types';
29
29
  import {CAPTURE_CAPTURING_SYMBOL, CAPTURE_NAME_SYMBOL, CaptureImpl, RAW_CODE_SYMBOL, RawCode} from './capture';
30
- import {DebugPatternMatchingComparator, MatcherCallbacks, MatcherState, PatternMatchingComparator} from './comparator';
30
+ import {
31
+ Focus,
32
+ MarkFocus,
33
+ MatcherCallbacks,
34
+ MatcherState,
35
+ PatternMatchingComparator,
36
+ PendingExplanation
37
+ } from './comparator';
31
38
  import {
32
39
  CaptureMarker,
33
40
  CaptureStorageValue,
@@ -41,8 +48,36 @@ import {walk} from '../scope';
41
48
  import {opensWithBrace, TemplateEngine} from './engine';
42
49
  import {TreePrinters} from '../../print';
43
50
  import {JS} from '../index';
44
- import {JavaScriptSemanticComparatorVisitor} from '../comparator';
51
+ import {
52
+ AnsiAwarePrintOutputCapture,
53
+ callSite,
54
+ CaptureHighlightMarker,
55
+ DebugPatternMatchingComparator,
56
+ aroundMarks,
57
+ describe,
58
+ describeKind,
59
+ ElementMarkerVisitor,
60
+ mismatchDelimiters,
61
+ narrowMark,
62
+ PATTERN_DEBUG_MARKER_PRINTER,
63
+ shouldUseEmoji,
64
+ sourceLocation
65
+ } from './debug';
66
+ import {dedent} from '../../util';
67
+ import {JavaScriptSemanticComparatorVisitor, JTree} from '../comparator';
68
+
45
69
 
70
+ /**
71
+ * Printed code without its leading blank lines and trailing whitespace, and without the indentation
72
+ * all its lines share. Its first line counts as starting at `column`, where the code starts in its
73
+ * file, so that the lines after it keep their indentation relative to it.
74
+ */
75
+ function layOut(printed: string, column?: number): string {
76
+ const text = printed.replace(/^\s*\n/, '');
77
+ const indent = text.length - text.trimStart().length;
78
+ const padded = column && column - 1 > indent ? ' '.repeat(column - 1 - indent) + text : text;
79
+ return dedent(padded).trimEnd().replace(/^[ \t]+/, '');
80
+ }
46
81
 
47
82
  /**
48
83
  * Builder for creating patterns programmatically.
@@ -136,7 +171,8 @@ export class PatternBuilder {
136
171
  }
137
172
 
138
173
  /**
139
- * Represents a pattern that can be matched against AST nodes.
174
+ * Represents a pattern that can be matched against AST nodes. Where it does not match code you
175
+ * expected it to, {@link Pattern.match} with `{debug: true}` prints why, as {@link PatternOptions.debug} describes.
140
176
  */
141
177
  export class Pattern {
142
178
  private _options: PatternOptions = {};
@@ -144,6 +180,7 @@ export class Pattern {
144
180
  private _cachedAstPatterns = new Map<boolean, J>();
145
181
  private static nextPatternId = 1;
146
182
  private readonly patternId: number;
183
+ private readonly printedAttempts = new Set<string>();
147
184
  private readonly unnamedCaptureMapping = new Map<string, string>();
148
185
 
149
186
  /**
@@ -184,13 +221,13 @@ export class Pattern {
184
221
  ) {
185
222
  this.patternId = Pattern.nextPatternId++;
186
223
 
187
- // Build mapping for unnamed captures (unnamed_N -> _X)
224
+ // Build mapping for unnamed captures (unnamed_N -> X, which will be displayed as 🪝X)
188
225
  let unnamedIndex = 1;
189
226
  for (const cap of captures) {
190
227
  if (cap && typeof cap === 'object' && 'getName' in cap) {
191
228
  const name = (cap as Capture<any> | Any<any>).getName();
192
- if (name && name.startsWith('unnamed_')) {
193
- this.unnamedCaptureMapping.set(name, `_${unnamedIndex}`);
229
+ if (name && name.startsWith('unnamed_') && !this.unnamedCaptureMapping.has(name)) {
230
+ this.unnamedCaptureMapping.set(name, `${unnamedIndex}`);
194
231
  unnamedIndex++;
195
232
  }
196
233
  }
@@ -209,9 +246,13 @@ export class Pattern {
209
246
  * context: ['import { forwardRef } from "react"'],
210
247
  * dependencies: {'@types/react': '^18.0.0'}
211
248
  * })
249
+ *
250
+ * @example
251
+ * // Print why each match attempt of this pattern matched or not
252
+ * pat.configure({debug: true})
212
253
  */
213
254
  configure(options: PatternOptions): Pattern {
214
- this._options = { ...this._options, ...options };
255
+ this._options = {...this._options, ...options};
215
256
  // Invalidate cache when configuration changes
216
257
  this._cachedAstPatterns.clear();
217
258
  return this;
@@ -287,12 +328,14 @@ export class Pattern {
287
328
  }
288
329
 
289
330
  /**
290
- * Creates a matcher for this pattern against a specific AST node.
331
+ * Matches this pattern against `tree`, returning what its captures hold, or `undefined` where it
332
+ * does not match. To see why it does not match, pass `{debug: true}`, or a predicate that picks
333
+ * the attempts to print, as {@link PatternOptions.debug} describes.
291
334
  *
292
335
  * @param tree The AST node to match against
293
336
  * @param cursor Cursor at the node's position in a larger tree. Used for context-aware
294
337
  * capture constraints to navigate to parent nodes.
295
- * @param options Optional match options (e.g., debug flag)
338
+ * @param options Optional match options, such as `debug`
296
339
  * @returns A MatchResult if the pattern matches, undefined otherwise
297
340
  *
298
341
  * @example
@@ -300,30 +343,21 @@ export class Pattern {
300
343
  * // Normal match
301
344
  * const match = await pattern.match(node, cursor);
302
345
  *
303
- * // Debug this specific call
304
- * const match = await pattern.match(node, cursor, { debug: true });
346
+ * // Print why this attempt matched or not
347
+ * const match = await pattern.match(node, cursor, {debug: true});
305
348
  * ```
306
349
  */
307
350
  async match(tree: J, cursor: Cursor, options?: MatchOptions): Promise<MatchResult | undefined> {
308
351
  // Three-level precedence: call > pattern > global
309
- const debugEnabled =
310
- options?.debug !== undefined
311
- ? options.debug // 1. Explicit call-level (true OR false)
312
- : (this._options.debug !== undefined
313
- ? this._options.debug // 2. Explicit pattern-level
314
- : process.env.PATTERN_DEBUG === 'true'); // 3. Global
315
-
316
- if (debugEnabled) {
317
- // Use matchWithExplanation and log the result
318
- const result = await this.matchWithExplanation(tree, cursor);
319
- await this.logMatchResult(tree, cursor, result);
320
-
321
- if (result.matched) {
322
- // result.result is the MatchResult class instance
323
- return result.result as MatchResult | undefined;
324
- } else {
325
- return undefined;
352
+ const debug = options?.debug ?? this._options.debug ?? process.env.PATTERN_DEBUG === 'true';
353
+ if (debug) {
354
+ // Taken before the first await, while the caller is still on the stack
355
+ const caller = callSite(new Error().stack);
356
+ const {attempt, patternAst, focus} = await this.attempt(tree, cursor);
357
+ if (debug === true || debug(tree, cursor, attempt)) {
358
+ await this.logMatchResult(tree, attempt, patternAst, focus, caller);
326
359
  }
360
+ return attempt.matched ? attempt.result as MatchResult : undefined;
327
361
  }
328
362
 
329
363
  // Fast path - no debug
@@ -338,117 +372,136 @@ export class Pattern {
338
372
  }
339
373
 
340
374
  /**
341
- * Formats and logs the match result to stderr.
342
- * @private
375
+ * Prints a match attempt to stderr, followed by a blank line. An attempt that prints the same as
376
+ * an earlier one prints only its heading.
343
377
  */
344
- private async logMatchResult(tree: J, cursor: Cursor | undefined, result: MatchAttemptResult): Promise<void> {
345
- const patternSource = this.getPatternSource();
346
- const patternId = `Pattern #${this.patternId}`;
347
- const nodeKind = (tree as any).kind || 'unknown';
348
- // Format kind: extract short name (e.g., "org.openrewrite.java.tree.J$Binary" -> "J$Binary")
349
- const shortKind = typeof nodeKind === 'string'
350
- ? nodeKind.split('.').pop() || nodeKind
351
- : nodeKind;
352
-
353
- // First, log the pattern source
354
- console.error(`[${patternId}] ${patternSource}`);
355
-
356
- // Build the complete match result message
357
- const lines: string[] = [];
358
-
359
- // Print the target tree being matched
360
- let treeStr: string;
361
- try {
362
- const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
363
- treeStr = await printer.print(tree);
364
- } catch (e) {
365
- treeStr = '(tree printing unavailable)';
378
+ private async logMatchResult(tree: J, attempt: MatchAttemptResult, patternAst: J, focus: Focus | undefined,
379
+ caller: string | undefined): Promise<void> {
380
+ const [source, heading, ...block] = await this.render(tree, attempt, patternAst, focus, caller, true);
381
+ const key = [heading, ...block.filter(line => !line.includes('called from'))].join('\n');
382
+ if (this.printedAttempts.has(key)) {
383
+ console.error(`${heading}, as before\n`);
384
+ return;
366
385
  }
386
+ this.printedAttempts.add(key);
387
+ console.error(source);
388
+ console.error([heading, ...block].join('\n') + '\n');
389
+ }
367
390
 
368
- if (result.matched) {
369
- // Success case - result first, then tree, then captures
370
- lines.push(`[${patternId}] ✅ SUCCESS matching against ${shortKind}:`);
371
- treeStr.split('\n').forEach(line => lines.push(`[${patternId}] ${line}`));
372
-
373
- // Log captured values
374
- if (result.result) {
375
- const storage = (result.result as any).storage as Map<string, CaptureStorageValue>;
376
- if (storage && storage.size > 0) {
377
- for (const [name, value] of storage) {
378
- const extractedValue = (result.result as any).extractElements(value);
379
- const valueStr = this.formatCapturedValue(extractedValue);
380
- const displayName = this.unnamedCaptureMapping.get(name) || name;
381
- lines.push(`[${patternId}] Captured '${displayName}': ${valueStr}`);
382
- }
383
- }
391
+ /**
392
+ * The lines debug output prints for a match attempt. They start with the pattern and a heading that
393
+ * says where the code is. A success follows with the code and each capture lettered. A failure follows
394
+ * with the pattern and the code around the mismatch marked, and how they differ.
395
+ */
396
+ private async render(tree: J, attempt: MatchAttemptResult, patternAst: J, focus: Focus | undefined,
397
+ caller: string | undefined, colours: boolean): Promise<string[]> {
398
+ const prefix = `[Pattern #${this.patternId}]`;
399
+ const location = attempt.location;
400
+ const where = location ? ` at ${location.sourcePath}` +
401
+ (location.line ? `:${location.line}:${location.column}` : '') : '';
402
+ const lines = [`${prefix} ${this.getPatternSource()}`,
403
+ `${prefix} ${attempt.matched ? '✅ SUCCESS' : '❌ FAILED'} matching against ${describeKind(tree)}${where}`];
404
+ if (caller) {
405
+ lines.push(`${prefix} called from ${caller}`);
406
+ }
407
+
408
+ if (attempt.matched) {
409
+ const result = attempt.result as any;
410
+ const captures = new Map<number, JTree | JTree[]>();
411
+ const legend: string[] = [];
412
+ for (const [name, value] of result.storage as Map<string, CaptureStorageValue>) {
413
+ const number = captures.size + 1;
414
+ const code = result.extractElements(value);
415
+ captures.set(number, code);
416
+ const displayName = this.unnamedCaptureMapping.get(name) ?? name;
417
+ const symbol = new CaptureHighlightMarker(number).symbol();
418
+ legend.push(`${prefix} ${symbol} 🪝${displayName} = ${await describe(code)}`);
419
+ }
420
+ const printed = await this.printCaptures(tree, captures, location?.column);
421
+ lines.push(...printed.map(line => `${prefix} ${line}`));
422
+ if (legend.length > 0) {
423
+ lines.push(prefix, `${prefix} Captures:`, ...legend);
384
424
  }
385
425
  } else {
386
- // Failure case - result first, then tree, then explanation
387
- lines.push(`[${patternId}] ❌ FAILED matching against ${shortKind}:`);
388
- treeStr.split('\n').forEach(line => lines.push(`[${patternId}] ${line}`));
389
-
390
- const explanation = result.explanation;
426
+ const explanation = attempt.explanation;
427
+ const emoji = !colours || shouldUseEmoji();
428
+ const [green, red, reset] = emoji ? ['', '', ''] : ['\x1b[32m', '\x1b[31m', '\x1b[0m'];
429
+ if (emoji) {
430
+ lines.push(`${prefix} (Mismatched elements are marked with 👉...👈)`);
431
+ }
432
+ const colored = (printed: string[], color: string) =>
433
+ printed.map(line => `${color}${prefix} ${line}${reset}`);
434
+ const patternLines = await this.printMismatch(patternAst, explanation?.patternElement, focus?.pattern,
435
+ emoji);
436
+ const sourceLines = await this.printMismatch(tree, explanation?.targetElement, focus?.target, emoji,
437
+ location?.column);
438
+ lines.push(prefix, `${green}${prefix} Pattern tree:${reset}`, ...colored(patternLines, green),
439
+ prefix, `${red}${prefix} Source tree:${reset}`, ...colored(sourceLines, red));
391
440
  if (explanation) {
392
- // Always show path, even if empty, to make it clear where the mismatch occurred
393
- const compactedPath = this.compactPath(explanation.path);
394
- const pathStr = compactedPath.length > 0 ? compactedPath.join(' → ') : '';
395
- lines.push(`[${patternId}] At path: [${pathStr}]`);
396
- lines.push(`[${patternId}] Reason: ${explanation.reason}`);
397
- lines.push(`[${patternId}] Expected: ${explanation.expected}`);
398
- lines.push(`[${patternId}] Actual: ${explanation.actual}`);
441
+ lines.push(prefix, `${prefix} Details:`,
442
+ `${prefix} Pattern: ${explanation.expected}`,
443
+ `${prefix} Source: ${explanation.actual}`,
444
+ ...(explanation.details ? [`${prefix} Note: ${explanation.details}`] : []));
399
445
  }
400
446
  }
401
-
402
- // Single console.error call with all lines joined
403
- console.error(lines.join('\n'));
447
+ return lines;
404
448
  }
405
449
 
406
- /**
407
- * Compacts array index navigations into the previous path element.
408
- * For example: ['J$VariableDeclarations#variables', '0'] → ['J$VariableDeclarations#variables[0]']
409
- * @private
410
- */
411
- private compactPath(path: string[]): string[] {
412
- const compacted: string[] = [];
413
- let i = 0;
414
-
415
- while (i < path.length) {
416
- const current = path[i];
417
-
418
- // Check if current element is itself a numeric index
419
- if (/^\d+$/.test(current)) {
420
- // This is a bare numeric index - shouldn't normally happen
421
- // If we have a previous element, append to it
422
- if (compacted.length > 0) {
423
- compacted[compacted.length - 1] += `[${current}]`;
424
- } else {
425
- // No previous element to attach to - this is an error in path construction
426
- // Skip it to avoid bare [0] in output
427
- console.warn(`Warning: Path starts with numeric index '${current}' - skipping`);
428
- }
429
- i++;
430
- continue;
431
- }
432
-
433
- // Look ahead to collect consecutive numeric indices
434
- let j = i + 1;
435
- const indices: string[] = [];
436
- while (j < path.length && /^\d+$/.test(path[j])) {
437
- indices.push(path[j]);
438
- j++;
450
+ /** The lines of `tree` around the mismatch, with it marked on `element` and narrowed to `focus` there. */
451
+ private async printMismatch(tree: J, element: JTree | undefined, focus: MarkFocus | undefined,
452
+ emoji: boolean, column?: number): Promise<string[]> {
453
+ try {
454
+ const delimiters = mismatchDelimiters(emoji);
455
+ const marked = element ? await new ElementMarkerVisitor(element, emoji).visit(tree, undefined) as J : tree;
456
+ let printed = await TreePrinters.printer(JS.Kind.CompilationUnit)
457
+ .print(marked, new AnsiAwarePrintOutputCapture(PATTERN_DEBUG_MARKER_PRINTER));
458
+ if (element && focus) {
459
+ printed = await narrowMark(printed, element as J, focus, delimiters);
439
460
  }
461
+ return aroundMarks(layOut(this.replacePlaceholderNames(printed), column).split('\n'), delimiters);
462
+ } catch (e) {
463
+ return [`(tree printing unavailable: ${e})`];
464
+ }
465
+ }
440
466
 
441
- // If we found numeric indices, append them to current element
442
- if (indices.length > 0) {
443
- compacted.push(current + indices.map(idx => `[${idx}]`).join(''));
444
- i = j; // Skip the indices we just processed
445
- } else {
446
- compacted.push(current);
447
- i++;
467
+ /** The lines of `tree` with each capture's code between its letter, as in `Ⓐuser?Ⓐ.name`. */
468
+ private async printCaptures(tree: J, captures: Map<number, JTree | JTree[]>, column?: number): Promise<string[]> {
469
+ try {
470
+ const marked = await new ElementMarkerVisitor(captures).visit(tree, undefined) as J;
471
+ let printed = await TreePrinters.printer(JS.Kind.CompilationUnit)
472
+ .print(marked, new AnsiAwarePrintOutputCapture(PATTERN_DEBUG_MARKER_PRINTER));
473
+ // An optional receiver's `?` and a non-null `!` belong to the captured code, which a template
474
+ // writes with them, but the printer writes them after the capture's closing letter
475
+ for (const [number, code] of captures) {
476
+ const last: any = [code].flat().pop();
477
+ const postfix = last?.markers?.markers.some((marker: any) =>
478
+ marker.kind === JS.Markers.Optional || marker.kind === JS.Markers.NonNullAssertion);
479
+ if (postfix) {
480
+ const symbol = new CaptureHighlightMarker(number).symbol();
481
+ printed = printed.split(symbol + '?').join('?' + symbol).split(symbol + '!').join('!' + symbol);
482
+ }
448
483
  }
484
+ return layOut(this.replacePlaceholderNames(printed), column).split('\n');
485
+ } catch (e) {
486
+ return [`(tree printing unavailable: ${e})`];
449
487
  }
488
+ }
450
489
 
451
- return compacted;
490
+ /**
491
+ * Replaces placeholder names in tree strings with clean display names.
492
+ * Uses 🪝 prefix to make captures easily identifiable.
493
+ * @private
494
+ */
495
+ private replacePlaceholderNames(treeStr: string): string {
496
+ let result = treeStr;
497
+ // Replace unnamed captures with their short forms (🪝1, 🪝2, etc.)
498
+ for (const [originalName, displayName] of this.unnamedCaptureMapping.entries()) {
499
+ const placeholder = `__capt_${originalName}__`;
500
+ result = result.split(placeholder).join(`🪝${displayName}`);
501
+ }
502
+ // Replace all remaining __capt_XXX__ with 🪝XXX (for named captures)
503
+ result = result.replace(/__capt_([^_]+(?:_[^_]+)*)__/g, '🪝$1');
504
+ return result;
452
505
  }
453
506
 
454
507
  /**
@@ -470,9 +523,9 @@ export class Pattern {
470
523
  // Show capture name or placeholder
471
524
  const name = (cap as any)[CAPTURE_NAME_SYMBOL];
472
525
  if (cap && typeof cap === 'object' && name) {
473
- // Use mapped name for unnamed captures, or original name
526
+ // Use mapped name for unnamed captures, or original name (with 🪝 prefix)
474
527
  const displayName = this.unnamedCaptureMapping.get(name) || name;
475
- source += `\${${displayName}}`;
528
+ source += `\${🪝${displayName}}`;
476
529
  } else {
477
530
  source += '${...}';
478
531
  }
@@ -483,82 +536,24 @@ export class Pattern {
483
536
  }
484
537
 
485
538
  /**
486
- * Formats a captured value for logging.
487
- * @private
488
- */
489
- private formatCapturedValue(value: any): string {
490
- if (value === null) return 'null';
491
- if (value === undefined) return 'undefined';
492
-
493
- // Check if it's an array (variadic capture)
494
- if (Array.isArray(value)) {
495
- if (value.length === 0) return '[]';
496
- const items = value.slice(0, 3).map(v => this.formatSingleValue(v));
497
- const suffix = value.length > 3 ? `, ... (${value.length} total)` : '';
498
- return `[${items.join(', ')}${suffix}]`;
499
- }
500
-
501
- return this.formatSingleValue(value);
502
- }
503
-
504
- /**
505
- * Formats a single AST node for logging.
506
- * @private
507
- */
508
- private formatSingleValue(value: any): string {
509
- if (!value || typeof value !== 'object') {
510
- return String(value);
511
- }
512
-
513
- const kind = (value as any).kind;
514
- if (!kind) return String(value);
515
-
516
- // Extract simple kind name (last segment)
517
- const kindStr = kind.split('.').pop();
518
-
519
- // For literals, show the value
520
- if (kindStr === 'Literal' && value.value !== undefined) {
521
- const litValue = typeof value.value === 'string'
522
- ? `"${value.value}"`
523
- : String(value.value);
524
- return `${kindStr}(${litValue})`;
525
- }
526
-
527
- // For identifiers, show the name
528
- if (kindStr === 'Identifier' && value.simpleName) {
529
- return `${kindStr}(${value.simpleName})`;
530
- }
531
-
532
- // Default: just the kind
533
- return kindStr;
534
- }
535
-
536
- /**
537
- * Matches a pattern against an AST node with detailed debug information.
538
- * Part of Layer 2 (Public API).
539
- *
540
- * This method always enables debug logging and returns detailed information about
541
- * the match attempt, including:
542
- * - Whether the pattern matched
543
- * - Captured nodes (if matched)
544
- * - Explanation of failure (if not matched)
545
- * - Debug log entries showing the matching process
539
+ * Matches like {@link match}, and returns why the pattern did not match rather than printing it.
540
+ * A failed attempt's `explanation` holds the reason, the expected and actual code, and the pattern
541
+ * and source nodes where they differ. `debugLog` holds an entry for each capture constraint evaluated.
546
542
  *
547
543
  * @param tree The AST node to match against
548
544
  * @param cursor Cursor at the node's position in a larger tree
549
- * @param debugOptions Optional debug options (defaults to all logging enabled)
550
- * @returns Detailed result with debug information
545
+ * @param debugOptions Which entries `debugLog` collects, by default all of them
546
+ * @returns Whether the pattern matched, with the captures where it did and the explanation where it did not
551
547
  *
552
548
  * @example
553
549
  * const x = capture('x');
554
550
  * const pat = pattern`console.log(${x})`;
555
551
  * const attempt = await pat.matchWithExplanation(node, cursor);
556
552
  * if (attempt.matched) {
557
- * console.log('Matched!');
558
553
  * console.log('Captured x:', attempt.result.get('x'));
559
554
  * } else {
560
- * console.log('Failed:', attempt.explanation);
561
- * console.log('Debug log:', attempt.debugLog);
555
+ * const {reason, expected, actual} = attempt.explanation!;
556
+ * console.log(`${reason}: the pattern has ${expected} where the source has ${actual}`);
562
557
  * }
563
558
  */
564
559
  async matchWithExplanation(
@@ -566,34 +561,36 @@ export class Pattern {
566
561
  cursor: Cursor,
567
562
  debugOptions?: DebugOptions
568
563
  ): Promise<MatchAttemptResult> {
569
- // Default to full debug logging if not specified
570
- const options: DebugOptions = {
571
- enabled: true,
572
- logComparison: true,
573
- logConstraints: true,
574
- ...debugOptions
575
- };
564
+ return (await this.attempt(tree, cursor, debugOptions, true)).attempt;
565
+ }
576
566
 
567
+ /**
568
+ * The attempt, the pattern tree it compared, which holds the explanation's pattern element, and
569
+ * where on each side the mismatch is narrower than its marked node.
570
+ */
571
+ private async attempt(tree: J, cursor: Cursor, debugOptions?: DebugOptions, report: boolean = false):
572
+ Promise<{ attempt: MatchAttemptResult, patternAst: J, focus?: Focus }> {
573
+ const options: DebugOptions = {enabled: true, logComparison: true, logConstraints: true, ...debugOptions};
577
574
  const matcher = new Matcher(this, tree, cursor, options);
578
- const success = await matcher.matches();
579
-
580
- if (success) {
581
- // Match succeeded - return MatchResult with debug info
582
- const storage = (matcher as any).storage;
583
- const matchResult = new MatchResult(new Map(storage), () => matcher.patternPrefixes());
584
- return {
585
- matched: true,
586
- result: matchResult,
587
- debugLog: matcher.getDebugLog()
588
- };
589
- } else {
590
- // Match failed - return explanation
591
- return {
592
- matched: false,
593
- explanation: matcher.getExplanation(),
594
- debugLog: matcher.getDebugLog()
595
- };
575
+ const matched = await matcher.matches();
576
+ const attempt: MatchAttemptResult = matched ? {
577
+ matched,
578
+ result: new MatchResult(new Map((matcher as any).storage), () => matcher.patternPrefixes()),
579
+ debugLog: matcher.getDebugLog()
580
+ } : {
581
+ matched,
582
+ explanation: await matcher.getExplanation(text => this.replacePlaceholderNames(text)),
583
+ debugLog: matcher.getDebugLog()
584
+ };
585
+ attempt.location = await sourceLocation(tree, cursor);
586
+ const patternAst = matcher.getPatternAst()!;
587
+ const focus = matcher.getFocus();
588
+ if (report) {
589
+ // Without the pattern's number, which depends on how many patterns were created before it
590
+ const lines = await this.render(tree, attempt, patternAst, focus, undefined, false);
591
+ attempt.report = lines.map(line => line.replace(/^\[Pattern #\d+] ?/, '')).join('\n') + '\n';
596
592
  }
593
+ return {attempt, patternAst, focus};
597
594
  }
598
595
  }
599
596
 
@@ -715,11 +712,10 @@ class Matcher {
715
712
  private readonly storage = new Map<string, CaptureStorageValue>();
716
713
  private patternAst?: J;
717
714
 
718
- // Debug tracking (Layer 1: Core Instrumentation)
715
+ // Debug tracking
719
716
  private readonly debugOptions: DebugOptions;
720
717
  private readonly debugLog: DebugLogEntry[] = [];
721
- private explanation?: MatchExplanation;
722
- private readonly currentPath: string[] = [];
718
+ private explanation?: PendingExplanation;
723
719
 
724
720
  /**
725
721
  * Creates a new matcher for a pattern against an AST node.
@@ -760,9 +756,10 @@ class Matcher {
760
756
  if ((this.ast.kind === J.Kind.Parentheses || this.ast.kind === J.Kind.ControlParentheses) &&
761
757
  this.patternAst.kind !== this.ast.kind) {
762
758
  if (this.debugOptions.enabled) {
763
- this.setExplanation('kind-mismatch', 'An expression without parentheses',
764
- `Parentheses (${this.ast.kind.split('.').pop()})`,
765
- 'The expression the parentheses hold is matched on its own');
759
+ this.setExplanation('kind-mismatch', 'an expression without parentheses',
760
+ `parentheses (${this.ast.kind.split('.').pop()})`,
761
+ 'A visitor reaches the expression inside the parentheses next, where this pattern can match it. ' +
762
+ 'To match the parentheses too, write them in the pattern.', this.patternAst, this.ast);
766
763
  }
767
764
  return false;
768
765
  }
@@ -830,7 +827,6 @@ class Matcher {
830
827
 
831
828
  /**
832
829
  * Logs a debug message if debugging is enabled.
833
- * Part of Layer 1 (Core Instrumentation).
834
830
  *
835
831
  * @param level The severity level
836
832
  * @param scope The scope/category
@@ -852,7 +848,6 @@ class Matcher {
852
848
  this.debugLog.push({
853
849
  level,
854
850
  scope,
855
- path: [...this.currentPath],
856
851
  message,
857
852
  data
858
853
  });
@@ -861,50 +856,37 @@ class Matcher {
861
856
  /**
862
857
  * Sets the explanation for why the pattern match failed.
863
858
  * Only sets the first failure (most relevant).
864
- * Part of Layer 1 (Core Instrumentation).
865
859
  *
866
860
  * @param reason The reason for failure
867
861
  * @param expected Human-readable description of what was expected
868
862
  * @param actual Human-readable description of what was found
869
863
  * @param details Optional additional context
864
+ * @param patternElement The actual pattern element that failed to match
865
+ * @param targetElement The actual target element that failed to match
870
866
  */
871
867
  private setExplanation(
872
868
  reason: MatchExplanation['reason'],
873
- expected: string,
874
- actual: string,
875
- details?: string
869
+ expected: string | Promise<string>,
870
+ actual: string | Promise<string>,
871
+ details?: string,
872
+ patternElement?: any,
873
+ targetElement?: any,
874
+ focus?: Focus
876
875
  ): void {
877
876
  // Only set the first failure (most relevant)
878
877
  if (this.explanation) return;
879
878
 
880
879
  this.explanation = {
881
880
  reason,
882
- path: [...this.currentPath],
883
881
  expected,
884
882
  actual,
885
- details
883
+ details,
884
+ patternElement,
885
+ targetElement,
886
+ focus
886
887
  };
887
888
  }
888
889
 
889
- /**
890
- * Pushes a path component onto the current path.
891
- * Used to track where in the AST tree we are during matching.
892
- * Part of Layer 1 (Core Instrumentation).
893
- *
894
- * @param name The path component to push
895
- */
896
- private pushPath(name: string): void {
897
- this.currentPath.push(name);
898
- }
899
-
900
- /**
901
- * Pops the last path component from the current path.
902
- * Part of Layer 1 (Core Instrumentation).
903
- */
904
- private popPath(): void {
905
- this.currentPath.pop();
906
- }
907
-
908
890
  /**
909
891
  * Matches a pattern node against a target node.
910
892
  *
@@ -923,17 +905,19 @@ class Matcher {
923
905
  const matcherCallbacks: MatcherCallbacks = {
924
906
  handleCapture: (capture: CaptureMarker, t: J, w?: J.RightPadded<J>) => this.handleCapture(capture, t, w),
925
907
  handleVariadicCapture: (capture: CaptureMarker, ts: J[], ws?: J.RightPadded<J>[]) => this.handleVariadicCapture(capture, ts, ws),
908
+ getCapture: (name: string) => this.storage.get(name),
926
909
  saveState: () => this.saveState(),
927
910
  restoreState: (state) => this.restoreState(state),
928
- // Debug callbacks (Layer 1) - grouped together, always present or absent
911
+ // Debug callbacks, all present or all absent
929
912
  debug: this.debugOptions.enabled ? {
930
913
  log: (level: DebugLogEntry['level'], scope: DebugLogEntry['scope'], message: string, data?: any) => this.log(level, scope, message, data),
931
- setExplanation: (reason: MatchExplanation['reason'], expected: string, actual: string, details?: string) => this.setExplanation(reason, expected, actual, details),
914
+ setExplanation: (reason: MatchExplanation['reason'], expected: string | Promise<string>,
915
+ actual: string | Promise<string>, details?: string, patternElement?: any,
916
+ targetElement?: any, focus?: Focus) =>
917
+ this.setExplanation(reason, expected, actual, details, patternElement, targetElement, focus),
932
918
  getExplanation: () => this.explanation,
933
- restoreExplanation: (explanation: MatchExplanation) => { this.explanation = explanation; },
934
- clearExplanation: () => { this.explanation = undefined; },
935
- pushPath: (name: string) => this.pushPath(name),
936
- popPath: () => this.popPath()
919
+ restoreExplanation: (explanation: PendingExplanation) => { this.explanation = explanation; },
920
+ clearExplanation: () => { this.explanation = undefined; }
937
921
  } : undefined
938
922
  };
939
923
 
@@ -952,7 +936,9 @@ class Matcher {
952
936
  'structural-mismatch',
953
937
  `Pattern node of type ${patternKind}`,
954
938
  `Target node of type ${targetKind}`,
955
- 'Nodes did not match structurally'
939
+ 'Nodes did not match structurally',
940
+ pattern,
941
+ target
956
942
  );
957
943
  }
958
944
 
@@ -961,7 +947,7 @@ class Matcher {
961
947
 
962
948
  /**
963
949
  * Saves the current state for backtracking.
964
- * Includes both capture storage AND debug state (explanation, log, path).
950
+ * Includes both capture storage AND debug state (explanation, log).
965
951
  *
966
952
  * @returns A snapshot of the current state
967
953
  */
@@ -970,8 +956,7 @@ class Matcher {
970
956
  storage: new Map(this.storage),
971
957
  debugState: this.debugOptions.enabled ? {
972
958
  explanation: this.explanation,
973
- logLength: this.debugLog.length,
974
- path: [...this.currentPath]
959
+ logLength: this.debugLog.length
975
960
  } : undefined
976
961
  };
977
962
  }
@@ -994,9 +979,6 @@ class Matcher {
994
979
  this.explanation = state.debugState.explanation;
995
980
  // Truncate debug log to saved length (remove entries added during failed attempt)
996
981
  this.debugLog.length = state.debugState.logLength;
997
- // Restore path
998
- this.currentPath.length = 0;
999
- this.currentPath.push(...state.debugState.path);
1000
982
  }
1001
983
  }
1002
984
 
@@ -1095,7 +1077,6 @@ class Matcher {
1095
1077
 
1096
1078
  /**
1097
1079
  * Gets the debug log entries collected during matching.
1098
- * Part of Layer 2 (Public API).
1099
1080
  *
1100
1081
  * @returns The debug log entries, or undefined if debug wasn't enabled
1101
1082
  */
@@ -1104,13 +1085,26 @@ class Matcher {
1104
1085
  }
1105
1086
 
1106
1087
  /**
1107
- * Gets the explanation for why the match failed.
1108
- * Part of Layer 2 (Public API).
1109
- *
1110
- * @returns The match explanation, or undefined if match succeeded or no explanation available
1088
+ * Why the match failed, once its expected and actual code have printed and `display` has
1089
+ * rewritten the capture placeholders in them.
1111
1090
  */
1112
- getExplanation(): MatchExplanation | undefined {
1113
- return this.explanation;
1091
+ async getExplanation(display: (text: string) => string): Promise<MatchExplanation | undefined> {
1092
+ if (!this.explanation) {
1093
+ return undefined;
1094
+ }
1095
+ const [expected, actual] = await Promise.all([this.explanation.expected, this.explanation.actual]);
1096
+ const {focus, ...explanation} = this.explanation;
1097
+ return {...explanation, expected: display(expected), actual: display(actual)};
1098
+ }
1099
+
1100
+ /** Where the mismatch is narrower than the nodes the explanation marks. */
1101
+ getFocus(): Focus | undefined {
1102
+ return this.explanation?.focus;
1103
+ }
1104
+
1105
+ /** The pattern tree the last attempt compared. */
1106
+ getPatternAst(): J | undefined {
1107
+ return this.patternAst;
1114
1108
  }
1115
1109
  }
1116
1110
 
@@ -1137,6 +1131,8 @@ class Matcher {
1137
1131
  */
1138
1132
  /**
1139
1133
  * Creates a pattern from a template literal (direct usage).
1134
+ * To see why it does or does not match some code, pass `{debug: true}` to `match()`
1135
+ * or create it with `pattern({debug: true})`, as {@link PatternOptions.debug} describes.
1140
1136
  *
1141
1137
  * @example
1142
1138
  * ```typescript
@@ -1150,7 +1146,8 @@ export function pattern(strings: TemplateStringsArray, ...captures: (Capture | A
1150
1146
  *
1151
1147
  * @example
1152
1148
  * ```typescript
1153
- * const pat = pattern({ debug: true })`console.log(${x})`;
1149
+ * // Prints why each match attempt matched or not, as PatternOptions.debug describes
1150
+ * const pat = pattern({debug: true})`console.log(${x})`;
1154
1151
  * ```
1155
1152
  */
1156
1153
  export function pattern(options: PatternOptions): (strings: TemplateStringsArray, ...captures: (Capture | Any<any> | RawCode | string)[]) => Pattern;