@openrewrite/rewrite 8.67.0-20251112-160335 → 8.67.0-20251113-160321

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.
@@ -18,6 +18,49 @@ import {J} from '../../java';
18
18
  import {JS} from '../index';
19
19
  import {JavaScriptSemanticComparatorVisitor} from '../comparator';
20
20
  import {CaptureMarker, CaptureStorageValue, PlaceholderUtils} from './utils';
21
+ import {DebugLogEntry, MatchExplanation} from './types';
22
+
23
+ /**
24
+ * Debug callbacks for pattern matching.
25
+ * These are always used together - either all present or all absent.
26
+ * Part of Layer 1 (Core Instrumentation).
27
+ */
28
+ export interface DebugCallbacks {
29
+ log: (level: DebugLogEntry['level'], scope: DebugLogEntry['scope'], message: string, data?: any) => void;
30
+ setExplanation: (reason: MatchExplanation['reason'], expected: string, actual: string, details?: string) => void;
31
+ getExplanation: () => MatchExplanation | undefined;
32
+ restoreExplanation: (explanation: MatchExplanation) => void;
33
+ clearExplanation: () => void;
34
+ pushPath: (name: string) => void;
35
+ popPath: () => void;
36
+ }
37
+
38
+ /**
39
+ * Snapshot of matcher state for backtracking.
40
+ * Includes both capture storage and debug state.
41
+ */
42
+ export interface MatcherState {
43
+ storage: Map<string, CaptureStorageValue>;
44
+ debugState?: {
45
+ explanation?: MatchExplanation;
46
+ logLength: number;
47
+ path: string[];
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Callbacks for the matcher (debug and capture handling).
53
+ * Part of Layer 1 (Core Instrumentation).
54
+ */
55
+ export interface MatcherCallbacks {
56
+ handleCapture: (capture: CaptureMarker, target: J, wrapper?: J.RightPadded<J>) => boolean;
57
+ handleVariadicCapture: (capture: CaptureMarker, targets: J[], wrappers?: J.RightPadded<J>[]) => boolean;
58
+ saveState: () => MatcherState;
59
+ restoreState: (state: MatcherState) => void;
60
+
61
+ // Debug callbacks - either all present (when debugging enabled) or absent
62
+ debug?: DebugCallbacks;
63
+ }
21
64
 
22
65
  /**
23
66
  * A comparator for pattern matching that is lenient about optional properties.
@@ -26,12 +69,7 @@ import {CaptureMarker, CaptureStorageValue, PlaceholderUtils} from './utils';
26
69
  */
27
70
  export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisitor {
28
71
  constructor(
29
- private readonly matcher: {
30
- handleCapture: (capture: CaptureMarker, target: J, wrapper?: J.RightPadded<J>) => boolean;
31
- handleVariadicCapture: (capture: CaptureMarker, targets: J[], wrappers?: J.RightPadded<J>[]) => boolean;
32
- saveState: () => Map<string, CaptureStorageValue>;
33
- restoreState: (state: Map<string, CaptureStorageValue>) => void;
34
- },
72
+ protected readonly matcher: MatcherCallbacks,
35
73
  lenientTypeMatching: boolean = true
36
74
  ) {
37
75
  // Enable lenient type matching based on pattern configuration (default: true for backward compatibility)
@@ -56,12 +94,15 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
56
94
  // Evaluate constraint with cursor at the captured node (always defined)
57
95
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
58
96
  if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(p, cursorAtCapturedNode)) {
59
- return this.abort(j) as R;
97
+ const captureName = captureMarker.captureName || 'unnamed';
98
+ const targetKind = (p as any).kind || 'unknown';
99
+ return this.constraintFailed(captureName, targetKind) as R;
60
100
  }
61
101
 
62
102
  const success = this.matcher.handleCapture(captureMarker, p, undefined);
63
103
  if (!success) {
64
- return this.abort(j) as R;
104
+ const captureName = captureMarker.captureName || 'unnamed';
105
+ return this.captureConflict(captureName) as R;
65
106
  }
66
107
  return j as R;
67
108
  } finally {
@@ -82,6 +123,20 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
82
123
  (j.kind == J.Kind.Identifier && PlaceholderUtils.isCapture(j as J.Identifier));
83
124
  }
84
125
 
126
+ /**
127
+ * Additional specialized abort methods for pattern matching scenarios.
128
+ */
129
+
130
+ protected constraintFailed(captureName: string, targetKind: string) {
131
+ const pattern = this.cursor?.value as any;
132
+ return this.abort(pattern, 'constraint-failed', `capture[${captureName}]`, 'constraint satisfied', `constraint failed for ${targetKind}`);
133
+ }
134
+
135
+ protected captureConflict(captureName: string) {
136
+ const pattern = this.cursor?.value as any;
137
+ return this.abort(pattern, 'capture-conflict', `capture[${captureName}]`, 'compatible binding', 'conflicting binding');
138
+ }
139
+
85
140
  /**
86
141
  * Override visitRightPadded to check if this wrapper has a CaptureMarker.
87
142
  * If so, capture the entire wrapper (to preserve markers like semicolons).
@@ -110,13 +165,16 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
110
165
  // Evaluate constraint with cursor at the captured node (always defined)
111
166
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
112
167
  if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(targetElement as J, cursorAtCapturedNode)) {
113
- return this.abort(right);
168
+ const captureName = captureMarker.captureName || 'unnamed';
169
+ const targetKind = (targetElement as any).kind || 'unknown';
170
+ return this.constraintFailed(captureName, targetKind);
114
171
  }
115
172
 
116
173
  // Handle the capture with the wrapper - use the element for pattern matching
117
174
  const success = this.matcher.handleCapture(captureMarker, targetElement as J, targetWrapper as J.RightPadded<J> | undefined);
118
175
  if (!success) {
119
- return this.abort(right);
176
+ const captureName = captureMarker.captureName || 'unnamed';
177
+ return this.captureConflict(captureName);
120
178
  }
121
179
  return right;
122
180
  } finally {
@@ -147,7 +205,17 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
147
205
  // Extract the other container
148
206
  const isContainer = (p as any).kind === J.Kind.Container;
149
207
  if (!isContainer) {
150
- return this.abort(container);
208
+ // Set up cursors temporarily for kindMismatch to use
209
+ const savedCursor = this.cursor;
210
+ const savedTargetCursor = this.targetCursor;
211
+ this.cursor = new Cursor(container, this.cursor);
212
+ this.targetCursor = new Cursor(p, this.targetCursor);
213
+ try {
214
+ return this.kindMismatch();
215
+ } finally {
216
+ this.cursor = savedCursor;
217
+ this.targetCursor = savedTargetCursor;
218
+ }
151
219
  }
152
220
  const otherContainer = p as unknown as J.Container<T>;
153
221
 
@@ -160,7 +228,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
160
228
  // Use matchSequence for variadic matching
161
229
  // filterEmpty=true to skip J.Empty elements (they represent missing elements in destructuring)
162
230
  if (!await this.matchSequence(container.elements as J.RightPadded<J>[], otherContainer.elements as J.RightPadded<J>[], true)) {
163
- return this.abort(container);
231
+ return this.structuralMismatch('elements');
164
232
  }
165
233
  } finally {
166
234
  this.cursor = savedCursor;
@@ -170,6 +238,24 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
170
238
  return container;
171
239
  }
172
240
 
241
+ /**
242
+ * Visit a single element in a container (for non-variadic matching).
243
+ * Extracted to allow debug subclass to add path tracking.
244
+ *
245
+ * @param element The pattern element
246
+ * @param otherElement The target element
247
+ * @param index The index in the container
248
+ * @returns true if matching should continue, false if it failed
249
+ */
250
+ protected async visitContainerElement<T extends J>(
251
+ element: J.RightPadded<T>,
252
+ otherElement: J.RightPadded<T>,
253
+ index: number
254
+ ): Promise<boolean> {
255
+ await this.visitRightPadded(element as any, otherElement as any);
256
+ return this.match;
257
+ }
258
+
173
259
  override async visitMethodInvocation(methodInvocation: J.MethodInvocation, other: J): Promise<J | undefined> {
174
260
  // Check if any arguments are variadic captures
175
261
  const hasVariadicCapture = methodInvocation.arguments.elements.some(arg =>
@@ -182,51 +268,77 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
182
268
  }
183
269
 
184
270
  // Otherwise, handle variadic captures ourselves
185
- if (!this.match || other.kind !== J.Kind.MethodInvocation) {
271
+ if (!this.match) {
186
272
  return this.abort(methodInvocation);
187
273
  }
188
274
 
275
+ if (other.kind !== J.Kind.MethodInvocation) {
276
+ // Set up cursors for kindMismatch
277
+ const savedCursor = this.cursor;
278
+ const savedTargetCursor = this.targetCursor;
279
+ this.cursor = new Cursor(methodInvocation, this.cursor);
280
+ this.targetCursor = new Cursor(other, this.targetCursor);
281
+ try {
282
+ return this.kindMismatch();
283
+ } finally {
284
+ this.cursor = savedCursor;
285
+ this.targetCursor = savedTargetCursor;
286
+ }
287
+ }
288
+
189
289
  const otherMethodInvocation = other as J.MethodInvocation;
190
290
 
191
- // Compare select
192
- if ((methodInvocation.select === undefined) !== (otherMethodInvocation.select === undefined)) {
193
- return this.abort(methodInvocation);
194
- }
291
+ // Set up cursors for the entire method
292
+ const savedCursor = this.cursor;
293
+ const savedTargetCursor = this.targetCursor;
294
+ this.cursor = new Cursor(methodInvocation, this.cursor);
295
+ this.targetCursor = new Cursor(otherMethodInvocation, this.targetCursor);
296
+ try {
297
+ // Compare select
298
+ if ((methodInvocation.select === undefined) !== (otherMethodInvocation.select === undefined)) {
299
+ return this.structuralMismatch('select');
300
+ }
195
301
 
196
- // Visit select if present
197
- if (methodInvocation.select && otherMethodInvocation.select) {
198
- await this.visit(methodInvocation.select.element, otherMethodInvocation.select.element);
199
- if (!this.match) return methodInvocation;
200
- }
302
+ // Visit select if present
303
+ if (methodInvocation.select && otherMethodInvocation.select) {
304
+ await this.visit(methodInvocation.select.element, otherMethodInvocation.select.element);
305
+ if (!this.match) return methodInvocation;
306
+ }
201
307
 
202
- // Compare typeParameters
203
- if ((methodInvocation.typeParameters === undefined) !== (otherMethodInvocation.typeParameters === undefined)) {
204
- return this.abort(methodInvocation);
205
- }
308
+ // Compare typeParameters
309
+ if ((methodInvocation.typeParameters === undefined) !== (otherMethodInvocation.typeParameters === undefined)) {
310
+ return this.structuralMismatch('typeParameters');
311
+ }
206
312
 
207
- // Visit typeParameters if present
208
- if (methodInvocation.typeParameters && otherMethodInvocation.typeParameters) {
209
- if (methodInvocation.typeParameters.elements.length !== otherMethodInvocation.typeParameters.elements.length) {
210
- return this.abort(methodInvocation);
313
+ // Visit typeParameters if present
314
+ if (methodInvocation.typeParameters && otherMethodInvocation.typeParameters) {
315
+ if (methodInvocation.typeParameters.elements.length !== otherMethodInvocation.typeParameters.elements.length) {
316
+ return this.arrayLengthMismatch('typeParameters.elements');
317
+ }
318
+
319
+ // Visit each type parameter in lock step (visit RightPadded to check for markers)
320
+ for (let i = 0; i < methodInvocation.typeParameters.elements.length; i++) {
321
+ await this.visitRightPadded(methodInvocation.typeParameters.elements[i], otherMethodInvocation.typeParameters.elements[i] as any);
322
+ if (!this.match) return methodInvocation;
323
+ }
211
324
  }
212
325
 
213
- // Visit each type parameter in lock step (visit RightPadded to check for markers)
214
- for (let i = 0; i < methodInvocation.typeParameters.elements.length; i++) {
215
- await this.visitRightPadded(methodInvocation.typeParameters.elements[i], otherMethodInvocation.typeParameters.elements[i] as any);
216
- if (!this.match) return methodInvocation;
326
+ // Visit name
327
+ await this.visit(methodInvocation.name, otherMethodInvocation.name);
328
+ if (!this.match) {
329
+ return methodInvocation;
217
330
  }
218
- }
219
331
 
220
- // Visit name
221
- await this.visit(methodInvocation.name, otherMethodInvocation.name);
222
- if (!this.match) return methodInvocation;
332
+ // Special handling for variadic captures in arguments
333
+ if (!await this.matchArguments(methodInvocation.arguments.elements, otherMethodInvocation.arguments.elements)) {
334
+ return this.structuralMismatch('arguments');
335
+ }
223
336
 
224
- // Special handling for variadic captures in arguments
225
- if (!await this.matchArguments(methodInvocation.arguments.elements, otherMethodInvocation.arguments.elements)) {
226
- return this.abort(methodInvocation);
337
+ return methodInvocation;
338
+ } finally {
339
+ this.cursor = savedCursor;
340
+ this.targetCursor = savedTargetCursor;
227
341
  }
228
-
229
- return methodInvocation;
230
342
  }
231
343
 
232
344
  override async visitBlock(block: J.Block, other: J): Promise<J | undefined> {
@@ -242,18 +354,42 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
242
354
  }
243
355
 
244
356
  // Otherwise, handle variadic captures ourselves
245
- if (!this.match || other.kind !== J.Kind.Block) {
357
+ if (!this.match) {
246
358
  return this.abort(block);
247
359
  }
248
360
 
361
+ if (other.kind !== J.Kind.Block) {
362
+ // Set up cursors for kindMismatch
363
+ const savedCursor = this.cursor;
364
+ const savedTargetCursor = this.targetCursor;
365
+ this.cursor = new Cursor(block, this.cursor);
366
+ this.targetCursor = new Cursor(other, this.targetCursor);
367
+ try {
368
+ return this.kindMismatch();
369
+ } finally {
370
+ this.cursor = savedCursor;
371
+ this.targetCursor = savedTargetCursor;
372
+ }
373
+ }
374
+
249
375
  const otherBlock = other as J.Block;
250
376
 
251
- // Special handling for variadic captures in statements
252
- if (!await this.matchSequence(block.statements, otherBlock.statements, false)) {
253
- return this.abort(block);
254
- }
377
+ // Set up cursors for structural comparison
378
+ const savedCursor = this.cursor;
379
+ const savedTargetCursor = this.targetCursor;
380
+ this.cursor = new Cursor(block, this.cursor);
381
+ this.targetCursor = new Cursor(otherBlock, this.targetCursor);
382
+ try {
383
+ // Special handling for variadic captures in statements
384
+ if (!await this.matchSequence(block.statements, otherBlock.statements, false)) {
385
+ return this.structuralMismatch('statements');
386
+ }
255
387
 
256
- return block;
388
+ return block;
389
+ } finally {
390
+ this.cursor = savedCursor;
391
+ this.targetCursor = savedTargetCursor;
392
+ }
257
393
  }
258
394
 
259
395
  override async visitJsCompilationUnit(compilationUnit: JS.CompilationUnit, other: J): Promise<J | undefined> {
@@ -268,18 +404,42 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
268
404
  }
269
405
 
270
406
  // Otherwise, handle variadic captures ourselves
271
- if (!this.match || other.kind !== JS.Kind.CompilationUnit) {
407
+ if (!this.match) {
272
408
  return this.abort(compilationUnit);
273
409
  }
274
410
 
411
+ if (other.kind !== JS.Kind.CompilationUnit) {
412
+ // Set up cursors for kindMismatch
413
+ const savedCursor = this.cursor;
414
+ const savedTargetCursor = this.targetCursor;
415
+ this.cursor = new Cursor(compilationUnit, this.cursor);
416
+ this.targetCursor = new Cursor(other, this.targetCursor);
417
+ try {
418
+ return this.kindMismatch();
419
+ } finally {
420
+ this.cursor = savedCursor;
421
+ this.targetCursor = savedTargetCursor;
422
+ }
423
+ }
424
+
275
425
  const otherCompilationUnit = other as JS.CompilationUnit;
276
426
 
277
- // Special handling for variadic captures in top-level statements
278
- if (!await this.matchSequence(compilationUnit.statements, otherCompilationUnit.statements, false)) {
279
- return this.abort(compilationUnit);
280
- }
427
+ // Set up cursors for structural comparison
428
+ const savedCursor = this.cursor;
429
+ const savedTargetCursor = this.targetCursor;
430
+ this.cursor = new Cursor(compilationUnit, this.cursor);
431
+ this.targetCursor = new Cursor(otherCompilationUnit, this.targetCursor);
432
+ try {
433
+ // Special handling for variadic captures in top-level statements
434
+ if (!await this.matchSequence(compilationUnit.statements, otherCompilationUnit.statements, false)) {
435
+ return this.structuralMismatch('statements');
436
+ }
281
437
 
282
- return compilationUnit;
438
+ return compilationUnit;
439
+ } finally {
440
+ this.cursor = savedCursor;
441
+ this.targetCursor = savedTargetCursor;
442
+ }
283
443
  }
284
444
 
285
445
  /**
@@ -287,7 +447,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
287
447
  * A variadic capture can match zero or more consecutive arguments.
288
448
  */
289
449
  private async matchArguments(patternArgs: J.RightPadded<J>[], targetArgs: J.RightPadded<J>[]): Promise<boolean> {
290
- return this.matchSequence(patternArgs, targetArgs, true);
450
+ return await this.matchSequence(patternArgs, targetArgs, true);
291
451
  }
292
452
 
293
453
  /**
@@ -302,7 +462,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
302
462
  * @param filterEmpty Whether to filter out J.Empty elements when capturing (true for arguments, false for statements)
303
463
  * @returns true if the sequence matches, false otherwise
304
464
  */
305
- private async matchSequence(patternElements: J.RightPadded<J>[], targetElements: J.RightPadded<J>[], filterEmpty: boolean): Promise<boolean> {
465
+ protected async matchSequence(patternElements: J.RightPadded<J>[], targetElements: J.RightPadded<J>[], filterEmpty: boolean): Promise<boolean> {
306
466
  return await this.matchSequenceOptimized(patternElements, targetElements, 0, 0, filterEmpty);
307
467
  }
308
468
 
@@ -318,7 +478,7 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
318
478
  * @param filterEmpty Whether to filter out J.Empty elements when capturing
319
479
  * @returns true if the remaining sequence matches, false otherwise
320
480
  */
321
- private async matchSequenceOptimized(
481
+ protected async matchSequenceOptimized(
322
482
  patternElements: J.RightPadded<J>[],
323
483
  targetElements: J.RightPadded<J>[],
324
484
  patternIdx: number,
@@ -341,14 +501,20 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
341
501
  const min = variadicOptions?.min ?? 0;
342
502
  const max = variadicOptions?.max ?? Infinity;
343
503
 
344
- // Calculate maximum possible consumption
504
+ // Calculate maximum possible consumption and check if remaining patterns are deterministic
345
505
  let nonVariadicRemainingPatterns = 0;
506
+ let allRemainingPatternsAreDeterministic = true;
346
507
  for (let i = patternIdx + 1; i < patternElements.length; i++) {
347
508
  const nextCaptureMarker = PlaceholderUtils.getCaptureMarker(patternElements[i]);
348
509
  const nextIsVariadic = nextCaptureMarker?.variadicOptions !== undefined;
349
510
  if (!nextIsVariadic) {
350
511
  nonVariadicRemainingPatterns++;
351
512
  }
513
+ // A pattern is deterministic if it's not a capture at all (i.e., a literal/fixed structure)
514
+ // Variadic captures and non-variadic captures are both non-deterministic
515
+ if (nextCaptureMarker) {
516
+ allRemainingPatternsAreDeterministic = false;
517
+ }
352
518
  }
353
519
  const remainingTargetElements = targetElements.length - targetIdx;
354
520
  const maxPossible = Math.min(remainingTargetElements - nonVariadicRemainingPatterns, max);
@@ -358,7 +524,11 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
358
524
  let pivotDetected = false;
359
525
  let pivotAt = -1;
360
526
 
361
- if (patternIdx + 1 < patternElements.length && min <= maxPossible) {
527
+ // Skip pivot detection if we're using deterministic optimization
528
+ // (when all remaining patterns are literals, there's only ONE valid consumption amount)
529
+ const useDeterministicOptimization = allRemainingPatternsAreDeterministic && maxPossible >= min && maxPossible <= max;
530
+
531
+ if (!useDeterministicOptimization && patternIdx + 1 < patternElements.length && min <= maxPossible) {
362
532
  const nextPattern = patternElements[patternIdx + 1];
363
533
 
364
534
  // Scan through possible consumption amounts starting from min
@@ -392,10 +562,15 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
392
562
  }
393
563
  }
394
564
 
395
- // Try different consumption amounts
396
- // If pivot detected, try that first; otherwise use greedy approach (max to min)
565
+ // Determine consumption order
397
566
  const consumptionOrder: number[] = [];
398
- if (pivotDetected && pivotAt >= 0) {
567
+
568
+ // OPTIMIZATION: If all remaining patterns are deterministic (literals, not captures),
569
+ // there's only ONE mathematically valid consumption amount. Skip backtracking entirely.
570
+ // Example: foo(${args}, 999) matching foo(1,2,42) -> args MUST be [1,2], only try consume=2
571
+ if (useDeterministicOptimization) {
572
+ consumptionOrder.push(maxPossible);
573
+ } else if (pivotDetected && pivotAt >= 0) {
399
574
  // Try pivot first, then others as fallback
400
575
  consumptionOrder.push(pivotAt);
401
576
  for (let c = maxPossible; c >= min; c--) {
@@ -412,23 +587,16 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
412
587
 
413
588
  for (const consume of consumptionOrder) {
414
589
  // Capture elements for this consumption amount
415
- const capturedWrappers: J.RightPadded<J>[] = [];
416
- for (let i = 0; i < consume; i++) {
417
- const wrapped = targetElements[targetIdx + i];
418
- const element = wrapped.element;
419
- // For arguments, filter out J.Empty as it represents an empty argument list
420
- // For statements, include all elements
421
- if (!filterEmpty || element.kind !== J.Kind.Empty) {
422
- capturedWrappers.push(wrapped);
423
- }
424
- }
425
-
426
- // Extract just the elements for the constraint check
590
+ // For empty argument lists, there will be a single J.Empty element that we need to filter out
591
+ const rawWrappers = targetElements.slice(targetIdx, targetIdx + consume);
592
+ const capturedWrappers = filterEmpty
593
+ ? rawWrappers.filter(w => w.element.kind !== J.Kind.Empty)
594
+ : rawWrappers;
427
595
  const capturedElements: J[] = capturedWrappers.map(w => w.element);
428
596
 
429
- // Re-check min/max constraints against actual captured elements (after filtering if applicable)
597
+ // Check min/max constraints against filtered elements
430
598
  if (capturedElements.length < min || capturedElements.length > max) {
431
- continue; // Try next consumption amount
599
+ continue;
432
600
  }
433
601
 
434
602
  // Evaluate constraint for variadic capture
@@ -484,6 +652,538 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
484
652
  return false;
485
653
  }
486
654
 
655
+ if (!await this.visitSequenceElement(patternWrapper, targetWrapper, targetIdx)) {
656
+ return false;
657
+ }
658
+
659
+ // Continue matching the rest
660
+ return await this.matchSequenceOptimized(
661
+ patternElements,
662
+ targetElements,
663
+ patternIdx + 1,
664
+ targetIdx + 1,
665
+ filterEmpty
666
+ );
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Visit a single element in a sequence during non-variadic matching.
672
+ * Extracted to allow debug subclass to add path tracking.
673
+ *
674
+ * @param patternWrapper The pattern element
675
+ * @param targetWrapper The target element
676
+ * @param targetIdx The index in the target sequence
677
+ * @returns true if matching succeeded, false otherwise
678
+ */
679
+ protected async visitSequenceElement(
680
+ patternWrapper: J.RightPadded<J>,
681
+ targetWrapper: J.RightPadded<J>,
682
+ targetIdx: number
683
+ ): Promise<boolean> {
684
+ // Save current state for backtracking (both match state and capture bindings)
685
+ const savedMatch = this.match;
686
+ const savedState = this.matcher.saveState();
687
+
688
+ await this.visitRightPadded(patternWrapper, targetWrapper as any);
689
+
690
+ if (!this.match) {
691
+ // Restore state on match failure
692
+ this.match = savedMatch;
693
+ this.matcher.restoreState(savedState);
694
+ return false;
695
+ }
696
+
697
+ return true;
698
+ }
699
+ }
700
+
701
+ /**
702
+ * Debug-instrumented version of PatternMatchingComparator.
703
+ * Overrides methods to add path tracking, logging, and explanation capture.
704
+ * Zero cost when not instantiated - production code uses the base class.
705
+ */
706
+ export class DebugPatternMatchingComparator extends PatternMatchingComparator {
707
+ private get debug(): DebugCallbacks {
708
+ return this.matcher.debug!;
709
+ }
710
+
711
+ /**
712
+ * Extracts the last segment of a kind string (after the last dot).
713
+ * For example: "org.openrewrite.java.tree.J.MethodInvocation" -> "MethodInvocation"
714
+ */
715
+ private formatKind(kind: string): string {
716
+ return kind.substring(kind.lastIndexOf('.') + 1);
717
+ }
718
+
719
+ /**
720
+ * Formats a value for display in error messages.
721
+ */
722
+ private formatValue(value: any): string {
723
+ if (value === null) return 'null';
724
+ if (value === undefined) return 'undefined';
725
+ if (typeof value === 'string') return `"${value}"`;
726
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
727
+
728
+ // For objects with a kind property (LST nodes)
729
+ if (value && typeof value === 'object' && value.kind) {
730
+ const kind = this.formatKind(value.kind);
731
+
732
+ // Show key identifying properties for common node types
733
+ if (value.simpleName) return `${kind}("${value.simpleName}")`;
734
+ if (value.value !== undefined) return `${kind}(${this.formatValue(value.value)})`;
735
+
736
+ return kind;
737
+ }
738
+
739
+ return String(value);
740
+ }
741
+
742
+ /**
743
+ * Override abort to capture explanation when debug is enabled.
744
+ * Only sets explanation on the first abort call (when this.match is still true).
745
+ * This preserves the most specific explanation closest to the actual mismatch.
746
+ */
747
+ protected override abort<T>(t: T, reason?: string, propertyName?: string, expected?: any, actual?: any): T {
748
+ // If already aborted, don't overwrite the explanation
749
+ // The first abort is typically the most specific
750
+ if (!this.match) {
751
+ return t;
752
+ }
753
+
754
+ // If we have context about the mismatch, capture it
755
+ if (reason && this.debug && (expected !== undefined || actual !== undefined)) {
756
+ const expectedStr = this.formatValue(expected);
757
+ const actualStr = this.formatValue(actual);
758
+
759
+ this.debug.setExplanation(
760
+ reason as any,
761
+ expectedStr,
762
+ actualStr,
763
+ 'Property values do not match'
764
+ );
765
+ }
766
+
767
+ // Set `this.match = false`
768
+ return super.abort(t, reason, propertyName, expected, actual);
769
+ }
770
+
771
+ /**
772
+ * Override helper methods to extract detailed context from cursors.
773
+ */
774
+
775
+ protected override kindMismatch() {
776
+ const pattern = this.cursor?.value as any;
777
+ const target = this.targetCursor?.value as any;
778
+ // Pass the full kind strings - formatValue() will detect and format them
779
+ return this.abort(pattern, 'kind-mismatch', 'kind', this.formatKind(pattern?.kind), this.formatKind(target?.kind));
780
+ }
781
+
782
+ protected override structuralMismatch(propertyName: string) {
783
+ const pattern = this.cursor?.value as any;
784
+ const target = this.targetCursor?.value as any;
785
+ const expectedValue = pattern?.[propertyName];
786
+ const actualValue = target?.[propertyName];
787
+ return this.abort(pattern, 'structural-mismatch', propertyName, expectedValue, actualValue);
788
+ }
789
+
790
+ protected override arrayLengthMismatch(propertyName: string) {
791
+ const pattern = this.cursor?.value as any;
792
+ const target = this.targetCursor?.value as any;
793
+ const expectedArray = pattern?.[propertyName];
794
+ const actualArray = target?.[propertyName];
795
+ const expectedLen = Array.isArray(expectedArray) ? expectedArray.length : 'not an array';
796
+ const actualLen = Array.isArray(actualArray) ? actualArray.length : 'not an array';
797
+ return this.abort(pattern, 'array-length-mismatch', propertyName, expectedLen, actualLen);
798
+ }
799
+
800
+ protected override valueMismatch(propertyName?: string, expected?: any, actual?: any) {
801
+ const pattern = this.cursor?.value as any;
802
+ const target = this.targetCursor?.value as any;
803
+
804
+ // Track number of paths pushed for cleanup
805
+ let pathsPushed = 0;
806
+
807
+ // Handle path tracking only if propertyName is provided
808
+ if (propertyName) {
809
+ // Split dotted property paths (e.g., "name.simpleName" → ["name", "simpleName"])
810
+ const pathParts = propertyName.split('.');
811
+ pathsPushed = pathParts.length;
812
+
813
+ // Add each property to path with kind information for nested objects
814
+ const kindStr = this.formatKind(pattern?.kind);
815
+ this.debug.pushPath(`${kindStr}#${pathParts[0]}`);
816
+
817
+ // For nested properties, try to get the kind of intermediate objects
818
+ let currentObj = pattern?.[pathParts[0]];
819
+ for (let i = 1; i < pathParts.length; i++) {
820
+ if (currentObj && typeof currentObj === 'object' && currentObj.kind) {
821
+ // Include the kind of the nested object
822
+ const nestedKind = this.formatKind(currentObj.kind);
823
+ this.debug.pushPath(`${nestedKind}#${pathParts[i]}`);
824
+ } else {
825
+ // Fallback to just the property name if no kind available
826
+ this.debug.pushPath(pathParts[i]);
827
+ }
828
+ currentObj = currentObj?.[pathParts[i]];
829
+ }
830
+ }
831
+
832
+ try {
833
+ // If expected/actual provided, use them directly
834
+ if (expected !== undefined || actual !== undefined) {
835
+ return this.abort(pattern, 'value-mismatch', propertyName, expected, actual);
836
+ }
837
+
838
+ // Otherwise, try to extract from cursors (fallback for older code)
839
+ if (propertyName) {
840
+ // Navigate dotted property paths
841
+ const getNestedValue = (obj: any, path: string) => {
842
+ return path.split('.').reduce((current, prop) => current?.[prop], obj);
843
+ };
844
+
845
+ const expectedValue = getNestedValue(pattern, propertyName);
846
+ const actualValue = getNestedValue(target, propertyName);
847
+ return this.abort(pattern, 'value-mismatch', propertyName, expectedValue, actualValue);
848
+ } else {
849
+ // No property name - compare whole objects
850
+ return this.abort(pattern, 'value-mismatch', propertyName, pattern, target);
851
+ }
852
+ } finally {
853
+ // Pop all the path components we pushed
854
+ for (let i = 0; i < pathsPushed; i++) {
855
+ this.debug.popPath();
856
+ }
857
+ }
858
+ }
859
+
860
+ override async visit<R extends J>(j: Tree, p: J, parent?: Cursor): Promise<R | undefined> {
861
+ const captureMarker = PlaceholderUtils.getCaptureMarker(j)!;
862
+ if (captureMarker) {
863
+ const savedTargetCursor = this.targetCursor;
864
+ const cursorAtCapturedNode = this.targetCursor !== undefined
865
+ ? new Cursor(p, this.targetCursor)
866
+ : new Cursor(p);
867
+ this.targetCursor = cursorAtCapturedNode;
868
+ try {
869
+ if (captureMarker.constraint && !captureMarker.variadicOptions) {
870
+ this.debug.log('debug', 'constraint', `Evaluating constraint for capture: ${captureMarker.captureName}`);
871
+ const constraintResult = captureMarker.constraint(p, cursorAtCapturedNode);
872
+ if (!constraintResult) {
873
+ this.debug.log('info', 'constraint', `Constraint failed for capture: ${captureMarker.captureName}`);
874
+ this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${(p as any).kind}`, `Constraint evaluation returned false`);
875
+ return this.abort(j) as R;
876
+ }
877
+ this.debug.log('debug', 'constraint', `Constraint passed for capture: ${captureMarker.captureName}`);
878
+ }
879
+
880
+ const success = this.matcher.handleCapture(captureMarker, p, undefined);
881
+ if (!success) {
882
+ return this.abort(j) as R;
883
+ }
884
+ return j as R;
885
+ } finally {
886
+ this.targetCursor = savedTargetCursor;
887
+ }
888
+ }
889
+
890
+ return await super.visit(j, p, parent);
891
+ }
892
+
893
+ protected override async visitElement<T extends J>(j: T, other: T): Promise<T> {
894
+ if (!this.match) {
895
+ return j;
896
+ }
897
+
898
+ const kindStr = this.formatKind(j.kind);
899
+ if (j.kind !== other.kind) {
900
+ return this.abort(j, 'kind-mismatch', 'kind', kindStr, this.formatKind(other.kind));
901
+ }
902
+
903
+ for (const key of Object.keys(j)) {
904
+ if (key.startsWith('_') || key === 'kind' || key === 'id' || key === 'markers' || key === 'prefix') {
905
+ continue;
906
+ }
907
+
908
+ const jValue = (j as any)[key];
909
+ const otherValue = (other as any)[key];
910
+
911
+ if (Array.isArray(jValue)) {
912
+ if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
913
+ this.debug.pushPath(`${kindStr}#${key}`);
914
+ const result = this.abort(j, 'array-length-mismatch', key, jValue.length,
915
+ Array.isArray(otherValue) ? otherValue.length : otherValue);
916
+ this.debug.popPath();
917
+ return result;
918
+ }
919
+
920
+ for (let i = 0; i < jValue.length; i++) {
921
+ this.debug.pushPath(`${kindStr}#${key}`);
922
+ this.debug.pushPath(i.toString());
923
+ try {
924
+ await this.visitProperty(jValue[i], otherValue[i]);
925
+ if (!this.match) {
926
+ return j;
927
+ }
928
+ } finally {
929
+ this.debug.popPath();
930
+ this.debug.popPath();
931
+ }
932
+ }
933
+ } else {
934
+ this.debug.pushPath(`${kindStr}#${key}`);
935
+ try {
936
+ await this.visitProperty(jValue, otherValue);
937
+ if (!this.match) {
938
+ return j;
939
+ }
940
+ } finally {
941
+ this.debug.popPath();
942
+ }
943
+ }
944
+ }
945
+
946
+ return j;
947
+ }
948
+
949
+ override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J): Promise<J.RightPadded<T>> {
950
+ if (!this.match) {
951
+ return right;
952
+ }
953
+
954
+ const captureMarker = PlaceholderUtils.getCaptureMarker(right);
955
+ if (captureMarker) {
956
+ const isRightPadded = (p as any).kind === J.Kind.RightPadded;
957
+ const targetWrapper = isRightPadded ? (p as unknown) as J.RightPadded<T> : undefined;
958
+ const targetElement = isRightPadded ? targetWrapper!.element : p;
959
+
960
+ const savedTargetCursor = this.targetCursor;
961
+ const cursorAtCapturedNode = this.targetCursor !== undefined
962
+ ? (targetWrapper ? new Cursor(targetWrapper, this.targetCursor) : new Cursor(targetElement, this.targetCursor))
963
+ : (targetWrapper ? new Cursor(targetWrapper) : new Cursor(targetElement));
964
+ this.targetCursor = cursorAtCapturedNode;
965
+ try {
966
+ if (captureMarker.constraint && !captureMarker.variadicOptions) {
967
+ this.debug.log('debug', 'constraint', `Evaluating constraint for wrapped capture: ${captureMarker.captureName}`);
968
+ const constraintResult = captureMarker.constraint(targetElement as J, cursorAtCapturedNode);
969
+ if (!constraintResult) {
970
+ this.debug.log('info', 'constraint', `Constraint failed for wrapped capture: ${captureMarker.captureName}`);
971
+ this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${(targetElement as any).kind}`, `Constraint evaluation returned false`);
972
+ return this.abort(right);
973
+ }
974
+ this.debug.log('debug', 'constraint', `Constraint passed for wrapped capture: ${captureMarker.captureName}`);
975
+ }
976
+
977
+ const success = this.matcher.handleCapture(captureMarker, targetElement as J, targetWrapper as J.RightPadded<J> | undefined);
978
+ if (!success) {
979
+ return this.abort(right);
980
+ }
981
+ return right;
982
+ } finally {
983
+ this.targetCursor = savedTargetCursor;
984
+ }
985
+ }
986
+
987
+ return await super.visitRightPadded(right, p);
988
+ }
989
+
990
+ override async visitContainer<T extends J>(container: J.Container<T>, p: J): Promise<J.Container<T>> {
991
+ if (!this.match) {
992
+ return container;
993
+ }
994
+
995
+ const isContainer = (p as any).kind === J.Kind.Container;
996
+ if (!isContainer) {
997
+ return this.abort(container);
998
+ }
999
+ const otherContainer = p as unknown as J.Container<T>;
1000
+
1001
+ const hasVariadicCapture = container.elements.some(elem =>
1002
+ PlaceholderUtils.isVariadicCapture(elem)
1003
+ );
1004
+
1005
+ const savedCursor = this.cursor;
1006
+ const savedTargetCursor = this.targetCursor;
1007
+ this.cursor = new Cursor(container, this.cursor);
1008
+ this.targetCursor = new Cursor(otherContainer, this.targetCursor);
1009
+ try {
1010
+ if (hasVariadicCapture) {
1011
+ if (!await this.matchSequence(container.elements as J.RightPadded<J>[], otherContainer.elements as J.RightPadded<J>[], true)) {
1012
+ return this.arrayLengthMismatch('elements');
1013
+ }
1014
+ } else {
1015
+ // Non-variadic path - track indices
1016
+ if (container.elements.length !== otherContainer.elements.length) {
1017
+ return this.arrayLengthMismatch('elements');
1018
+ }
1019
+
1020
+ for (let i = 0; i < container.elements.length; i++) {
1021
+ this.debug.pushPath(i.toString());
1022
+ try {
1023
+ if (!await this.visitContainerElement(container.elements[i], otherContainer.elements[i], i)) {
1024
+ return container;
1025
+ }
1026
+ } finally {
1027
+ this.debug.popPath();
1028
+ }
1029
+ }
1030
+ }
1031
+ } finally {
1032
+ this.cursor = savedCursor;
1033
+ this.targetCursor = savedTargetCursor;
1034
+ }
1035
+
1036
+ return container;
1037
+ }
1038
+
1039
+ /**
1040
+ * Override visitContainerProperty to add path tracking with property context.
1041
+ */
1042
+ protected override async visitContainerProperty<T extends J>(
1043
+ propertyName: string,
1044
+ container: J.Container<T>,
1045
+ otherContainer: J.Container<T>
1046
+ ): Promise<J.Container<T>> {
1047
+ // Get parent from cursor
1048
+ const parent = this.cursor.value as J;
1049
+
1050
+ // Push path for the property
1051
+ const kindStr = this.formatKind((parent as any).kind);
1052
+ this.debug.pushPath(`${kindStr}#${propertyName}`);
1053
+
1054
+ try {
1055
+ await this.visitContainer(container, otherContainer as any);
1056
+ return container;
1057
+ } finally {
1058
+ this.debug.popPath();
1059
+ }
1060
+ }
1061
+
1062
+ /**
1063
+ * Override visitRightPaddedProperty to add path tracking with property context.
1064
+ */
1065
+ protected override async visitRightPaddedProperty<T extends J | boolean>(
1066
+ propertyName: string,
1067
+ rightPadded: J.RightPadded<T>,
1068
+ otherRightPadded: J.RightPadded<T>
1069
+ ): Promise<J.RightPadded<T>> {
1070
+ // Get parent from cursor
1071
+ const parent = this.cursor.value as J;
1072
+
1073
+ // Push path for the property
1074
+ const kindStr = this.formatKind((parent as any).kind);
1075
+ this.debug.pushPath(`${kindStr}#${propertyName}`);
1076
+
1077
+ try {
1078
+ return await this.visitRightPadded(rightPadded, otherRightPadded as any);
1079
+ } finally {
1080
+ this.debug.popPath();
1081
+ }
1082
+ }
1083
+
1084
+ /**
1085
+ * Override visitLeftPaddedProperty to add path tracking with property context.
1086
+ */
1087
+ protected override async visitLeftPaddedProperty<T extends J | J.Space | number | string | boolean>(
1088
+ propertyName: string,
1089
+ leftPadded: J.LeftPadded<T>,
1090
+ otherLeftPadded: J.LeftPadded<T>
1091
+ ): Promise<J.LeftPadded<T>> {
1092
+ // Get parent from cursor
1093
+ const parent = this.cursor.value as J;
1094
+
1095
+ // Push path for the property
1096
+ const kindStr = this.formatKind((parent as any).kind);
1097
+ this.debug.pushPath(`${kindStr}#${propertyName}`);
1098
+
1099
+ try {
1100
+ return await this.visitLeftPadded(leftPadded, otherLeftPadded as any);
1101
+ } finally {
1102
+ this.debug.popPath();
1103
+ }
1104
+ }
1105
+
1106
+
1107
+ protected override async visitContainerElement<T extends J>(
1108
+ element: J.RightPadded<T>,
1109
+ otherElement: J.RightPadded<T>,
1110
+ index: number
1111
+ ): Promise<boolean> {
1112
+ // Don't push index here - it should be handled by the caller with proper context
1113
+ return await super.visitContainerElement(element, otherElement, index);
1114
+ }
1115
+
1116
+ protected override async visitArrayProperty<T>(
1117
+ parent: J,
1118
+ propertyName: string,
1119
+ array1: T[],
1120
+ array2: T[],
1121
+ visitor: (item1: T, item2: T, index: number) => Promise<void>
1122
+ ): Promise<void> {
1123
+ // Push path for the property
1124
+ const kindStr = this.formatKind((parent as any).kind);
1125
+ this.debug.pushPath(`${kindStr}#${propertyName}`);
1126
+
1127
+ try {
1128
+ // Check length mismatch (will have path context)
1129
+ if (array1.length !== array2.length) {
1130
+ this.arrayLengthMismatch(propertyName);
1131
+ return;
1132
+ }
1133
+
1134
+ // Visit each element with index tracking
1135
+ for (let i = 0; i < array1.length; i++) {
1136
+ this.debug.pushPath(i.toString());
1137
+ try {
1138
+ await visitor(array1[i], array2[i], i);
1139
+ if (!this.match) {
1140
+ return;
1141
+ }
1142
+ } finally {
1143
+ this.debug.popPath();
1144
+ }
1145
+ }
1146
+ } finally {
1147
+ this.debug.popPath();
1148
+ }
1149
+ }
1150
+
1151
+ protected override async matchSequence(
1152
+ patternElements: J.RightPadded<J>[],
1153
+ targetElements: J.RightPadded<J>[],
1154
+ filterEmpty: boolean
1155
+ ): Promise<boolean> {
1156
+ // Push path component for the container
1157
+ // Extract kind from cursors if available
1158
+ const pattern = this.cursor?.value as any;
1159
+ if (pattern && pattern.kind) {
1160
+ const kindStr = this.formatKind(pattern.kind);
1161
+ // Determine property name based on the kind
1162
+ let propertyName = 'elements';
1163
+ if (pattern.kind.includes('MethodInvocation')) {
1164
+ propertyName = 'arguments';
1165
+ } else if (pattern.kind.includes('Block')) {
1166
+ propertyName = 'statements';
1167
+ }
1168
+ this.debug.pushPath(`${kindStr}#${propertyName}`);
1169
+ }
1170
+
1171
+ try {
1172
+ return await super.matchSequence(patternElements, targetElements, filterEmpty);
1173
+ } finally {
1174
+ if (this.cursor?.value) {
1175
+ this.debug.popPath();
1176
+ }
1177
+ }
1178
+ }
1179
+
1180
+ protected override async visitSequenceElement(
1181
+ patternWrapper: J.RightPadded<J>,
1182
+ targetWrapper: J.RightPadded<J>,
1183
+ targetIdx: number
1184
+ ): Promise<boolean> {
1185
+ this.debug.pushPath(targetIdx.toString());
1186
+ try {
487
1187
  // Save current state for backtracking (both match state and capture bindings)
488
1188
  const savedMatch = this.match;
489
1189
  const savedState = this.matcher.saveState();
@@ -491,28 +1191,193 @@ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisit
491
1191
  await this.visitRightPadded(patternWrapper, targetWrapper as any);
492
1192
 
493
1193
  if (!this.match) {
1194
+ // Preserve explanation before restoring state
1195
+ const explanation = this.debug.getExplanation();
494
1196
  // Restore state on match failure
495
1197
  this.match = savedMatch;
496
1198
  this.matcher.restoreState(savedState);
1199
+ // Restore the explanation if one was set during matching
1200
+ if (explanation) {
1201
+ this.debug.restoreExplanation(explanation);
1202
+ }
497
1203
  return false;
498
1204
  }
499
1205
 
500
- // Continue matching the rest
501
- const restMatches = await this.matchSequenceOptimized(
1206
+ return true;
1207
+ } finally {
1208
+ this.debug.popPath();
1209
+ }
1210
+ }
1211
+
1212
+ protected override async matchSequenceOptimized(
1213
+ patternElements: J.RightPadded<J>[],
1214
+ targetElements: J.RightPadded<J>[],
1215
+ patternIdx: number,
1216
+ targetIdx: number,
1217
+ filterEmpty: boolean
1218
+ ): Promise<boolean> {
1219
+ if (patternIdx >= patternElements.length) {
1220
+ return targetIdx >= targetElements.length;
1221
+ }
1222
+
1223
+ const patternWrapper = patternElements[patternIdx];
1224
+ const captureMarker = PlaceholderUtils.getCaptureMarker(patternWrapper);
1225
+ const isVariadic = captureMarker?.variadicOptions !== undefined;
1226
+
1227
+ if (isVariadic) {
1228
+ const variadicOptions = captureMarker!.variadicOptions;
1229
+ const min = variadicOptions?.min ?? 0;
1230
+ const max = variadicOptions?.max ?? Infinity;
1231
+
1232
+ let nonVariadicRemainingPatterns = 0;
1233
+ let allRemainingPatternsAreDeterministic = true;
1234
+ for (let i = patternIdx + 1; i < patternElements.length; i++) {
1235
+ const nextCaptureMarker = PlaceholderUtils.getCaptureMarker(patternElements[i]);
1236
+ const nextIsVariadic = nextCaptureMarker?.variadicOptions !== undefined;
1237
+ if (!nextIsVariadic) {
1238
+ nonVariadicRemainingPatterns++;
1239
+ }
1240
+ if (nextCaptureMarker) {
1241
+ allRemainingPatternsAreDeterministic = false;
1242
+ }
1243
+ }
1244
+ const remainingTargetElements = targetElements.length - targetIdx;
1245
+ const maxPossible = Math.min(remainingTargetElements - nonVariadicRemainingPatterns, max);
1246
+
1247
+ let pivotDetected = false;
1248
+ let pivotAt = -1;
1249
+
1250
+ // Skip pivot detection if we're using deterministic optimization
1251
+ // (when all remaining patterns are literals, there's only ONE valid consumption amount)
1252
+ const useDeterministicOptimization = allRemainingPatternsAreDeterministic && maxPossible >= min && maxPossible <= max;
1253
+
1254
+ if (!useDeterministicOptimization && patternIdx + 1 < patternElements.length && min <= maxPossible) {
1255
+ const nextPattern = patternElements[patternIdx + 1];
1256
+
1257
+ for (let tryConsume = min; tryConsume <= maxPossible; tryConsume++) {
1258
+ if (targetIdx + tryConsume < targetElements.length) {
1259
+ const candidateElement = targetElements[targetIdx + tryConsume];
1260
+
1261
+ if (filterEmpty && candidateElement.element.kind === J.Kind.Empty) {
1262
+ continue;
1263
+ }
1264
+
1265
+ const savedMatch = this.match;
1266
+ const savedState = this.matcher.saveState();
1267
+
1268
+ await this.visitRightPadded(nextPattern, candidateElement as any);
1269
+ const matchesNext = this.match;
1270
+
1271
+ this.match = savedMatch;
1272
+ this.matcher.restoreState(savedState);
1273
+
1274
+ if (matchesNext) {
1275
+ pivotDetected = true;
1276
+ pivotAt = tryConsume;
1277
+ break;
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+
1283
+ const consumptionOrder: number[] = [];
1284
+ // OPTIMIZATION: If all remaining patterns are deterministic (literals, not captures),
1285
+ // there's only ONE mathematically valid consumption amount. Skip backtracking entirely.
1286
+ // Example: foo(${args}, 999) matching foo(1,2,42) -> args MUST be [1,2], only try consume=2
1287
+ if (useDeterministicOptimization) {
1288
+ consumptionOrder.push(maxPossible);
1289
+ } else if (pivotDetected && pivotAt >= 0) {
1290
+ consumptionOrder.push(pivotAt);
1291
+ for (let c = maxPossible; c >= min; c--) {
1292
+ if (c !== pivotAt) {
1293
+ consumptionOrder.push(c);
1294
+ }
1295
+ }
1296
+ } else {
1297
+ for (let c = maxPossible; c >= min; c--) {
1298
+ consumptionOrder.push(c);
1299
+ }
1300
+ }
1301
+
1302
+ for (const consume of consumptionOrder) {
1303
+ // Capture elements for this consumption amount
1304
+ // For empty argument lists, there will be a single J.Empty element that we need to filter out
1305
+ const rawWrappers = targetElements.slice(targetIdx, targetIdx + consume);
1306
+ const capturedWrappers = filterEmpty
1307
+ ? rawWrappers.filter(w => w.element.kind !== J.Kind.Empty)
1308
+ : rawWrappers;
1309
+ const capturedElements: J[] = capturedWrappers.map(w => w.element);
1310
+
1311
+ // Check min/max constraints against filtered elements
1312
+ if (capturedElements.length < min || capturedElements.length > max) {
1313
+ continue;
1314
+ }
1315
+
1316
+ if (captureMarker.constraint) {
1317
+ this.debug.log('debug', 'constraint', `Evaluating variadic constraint for capture: ${captureMarker.captureName} (${capturedElements.length} elements)`);
1318
+ const cursor = this.targetCursor || new Cursor(targetElements[0]);
1319
+ const constraintResult = captureMarker.constraint(capturedElements as any, cursor);
1320
+ if (!constraintResult) {
1321
+ this.debug.log('info', 'constraint', `Variadic constraint failed for capture: ${captureMarker.captureName}`);
1322
+ continue;
1323
+ }
1324
+ this.debug.log('debug', 'constraint', `Variadic constraint passed for capture: ${captureMarker.captureName}`);
1325
+ }
1326
+
1327
+ const savedState = this.matcher.saveState();
1328
+
1329
+ const success = this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
1330
+ if (!success) {
1331
+ this.matcher.restoreState(savedState);
1332
+ continue;
1333
+ }
1334
+
1335
+ const restMatches = await this.matchSequenceOptimized(
1336
+ patternElements,
1337
+ targetElements,
1338
+ patternIdx + 1,
1339
+ targetIdx + consume,
1340
+ filterEmpty
1341
+ );
1342
+
1343
+ if (restMatches) {
1344
+ return true;
1345
+ }
1346
+
1347
+ // Preserve explanation from this failed attempt before restoring state
1348
+ // This is especially important when using deterministic optimization (only one attempt)
1349
+ const currentExplanation = this.debug.getExplanation();
1350
+ this.matcher.restoreState(savedState);
1351
+ // Restore the explanation if one was set during this attempt
1352
+ if (currentExplanation) {
1353
+ this.debug.restoreExplanation(currentExplanation);
1354
+ }
1355
+ }
1356
+
1357
+ return false;
1358
+ } else {
1359
+ if (targetIdx >= targetElements.length) {
1360
+ return false;
1361
+ }
1362
+
1363
+ const targetWrapper = targetElements[targetIdx];
1364
+ const targetElement = targetWrapper.element;
1365
+
1366
+ if (filterEmpty && targetElement.kind === J.Kind.Empty) {
1367
+ return false;
1368
+ }
1369
+
1370
+ if (!await this.visitSequenceElement(patternWrapper, targetWrapper, targetIdx)) {
1371
+ return false;
1372
+ }
1373
+
1374
+ return await this.matchSequenceOptimized(
502
1375
  patternElements,
503
1376
  targetElements,
504
1377
  patternIdx + 1,
505
1378
  targetIdx + 1,
506
1379
  filterEmpty
507
1380
  );
508
-
509
- if (!restMatches) {
510
- // Restore full state on backtracking failure
511
- this.match = savedMatch;
512
- this.matcher.restoreState(savedState);
513
- }
514
-
515
- return restMatches;
516
1381
  }
517
1382
  }
518
1383
  }