@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
@@ -16,26 +16,45 @@
16
16
  import {Cursor, Tree} from '../..';
17
17
  import {J, Type} from '../../java';
18
18
  import {JS} from '../index';
19
- import {JavaScriptSemanticComparatorVisitor} from '../comparator';
19
+ import {JavaScriptSemanticComparatorVisitor, JTree} from '../comparator';
20
20
  import {CaptureMarker, CaptureStorageValue, PlaceholderUtils, TEMPLATE_MODULE} from './utils';
21
21
  import {Capture, CaptureConstraintContext, CaptureMap, DebugLogEntry, MatchExplanation} from './types';
22
22
  import {CAPTURE_NAME_SYMBOL} from './capture';
23
23
 
24
+ // ============================================================================
25
+ // Debug Callbacks
26
+ // ============================================================================
27
+
24
28
  /**
25
29
  * Debug callbacks for pattern matching.
26
30
  * These are always used together - either all present or all absent.
27
- * Part of Layer 1 (Core Instrumentation).
28
31
  */
29
32
  export interface DebugCallbacks {
30
33
  log: (level: DebugLogEntry['level'], scope: DebugLogEntry['scope'], message: string, data?: any) => void;
31
- setExplanation: (reason: MatchExplanation['reason'], expected: string, actual: string, details?: string) => void;
32
- getExplanation: () => MatchExplanation | undefined;
33
- restoreExplanation: (explanation: MatchExplanation) => void;
34
+ setExplanation: (reason: MatchExplanation['reason'], expected: string | Promise<string>,
35
+ actual: string | Promise<string>, details?: string, patternElement?: any,
36
+ targetElement?: any, focus?: Focus) => void;
37
+ getExplanation: () => PendingExplanation | undefined;
38
+ restoreExplanation: (explanation: PendingExplanation) => void;
34
39
  clearExplanation: () => void;
35
- pushPath: (name: string) => void;
36
- popPath: () => void;
37
40
  }
38
41
 
42
+ /** A match explanation whose expected and actual code may still be printing. */
43
+ export type PendingExplanation = Omit<MatchExplanation, 'expected' | 'actual'> & {
44
+ expected: string | Promise<string>;
45
+ actual: string | Promise<string>;
46
+ focus?: Focus;
47
+ };
48
+
49
+ /**
50
+ * Where within the marked node a mismatch is. That is its operator, or an empty mark at its start or
51
+ * after one of its children, where the other side has something this side lacks.
52
+ */
53
+ export type MarkFocus = 'operator' | 'start' | { after: J };
54
+
55
+ /** The {@link MarkFocus} on each side, where the mark is narrower than its node. */
56
+ export type Focus = { pattern?: MarkFocus, target?: MarkFocus };
57
+
39
58
  /**
40
59
  * Snapshot of matcher state for backtracking.
41
60
  * Includes both capture storage and debug state.
@@ -43,19 +62,18 @@ export interface DebugCallbacks {
43
62
  export interface MatcherState {
44
63
  storage: Map<string, CaptureStorageValue>;
45
64
  debugState?: {
46
- explanation?: MatchExplanation;
65
+ explanation?: PendingExplanation;
47
66
  logLength: number;
48
- path: string[];
49
67
  };
50
68
  }
51
69
 
52
70
  /**
53
71
  * Callbacks for the matcher (debug and capture handling).
54
- * Part of Layer 1 (Core Instrumentation).
55
72
  */
56
73
  export interface MatcherCallbacks {
57
74
  handleCapture: (capture: CaptureMarker, target: J, wrapper?: J.RightPadded<J>) => Promise<boolean>;
58
75
  handleVariadicCapture: (capture: CaptureMarker, targets: J[], wrappers?: J.RightPadded<J>[]) => Promise<boolean>;
76
+ getCapture: (name: string) => CaptureStorageValue | undefined;
59
77
  saveState: () => MatcherState;
60
78
  restoreState: (state: MatcherState) => void;
61
79
 
@@ -164,21 +182,16 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
164
182
  : new Cursor(target);
165
183
  this.targetCursor = cursorAtCapturedNode;
166
184
  try {
167
- // Evaluate constraint with context (cursor + previous captures)
168
185
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
169
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
170
- const context = this.buildConstraintContext(cursorAtCapturedNode);
171
- if (!captureMarker.constraint(target, context)) {
172
- const captureName = captureMarker.captureName || 'unnamed';
173
- const targetKind = (target as any).kind || 'unknown';
174
- return this.constraintFailed(captureName, targetKind) as R;
175
- }
186
+ if (captureMarker.constraint && !captureMarker.variadicOptions &&
187
+ !this.satisfiesConstraint(captureMarker, j as J, target, cursorAtCapturedNode)) {
188
+ return this.abort(j) as R;
176
189
  }
177
190
 
178
191
  const success = await this.matcher.handleCapture(captureMarker, target, undefined);
179
192
  if (!success) {
180
- const captureName = captureMarker.captureName || 'unnamed';
181
- return this.captureConflict(captureName) as R;
193
+ this.explainCaptureConflict(captureMarker, j as J, [target]);
194
+ return this.abort(j) as R;
182
195
  }
183
196
  return j as R;
184
197
  } finally {
@@ -207,25 +220,30 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
207
220
  (j.kind == J.Kind.Identifier && PlaceholderUtils.isCapture(j as J.Identifier));
208
221
  }
209
222
 
210
- /**
211
- * Additional specialized abort methods for pattern matching scenarios.
212
- */
223
+ /** Whether `target`, the code at `patternElement`'s capture, satisfies the capture's constraint. */
224
+ protected satisfiesConstraint(marker: CaptureMarker, _patternElement: JTree, target: J | J[],
225
+ cursor: Cursor): boolean {
226
+ return marker.constraint!(target as any, this.buildConstraintContext(cursor));
227
+ }
213
228
 
214
- protected constraintFailed(captureName: string, targetKind: string) {
215
- const pattern = this.cursor?.value as any;
216
- return this.abort(pattern, 'constraint-failed', `capture[${captureName}]`, 'constraint satisfied', `constraint failed for ${targetKind}`);
229
+ /** Called where a capture the pattern names twice holds other code than `targets`. Matching ignores it. */
230
+ protected explainCaptureConflict(_marker: CaptureMarker, _patternElement: JTree, _targets: J[]): void {
217
231
  }
218
232
 
219
- protected captureConflict(captureName: string) {
220
- const pattern = this.cursor?.value as any;
221
- return this.abort(pattern, 'capture-conflict', `capture[${captureName}]`, 'compatible binding', 'conflicting binding');
233
+ /** Restores `state` after a failed alternative, keeping why it failed in case no other alternative matches. */
234
+ private backtrack(state: MatcherState): void {
235
+ const failure = this.matcher.debug?.getExplanation();
236
+ this.matcher.restoreState(state);
237
+ if (failure) {
238
+ this.matcher.debug!.restoreExplanation(failure);
239
+ }
222
240
  }
223
241
 
224
242
  /**
225
243
  * Override visitRightPadded to check if this wrapper has a CaptureMarker.
226
244
  * If so, capture the entire wrapper (to preserve markers like semicolons).
227
245
  */
228
- override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J): Promise<J.RightPadded<T>> {
246
+ override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J.RightPadded<T>): Promise<J.RightPadded<T>> {
229
247
  if (!this.match) {
230
248
  return right;
231
249
  }
@@ -235,8 +253,8 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
235
253
  const captureMarker = PlaceholderUtils.getCaptureMarker(right);
236
254
  if (captureMarker) {
237
255
  // Extract the target wrapper if it's also a RightPadded
238
- const isRightPadded = (p as any).kind === J.Kind.RightPadded;
239
- const targetWrapper = isRightPadded ? (p as unknown) as J.RightPadded<T> : undefined;
256
+ const isRightPadded = p.kind === J.Kind.RightPadded;
257
+ const targetWrapper = isRightPadded ? p : undefined;
240
258
  const targetElement = isRightPadded ? targetWrapper!.element : p;
241
259
 
242
260
  // Push targetCursor to position it at the captured element for constraint evaluation
@@ -246,19 +264,17 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
246
264
  : (targetWrapper ? new Cursor(targetWrapper) : new Cursor(targetElement));
247
265
  this.targetCursor = cursorAtCapturedNode;
248
266
  try {
249
- // Evaluate constraint with cursor at the captured node (always defined)
250
267
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
251
- if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(targetElement as J, this.buildConstraintContext(cursorAtCapturedNode))) {
252
- const captureName = captureMarker.captureName || 'unnamed';
253
- const targetKind = (targetElement as any).kind || 'unknown';
254
- return this.constraintFailed(captureName, targetKind);
268
+ if (captureMarker.constraint && !captureMarker.variadicOptions &&
269
+ !this.satisfiesConstraint(captureMarker, right, targetElement as J, cursorAtCapturedNode)) {
270
+ return this.abort(right);
255
271
  }
256
272
 
257
273
  // Handle the capture with the wrapper - use the element for pattern matching
258
274
  const success = await this.matcher.handleCapture(captureMarker, targetElement as J, targetWrapper as J.RightPadded<J> | undefined);
259
275
  if (!success) {
260
- const captureName = captureMarker.captureName || 'unnamed';
261
- return this.captureConflict(captureName);
276
+ this.explainCaptureConflict(captureMarker, right, [targetElement as J]);
277
+ return this.abort(right);
262
278
  }
263
279
  return right;
264
280
  } finally {
@@ -270,7 +286,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
270
286
  return super.visitRightPadded(right, p);
271
287
  }
272
288
 
273
- override async visitContainer<T extends J>(container: J.Container<T>, p: J): Promise<J.Container<T>> {
289
+ override async visitContainer<T extends J>(container: J.Container<T>, p: J.Container<T>): Promise<J.Container<T>> {
274
290
  // Check if any elements are variadic captures
275
291
  const hasVariadicCapture = container.elements.some(elem =>
276
292
  PlaceholderUtils.isVariadicCapture(elem)
@@ -287,7 +303,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
287
303
  }
288
304
 
289
305
  // Extract the other container
290
- const isContainer = (p as any).kind === J.Kind.Container;
306
+ const isContainer = p.kind === J.Kind.Container;
291
307
  if (!isContainer) {
292
308
  // Set up cursors temporarily for kindMismatch to use
293
309
  const savedCursor = this.cursor;
@@ -295,13 +311,13 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
295
311
  this.cursor = new Cursor(container, this.cursor);
296
312
  this.targetCursor = new Cursor(p, this.targetCursor);
297
313
  try {
298
- return this.kindMismatch();
314
+ return this.kindMismatch<J.Container<T>>();
299
315
  } finally {
300
316
  this.cursor = savedCursor;
301
317
  this.targetCursor = savedTargetCursor;
302
318
  }
303
319
  }
304
- const otherContainer = p as unknown as J.Container<T>;
320
+ const otherContainer = p;
305
321
 
306
322
  // Push wrappers onto both cursors
307
323
  const savedCursor = this.cursor;
@@ -312,7 +328,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
312
328
  // Use matchSequence for variadic matching
313
329
  // filterEmpty=true to skip J.Empty elements (they represent missing elements in destructuring)
314
330
  if (!await this.matchSequence(container.elements as J.RightPadded<J>[], otherContainer.elements as J.RightPadded<J>[], true)) {
315
- return this.structuralMismatch('elements');
331
+ return this.structuralMismatch<J.Container<T>>('elements');
316
332
  }
317
333
  } finally {
318
334
  this.cursor = savedCursor;
@@ -322,24 +338,6 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
322
338
  return container;
323
339
  }
324
340
 
325
- /**
326
- * Visit a single element in a container (for non-variadic matching).
327
- * Extracted to allow debug subclass to add path tracking.
328
- *
329
- * @param element The pattern element
330
- * @param otherElement The target element
331
- * @param index The index in the container
332
- * @returns true if matching should continue, false if it failed
333
- */
334
- protected async visitContainerElement<T extends J>(
335
- element: J.RightPadded<T>,
336
- otherElement: J.RightPadded<T>,
337
- index: number
338
- ): Promise<boolean> {
339
- await this.visitRightPadded(element as any, otherElement as any);
340
- return this.match;
341
- }
342
-
343
341
  override async visitBlock(block: J.Block, other: J): Promise<J | undefined> {
344
342
  // Check if any statements have CaptureMarker indicating they're variadic
345
343
  const hasVariadicCapture = block.statements.some(stmt => {
@@ -364,7 +362,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
364
362
  this.cursor = new Cursor(block, this.cursor);
365
363
  this.targetCursor = new Cursor(other, this.targetCursor);
366
364
  try {
367
- return this.kindMismatch();
365
+ return this.kindMismatch<J>();
368
366
  } finally {
369
367
  this.cursor = savedCursor;
370
368
  this.targetCursor = savedTargetCursor;
@@ -381,7 +379,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
381
379
  try {
382
380
  // Special handling for variadic captures in statements
383
381
  if (!await this.matchSequence(block.statements, otherBlock.statements, false)) {
384
- return this.structuralMismatch('statements');
382
+ return this.structuralMismatch<J>('statements');
385
383
  }
386
384
 
387
385
  return block;
@@ -414,7 +412,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
414
412
  this.cursor = new Cursor(compilationUnit, this.cursor);
415
413
  this.targetCursor = new Cursor(other, this.targetCursor);
416
414
  try {
417
- return this.kindMismatch();
415
+ return this.kindMismatch<J>();
418
416
  } finally {
419
417
  this.cursor = savedCursor;
420
418
  this.targetCursor = savedTargetCursor;
@@ -431,7 +429,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
431
429
  try {
432
430
  // Special handling for variadic captures in top-level statements
433
431
  if (!await this.matchSequence(compilationUnit.statements, otherCompilationUnit.statements, false)) {
434
- return this.structuralMismatch('statements');
432
+ return this.structuralMismatch<J>('statements');
435
433
  }
436
434
 
437
435
  return compilationUnit;
@@ -537,7 +535,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
537
535
  const savedMatch = this.match;
538
536
  const savedState = this.matcher.saveState();
539
537
 
540
- await this.visitRightPadded(nextPattern, candidateElement as any);
538
+ await this.visitRightPadded(nextPattern, candidateElement);
541
539
  const matchesNext = this.match;
542
540
 
543
541
  this.match = savedMatch;
@@ -590,14 +588,12 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
590
588
  continue;
591
589
  }
592
590
 
593
- // Evaluate constraint for variadic capture
594
591
  // For variadic captures, constraint receives the entire array of captured elements
595
592
  // The targetCursor points to the parent container (always defined in container matching)
596
- if (captureMarker.constraint) {
597
- const cursor = this.targetCursor || new Cursor(targetElements[0]);
598
- if (!captureMarker.constraint(capturedElements as any, this.buildConstraintContext(cursor))) {
599
- continue; // Try next consumption amount
600
- }
593
+ const constraintCursor = this.targetCursor || new Cursor(targetElements[0]);
594
+ if (captureMarker.constraint &&
595
+ !this.satisfiesConstraint(captureMarker, patternWrapper, capturedElements, constraintCursor)) {
596
+ continue; // Try next consumption amount
601
597
  }
602
598
 
603
599
  // Save current state for backtracking
@@ -606,8 +602,8 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
606
602
  // Handle the variadic capture
607
603
  const success = await this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
608
604
  if (!success) {
609
- // Restore state and try next amount
610
605
  this.matcher.restoreState(savedState);
606
+ this.explainCaptureConflict(captureMarker, patternWrapper, capturedElements);
611
607
  continue;
612
608
  }
613
609
 
@@ -621,11 +617,12 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
621
617
  );
622
618
 
623
619
  if (restMatches) {
624
- return true; // Found a valid matching
620
+ // Why earlier alternatives failed explains nothing about a match that went on
621
+ this.matcher.debug?.clearExplanation();
622
+ return true;
625
623
  }
626
624
 
627
- // Backtrack: restore state and try next amount
628
- this.matcher.restoreState(savedState);
625
+ this.backtrack(savedState);
629
626
  }
630
627
 
631
628
  return false; // No consumption amount worked
@@ -660,7 +657,6 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
660
657
 
661
658
  /**
662
659
  * Visit a single element in a sequence during non-variadic matching.
663
- * Extracted to allow debug subclass to add path tracking.
664
660
  *
665
661
  * @param patternWrapper The pattern element
666
662
  * @param targetWrapper The target element
@@ -676,700 +672,14 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
676
672
  const savedMatch = this.match;
677
673
  const savedState = this.matcher.saveState();
678
674
 
679
- await this.visitRightPadded(patternWrapper, targetWrapper as any);
675
+ await this.visitRightPadded(patternWrapper, targetWrapper);
680
676
 
681
677
  if (!this.match) {
682
- // Restore state on match failure
683
678
  this.match = savedMatch;
684
- this.matcher.restoreState(savedState);
679
+ this.backtrack(savedState);
685
680
  return false;
686
681
  }
687
682
 
688
683
  return true;
689
684
  }
690
685
  }
691
-
692
- /**
693
- * Debug-instrumented version of PatternMatchingComparator.
694
- * Overrides methods to add path tracking, logging, and explanation capture.
695
- * Zero cost when not instantiated - production code uses the base class.
696
- */
697
- export class DebugPatternMatchingComparator extends PatternMatchingComparator {
698
- private get debug(): DebugCallbacks {
699
- return this.matcher.debug!;
700
- }
701
-
702
- /**
703
- * Extracts the last segment of a kind string (after the last dot).
704
- * For example: "org.openrewrite.java.tree.J.MethodInvocation" -> "MethodInvocation"
705
- */
706
- private formatKind(kind: string): string {
707
- return kind.substring(kind.lastIndexOf('.') + 1);
708
- }
709
-
710
- /**
711
- * Formats a value for display in error messages.
712
- */
713
- private formatValue(value: any): string {
714
- if (value === null) return 'null';
715
- if (value === undefined) return 'undefined';
716
- if (typeof value === 'string') return `"${value}"`;
717
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
718
-
719
- // For objects with a kind property (LST nodes)
720
- if (value && typeof value === 'object' && value.kind) {
721
- const kind = this.formatKind(value.kind);
722
-
723
- // Show key identifying properties for common node types
724
- if (value.simpleName) return `${kind}("${value.simpleName}")`;
725
- if (value.value !== undefined) return `${kind}(${this.formatValue(value.value)})`;
726
-
727
- return kind;
728
- }
729
-
730
- return String(value);
731
- }
732
-
733
- /**
734
- * Override abort to capture explanation when debug is enabled.
735
- * Only sets explanation on the first abort call (when this.match is still true).
736
- * This preserves the most specific explanation closest to the actual mismatch.
737
- */
738
- protected override abort<T>(t: T, reason?: string, propertyName?: string, expected?: any, actual?: any): T {
739
- // If already aborted, don't overwrite the explanation
740
- // The first abort is typically the most specific
741
- if (!this.match) {
742
- return t;
743
- }
744
-
745
- // If we have context about the mismatch, capture it
746
- if (reason && this.debug && (expected !== undefined || actual !== undefined)) {
747
- const expectedStr = this.formatValue(expected);
748
- const actualStr = this.formatValue(actual);
749
-
750
- this.debug.setExplanation(
751
- reason as any,
752
- expectedStr,
753
- actualStr,
754
- 'Property values do not match'
755
- );
756
- }
757
-
758
- // Set `this.match = false`
759
- return super.abort(t, reason, propertyName, expected, actual);
760
- }
761
-
762
- /**
763
- * Override helper methods to extract detailed context from cursors.
764
- */
765
-
766
- protected override kindMismatch() {
767
- const pattern = this.cursor?.value as any;
768
- const target = this.targetCursor?.value as any;
769
- // Pass the full kind strings - formatValue() will detect and format them
770
- return this.abort(pattern, 'kind-mismatch', 'kind', this.formatKind(pattern?.kind), this.formatKind(target?.kind));
771
- }
772
-
773
- protected override structuralMismatch(propertyName: string) {
774
- const pattern = this.cursor?.value as any;
775
- const target = this.targetCursor?.value as any;
776
- const expectedValue = pattern?.[propertyName];
777
- const actualValue = target?.[propertyName];
778
- return this.abort(pattern, 'structural-mismatch', propertyName, expectedValue, actualValue);
779
- }
780
-
781
- protected override arrayLengthMismatch(propertyName: string) {
782
- const pattern = this.cursor?.value as any;
783
- const target = this.targetCursor?.value as any;
784
- const expectedArray = pattern?.[propertyName];
785
- const actualArray = target?.[propertyName];
786
- const expectedLen = Array.isArray(expectedArray) ? expectedArray.length : 'not an array';
787
- const actualLen = Array.isArray(actualArray) ? actualArray.length : 'not an array';
788
- return this.abort(pattern, 'array-length-mismatch', propertyName, expectedLen, actualLen);
789
- }
790
-
791
- protected override valueMismatch(propertyName?: string, expected?: any, actual?: any) {
792
- const pattern = this.cursor?.value as any;
793
- const target = this.targetCursor?.value as any;
794
-
795
- // Track number of paths pushed for cleanup
796
- let pathsPushed = 0;
797
-
798
- // Handle path tracking only if propertyName is provided
799
- if (propertyName) {
800
- // Split dotted property paths (e.g., "name.simpleName" → ["name", "simpleName"])
801
- const pathParts = propertyName.split('.');
802
- pathsPushed = pathParts.length;
803
-
804
- // Add each property to path with kind information for nested objects
805
- const kindStr = this.formatKind(pattern?.kind);
806
- this.debug.pushPath(`${kindStr}#${pathParts[0]}`);
807
-
808
- // For nested properties, try to get the kind of intermediate objects
809
- let currentObj = pattern?.[pathParts[0]];
810
- for (let i = 1; i < pathParts.length; i++) {
811
- if (currentObj && typeof currentObj === 'object' && currentObj.kind) {
812
- // Include the kind of the nested object
813
- const nestedKind = this.formatKind(currentObj.kind);
814
- this.debug.pushPath(`${nestedKind}#${pathParts[i]}`);
815
- } else {
816
- // Fallback to just the property name if no kind available
817
- this.debug.pushPath(pathParts[i]);
818
- }
819
- currentObj = currentObj?.[pathParts[i]];
820
- }
821
- }
822
-
823
- try {
824
- // If expected/actual provided, use them directly
825
- if (expected !== undefined || actual !== undefined) {
826
- return this.abort(pattern, 'value-mismatch', propertyName, expected, actual);
827
- }
828
-
829
- // Otherwise, try to extract from cursors (fallback for older code)
830
- if (propertyName) {
831
- // Navigate dotted property paths
832
- const getNestedValue = (obj: any, path: string) => {
833
- return path.split('.').reduce((current, prop) => current?.[prop], obj);
834
- };
835
-
836
- const expectedValue = getNestedValue(pattern, propertyName);
837
- const actualValue = getNestedValue(target, propertyName);
838
- return this.abort(pattern, 'value-mismatch', propertyName, expectedValue, actualValue);
839
- } else {
840
- // No property name - compare whole objects
841
- return this.abort(pattern, 'value-mismatch', propertyName, pattern, target);
842
- }
843
- } finally {
844
- // Pop all the path components we pushed
845
- for (let i = 0; i < pathsPushed; i++) {
846
- this.debug.popPath();
847
- }
848
- }
849
- }
850
-
851
- override async visit<R extends J>(j: Tree, p: J, parent?: Cursor): Promise<R | undefined> {
852
- const capture = this.captureAt(j, p);
853
- if (capture) {
854
- const {marker: captureMarker, target} = capture;
855
- const savedTargetCursor = this.targetCursor;
856
- const cursorAtCapturedNode = this.targetCursor !== undefined
857
- ? new Cursor(target, this.targetCursor)
858
- : new Cursor(target);
859
- this.targetCursor = cursorAtCapturedNode;
860
- try {
861
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
862
- this.debug.log('debug', 'constraint', `Evaluating constraint for capture: ${captureMarker.captureName}`);
863
- const constraintResult = captureMarker.constraint(target, this.buildConstraintContext(cursorAtCapturedNode));
864
- if (!constraintResult) {
865
- this.debug.log('info', 'constraint', `Constraint failed for capture: ${captureMarker.captureName}`);
866
- this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${(target as any).kind}`, `Constraint evaluation returned false`);
867
- return this.abort(j) as R;
868
- }
869
- this.debug.log('debug', 'constraint', `Constraint passed for capture: ${captureMarker.captureName}`);
870
- }
871
-
872
- const success = await this.matcher.handleCapture(captureMarker, target, undefined);
873
- if (!success) {
874
- return this.abort(j) as R;
875
- }
876
- return j as R;
877
- } finally {
878
- this.targetCursor = savedTargetCursor;
879
- }
880
- }
881
-
882
- return await super.visit(j, p, parent);
883
- }
884
-
885
- protected override async visitElement<T extends J>(j: T, other: T): Promise<T> {
886
- if (!this.match) {
887
- return j;
888
- }
889
-
890
- const kindStr = this.formatKind(j.kind);
891
- if (j.kind !== other.kind) {
892
- return this.abort(j, 'kind-mismatch', 'kind', kindStr, this.formatKind(other.kind));
893
- }
894
-
895
- for (const key of Object.keys(j)) {
896
- if (key.startsWith('_') || key === 'kind' || key === 'id' || key === 'markers' || key === 'prefix') {
897
- continue;
898
- }
899
-
900
- const jValue = (j as any)[key];
901
- const otherValue = (other as any)[key];
902
-
903
- if (Array.isArray(jValue)) {
904
- if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
905
- this.debug.pushPath(`${kindStr}#${key}`);
906
- const result = this.abort(j, 'array-length-mismatch', key, jValue.length,
907
- Array.isArray(otherValue) ? otherValue.length : otherValue);
908
- this.debug.popPath();
909
- return result;
910
- }
911
-
912
- for (let i = 0; i < jValue.length; i++) {
913
- this.debug.pushPath(`${kindStr}#${key}`);
914
- this.debug.pushPath(i.toString());
915
- try {
916
- await this.visitProperty(jValue[i], otherValue[i]);
917
- if (!this.match) {
918
- return j;
919
- }
920
- } finally {
921
- this.debug.popPath();
922
- this.debug.popPath();
923
- }
924
- }
925
- } else {
926
- this.debug.pushPath(`${kindStr}#${key}`);
927
- try {
928
- await this.visitProperty(jValue, otherValue);
929
- if (!this.match) {
930
- return j;
931
- }
932
- } finally {
933
- this.debug.popPath();
934
- }
935
- }
936
- }
937
-
938
- return j;
939
- }
940
-
941
- override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J): Promise<J.RightPadded<T>> {
942
- if (!this.match) {
943
- return right;
944
- }
945
-
946
- const captureMarker = PlaceholderUtils.getCaptureMarker(right);
947
- if (captureMarker) {
948
- const isRightPadded = (p as any).kind === J.Kind.RightPadded;
949
- const targetWrapper = isRightPadded ? (p as unknown) as J.RightPadded<T> : undefined;
950
- const targetElement = isRightPadded ? targetWrapper!.element : p;
951
-
952
- const savedTargetCursor = this.targetCursor;
953
- const cursorAtCapturedNode = this.targetCursor !== undefined
954
- ? (targetWrapper ? new Cursor(targetWrapper, this.targetCursor) : new Cursor(targetElement, this.targetCursor))
955
- : (targetWrapper ? new Cursor(targetWrapper) : new Cursor(targetElement));
956
- this.targetCursor = cursorAtCapturedNode;
957
- try {
958
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
959
- this.debug.log('debug', 'constraint', `Evaluating constraint for wrapped capture: ${captureMarker.captureName}`);
960
- const constraintResult = captureMarker.constraint(targetElement as J, this.buildConstraintContext(cursorAtCapturedNode));
961
- if (!constraintResult) {
962
- this.debug.log('info', 'constraint', `Constraint failed for wrapped capture: ${captureMarker.captureName}`);
963
- this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${(targetElement as any).kind}`, `Constraint evaluation returned false`);
964
- return this.abort(right);
965
- }
966
- this.debug.log('debug', 'constraint', `Constraint passed for wrapped capture: ${captureMarker.captureName}`);
967
- }
968
-
969
- const success = await this.matcher.handleCapture(captureMarker, targetElement as J, targetWrapper as J.RightPadded<J> | undefined);
970
- if (!success) {
971
- return this.abort(right);
972
- }
973
- return right;
974
- } finally {
975
- this.targetCursor = savedTargetCursor;
976
- }
977
- }
978
-
979
- return await super.visitRightPadded(right, p);
980
- }
981
-
982
- override async visitContainer<T extends J>(container: J.Container<T>, p: J): Promise<J.Container<T>> {
983
- if (!this.match) {
984
- return container;
985
- }
986
-
987
- const isContainer = (p as any).kind === J.Kind.Container;
988
- if (!isContainer) {
989
- return this.abort(container);
990
- }
991
- const otherContainer = p as unknown as J.Container<T>;
992
-
993
- const hasVariadicCapture = container.elements.some(elem =>
994
- PlaceholderUtils.isVariadicCapture(elem)
995
- );
996
-
997
- const savedCursor = this.cursor;
998
- const savedTargetCursor = this.targetCursor;
999
- this.cursor = new Cursor(container, this.cursor);
1000
- this.targetCursor = new Cursor(otherContainer, this.targetCursor);
1001
- try {
1002
- if (hasVariadicCapture) {
1003
- if (!await this.matchSequence(container.elements as J.RightPadded<J>[], otherContainer.elements as J.RightPadded<J>[], true)) {
1004
- return this.arrayLengthMismatch('elements');
1005
- }
1006
- } else {
1007
- // Non-variadic path - track indices
1008
- if (container.elements.length !== otherContainer.elements.length) {
1009
- return this.arrayLengthMismatch('elements');
1010
- }
1011
-
1012
- for (let i = 0; i < container.elements.length; i++) {
1013
- this.debug.pushPath(i.toString());
1014
- try {
1015
- if (!await this.visitContainerElement(container.elements[i], otherContainer.elements[i], i)) {
1016
- return container;
1017
- }
1018
- } finally {
1019
- this.debug.popPath();
1020
- }
1021
- }
1022
- }
1023
- } finally {
1024
- this.cursor = savedCursor;
1025
- this.targetCursor = savedTargetCursor;
1026
- }
1027
-
1028
- return container;
1029
- }
1030
-
1031
- /**
1032
- * Override visitContainerProperty to add path tracking with property context.
1033
- */
1034
- protected override async visitContainerProperty<T extends J>(
1035
- propertyName: string,
1036
- container: J.Container<T>,
1037
- otherContainer: J.Container<T>
1038
- ): Promise<J.Container<T>> {
1039
- // Get parent from cursor
1040
- const parent = this.cursor.value as J;
1041
-
1042
- // Push path for the property
1043
- const kindStr = this.formatKind((parent as any).kind);
1044
- this.debug.pushPath(`${kindStr}#${propertyName}`);
1045
-
1046
- try {
1047
- await this.visitContainer(container, otherContainer as any);
1048
- return container;
1049
- } finally {
1050
- this.debug.popPath();
1051
- }
1052
- }
1053
-
1054
- /**
1055
- * Override visitRightPaddedProperty to add path tracking with property context.
1056
- */
1057
- protected override async visitRightPaddedProperty<T extends J | boolean>(
1058
- propertyName: string,
1059
- rightPadded: J.RightPadded<T>,
1060
- otherRightPadded: J.RightPadded<T>
1061
- ): Promise<J.RightPadded<T>> {
1062
- // Get parent from cursor
1063
- const parent = this.cursor.value as J;
1064
-
1065
- // Push path for the property
1066
- const kindStr = this.formatKind((parent as any).kind);
1067
- this.debug.pushPath(`${kindStr}#${propertyName}`);
1068
-
1069
- try {
1070
- return await this.visitRightPadded(rightPadded, otherRightPadded as any);
1071
- } finally {
1072
- this.debug.popPath();
1073
- }
1074
- }
1075
-
1076
- /**
1077
- * Override visitLeftPaddedProperty to add path tracking with property context.
1078
- */
1079
- protected override async visitLeftPaddedProperty<T extends J | J.Space | number | string | boolean>(
1080
- propertyName: string,
1081
- leftPadded: J.LeftPadded<T>,
1082
- otherLeftPadded: J.LeftPadded<T>
1083
- ): Promise<J.LeftPadded<T>> {
1084
- // Get parent from cursor
1085
- const parent = this.cursor.value as J;
1086
-
1087
- // Push path for the property
1088
- const kindStr = this.formatKind((parent as any).kind);
1089
- this.debug.pushPath(`${kindStr}#${propertyName}`);
1090
-
1091
- try {
1092
- return await this.visitLeftPadded(leftPadded, otherLeftPadded as any);
1093
- } finally {
1094
- this.debug.popPath();
1095
- }
1096
- }
1097
-
1098
-
1099
- protected override async visitContainerElement<T extends J>(
1100
- element: J.RightPadded<T>,
1101
- otherElement: J.RightPadded<T>,
1102
- index: number
1103
- ): Promise<boolean> {
1104
- // Don't push index here - it should be handled by the caller with proper context
1105
- return await super.visitContainerElement(element, otherElement, index);
1106
- }
1107
-
1108
- protected override async visitArrayProperty<T>(
1109
- parent: J,
1110
- propertyName: string,
1111
- array1: T[],
1112
- array2: T[],
1113
- visitor: (item1: T, item2: T, index: number) => Promise<void>
1114
- ): Promise<void> {
1115
- // Push path for the property
1116
- const kindStr = this.formatKind((parent as any).kind);
1117
- this.debug.pushPath(`${kindStr}#${propertyName}`);
1118
-
1119
- try {
1120
- // Check length mismatch (will have path context)
1121
- if (array1.length !== array2.length) {
1122
- this.arrayLengthMismatch(propertyName);
1123
- return;
1124
- }
1125
-
1126
- // Visit each element with index tracking
1127
- for (let i = 0; i < array1.length; i++) {
1128
- this.debug.pushPath(i.toString());
1129
- try {
1130
- await visitor(array1[i], array2[i], i);
1131
- if (!this.match) {
1132
- return;
1133
- }
1134
- } finally {
1135
- this.debug.popPath();
1136
- }
1137
- }
1138
- } finally {
1139
- this.debug.popPath();
1140
- }
1141
- }
1142
-
1143
- protected override async matchSequence(
1144
- patternElements: J.RightPadded<J>[],
1145
- targetElements: J.RightPadded<J>[],
1146
- filterEmpty: boolean
1147
- ): Promise<boolean> {
1148
- // Push path component for the container
1149
- // Extract kind from cursors if available
1150
- const pattern = this.cursor?.value as any;
1151
- if (pattern && pattern.kind) {
1152
- const kindStr = this.formatKind(pattern.kind);
1153
- // Determine property name based on the kind
1154
- let propertyName = 'elements';
1155
- if (pattern.kind.includes('MethodInvocation')) {
1156
- propertyName = 'arguments';
1157
- } else if (pattern.kind.includes('Block')) {
1158
- propertyName = 'statements';
1159
- }
1160
- this.debug.pushPath(`${kindStr}#${propertyName}`);
1161
- }
1162
-
1163
- try {
1164
- return await super.matchSequence(patternElements, targetElements, filterEmpty);
1165
- } finally {
1166
- if (this.cursor?.value) {
1167
- this.debug.popPath();
1168
- }
1169
- }
1170
- }
1171
-
1172
- protected override async visitSequenceElement(
1173
- patternWrapper: J.RightPadded<J>,
1174
- targetWrapper: J.RightPadded<J>,
1175
- targetIdx: number
1176
- ): Promise<boolean> {
1177
- this.debug.pushPath(targetIdx.toString());
1178
- try {
1179
- // Save current state for backtracking (both match state and capture bindings)
1180
- const savedMatch = this.match;
1181
- const savedState = this.matcher.saveState();
1182
-
1183
- await this.visitRightPadded(patternWrapper, targetWrapper as any);
1184
-
1185
- if (!this.match) {
1186
- // Preserve explanation before restoring state
1187
- const explanation = this.debug.getExplanation();
1188
- // Restore state on match failure
1189
- this.match = savedMatch;
1190
- this.matcher.restoreState(savedState);
1191
- // Restore the explanation if one was set during matching
1192
- if (explanation) {
1193
- this.debug.restoreExplanation(explanation);
1194
- }
1195
- return false;
1196
- }
1197
-
1198
- return true;
1199
- } finally {
1200
- this.debug.popPath();
1201
- }
1202
- }
1203
-
1204
- protected override async matchSequenceOptimized(
1205
- patternElements: J.RightPadded<J>[],
1206
- targetElements: J.RightPadded<J>[],
1207
- patternIdx: number,
1208
- targetIdx: number,
1209
- filterEmpty: boolean
1210
- ): Promise<boolean> {
1211
- if (patternIdx >= patternElements.length) {
1212
- return targetIdx >= targetElements.length;
1213
- }
1214
-
1215
- const patternWrapper = patternElements[patternIdx];
1216
- const captureMarker = PlaceholderUtils.getCaptureMarker(patternWrapper);
1217
- const isVariadic = captureMarker?.variadicOptions !== undefined;
1218
-
1219
- if (isVariadic) {
1220
- const variadicOptions = captureMarker!.variadicOptions;
1221
- const min = variadicOptions?.min ?? 0;
1222
- const max = variadicOptions?.max ?? Infinity;
1223
-
1224
- let nonVariadicRemainingPatterns = 0;
1225
- let allRemainingPatternsAreDeterministic = true;
1226
- for (let i = patternIdx + 1; i < patternElements.length; i++) {
1227
- const nextCaptureMarker = PlaceholderUtils.getCaptureMarker(patternElements[i]);
1228
- const nextIsVariadic = nextCaptureMarker?.variadicOptions !== undefined;
1229
- if (!nextIsVariadic) {
1230
- nonVariadicRemainingPatterns++;
1231
- }
1232
- if (nextCaptureMarker) {
1233
- allRemainingPatternsAreDeterministic = false;
1234
- }
1235
- }
1236
- const remainingTargetElements = targetElements.length - targetIdx;
1237
- const maxPossible = Math.min(remainingTargetElements - nonVariadicRemainingPatterns, max);
1238
-
1239
- let pivotDetected = false;
1240
- let pivotAt = -1;
1241
-
1242
- // Skip pivot detection if we're using deterministic optimization
1243
- // (when all remaining patterns are literals, there's only ONE valid consumption amount)
1244
- const useDeterministicOptimization = allRemainingPatternsAreDeterministic && maxPossible >= min && maxPossible <= max;
1245
-
1246
- if (!useDeterministicOptimization && patternIdx + 1 < patternElements.length && min <= maxPossible) {
1247
- const nextPattern = patternElements[patternIdx + 1];
1248
-
1249
- for (let tryConsume = min; tryConsume <= maxPossible; tryConsume++) {
1250
- if (targetIdx + tryConsume < targetElements.length) {
1251
- const candidateElement = targetElements[targetIdx + tryConsume];
1252
-
1253
- if (filterEmpty && candidateElement.element.kind === J.Kind.Empty) {
1254
- continue;
1255
- }
1256
-
1257
- const savedMatch = this.match;
1258
- const savedState = this.matcher.saveState();
1259
-
1260
- await this.visitRightPadded(nextPattern, candidateElement as any);
1261
- const matchesNext = this.match;
1262
-
1263
- this.match = savedMatch;
1264
- this.matcher.restoreState(savedState);
1265
-
1266
- if (matchesNext) {
1267
- pivotDetected = true;
1268
- pivotAt = tryConsume;
1269
- break;
1270
- }
1271
- }
1272
- }
1273
- }
1274
-
1275
- const consumptionOrder: number[] = [];
1276
- // OPTIMIZATION: If all remaining patterns are deterministic (literals, not captures),
1277
- // there's only ONE mathematically valid consumption amount. Skip backtracking entirely.
1278
- // Example: foo(${args}, 999) matching foo(1,2,42) -> args MUST be [1,2], only try consume=2
1279
- if (useDeterministicOptimization) {
1280
- consumptionOrder.push(maxPossible);
1281
- } else if (pivotDetected && pivotAt >= 0) {
1282
- consumptionOrder.push(pivotAt);
1283
- for (let c = maxPossible; c >= min; c--) {
1284
- if (c !== pivotAt) {
1285
- consumptionOrder.push(c);
1286
- }
1287
- }
1288
- } else {
1289
- for (let c = maxPossible; c >= min; c--) {
1290
- consumptionOrder.push(c);
1291
- }
1292
- }
1293
-
1294
- for (const consume of consumptionOrder) {
1295
- // Capture elements for this consumption amount
1296
- // For empty argument lists, there will be a single J.Empty element that we need to filter out
1297
- const rawWrappers = targetElements.slice(targetIdx, targetIdx + consume);
1298
- const capturedWrappers = filterEmpty
1299
- ? rawWrappers.filter(w => w.element.kind !== J.Kind.Empty)
1300
- : rawWrappers;
1301
- const capturedElements: J[] = capturedWrappers.map(w => w.element);
1302
-
1303
- // Check min/max constraints against filtered elements
1304
- if (capturedElements.length < min || capturedElements.length > max) {
1305
- continue;
1306
- }
1307
-
1308
- if (captureMarker.constraint) {
1309
- this.debug.log('debug', 'constraint', `Evaluating variadic constraint for capture: ${captureMarker.captureName} (${capturedElements.length} elements)`);
1310
- const cursor = this.targetCursor || new Cursor(targetElements[0]);
1311
- const constraintResult = captureMarker.constraint(capturedElements as any, this.buildConstraintContext(cursor));
1312
- if (!constraintResult) {
1313
- this.debug.log('info', 'constraint', `Variadic constraint failed for capture: ${captureMarker.captureName}`);
1314
- continue;
1315
- }
1316
- this.debug.log('debug', 'constraint', `Variadic constraint passed for capture: ${captureMarker.captureName}`);
1317
- }
1318
-
1319
- const savedState = this.matcher.saveState();
1320
-
1321
- const success = await this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
1322
- if (!success) {
1323
- this.matcher.restoreState(savedState);
1324
- continue;
1325
- }
1326
-
1327
- const restMatches = await this.matchSequenceOptimized(
1328
- patternElements,
1329
- targetElements,
1330
- patternIdx + 1,
1331
- targetIdx + consume,
1332
- filterEmpty
1333
- );
1334
-
1335
- if (restMatches) {
1336
- return true;
1337
- }
1338
-
1339
- // Preserve explanation from this failed attempt before restoring state
1340
- // This is especially important when using deterministic optimization (only one attempt)
1341
- const currentExplanation = this.debug.getExplanation();
1342
- this.matcher.restoreState(savedState);
1343
- // Restore the explanation if one was set during this attempt
1344
- if (currentExplanation) {
1345
- this.debug.restoreExplanation(currentExplanation);
1346
- }
1347
- }
1348
-
1349
- return false;
1350
- } else {
1351
- if (targetIdx >= targetElements.length) {
1352
- return false;
1353
- }
1354
-
1355
- const targetWrapper = targetElements[targetIdx];
1356
- const targetElement = targetWrapper.element;
1357
-
1358
- if (filterEmpty && targetElement.kind === J.Kind.Empty) {
1359
- return false;
1360
- }
1361
-
1362
- if (!await this.visitSequenceElement(patternWrapper, targetWrapper, targetIdx)) {
1363
- return false;
1364
- }
1365
-
1366
- return await this.matchSequenceOptimized(
1367
- patternElements,
1368
- targetElements,
1369
- patternIdx + 1,
1370
- targetIdx + 1,
1371
- filterEmpty
1372
- );
1373
- }
1374
- }
1375
- }