@openrewrite/rewrite 8.97.0 → 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 (152) hide show
  1. package/README.md +42 -0
  2. package/dist/java/visitor.d.ts +2 -0
  3. package/dist/java/visitor.d.ts.map +1 -1
  4. package/dist/java/visitor.js +7 -3
  5. package/dist/java/visitor.js.map +1 -1
  6. package/dist/javascript/add-import.d.ts +1 -6
  7. package/dist/javascript/add-import.d.ts.map +1 -1
  8. package/dist/javascript/add-import.js +90 -58
  9. package/dist/javascript/add-import.js.map +1 -1
  10. package/dist/javascript/comparator.d.ts +16 -10
  11. package/dist/javascript/comparator.d.ts.map +1 -1
  12. package/dist/javascript/comparator.js +10 -8
  13. package/dist/javascript/comparator.js.map +1 -1
  14. package/dist/javascript/package-json-parser.d.ts +2 -0
  15. package/dist/javascript/package-json-parser.d.ts.map +1 -1
  16. package/dist/javascript/package-json-parser.js +27 -15
  17. package/dist/javascript/package-json-parser.js.map +1 -1
  18. package/dist/javascript/package-manager.d.ts +13 -4
  19. package/dist/javascript/package-manager.d.ts.map +1 -1
  20. package/dist/javascript/package-manager.js +134 -17
  21. package/dist/javascript/package-manager.js.map +1 -1
  22. package/dist/javascript/parser.d.ts +2 -0
  23. package/dist/javascript/parser.d.ts.map +1 -1
  24. package/dist/javascript/parser.js +23 -58
  25. package/dist/javascript/parser.js.map +1 -1
  26. package/dist/javascript/print.d.ts.map +1 -1
  27. package/dist/javascript/print.js +1 -1
  28. package/dist/javascript/print.js.map +1 -1
  29. package/dist/javascript/recipes/change-method-target-to-import.d.ts +4 -0
  30. package/dist/javascript/recipes/change-method-target-to-import.d.ts.map +1 -1
  31. package/dist/javascript/recipes/change-method-target-to-import.js +20 -2
  32. package/dist/javascript/recipes/change-method-target-to-import.js.map +1 -1
  33. package/dist/javascript/recipes/dependencies.d.ts +19 -0
  34. package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
  35. package/dist/javascript/recipes/dependencies.js +8 -0
  36. package/dist/javascript/recipes/dependencies.js.map +1 -1
  37. package/dist/javascript/recipes/order-imports.js +3 -3
  38. package/dist/javascript/recipes/order-imports.js.map +1 -1
  39. package/dist/javascript/remove-import.d.ts.map +1 -1
  40. package/dist/javascript/remove-import.js +115 -33
  41. package/dist/javascript/remove-import.js.map +1 -1
  42. package/dist/javascript/scope.d.ts +7 -0
  43. package/dist/javascript/scope.d.ts.map +1 -1
  44. package/dist/javascript/scope.js +23 -0
  45. package/dist/javascript/scope.js.map +1 -1
  46. package/dist/javascript/templating/bindings.d.ts.map +1 -1
  47. package/dist/javascript/templating/bindings.js +0 -4
  48. package/dist/javascript/templating/bindings.js.map +1 -1
  49. package/dist/javascript/templating/comparator.d.ts +32 -79
  50. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  51. package/dist/javascript/templating/comparator.js +35 -628
  52. package/dist/javascript/templating/comparator.js.map +1 -1
  53. package/dist/javascript/templating/debug.d.ts +143 -0
  54. package/dist/javascript/templating/debug.d.ts.map +1 -0
  55. package/dist/javascript/templating/debug.js +769 -0
  56. package/dist/javascript/templating/debug.js.map +1 -0
  57. package/dist/javascript/templating/engine.d.ts +12 -3
  58. package/dist/javascript/templating/engine.d.ts.map +1 -1
  59. package/dist/javascript/templating/engine.js +135 -76
  60. package/dist/javascript/templating/engine.js.map +1 -1
  61. package/dist/javascript/templating/index.d.ts +1 -1
  62. package/dist/javascript/templating/index.d.ts.map +1 -1
  63. package/dist/javascript/templating/index.js.map +1 -1
  64. package/dist/javascript/templating/pattern.d.ts +44 -35
  65. package/dist/javascript/templating/pattern.d.ts.map +1 -1
  66. package/dist/javascript/templating/pattern.js +224 -238
  67. package/dist/javascript/templating/pattern.js.map +1 -1
  68. package/dist/javascript/templating/rewrite.d.ts +4 -0
  69. package/dist/javascript/templating/rewrite.d.ts.map +1 -1
  70. package/dist/javascript/templating/rewrite.js +5 -1
  71. package/dist/javascript/templating/rewrite.js.map +1 -1
  72. package/dist/javascript/templating/template.js +1 -1
  73. package/dist/javascript/templating/template.js.map +1 -1
  74. package/dist/javascript/templating/types.d.ts +38 -35
  75. package/dist/javascript/templating/types.d.ts.map +1 -1
  76. package/dist/javascript/templating/utils.d.ts.map +1 -1
  77. package/dist/javascript/templating/utils.js +18 -9
  78. package/dist/javascript/templating/utils.js.map +1 -1
  79. package/dist/javascript/tree.d.ts +3 -1
  80. package/dist/javascript/tree.d.ts.map +1 -1
  81. package/dist/javascript/tree.js +5 -0
  82. package/dist/javascript/tree.js.map +1 -1
  83. package/dist/json/tree.d.ts +1 -2
  84. package/dist/json/tree.d.ts.map +1 -1
  85. package/dist/json/tree.js +10 -7
  86. package/dist/json/tree.js.map +1 -1
  87. package/dist/rewrite-javascript-version.txt +1 -1
  88. package/dist/rpc/request/get-object.d.ts.map +1 -1
  89. package/dist/rpc/request/get-object.js +5 -3
  90. package/dist/rpc/request/get-object.js.map +1 -1
  91. package/dist/rpc/request/install-recipes.d.ts +10 -0
  92. package/dist/rpc/request/install-recipes.d.ts.map +1 -1
  93. package/dist/rpc/request/install-recipes.js +125 -51
  94. package/dist/rpc/request/install-recipes.js.map +1 -1
  95. package/dist/rpc/request/prepare-recipe.d.ts +1 -0
  96. package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
  97. package/dist/rpc/request/prepare-recipe.js +13 -6
  98. package/dist/rpc/request/prepare-recipe.js.map +1 -1
  99. package/dist/rpc/rewrite-rpc.d.ts +1 -1
  100. package/dist/rpc/rewrite-rpc.d.ts.map +1 -1
  101. package/dist/rpc/rewrite-rpc.js +2 -3
  102. package/dist/rpc/rewrite-rpc.js.map +1 -1
  103. package/dist/rpc/worker-transport.d.ts +7 -3
  104. package/dist/rpc/worker-transport.d.ts.map +1 -1
  105. package/dist/rpc/worker-transport.js +54 -41
  106. package/dist/rpc/worker-transport.js.map +1 -1
  107. package/dist/test/rewrite-test.d.ts +1 -16
  108. package/dist/test/rewrite-test.d.ts.map +1 -1
  109. package/dist/test/rewrite-test.js +7 -58
  110. package/dist/test/rewrite-test.js.map +1 -1
  111. package/dist/util.d.ts +16 -0
  112. package/dist/util.d.ts.map +1 -1
  113. package/dist/util.js +53 -0
  114. package/dist/util.js.map +1 -1
  115. package/dist/yaml/parser.js +8 -5
  116. package/dist/yaml/parser.js.map +1 -1
  117. package/dist/yaml/print.js +9 -3
  118. package/dist/yaml/print.js.map +1 -1
  119. package/package.json +1 -1
  120. package/src/java/visitor.ts +8 -3
  121. package/src/javascript/add-import.ts +98 -64
  122. package/src/javascript/comparator.ts +66 -53
  123. package/src/javascript/package-json-parser.ts +25 -16
  124. package/src/javascript/package-manager.ts +121 -15
  125. package/src/javascript/parser.ts +29 -81
  126. package/src/javascript/print.ts +1 -2
  127. package/src/javascript/recipes/change-method-target-to-import.ts +23 -3
  128. package/src/javascript/recipes/dependencies.ts +23 -0
  129. package/src/javascript/recipes/order-imports.ts +5 -5
  130. package/src/javascript/remove-import.ts +113 -41
  131. package/src/javascript/scope.ts +23 -0
  132. package/src/javascript/templating/bindings.ts +1 -6
  133. package/src/javascript/templating/comparator.ts +76 -766
  134. package/src/javascript/templating/debug.ts +806 -0
  135. package/src/javascript/templating/engine.ts +138 -77
  136. package/src/javascript/templating/index.ts +1 -0
  137. package/src/javascript/templating/pattern.ts +267 -270
  138. package/src/javascript/templating/rewrite.ts +5 -1
  139. package/src/javascript/templating/template.ts +1 -1
  140. package/src/javascript/templating/types.ts +40 -37
  141. package/src/javascript/templating/utils.ts +4 -12
  142. package/src/javascript/tree.ts +6 -1
  143. package/src/json/tree.ts +9 -7
  144. package/src/rpc/request/get-object.ts +34 -28
  145. package/src/rpc/request/install-recipes.ts +128 -52
  146. package/src/rpc/request/prepare-recipe.ts +18 -15
  147. package/src/rpc/rewrite-rpc.ts +2 -4
  148. package/src/rpc/worker-transport.ts +63 -43
  149. package/src/test/rewrite-test.ts +2 -59
  150. package/src/util.ts +58 -0
  151. package/src/yaml/parser.ts +9 -5
  152. package/src/yaml/print.ts +9 -3
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: true });
3
14
  exports.MatchResult = exports.Pattern = exports.PatternBuilder = void 0;
4
15
  exports.pattern = pattern;
@@ -10,7 +21,20 @@ const scope_1 = require("../scope");
10
21
  const engine_1 = require("./engine");
11
22
  const print_1 = require("../../print");
12
23
  const index_1 = require("../index");
24
+ const debug_1 = require("./debug");
25
+ const util_1 = require("../../util");
13
26
  const comparator_2 = require("../comparator");
27
+ /**
28
+ * Printed code without its leading blank lines and trailing whitespace, and without the indentation
29
+ * all its lines share. Its first line counts as starting at `column`, where the code starts in its
30
+ * file, so that the lines after it keep their indentation relative to it.
31
+ */
32
+ function layOut(printed, column) {
33
+ const text = printed.replace(/^\s*\n/, '');
34
+ const indent = text.length - text.trimStart().length;
35
+ const padded = column && column - 1 > indent ? ' '.repeat(column - 1 - indent) + text : text;
36
+ return (0, util_1.dedent)(padded).trimEnd().replace(/^[ \t]+/, '');
37
+ }
14
38
  /**
15
39
  * Builder for creating patterns programmatically.
16
40
  * Use when pattern structure is not known at compile time.
@@ -101,7 +125,8 @@ class PatternBuilder {
101
125
  }
102
126
  exports.PatternBuilder = PatternBuilder;
103
127
  /**
104
- * Represents a pattern that can be matched against AST nodes.
128
+ * Represents a pattern that can be matched against AST nodes. Where it does not match code you
129
+ * expected it to, {@link Pattern.match} with `{debug: true}` prints why, as {@link PatternOptions.debug} describes.
105
130
  */
106
131
  class Pattern {
107
132
  /**
@@ -140,15 +165,16 @@ class Pattern {
140
165
  this._options = {};
141
166
  /** The pattern tree, keyed by whether its code was parsed as an expression. */
142
167
  this._cachedAstPatterns = new Map();
168
+ this.printedAttempts = new Set();
143
169
  this.unnamedCaptureMapping = new Map();
144
170
  this.patternId = Pattern.nextPatternId++;
145
- // Build mapping for unnamed captures (unnamed_N -> _X)
171
+ // Build mapping for unnamed captures (unnamed_N -> X, which will be displayed as 🪝X)
146
172
  let unnamedIndex = 1;
147
173
  for (const cap of captures) {
148
174
  if (cap && typeof cap === 'object' && 'getName' in cap) {
149
175
  const name = cap.getName();
150
- if (name && name.startsWith('unnamed_')) {
151
- this.unnamedCaptureMapping.set(name, `_${unnamedIndex}`);
176
+ if (name && name.startsWith('unnamed_') && !this.unnamedCaptureMapping.has(name)) {
177
+ this.unnamedCaptureMapping.set(name, `${unnamedIndex}`);
152
178
  unnamedIndex++;
153
179
  }
154
180
  }
@@ -166,6 +192,10 @@ class Pattern {
166
192
  * context: ['import { forwardRef } from "react"'],
167
193
  * dependencies: {'@types/react': '^18.0.0'}
168
194
  * })
195
+ *
196
+ * @example
197
+ * // Print why each match attempt of this pattern matched or not
198
+ * pat.configure({debug: true})
169
199
  */
170
200
  configure(options) {
171
201
  this._options = Object.assign(Object.assign({}, this._options), options);
@@ -227,12 +257,14 @@ class Pattern {
227
257
  return result;
228
258
  }
229
259
  /**
230
- * Creates a matcher for this pattern against a specific AST node.
260
+ * Matches this pattern against `tree`, returning what its captures hold, or `undefined` where it
261
+ * does not match. To see why it does not match, pass `{debug: true}`, or a predicate that picks
262
+ * the attempts to print, as {@link PatternOptions.debug} describes.
231
263
  *
232
264
  * @param tree The AST node to match against
233
265
  * @param cursor Cursor at the node's position in a larger tree. Used for context-aware
234
266
  * capture constraints to navigate to parent nodes.
235
- * @param options Optional match options (e.g., debug flag)
267
+ * @param options Optional match options, such as `debug`
236
268
  * @returns A MatchResult if the pattern matches, undefined otherwise
237
269
  *
238
270
  * @example
@@ -240,28 +272,22 @@ class Pattern {
240
272
  * // Normal match
241
273
  * const match = await pattern.match(node, cursor);
242
274
  *
243
- * // Debug this specific call
244
- * const match = await pattern.match(node, cursor, { debug: true });
275
+ * // Print why this attempt matched or not
276
+ * const match = await pattern.match(node, cursor, {debug: true});
245
277
  * ```
246
278
  */
247
279
  async match(tree, cursor, options) {
280
+ var _a, _b;
248
281
  // Three-level precedence: call > pattern > global
249
- const debugEnabled = (options === null || options === void 0 ? void 0 : options.debug) !== undefined
250
- ? options.debug // 1. Explicit call-level (true OR false)
251
- : (this._options.debug !== undefined
252
- ? this._options.debug // 2. Explicit pattern-level
253
- : process.env.PATTERN_DEBUG === 'true'); // 3. Global
254
- if (debugEnabled) {
255
- // Use matchWithExplanation and log the result
256
- const result = await this.matchWithExplanation(tree, cursor);
257
- await this.logMatchResult(tree, cursor, result);
258
- if (result.matched) {
259
- // result.result is the MatchResult class instance
260
- return result.result;
261
- }
262
- else {
263
- return undefined;
282
+ const debug = (_b = (_a = options === null || options === void 0 ? void 0 : options.debug) !== null && _a !== void 0 ? _a : this._options.debug) !== null && _b !== void 0 ? _b : process.env.PATTERN_DEBUG === 'true';
283
+ if (debug) {
284
+ // Taken before the first await, while the caller is still on the stack
285
+ const caller = (0, debug_1.callSite)(new Error().stack);
286
+ const { attempt, patternAst, focus } = await this.attempt(tree, cursor);
287
+ if (debug === true || debug(tree, cursor, attempt)) {
288
+ await this.logMatchResult(tree, attempt, patternAst, focus, caller);
264
289
  }
290
+ return attempt.matched ? attempt.result : undefined;
265
291
  }
266
292
  // Fast path - no debug
267
293
  const matcher = new Matcher(this, tree, cursor);
@@ -274,108 +300,125 @@ class Pattern {
274
300
  return new MatchResult(new Map(storage), () => matcher.patternPrefixes());
275
301
  }
276
302
  /**
277
- * Formats and logs the match result to stderr.
278
- * @private
303
+ * Prints a match attempt to stderr, followed by a blank line. An attempt that prints the same as
304
+ * an earlier one prints only its heading.
279
305
  */
280
- async logMatchResult(tree, cursor, result) {
281
- const patternSource = this.getPatternSource();
282
- const patternId = `Pattern #${this.patternId}`;
283
- const nodeKind = tree.kind || 'unknown';
284
- // Format kind: extract short name (e.g., "org.openrewrite.java.tree.J$Binary" -> "J$Binary")
285
- const shortKind = typeof nodeKind === 'string'
286
- ? nodeKind.split('.').pop() || nodeKind
287
- : nodeKind;
288
- // First, log the pattern source
289
- console.error(`[${patternId}] ${patternSource}`);
290
- // Build the complete match result message
291
- const lines = [];
292
- // Print the target tree being matched
293
- let treeStr;
294
- try {
295
- const printer = print_1.TreePrinters.printer(index_1.JS.Kind.CompilationUnit);
296
- treeStr = await printer.print(tree);
306
+ async logMatchResult(tree, attempt, patternAst, focus, caller) {
307
+ const [source, heading, ...block] = await this.render(tree, attempt, patternAst, focus, caller, true);
308
+ const key = [heading, ...block.filter(line => !line.includes('called from'))].join('\n');
309
+ if (this.printedAttempts.has(key)) {
310
+ console.error(`${heading}, as before\n`);
311
+ return;
297
312
  }
298
- catch (e) {
299
- treeStr = '(tree printing unavailable)';
300
- }
301
- if (result.matched) {
302
- // Success case - result first, then tree, then captures
303
- lines.push(`[${patternId}] ✅ SUCCESS matching against ${shortKind}:`);
304
- treeStr.split('\n').forEach(line => lines.push(`[${patternId}] ${line}`));
305
- // Log captured values
306
- if (result.result) {
307
- const storage = result.result.storage;
308
- if (storage && storage.size > 0) {
309
- for (const [name, value] of storage) {
310
- const extractedValue = result.result.extractElements(value);
311
- const valueStr = this.formatCapturedValue(extractedValue);
312
- const displayName = this.unnamedCaptureMapping.get(name) || name;
313
- lines.push(`[${patternId}] Captured '${displayName}': ${valueStr}`);
314
- }
315
- }
313
+ this.printedAttempts.add(key);
314
+ console.error(source);
315
+ console.error([heading, ...block].join('\n') + '\n');
316
+ }
317
+ /**
318
+ * The lines debug output prints for a match attempt. They start with the pattern and a heading that
319
+ * says where the code is. A success follows with the code and each capture lettered. A failure follows
320
+ * with the pattern and the code around the mismatch marked, and how they differ.
321
+ */
322
+ async render(tree, attempt, patternAst, focus, caller, colours) {
323
+ var _a;
324
+ const prefix = `[Pattern #${this.patternId}]`;
325
+ const location = attempt.location;
326
+ const where = location ? ` at ${location.sourcePath}` +
327
+ (location.line ? `:${location.line}:${location.column}` : '') : '';
328
+ const lines = [`${prefix} ${this.getPatternSource()}`,
329
+ `${prefix} ${attempt.matched ? '✅ SUCCESS' : '❌ FAILED'} matching against ${(0, debug_1.describeKind)(tree)}${where}`];
330
+ if (caller) {
331
+ lines.push(`${prefix} called from ${caller}`);
332
+ }
333
+ if (attempt.matched) {
334
+ const result = attempt.result;
335
+ const captures = new Map();
336
+ const legend = [];
337
+ for (const [name, value] of result.storage) {
338
+ const number = captures.size + 1;
339
+ const code = result.extractElements(value);
340
+ captures.set(number, code);
341
+ const displayName = (_a = this.unnamedCaptureMapping.get(name)) !== null && _a !== void 0 ? _a : name;
342
+ const symbol = new debug_1.CaptureHighlightMarker(number).symbol();
343
+ legend.push(`${prefix} ${symbol} 🪝${displayName} = ${await (0, debug_1.describe)(code)}`);
344
+ }
345
+ const printed = await this.printCaptures(tree, captures, location === null || location === void 0 ? void 0 : location.column);
346
+ lines.push(...printed.map(line => `${prefix} ${line}`));
347
+ if (legend.length > 0) {
348
+ lines.push(prefix, `${prefix} Captures:`, ...legend);
316
349
  }
317
350
  }
318
351
  else {
319
- // Failure case - result first, then tree, then explanation
320
- lines.push(`[${patternId}] ❌ FAILED matching against ${shortKind}:`);
321
- treeStr.split('\n').forEach(line => lines.push(`[${patternId}] ${line}`));
322
- const explanation = result.explanation;
352
+ const explanation = attempt.explanation;
353
+ const emoji = !colours || (0, debug_1.shouldUseEmoji)();
354
+ const [green, red, reset] = emoji ? ['', '', ''] : ['\x1b[32m', '\x1b[31m', '\x1b[0m'];
355
+ if (emoji) {
356
+ lines.push(`${prefix} (Mismatched elements are marked with 👉...👈)`);
357
+ }
358
+ const colored = (printed, color) => printed.map(line => `${color}${prefix} ${line}${reset}`);
359
+ const patternLines = await this.printMismatch(patternAst, explanation === null || explanation === void 0 ? void 0 : explanation.patternElement, focus === null || focus === void 0 ? void 0 : focus.pattern, emoji);
360
+ const sourceLines = await this.printMismatch(tree, explanation === null || explanation === void 0 ? void 0 : explanation.targetElement, focus === null || focus === void 0 ? void 0 : focus.target, emoji, location === null || location === void 0 ? void 0 : location.column);
361
+ lines.push(prefix, `${green}${prefix} Pattern tree:${reset}`, ...colored(patternLines, green), prefix, `${red}${prefix} Source tree:${reset}`, ...colored(sourceLines, red));
323
362
  if (explanation) {
324
- // Always show path, even if empty, to make it clear where the mismatch occurred
325
- const compactedPath = this.compactPath(explanation.path);
326
- const pathStr = compactedPath.length > 0 ? compactedPath.join(' → ') : '';
327
- lines.push(`[${patternId}] At path: [${pathStr}]`);
328
- lines.push(`[${patternId}] Reason: ${explanation.reason}`);
329
- lines.push(`[${patternId}] Expected: ${explanation.expected}`);
330
- lines.push(`[${patternId}] Actual: ${explanation.actual}`);
363
+ lines.push(prefix, `${prefix} Details:`, `${prefix} Pattern: ${explanation.expected}`, `${prefix} Source: ${explanation.actual}`, ...(explanation.details ? [`${prefix} Note: ${explanation.details}`] : []));
331
364
  }
332
365
  }
333
- // Single console.error call with all lines joined
334
- console.error(lines.join('\n'));
366
+ return lines;
367
+ }
368
+ /** The lines of `tree` around the mismatch, with it marked on `element` and narrowed to `focus` there. */
369
+ async printMismatch(tree, element, focus, emoji, column) {
370
+ try {
371
+ const delimiters = (0, debug_1.mismatchDelimiters)(emoji);
372
+ const marked = element ? await new debug_1.ElementMarkerVisitor(element, emoji).visit(tree, undefined) : tree;
373
+ let printed = await print_1.TreePrinters.printer(index_1.JS.Kind.CompilationUnit)
374
+ .print(marked, new debug_1.AnsiAwarePrintOutputCapture(debug_1.PATTERN_DEBUG_MARKER_PRINTER));
375
+ if (element && focus) {
376
+ printed = await (0, debug_1.narrowMark)(printed, element, focus, delimiters);
377
+ }
378
+ return (0, debug_1.aroundMarks)(layOut(this.replacePlaceholderNames(printed), column).split('\n'), delimiters);
379
+ }
380
+ catch (e) {
381
+ return [`(tree printing unavailable: ${e})`];
382
+ }
383
+ }
384
+ /** The lines of `tree` with each capture's code between its letter, as in `Ⓐuser?Ⓐ.name`. */
385
+ async printCaptures(tree, captures, column) {
386
+ var _a;
387
+ try {
388
+ const marked = await new debug_1.ElementMarkerVisitor(captures).visit(tree, undefined);
389
+ let printed = await print_1.TreePrinters.printer(index_1.JS.Kind.CompilationUnit)
390
+ .print(marked, new debug_1.AnsiAwarePrintOutputCapture(debug_1.PATTERN_DEBUG_MARKER_PRINTER));
391
+ // An optional receiver's `?` and a non-null `!` belong to the captured code, which a template
392
+ // writes with them, but the printer writes them after the capture's closing letter
393
+ for (const [number, code] of captures) {
394
+ const last = [code].flat().pop();
395
+ const postfix = (_a = last === null || last === void 0 ? void 0 : last.markers) === null || _a === void 0 ? void 0 : _a.markers.some((marker) => marker.kind === index_1.JS.Markers.Optional || marker.kind === index_1.JS.Markers.NonNullAssertion);
396
+ if (postfix) {
397
+ const symbol = new debug_1.CaptureHighlightMarker(number).symbol();
398
+ printed = printed.split(symbol + '?').join('?' + symbol).split(symbol + '!').join('!' + symbol);
399
+ }
400
+ }
401
+ return layOut(this.replacePlaceholderNames(printed), column).split('\n');
402
+ }
403
+ catch (e) {
404
+ return [`(tree printing unavailable: ${e})`];
405
+ }
335
406
  }
336
407
  /**
337
- * Compacts array index navigations into the previous path element.
338
- * For example: ['J$VariableDeclarations#variables', '0'] → ['J$VariableDeclarations#variables[0]']
408
+ * Replaces placeholder names in tree strings with clean display names.
409
+ * Uses 🪝 prefix to make captures easily identifiable.
339
410
  * @private
340
411
  */
341
- compactPath(path) {
342
- const compacted = [];
343
- let i = 0;
344
- while (i < path.length) {
345
- const current = path[i];
346
- // Check if current element is itself a numeric index
347
- if (/^\d+$/.test(current)) {
348
- // This is a bare numeric index - shouldn't normally happen
349
- // If we have a previous element, append to it
350
- if (compacted.length > 0) {
351
- compacted[compacted.length - 1] += `[${current}]`;
352
- }
353
- else {
354
- // No previous element to attach to - this is an error in path construction
355
- // Skip it to avoid bare [0] in output
356
- console.warn(`Warning: Path starts with numeric index '${current}' - skipping`);
357
- }
358
- i++;
359
- continue;
360
- }
361
- // Look ahead to collect consecutive numeric indices
362
- let j = i + 1;
363
- const indices = [];
364
- while (j < path.length && /^\d+$/.test(path[j])) {
365
- indices.push(path[j]);
366
- j++;
367
- }
368
- // If we found numeric indices, append them to current element
369
- if (indices.length > 0) {
370
- compacted.push(current + indices.map(idx => `[${idx}]`).join(''));
371
- i = j; // Skip the indices we just processed
372
- }
373
- else {
374
- compacted.push(current);
375
- i++;
376
- }
412
+ replacePlaceholderNames(treeStr) {
413
+ let result = treeStr;
414
+ // Replace unnamed captures with their short forms (🪝1, 🪝2, etc.)
415
+ for (const [originalName, displayName] of this.unnamedCaptureMapping.entries()) {
416
+ const placeholder = `__capt_${originalName}__`;
417
+ result = result.split(placeholder).join(`🪝${displayName}`);
377
418
  }
378
- return compacted;
419
+ // Replace all remaining __capt_XXX__ with 🪝XXX (for named captures)
420
+ result = result.replace(/__capt_([^_]+(?:_[^_]+)*)__/g, '🪝$1');
421
+ return result;
379
422
  }
380
423
  /**
381
424
  * Gets the source code representation of this pattern for logging.
@@ -396,9 +439,9 @@ class Pattern {
396
439
  // Show capture name or placeholder
397
440
  const name = cap[capture_1.CAPTURE_NAME_SYMBOL];
398
441
  if (cap && typeof cap === 'object' && name) {
399
- // Use mapped name for unnamed captures, or original name
442
+ // Use mapped name for unnamed captures, or original name (with 🪝 prefix)
400
443
  const displayName = this.unnamedCaptureMapping.get(name) || name;
401
- source += `\${${displayName}}`;
444
+ source += `\${🪝${displayName}}`;
402
445
  }
403
446
  else {
404
447
  source += '${...}';
@@ -408,102 +451,55 @@ class Pattern {
408
451
  return source;
409
452
  }
410
453
  /**
411
- * Formats a captured value for logging.
412
- * @private
413
- */
414
- formatCapturedValue(value) {
415
- if (value === null)
416
- return 'null';
417
- if (value === undefined)
418
- return 'undefined';
419
- // Check if it's an array (variadic capture)
420
- if (Array.isArray(value)) {
421
- if (value.length === 0)
422
- return '[]';
423
- const items = value.slice(0, 3).map(v => this.formatSingleValue(v));
424
- const suffix = value.length > 3 ? `, ... (${value.length} total)` : '';
425
- return `[${items.join(', ')}${suffix}]`;
426
- }
427
- return this.formatSingleValue(value);
428
- }
429
- /**
430
- * Formats a single AST node for logging.
431
- * @private
432
- */
433
- formatSingleValue(value) {
434
- if (!value || typeof value !== 'object') {
435
- return String(value);
436
- }
437
- const kind = value.kind;
438
- if (!kind)
439
- return String(value);
440
- // Extract simple kind name (last segment)
441
- const kindStr = kind.split('.').pop();
442
- // For literals, show the value
443
- if (kindStr === 'Literal' && value.value !== undefined) {
444
- const litValue = typeof value.value === 'string'
445
- ? `"${value.value}"`
446
- : String(value.value);
447
- return `${kindStr}(${litValue})`;
448
- }
449
- // For identifiers, show the name
450
- if (kindStr === 'Identifier' && value.simpleName) {
451
- return `${kindStr}(${value.simpleName})`;
452
- }
453
- // Default: just the kind
454
- return kindStr;
455
- }
456
- /**
457
- * Matches a pattern against an AST node with detailed debug information.
458
- * Part of Layer 2 (Public API).
459
- *
460
- * This method always enables debug logging and returns detailed information about
461
- * the match attempt, including:
462
- * - Whether the pattern matched
463
- * - Captured nodes (if matched)
464
- * - Explanation of failure (if not matched)
465
- * - Debug log entries showing the matching process
454
+ * Matches like {@link match}, and returns why the pattern did not match rather than printing it.
455
+ * A failed attempt's `explanation` holds the reason, the expected and actual code, and the pattern
456
+ * and source nodes where they differ. `debugLog` holds an entry for each capture constraint evaluated.
466
457
  *
467
458
  * @param tree The AST node to match against
468
459
  * @param cursor Cursor at the node's position in a larger tree
469
- * @param debugOptions Optional debug options (defaults to all logging enabled)
470
- * @returns Detailed result with debug information
460
+ * @param debugOptions Which entries `debugLog` collects, by default all of them
461
+ * @returns Whether the pattern matched, with the captures where it did and the explanation where it did not
471
462
  *
472
463
  * @example
473
464
  * const x = capture('x');
474
465
  * const pat = pattern`console.log(${x})`;
475
466
  * const attempt = await pat.matchWithExplanation(node, cursor);
476
467
  * if (attempt.matched) {
477
- * console.log('Matched!');
478
468
  * console.log('Captured x:', attempt.result.get('x'));
479
469
  * } else {
480
- * console.log('Failed:', attempt.explanation);
481
- * console.log('Debug log:', attempt.debugLog);
470
+ * const {reason, expected, actual} = attempt.explanation!;
471
+ * console.log(`${reason}: the pattern has ${expected} where the source has ${actual}`);
482
472
  * }
483
473
  */
484
474
  async matchWithExplanation(tree, cursor, debugOptions) {
485
- // Default to full debug logging if not specified
475
+ return (await this.attempt(tree, cursor, debugOptions, true)).attempt;
476
+ }
477
+ /**
478
+ * The attempt, the pattern tree it compared, which holds the explanation's pattern element, and
479
+ * where on each side the mismatch is narrower than its marked node.
480
+ */
481
+ async attempt(tree, cursor, debugOptions, report = false) {
486
482
  const options = Object.assign({ enabled: true, logComparison: true, logConstraints: true }, debugOptions);
487
483
  const matcher = new Matcher(this, tree, cursor, options);
488
- const success = await matcher.matches();
489
- if (success) {
490
- // Match succeeded - return MatchResult with debug info
491
- const storage = matcher.storage;
492
- const matchResult = new MatchResult(new Map(storage), () => matcher.patternPrefixes());
493
- return {
494
- matched: true,
495
- result: matchResult,
496
- debugLog: matcher.getDebugLog()
497
- };
498
- }
499
- else {
500
- // Match failed - return explanation
501
- return {
502
- matched: false,
503
- explanation: matcher.getExplanation(),
504
- debugLog: matcher.getDebugLog()
505
- };
484
+ const matched = await matcher.matches();
485
+ const attempt = matched ? {
486
+ matched,
487
+ result: new MatchResult(new Map(matcher.storage), () => matcher.patternPrefixes()),
488
+ debugLog: matcher.getDebugLog()
489
+ } : {
490
+ matched,
491
+ explanation: await matcher.getExplanation(text => this.replacePlaceholderNames(text)),
492
+ debugLog: matcher.getDebugLog()
493
+ };
494
+ attempt.location = await (0, debug_1.sourceLocation)(tree, cursor);
495
+ const patternAst = matcher.getPatternAst();
496
+ const focus = matcher.getFocus();
497
+ if (report) {
498
+ // Without the pattern's number, which depends on how many patterns were created before it
499
+ const lines = await this.render(tree, attempt, patternAst, focus, undefined, false);
500
+ attempt.report = lines.map(line => line.replace(/^\[Pattern #\d+] ?/, '')).join('\n') + '\n';
506
501
  }
502
+ return { attempt, patternAst, focus };
507
503
  }
508
504
  }
509
505
  exports.Pattern = Pattern;
@@ -627,7 +623,6 @@ class Matcher {
627
623
  // Unified storage: holds J for scalar captures, J.RightPadded<J>[] or J[] for variadic captures
628
624
  this.storage = new Map();
629
625
  this.debugLog = [];
630
- this.currentPath = [];
631
626
  this.cursor = cursor;
632
627
  this.debugOptions = debugOptions !== null && debugOptions !== void 0 ? debugOptions : {};
633
628
  this.lenientTypeMatching = (_a = pattern.options.lenientTypeMatching) !== null && _a !== void 0 ? _a : true;
@@ -646,7 +641,8 @@ class Matcher {
646
641
  if ((this.ast.kind === java_1.J.Kind.Parentheses || this.ast.kind === java_1.J.Kind.ControlParentheses) &&
647
642
  this.patternAst.kind !== this.ast.kind) {
648
643
  if (this.debugOptions.enabled) {
649
- this.setExplanation('kind-mismatch', 'An expression without parentheses', `Parentheses (${this.ast.kind.split('.').pop()})`, 'The expression the parentheses hold is matched on its own');
644
+ this.setExplanation('kind-mismatch', 'an expression without parentheses', `parentheses (${this.ast.kind.split('.').pop()})`, 'A visitor reaches the expression inside the parentheses next, where this pattern can match it. ' +
645
+ 'To match the parentheses too, write them in the pattern.', this.patternAst, this.ast);
650
646
  }
651
647
  return false;
652
648
  }
@@ -709,7 +705,6 @@ class Matcher {
709
705
  }
710
706
  /**
711
707
  * Logs a debug message if debugging is enabled.
712
- * Part of Layer 1 (Core Instrumentation).
713
708
  *
714
709
  * @param level The severity level
715
710
  * @param scope The scope/category
@@ -727,7 +722,6 @@ class Matcher {
727
722
  this.debugLog.push({
728
723
  level,
729
724
  scope,
730
- path: [...this.currentPath],
731
725
  message,
732
726
  data
733
727
  });
@@ -735,42 +729,28 @@ class Matcher {
735
729
  /**
736
730
  * Sets the explanation for why the pattern match failed.
737
731
  * Only sets the first failure (most relevant).
738
- * Part of Layer 1 (Core Instrumentation).
739
732
  *
740
733
  * @param reason The reason for failure
741
734
  * @param expected Human-readable description of what was expected
742
735
  * @param actual Human-readable description of what was found
743
736
  * @param details Optional additional context
737
+ * @param patternElement The actual pattern element that failed to match
738
+ * @param targetElement The actual target element that failed to match
744
739
  */
745
- setExplanation(reason, expected, actual, details) {
740
+ setExplanation(reason, expected, actual, details, patternElement, targetElement, focus) {
746
741
  // Only set the first failure (most relevant)
747
742
  if (this.explanation)
748
743
  return;
749
744
  this.explanation = {
750
745
  reason,
751
- path: [...this.currentPath],
752
746
  expected,
753
747
  actual,
754
- details
748
+ details,
749
+ patternElement,
750
+ targetElement,
751
+ focus
755
752
  };
756
753
  }
757
- /**
758
- * Pushes a path component onto the current path.
759
- * Used to track where in the AST tree we are during matching.
760
- * Part of Layer 1 (Core Instrumentation).
761
- *
762
- * @param name The path component to push
763
- */
764
- pushPath(name) {
765
- this.currentPath.push(name);
766
- }
767
- /**
768
- * Pops the last path component from the current path.
769
- * Part of Layer 1 (Core Instrumentation).
770
- */
771
- popPath() {
772
- this.currentPath.pop();
773
- }
774
754
  /**
775
755
  * Matches a pattern node against a target node.
776
756
  *
@@ -790,21 +770,20 @@ class Matcher {
790
770
  const matcherCallbacks = {
791
771
  handleCapture: (capture, t, w) => this.handleCapture(capture, t, w),
792
772
  handleVariadicCapture: (capture, ts, ws) => this.handleVariadicCapture(capture, ts, ws),
773
+ getCapture: (name) => this.storage.get(name),
793
774
  saveState: () => this.saveState(),
794
775
  restoreState: (state) => this.restoreState(state),
795
- // Debug callbacks (Layer 1) - grouped together, always present or absent
776
+ // Debug callbacks, all present or all absent
796
777
  debug: this.debugOptions.enabled ? {
797
778
  log: (level, scope, message, data) => this.log(level, scope, message, data),
798
- setExplanation: (reason, expected, actual, details) => this.setExplanation(reason, expected, actual, details),
779
+ setExplanation: (reason, expected, actual, details, patternElement, targetElement, focus) => this.setExplanation(reason, expected, actual, details, patternElement, targetElement, focus),
799
780
  getExplanation: () => this.explanation,
800
781
  restoreExplanation: (explanation) => { this.explanation = explanation; },
801
- clearExplanation: () => { this.explanation = undefined; },
802
- pushPath: (name) => this.pushPath(name),
803
- popPath: () => this.popPath()
782
+ clearExplanation: () => { this.explanation = undefined; }
804
783
  } : undefined
805
784
  };
806
785
  const comparator = this.debugOptions.enabled
807
- ? new comparator_1.DebugPatternMatchingComparator(matcherCallbacks, this.lenientTypeMatching)
786
+ ? new debug_1.DebugPatternMatchingComparator(matcherCallbacks, this.lenientTypeMatching)
808
787
  : new comparator_1.PatternMatchingComparator(matcherCallbacks, this.lenientTypeMatching);
809
788
  // Pass cursors to allow constraints to navigate to root
810
789
  // Pattern cursor is undefined (pattern is the root), target cursor is provided by user
@@ -813,13 +792,13 @@ class Matcher {
813
792
  if (!result && this.debugOptions.enabled && !this.explanation) {
814
793
  const patternKind = ((_a = pattern.kind) === null || _a === void 0 ? void 0 : _a.split('.').pop()) || 'unknown';
815
794
  const targetKind = ((_b = target.kind) === null || _b === void 0 ? void 0 : _b.split('.').pop()) || 'unknown';
816
- this.setExplanation('structural-mismatch', `Pattern node of type ${patternKind}`, `Target node of type ${targetKind}`, 'Nodes did not match structurally');
795
+ this.setExplanation('structural-mismatch', `Pattern node of type ${patternKind}`, `Target node of type ${targetKind}`, 'Nodes did not match structurally', pattern, target);
817
796
  }
818
797
  return result;
819
798
  }
820
799
  /**
821
800
  * Saves the current state for backtracking.
822
- * Includes both capture storage AND debug state (explanation, log, path).
801
+ * Includes both capture storage AND debug state (explanation, log).
823
802
  *
824
803
  * @returns A snapshot of the current state
825
804
  */
@@ -828,8 +807,7 @@ class Matcher {
828
807
  storage: new Map(this.storage),
829
808
  debugState: this.debugOptions.enabled ? {
830
809
  explanation: this.explanation,
831
- logLength: this.debugLog.length,
832
- path: [...this.currentPath]
810
+ logLength: this.debugLog.length
833
811
  } : undefined
834
812
  };
835
813
  }
@@ -850,9 +828,6 @@ class Matcher {
850
828
  this.explanation = state.debugState.explanation;
851
829
  // Truncate debug log to saved length (remove entries added during failed attempt)
852
830
  this.debugLog.length = state.debugState.logLength;
853
- // Restore path
854
- this.currentPath.length = 0;
855
- this.currentPath.push(...state.debugState.path);
856
831
  }
857
832
  }
858
833
  /**
@@ -937,7 +912,6 @@ class Matcher {
937
912
  }
938
913
  /**
939
914
  * Gets the debug log entries collected during matching.
940
- * Part of Layer 2 (Public API).
941
915
  *
942
916
  * @returns The debug log entries, or undefined if debug wasn't enabled
943
917
  */
@@ -945,13 +919,25 @@ class Matcher {
945
919
  return this.debugOptions.enabled ? [...this.debugLog] : undefined;
946
920
  }
947
921
  /**
948
- * Gets the explanation for why the match failed.
949
- * Part of Layer 2 (Public API).
950
- *
951
- * @returns The match explanation, or undefined if match succeeded or no explanation available
922
+ * Why the match failed, once its expected and actual code have printed and `display` has
923
+ * rewritten the capture placeholders in them.
952
924
  */
953
- getExplanation() {
954
- return this.explanation;
925
+ async getExplanation(display) {
926
+ if (!this.explanation) {
927
+ return undefined;
928
+ }
929
+ const [expected, actual] = await Promise.all([this.explanation.expected, this.explanation.actual]);
930
+ const _a = this.explanation, { focus } = _a, explanation = __rest(_a, ["focus"]);
931
+ return Object.assign(Object.assign({}, explanation), { expected: display(expected), actual: display(actual) });
932
+ }
933
+ /** Where the mismatch is narrower than the nodes the explanation marks. */
934
+ getFocus() {
935
+ var _a;
936
+ return (_a = this.explanation) === null || _a === void 0 ? void 0 : _a.focus;
937
+ }
938
+ /** The pattern tree the last attempt compared. */
939
+ getPatternAst() {
940
+ return this.patternAst;
955
941
  }
956
942
  }
957
943
  // Implementation