@openrewrite/rewrite 8.66.0 → 8.66.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 (113) hide show
  1. package/dist/java/tree.d.ts +10 -1
  2. package/dist/java/tree.d.ts.map +1 -1
  3. package/dist/java/tree.js +21 -5
  4. package/dist/java/tree.js.map +1 -1
  5. package/dist/java/type-visitor.d.ts +1 -1
  6. package/dist/java/type-visitor.d.ts.map +1 -1
  7. package/dist/java/visitor.d.ts +2 -2
  8. package/dist/java/visitor.d.ts.map +1 -1
  9. package/dist/java/visitor.js +8 -2
  10. package/dist/java/visitor.js.map +1 -1
  11. package/dist/javascript/assertions.d.ts +6 -0
  12. package/dist/javascript/assertions.d.ts.map +1 -1
  13. package/dist/javascript/assertions.js +14 -6
  14. package/dist/javascript/assertions.js.map +1 -1
  15. package/dist/javascript/comparator.d.ts +217 -7
  16. package/dist/javascript/comparator.d.ts.map +1 -1
  17. package/dist/javascript/comparator.js +1020 -2848
  18. package/dist/javascript/comparator.js.map +1 -1
  19. package/dist/javascript/format.d.ts +5 -3
  20. package/dist/javascript/format.d.ts.map +1 -1
  21. package/dist/javascript/format.js +87 -44
  22. package/dist/javascript/format.js.map +1 -1
  23. package/dist/javascript/index.d.ts +2 -1
  24. package/dist/javascript/index.d.ts.map +1 -1
  25. package/dist/javascript/index.js +2 -1
  26. package/dist/javascript/index.js.map +1 -1
  27. package/dist/javascript/parser.d.ts +2 -1
  28. package/dist/javascript/parser.d.ts.map +1 -1
  29. package/dist/javascript/parser.js +54 -43
  30. package/dist/javascript/parser.js.map +1 -1
  31. package/dist/javascript/templating/capture.d.ts +293 -0
  32. package/dist/javascript/templating/capture.d.ts.map +1 -0
  33. package/dist/javascript/templating/capture.js +461 -0
  34. package/dist/javascript/templating/capture.js.map +1 -0
  35. package/dist/javascript/templating/comparator.d.ts +171 -0
  36. package/dist/javascript/templating/comparator.d.ts.map +1 -0
  37. package/dist/javascript/templating/comparator.js +1221 -0
  38. package/dist/javascript/templating/comparator.js.map +1 -0
  39. package/dist/javascript/templating/engine.d.ts +108 -0
  40. package/dist/javascript/templating/engine.d.ts.map +1 -0
  41. package/dist/javascript/templating/engine.js +661 -0
  42. package/dist/javascript/templating/engine.js.map +1 -0
  43. package/dist/javascript/templating/index.d.ts +6 -0
  44. package/dist/javascript/templating/index.d.ts.map +1 -0
  45. package/dist/javascript/templating/index.js +44 -0
  46. package/dist/javascript/templating/index.js.map +1 -0
  47. package/dist/javascript/templating/pattern.d.ts +276 -0
  48. package/dist/javascript/templating/pattern.d.ts.map +1 -0
  49. package/dist/javascript/templating/pattern.js +952 -0
  50. package/dist/javascript/templating/pattern.js.map +1 -0
  51. package/dist/javascript/templating/placeholder-replacement.d.ts +83 -0
  52. package/dist/javascript/templating/placeholder-replacement.d.ts.map +1 -0
  53. package/dist/javascript/templating/placeholder-replacement.js +467 -0
  54. package/dist/javascript/templating/placeholder-replacement.js.map +1 -0
  55. package/dist/javascript/templating/rewrite.d.ts +84 -0
  56. package/dist/javascript/templating/rewrite.d.ts.map +1 -0
  57. package/dist/javascript/templating/rewrite.js +208 -0
  58. package/dist/javascript/templating/rewrite.js.map +1 -0
  59. package/dist/javascript/templating/template.d.ts +230 -0
  60. package/dist/javascript/templating/template.d.ts.map +1 -0
  61. package/dist/javascript/templating/template.js +367 -0
  62. package/dist/javascript/templating/template.js.map +1 -0
  63. package/dist/javascript/templating/types.d.ts +610 -0
  64. package/dist/javascript/templating/types.d.ts.map +1 -0
  65. package/dist/javascript/templating/types.js +3 -0
  66. package/dist/javascript/templating/types.js.map +1 -0
  67. package/dist/javascript/templating/utils.d.ts +135 -0
  68. package/dist/javascript/templating/utils.d.ts.map +1 -0
  69. package/dist/javascript/templating/utils.js +251 -0
  70. package/dist/javascript/templating/utils.js.map +1 -0
  71. package/dist/javascript/type-mapping.d.ts.map +1 -1
  72. package/dist/javascript/type-mapping.js +21 -11
  73. package/dist/javascript/type-mapping.js.map +1 -1
  74. package/dist/json/rpc.js +2 -2
  75. package/dist/json/rpc.js.map +1 -1
  76. package/dist/recipe/order-imports.js.map +1 -1
  77. package/dist/test/rewrite-test.d.ts.map +1 -1
  78. package/dist/test/rewrite-test.js +10 -6
  79. package/dist/test/rewrite-test.js.map +1 -1
  80. package/dist/version.txt +1 -1
  81. package/dist/visitor.d.ts +4 -4
  82. package/dist/visitor.d.ts.map +1 -1
  83. package/dist/visitor.js +8 -3
  84. package/dist/visitor.js.map +1 -1
  85. package/package.json +5 -2
  86. package/src/java/tree.ts +10 -3
  87. package/src/java/type-visitor.ts +1 -1
  88. package/src/java/visitor.ts +11 -5
  89. package/src/javascript/assertions.ts +9 -3
  90. package/src/javascript/comparator.ts +1095 -3373
  91. package/src/javascript/format.ts +72 -33
  92. package/src/javascript/index.ts +2 -1
  93. package/src/javascript/parser.ts +67 -45
  94. package/src/javascript/templating/capture.ts +595 -0
  95. package/src/javascript/templating/comparator.ts +1383 -0
  96. package/src/javascript/templating/engine.ts +750 -0
  97. package/src/javascript/templating/index.ts +67 -0
  98. package/src/javascript/templating/pattern.ts +1101 -0
  99. package/src/javascript/templating/placeholder-replacement.ts +475 -0
  100. package/src/javascript/templating/rewrite.ts +229 -0
  101. package/src/javascript/templating/template.ts +414 -0
  102. package/src/javascript/templating/types.ts +674 -0
  103. package/src/javascript/templating/utils.ts +298 -0
  104. package/src/javascript/type-mapping.ts +20 -11
  105. package/src/json/rpc.ts +2 -2
  106. package/src/recipe/order-imports.ts +1 -1
  107. package/src/test/rewrite-test.ts +12 -7
  108. package/src/visitor.ts +14 -6
  109. package/dist/javascript/templating.d.ts +0 -265
  110. package/dist/javascript/templating.d.ts.map +0 -1
  111. package/dist/javascript/templating.js +0 -1027
  112. package/dist/javascript/templating.js.map +0 -1
  113. package/src/javascript/templating.ts +0 -1226
@@ -0,0 +1,1383 @@
1
+ /*
2
+ * Copyright 2025 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import {Cursor, Tree} from '../..';
17
+ import {J} from '../../java';
18
+ import {JS} from '../index';
19
+ import {JavaScriptSemanticComparatorVisitor} from '../comparator';
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
+ }
64
+
65
+ /**
66
+ * A comparator for pattern matching that is lenient about optional properties.
67
+ * Allows patterns without type annotations to match actual code with type annotations.
68
+ * Uses semantic comparison to match semantically equivalent code (e.g., isDate() and util.isDate()).
69
+ */
70
+ export class PatternMatchingComparator extends JavaScriptSemanticComparatorVisitor {
71
+ constructor(
72
+ protected readonly matcher: MatcherCallbacks,
73
+ lenientTypeMatching: boolean = true
74
+ ) {
75
+ // Enable lenient type matching based on pattern configuration (default: true for backward compatibility)
76
+ super(lenientTypeMatching);
77
+ }
78
+
79
+ override async visit<R extends J>(j: Tree, p: J, parent?: Cursor): Promise<R | undefined> {
80
+ // Check if the pattern node is a capture - this handles unwrapped captures
81
+ // (Wrapped captures in J.RightPadded are handled by visitRightPadded override)
82
+ // Note: targetCursor will be pushed by parent's visit() method after this check
83
+ const captureMarker = PlaceholderUtils.getCaptureMarker(j)!;
84
+ if (captureMarker) {
85
+
86
+ // Push targetCursor to position it at the captured node for constraint evaluation
87
+ // Only create cursor if targetCursor was initialized (meaning user provided one)
88
+ const savedTargetCursor = this.targetCursor;
89
+ const cursorAtCapturedNode = this.targetCursor !== undefined
90
+ ? new Cursor(p, this.targetCursor)
91
+ : new Cursor(p);
92
+ this.targetCursor = cursorAtCapturedNode;
93
+ try {
94
+ // Evaluate constraint with cursor at the captured node (always defined)
95
+ // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
96
+ if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(p, cursorAtCapturedNode)) {
97
+ const captureName = captureMarker.captureName || 'unnamed';
98
+ const targetKind = (p as any).kind || 'unknown';
99
+ return this.constraintFailed(captureName, targetKind) as R;
100
+ }
101
+
102
+ const success = this.matcher.handleCapture(captureMarker, p, undefined);
103
+ if (!success) {
104
+ const captureName = captureMarker.captureName || 'unnamed';
105
+ return this.captureConflict(captureName) as R;
106
+ }
107
+ return j as R;
108
+ } finally {
109
+ this.targetCursor = savedTargetCursor;
110
+ }
111
+ }
112
+
113
+ if (!this.match) {
114
+ return j as R;
115
+ }
116
+
117
+ // Continue with parent's visit which will push targetCursor and traverse
118
+ return await super.visit(j, p, parent);
119
+ }
120
+
121
+ protected hasSameKind(j: J, other: J): boolean {
122
+ return super.hasSameKind(j, other) ||
123
+ (j.kind == J.Kind.Identifier && PlaceholderUtils.isCapture(j as J.Identifier));
124
+ }
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
+
140
+ /**
141
+ * Override visitRightPadded to check if this wrapper has a CaptureMarker.
142
+ * If so, capture the entire wrapper (to preserve markers like semicolons).
143
+ */
144
+ override async visitRightPadded<T extends J | boolean>(right: J.RightPadded<T>, p: J): Promise<J.RightPadded<T>> {
145
+ if (!this.match) {
146
+ return right;
147
+ }
148
+
149
+ // Check if this RightPadded has a CaptureMarker (attached during pattern construction)
150
+ // Note: Markers are now only at the wrapper level, not at the element level
151
+ const captureMarker = PlaceholderUtils.getCaptureMarker(right);
152
+ if (captureMarker) {
153
+ // Extract the target wrapper if it's also a RightPadded
154
+ const isRightPadded = (p as any).kind === J.Kind.RightPadded;
155
+ const targetWrapper = isRightPadded ? (p as unknown) as J.RightPadded<T> : undefined;
156
+ const targetElement = isRightPadded ? targetWrapper!.element : p;
157
+
158
+ // Push targetCursor to position it at the captured element for constraint evaluation
159
+ const savedTargetCursor = this.targetCursor;
160
+ const cursorAtCapturedNode = this.targetCursor !== undefined
161
+ ? (targetWrapper ? new Cursor(targetWrapper, this.targetCursor) : new Cursor(targetElement, this.targetCursor))
162
+ : (targetWrapper ? new Cursor(targetWrapper) : new Cursor(targetElement));
163
+ this.targetCursor = cursorAtCapturedNode;
164
+ try {
165
+ // Evaluate constraint with cursor at the captured node (always defined)
166
+ // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
167
+ if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(targetElement as J, cursorAtCapturedNode)) {
168
+ const captureName = captureMarker.captureName || 'unnamed';
169
+ const targetKind = (targetElement as any).kind || 'unknown';
170
+ return this.constraintFailed(captureName, targetKind);
171
+ }
172
+
173
+ // Handle the capture with the wrapper - use the element for pattern matching
174
+ const success = this.matcher.handleCapture(captureMarker, targetElement as J, targetWrapper as J.RightPadded<J> | undefined);
175
+ if (!success) {
176
+ const captureName = captureMarker.captureName || 'unnamed';
177
+ return this.captureConflict(captureName);
178
+ }
179
+ return right;
180
+ } finally {
181
+ this.targetCursor = savedTargetCursor;
182
+ }
183
+ }
184
+
185
+ // Not a capture wrapper - use parent implementation
186
+ return super.visitRightPadded(right, p);
187
+ }
188
+
189
+ override async visitContainer<T extends J>(container: J.Container<T>, p: J): Promise<J.Container<T>> {
190
+ // Check if any elements are variadic captures
191
+ const hasVariadicCapture = container.elements.some(elem =>
192
+ PlaceholderUtils.isVariadicCapture(elem)
193
+ );
194
+
195
+ // If no variadic captures, use parent implementation
196
+ if (!hasVariadicCapture) {
197
+ return super.visitContainer(container, p);
198
+ }
199
+
200
+ // Otherwise, handle variadic captures ourselves
201
+ if (!this.match) {
202
+ return container;
203
+ }
204
+
205
+ // Extract the other container
206
+ const isContainer = (p as any).kind === J.Kind.Container;
207
+ if (!isContainer) {
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
+ }
219
+ }
220
+ const otherContainer = p as unknown as J.Container<T>;
221
+
222
+ // Push wrappers onto both cursors
223
+ const savedCursor = this.cursor;
224
+ const savedTargetCursor = this.targetCursor;
225
+ this.cursor = new Cursor(container, this.cursor);
226
+ this.targetCursor = new Cursor(otherContainer, this.targetCursor);
227
+ try {
228
+ // Use matchSequence for variadic matching
229
+ // filterEmpty=true to skip J.Empty elements (they represent missing elements in destructuring)
230
+ if (!await this.matchSequence(container.elements as J.RightPadded<J>[], otherContainer.elements as J.RightPadded<J>[], true)) {
231
+ return this.structuralMismatch('elements');
232
+ }
233
+ } finally {
234
+ this.cursor = savedCursor;
235
+ this.targetCursor = savedTargetCursor;
236
+ }
237
+
238
+ return container;
239
+ }
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
+
259
+ override async visitMethodInvocation(methodInvocation: J.MethodInvocation, other: J): Promise<J | undefined> {
260
+ // Check if any arguments are variadic captures
261
+ const hasVariadicCapture = methodInvocation.arguments.elements.some(arg =>
262
+ PlaceholderUtils.isVariadicCapture(arg)
263
+ );
264
+
265
+ // If no variadic captures, use parent implementation (which includes semantic/type-aware matching)
266
+ if (!hasVariadicCapture) {
267
+ return super.visitMethodInvocation(methodInvocation, other);
268
+ }
269
+
270
+ // Otherwise, handle variadic captures ourselves
271
+ if (!this.match) {
272
+ return this.abort(methodInvocation);
273
+ }
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
+
289
+ const otherMethodInvocation = other as J.MethodInvocation;
290
+
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
+ }
301
+
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
+ }
307
+
308
+ // Compare typeParameters
309
+ if ((methodInvocation.typeParameters === undefined) !== (otherMethodInvocation.typeParameters === undefined)) {
310
+ return this.structuralMismatch('typeParameters');
311
+ }
312
+
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
+ }
324
+ }
325
+
326
+ // Visit name
327
+ await this.visit(methodInvocation.name, otherMethodInvocation.name);
328
+ if (!this.match) {
329
+ return methodInvocation;
330
+ }
331
+
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
+ }
336
+
337
+ return methodInvocation;
338
+ } finally {
339
+ this.cursor = savedCursor;
340
+ this.targetCursor = savedTargetCursor;
341
+ }
342
+ }
343
+
344
+ override async visitBlock(block: J.Block, other: J): Promise<J | undefined> {
345
+ // Check if any statements have CaptureMarker indicating they're variadic
346
+ const hasVariadicCapture = block.statements.some(stmt => {
347
+ const captureMarker = PlaceholderUtils.getCaptureMarker(stmt);
348
+ return captureMarker?.variadicOptions !== undefined;
349
+ });
350
+
351
+ // If no variadic captures, use parent implementation
352
+ if (!hasVariadicCapture) {
353
+ return super.visitBlock(block, other);
354
+ }
355
+
356
+ // Otherwise, handle variadic captures ourselves
357
+ if (!this.match) {
358
+ return this.abort(block);
359
+ }
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
+
375
+ const otherBlock = other as J.Block;
376
+
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
+ }
387
+
388
+ return block;
389
+ } finally {
390
+ this.cursor = savedCursor;
391
+ this.targetCursor = savedTargetCursor;
392
+ }
393
+ }
394
+
395
+ override async visitJsCompilationUnit(compilationUnit: JS.CompilationUnit, other: J): Promise<J | undefined> {
396
+ // Check if any statements are variadic captures
397
+ const hasVariadicCapture = compilationUnit.statements.some(stmt => {
398
+ return PlaceholderUtils.isVariadicCapture(stmt);
399
+ });
400
+
401
+ // If no variadic captures, use parent implementation
402
+ if (!hasVariadicCapture) {
403
+ return super.visitJsCompilationUnit(compilationUnit, other);
404
+ }
405
+
406
+ // Otherwise, handle variadic captures ourselves
407
+ if (!this.match) {
408
+ return this.abort(compilationUnit);
409
+ }
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
+
425
+ const otherCompilationUnit = other as JS.CompilationUnit;
426
+
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
+ }
437
+
438
+ return compilationUnit;
439
+ } finally {
440
+ this.cursor = savedCursor;
441
+ this.targetCursor = savedTargetCursor;
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Matches argument lists, with special handling for variadic captures.
447
+ * A variadic capture can match zero or more consecutive arguments.
448
+ */
449
+ private async matchArguments(patternArgs: J.RightPadded<J>[], targetArgs: J.RightPadded<J>[]): Promise<boolean> {
450
+ return await this.matchSequence(patternArgs, targetArgs, true);
451
+ }
452
+
453
+ /**
454
+ * Generic sequence matching with variadic capture support.
455
+ * Works for any sequence of JRightPadded elements (arguments, statements, etc.).
456
+ * A variadic capture can match zero or more consecutive elements.
457
+ *
458
+ * Uses pivot detection to optimize matching, with backtracking as fallback.
459
+ *
460
+ * @param patternElements The pattern elements (JRightPadded)
461
+ * @param targetElements The target elements to match against (JRightPadded)
462
+ * @param filterEmpty Whether to filter out J.Empty elements when capturing (true for arguments, false for statements)
463
+ * @returns true if the sequence matches, false otherwise
464
+ */
465
+ protected async matchSequence(patternElements: J.RightPadded<J>[], targetElements: J.RightPadded<J>[], filterEmpty: boolean): Promise<boolean> {
466
+ return await this.matchSequenceOptimized(patternElements, targetElements, 0, 0, filterEmpty);
467
+ }
468
+
469
+ /**
470
+ * Optimized sequence matcher with pivot detection and backtracking.
471
+ * For variadic patterns, tries to detect pivots (where next pattern matches) to avoid
472
+ * unnecessary backtracking. Falls back to full backtracking when pivots are ambiguous.
473
+ *
474
+ * @param patternElements The pattern elements (JRightPadded)
475
+ * @param targetElements The target elements to match against (JRightPadded)
476
+ * @param patternIdx Current position in pattern
477
+ * @param targetIdx Current position in target
478
+ * @param filterEmpty Whether to filter out J.Empty elements when capturing
479
+ * @returns true if the remaining sequence matches, false otherwise
480
+ */
481
+ protected async matchSequenceOptimized(
482
+ patternElements: J.RightPadded<J>[],
483
+ targetElements: J.RightPadded<J>[],
484
+ patternIdx: number,
485
+ targetIdx: number,
486
+ filterEmpty: boolean
487
+ ): Promise<boolean> {
488
+ // Base case: all patterns matched
489
+ if (patternIdx >= patternElements.length) {
490
+ return targetIdx >= targetElements.length; // Success if all targets consumed
491
+ }
492
+
493
+ // Check for markers at wrapper level only (markers are now only at the outermost level)
494
+ const patternWrapper = patternElements[patternIdx];
495
+ const captureMarker = PlaceholderUtils.getCaptureMarker(patternWrapper);
496
+ const isVariadic = captureMarker?.variadicOptions !== undefined;
497
+
498
+ if (isVariadic) {
499
+ // Variadic pattern: try different consumption amounts with backtracking
500
+ const variadicOptions = captureMarker!.variadicOptions;
501
+ const min = variadicOptions?.min ?? 0;
502
+ const max = variadicOptions?.max ?? Infinity;
503
+
504
+ // Calculate maximum possible consumption and check if remaining patterns are deterministic
505
+ let nonVariadicRemainingPatterns = 0;
506
+ let allRemainingPatternsAreDeterministic = true;
507
+ for (let i = patternIdx + 1; i < patternElements.length; i++) {
508
+ const nextCaptureMarker = PlaceholderUtils.getCaptureMarker(patternElements[i]);
509
+ const nextIsVariadic = nextCaptureMarker?.variadicOptions !== undefined;
510
+ if (!nextIsVariadic) {
511
+ nonVariadicRemainingPatterns++;
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
+ }
518
+ }
519
+ const remainingTargetElements = targetElements.length - targetIdx;
520
+ const maxPossible = Math.min(remainingTargetElements - nonVariadicRemainingPatterns, max);
521
+
522
+ // Pivot detection optimization: try to find where next pattern matches
523
+ // This avoids unnecessary backtracking when constraints make the split point obvious
524
+ let pivotDetected = false;
525
+ let pivotAt = -1;
526
+
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) {
532
+ const nextPattern = patternElements[patternIdx + 1];
533
+
534
+ // Scan through possible consumption amounts starting from min
535
+ for (let tryConsume = min; tryConsume <= maxPossible; tryConsume++) {
536
+ // Check if element after our consumption would match next pattern
537
+ if (targetIdx + tryConsume < targetElements.length) {
538
+ const candidateElement = targetElements[targetIdx + tryConsume];
539
+
540
+ // Skip J.Empty for arguments
541
+ if (filterEmpty && candidateElement.element.kind === J.Kind.Empty) {
542
+ continue;
543
+ }
544
+
545
+ // Test if next pattern matches this element
546
+ const savedMatch = this.match;
547
+ const savedState = this.matcher.saveState();
548
+
549
+ await this.visitRightPadded(nextPattern, candidateElement as any);
550
+ const matchesNext = this.match;
551
+
552
+ this.match = savedMatch;
553
+ this.matcher.restoreState(savedState);
554
+
555
+ if (matchesNext) {
556
+ // Found pivot! Try this consumption amount first
557
+ pivotDetected = true;
558
+ pivotAt = tryConsume;
559
+ break;
560
+ }
561
+ }
562
+ }
563
+ }
564
+
565
+ // Determine consumption order
566
+ const consumptionOrder: number[] = [];
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) {
574
+ // Try pivot first, then others as fallback
575
+ consumptionOrder.push(pivotAt);
576
+ for (let c = maxPossible; c >= min; c--) {
577
+ if (c !== pivotAt) {
578
+ consumptionOrder.push(c);
579
+ }
580
+ }
581
+ } else {
582
+ // Greedy approach: max to min
583
+ for (let c = maxPossible; c >= min; c--) {
584
+ consumptionOrder.push(c);
585
+ }
586
+ }
587
+
588
+ for (const consume of consumptionOrder) {
589
+ // Capture elements for this consumption amount
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;
595
+ const capturedElements: J[] = capturedWrappers.map(w => w.element);
596
+
597
+ // Check min/max constraints against filtered elements
598
+ if (capturedElements.length < min || capturedElements.length > max) {
599
+ continue;
600
+ }
601
+
602
+ // Evaluate constraint for variadic capture
603
+ // For variadic captures, constraint receives the entire array of captured elements
604
+ // The targetCursor points to the parent container (always defined in container matching)
605
+ if (captureMarker.constraint) {
606
+ const cursor = this.targetCursor || new Cursor(targetElements[0]);
607
+ if (!captureMarker.constraint(capturedElements as any, cursor)) {
608
+ continue; // Try next consumption amount
609
+ }
610
+ }
611
+
612
+ // Save current state for backtracking
613
+ const savedState = this.matcher.saveState();
614
+
615
+ // Handle the variadic capture
616
+ const success = this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
617
+ if (!success) {
618
+ // Restore state and try next amount
619
+ this.matcher.restoreState(savedState);
620
+ continue;
621
+ }
622
+
623
+ // Try to match the rest of the pattern
624
+ const restMatches = await this.matchSequenceOptimized(
625
+ patternElements,
626
+ targetElements,
627
+ patternIdx + 1,
628
+ targetIdx + consume,
629
+ filterEmpty
630
+ );
631
+
632
+ if (restMatches) {
633
+ return true; // Found a valid matching
634
+ }
635
+
636
+ // Backtrack: restore state and try next amount
637
+ this.matcher.restoreState(savedState);
638
+ }
639
+
640
+ return false; // No consumption amount worked
641
+ } else {
642
+ // Regular non-variadic element - must match exactly one target element
643
+ if (targetIdx >= targetElements.length) {
644
+ return false; // Pattern has more elements than target
645
+ }
646
+
647
+ const targetWrapper = targetElements[targetIdx];
648
+ const targetElement = targetWrapper.element;
649
+
650
+ // For arguments, J.Empty represents no argument, so regular captures should not match it
651
+ if (filterEmpty && targetElement.kind === J.Kind.Empty) {
652
+ return false;
653
+ }
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 {
1187
+ // Save current state for backtracking (both match state and capture bindings)
1188
+ const savedMatch = this.match;
1189
+ const savedState = this.matcher.saveState();
1190
+
1191
+ await this.visitRightPadded(patternWrapper, targetWrapper as any);
1192
+
1193
+ if (!this.match) {
1194
+ // Preserve explanation before restoring state
1195
+ const explanation = this.debug.getExplanation();
1196
+ // Restore state on match failure
1197
+ this.match = savedMatch;
1198
+ this.matcher.restoreState(savedState);
1199
+ // Restore the explanation if one was set during matching
1200
+ if (explanation) {
1201
+ this.debug.restoreExplanation(explanation);
1202
+ }
1203
+ return false;
1204
+ }
1205
+
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(
1375
+ patternElements,
1376
+ targetElements,
1377
+ patternIdx + 1,
1378
+ targetIdx + 1,
1379
+ filterEmpty
1380
+ );
1381
+ }
1382
+ }
1383
+ }