@openrewrite/rewrite 8.97.1 → 8.97.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +42 -0
  2. package/dist/javascript/comparator.d.ts +16 -10
  3. package/dist/javascript/comparator.d.ts.map +1 -1
  4. package/dist/javascript/comparator.js +10 -8
  5. package/dist/javascript/comparator.js.map +1 -1
  6. package/dist/javascript/package-json-parser.d.ts +2 -0
  7. package/dist/javascript/package-json-parser.d.ts.map +1 -1
  8. package/dist/javascript/package-json-parser.js +27 -15
  9. package/dist/javascript/package-json-parser.js.map +1 -1
  10. package/dist/javascript/package-manager.d.ts +13 -4
  11. package/dist/javascript/package-manager.d.ts.map +1 -1
  12. package/dist/javascript/package-manager.js +134 -17
  13. package/dist/javascript/package-manager.js.map +1 -1
  14. package/dist/javascript/print.d.ts.map +1 -1
  15. package/dist/javascript/print.js +1 -1
  16. package/dist/javascript/print.js.map +1 -1
  17. package/dist/javascript/recipes/dependencies.d.ts +17 -0
  18. package/dist/javascript/recipes/dependencies.d.ts.map +1 -1
  19. package/dist/javascript/recipes/dependencies.js +8 -0
  20. package/dist/javascript/recipes/dependencies.js.map +1 -1
  21. package/dist/javascript/templating/comparator.d.ts +32 -79
  22. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  23. package/dist/javascript/templating/comparator.js +35 -628
  24. package/dist/javascript/templating/comparator.js.map +1 -1
  25. package/dist/javascript/templating/debug.d.ts +143 -0
  26. package/dist/javascript/templating/debug.d.ts.map +1 -0
  27. package/dist/javascript/templating/debug.js +769 -0
  28. package/dist/javascript/templating/debug.js.map +1 -0
  29. package/dist/javascript/templating/index.d.ts +1 -1
  30. package/dist/javascript/templating/index.d.ts.map +1 -1
  31. package/dist/javascript/templating/index.js.map +1 -1
  32. package/dist/javascript/templating/pattern.d.ts +44 -35
  33. package/dist/javascript/templating/pattern.d.ts.map +1 -1
  34. package/dist/javascript/templating/pattern.js +224 -238
  35. package/dist/javascript/templating/pattern.js.map +1 -1
  36. package/dist/javascript/templating/rewrite.d.ts +4 -0
  37. package/dist/javascript/templating/rewrite.d.ts.map +1 -1
  38. package/dist/javascript/templating/rewrite.js +5 -1
  39. package/dist/javascript/templating/rewrite.js.map +1 -1
  40. package/dist/javascript/templating/types.d.ts +38 -35
  41. package/dist/javascript/templating/types.d.ts.map +1 -1
  42. package/dist/javascript/templating/utils.d.ts.map +1 -1
  43. package/dist/javascript/templating/utils.js +15 -0
  44. package/dist/javascript/templating/utils.js.map +1 -1
  45. package/dist/rewrite-javascript-version.txt +1 -1
  46. package/dist/rpc/request/install-recipes.d.ts +10 -0
  47. package/dist/rpc/request/install-recipes.d.ts.map +1 -1
  48. package/dist/rpc/request/install-recipes.js +51 -0
  49. package/dist/rpc/request/install-recipes.js.map +1 -1
  50. package/dist/rpc/request/prepare-recipe.d.ts +1 -0
  51. package/dist/rpc/request/prepare-recipe.d.ts.map +1 -1
  52. package/dist/rpc/request/prepare-recipe.js +13 -6
  53. package/dist/rpc/request/prepare-recipe.js.map +1 -1
  54. package/dist/test/rewrite-test.d.ts +1 -16
  55. package/dist/test/rewrite-test.d.ts.map +1 -1
  56. package/dist/test/rewrite-test.js +7 -58
  57. package/dist/test/rewrite-test.js.map +1 -1
  58. package/dist/util.d.ts +16 -0
  59. package/dist/util.d.ts.map +1 -1
  60. package/dist/util.js +53 -0
  61. package/dist/util.js.map +1 -1
  62. package/dist/yaml/parser.js +8 -5
  63. package/dist/yaml/parser.js.map +1 -1
  64. package/dist/yaml/print.js +9 -3
  65. package/dist/yaml/print.js.map +1 -1
  66. package/package.json +1 -1
  67. package/src/javascript/comparator.ts +66 -53
  68. package/src/javascript/package-json-parser.ts +25 -16
  69. package/src/javascript/package-manager.ts +121 -15
  70. package/src/javascript/print.ts +1 -2
  71. package/src/javascript/recipes/dependencies.ts +21 -0
  72. package/src/javascript/templating/comparator.ts +76 -766
  73. package/src/javascript/templating/debug.ts +806 -0
  74. package/src/javascript/templating/index.ts +1 -0
  75. package/src/javascript/templating/pattern.ts +267 -270
  76. package/src/javascript/templating/rewrite.ts +5 -1
  77. package/src/javascript/templating/types.ts +40 -37
  78. package/src/javascript/templating/utils.ts +0 -1
  79. package/src/rpc/request/install-recipes.ts +54 -0
  80. package/src/rpc/request/prepare-recipe.ts +18 -15
  81. package/src/test/rewrite-test.ts +2 -59
  82. package/src/util.ts +58 -0
  83. package/src/yaml/parser.ts +9 -5
  84. package/src/yaml/print.ts +9 -3
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DebugPatternMatchingComparator = exports.PatternMatchingComparator = void 0;
3
+ exports.PatternMatchingComparator = void 0;
4
4
  /*
5
5
  * Copyright 2025 the original author or authors.
6
6
  * <p>
@@ -106,20 +106,15 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
106
106
  : new __1.Cursor(target);
107
107
  this.targetCursor = cursorAtCapturedNode;
108
108
  try {
109
- // Evaluate constraint with context (cursor + previous captures)
110
109
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
111
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
112
- const context = this.buildConstraintContext(cursorAtCapturedNode);
113
- if (!captureMarker.constraint(target, context)) {
114
- const captureName = captureMarker.captureName || 'unnamed';
115
- const targetKind = target.kind || 'unknown';
116
- return this.constraintFailed(captureName, targetKind);
117
- }
110
+ if (captureMarker.constraint && !captureMarker.variadicOptions &&
111
+ !this.satisfiesConstraint(captureMarker, j, target, cursorAtCapturedNode)) {
112
+ return this.abort(j);
118
113
  }
119
114
  const success = await this.matcher.handleCapture(captureMarker, target, undefined);
120
115
  if (!success) {
121
- const captureName = captureMarker.captureName || 'unnamed';
122
- return this.captureConflict(captureName);
116
+ this.explainCaptureConflict(captureMarker, j, [target]);
117
+ return this.abort(j);
123
118
  }
124
119
  return j;
125
120
  }
@@ -144,18 +139,21 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
144
139
  return super.hasSameKind(j, other) ||
145
140
  (j.kind == java_1.J.Kind.Identifier && utils_1.PlaceholderUtils.isCapture(j));
146
141
  }
147
- /**
148
- * Additional specialized abort methods for pattern matching scenarios.
149
- */
150
- constraintFailed(captureName, targetKind) {
151
- var _a;
152
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
153
- return this.abort(pattern, 'constraint-failed', `capture[${captureName}]`, 'constraint satisfied', `constraint failed for ${targetKind}`);
142
+ /** Whether `target`, the code at `patternElement`'s capture, satisfies the capture's constraint. */
143
+ satisfiesConstraint(marker, _patternElement, target, cursor) {
144
+ return marker.constraint(target, this.buildConstraintContext(cursor));
145
+ }
146
+ /** Called where a capture the pattern names twice holds other code than `targets`. Matching ignores it. */
147
+ explainCaptureConflict(_marker, _patternElement, _targets) {
154
148
  }
155
- captureConflict(captureName) {
149
+ /** Restores `state` after a failed alternative, keeping why it failed in case no other alternative matches. */
150
+ backtrack(state) {
156
151
  var _a;
157
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
158
- return this.abort(pattern, 'capture-conflict', `capture[${captureName}]`, 'compatible binding', 'conflicting binding');
152
+ const failure = (_a = this.matcher.debug) === null || _a === void 0 ? void 0 : _a.getExplanation();
153
+ this.matcher.restoreState(state);
154
+ if (failure) {
155
+ this.matcher.debug.restoreExplanation(failure);
156
+ }
159
157
  }
160
158
  /**
161
159
  * Override visitRightPadded to check if this wrapper has a CaptureMarker.
@@ -180,18 +178,16 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
180
178
  : (targetWrapper ? new __1.Cursor(targetWrapper) : new __1.Cursor(targetElement));
181
179
  this.targetCursor = cursorAtCapturedNode;
182
180
  try {
183
- // Evaluate constraint with cursor at the captured node (always defined)
184
181
  // Skip constraint for variadic captures - they're evaluated in matchSequence with the full array
185
- if (captureMarker.constraint && !captureMarker.variadicOptions && !captureMarker.constraint(targetElement, this.buildConstraintContext(cursorAtCapturedNode))) {
186
- const captureName = captureMarker.captureName || 'unnamed';
187
- const targetKind = targetElement.kind || 'unknown';
188
- return this.constraintFailed(captureName, targetKind);
182
+ if (captureMarker.constraint && !captureMarker.variadicOptions &&
183
+ !this.satisfiesConstraint(captureMarker, right, targetElement, cursorAtCapturedNode)) {
184
+ return this.abort(right);
189
185
  }
190
186
  // Handle the capture with the wrapper - use the element for pattern matching
191
187
  const success = await this.matcher.handleCapture(captureMarker, targetElement, targetWrapper);
192
188
  if (!success) {
193
- const captureName = captureMarker.captureName || 'unnamed';
194
- return this.captureConflict(captureName);
189
+ this.explainCaptureConflict(captureMarker, right, [targetElement]);
190
+ return this.abort(right);
195
191
  }
196
192
  return right;
197
193
  }
@@ -248,19 +244,6 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
248
244
  }
249
245
  return container;
250
246
  }
251
- /**
252
- * Visit a single element in a container (for non-variadic matching).
253
- * Extracted to allow debug subclass to add path tracking.
254
- *
255
- * @param element The pattern element
256
- * @param otherElement The target element
257
- * @param index The index in the container
258
- * @returns true if matching should continue, false if it failed
259
- */
260
- async visitContainerElement(element, otherElement, index) {
261
- await this.visitRightPadded(element, otherElement);
262
- return this.match;
263
- }
264
247
  async visitBlock(block, other) {
265
248
  // Check if any statements have CaptureMarker indicating they're variadic
266
249
  const hasVariadicCapture = block.statements.some(stmt => {
@@ -380,7 +363,7 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
380
363
  * @returns true if the remaining sequence matches, false otherwise
381
364
  */
382
365
  async matchSequenceOptimized(patternElements, targetElements, patternIdx, targetIdx, filterEmpty) {
383
- var _a, _b;
366
+ var _a, _b, _c;
384
367
  // Base case: all patterns matched
385
368
  if (patternIdx >= patternElements.length) {
386
369
  return targetIdx >= targetElements.length; // Success if all targets consumed
@@ -480,31 +463,30 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
480
463
  if (capturedElements.length < min || capturedElements.length > max) {
481
464
  continue;
482
465
  }
483
- // Evaluate constraint for variadic capture
484
466
  // For variadic captures, constraint receives the entire array of captured elements
485
467
  // The targetCursor points to the parent container (always defined in container matching)
486
- if (captureMarker.constraint) {
487
- const cursor = this.targetCursor || new __1.Cursor(targetElements[0]);
488
- if (!captureMarker.constraint(capturedElements, this.buildConstraintContext(cursor))) {
489
- continue; // Try next consumption amount
490
- }
468
+ const constraintCursor = this.targetCursor || new __1.Cursor(targetElements[0]);
469
+ if (captureMarker.constraint &&
470
+ !this.satisfiesConstraint(captureMarker, patternWrapper, capturedElements, constraintCursor)) {
471
+ continue; // Try next consumption amount
491
472
  }
492
473
  // Save current state for backtracking
493
474
  const savedState = this.matcher.saveState();
494
475
  // Handle the variadic capture
495
476
  const success = await this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
496
477
  if (!success) {
497
- // Restore state and try next amount
498
478
  this.matcher.restoreState(savedState);
479
+ this.explainCaptureConflict(captureMarker, patternWrapper, capturedElements);
499
480
  continue;
500
481
  }
501
482
  // Try to match the rest of the pattern
502
483
  const restMatches = await this.matchSequenceOptimized(patternElements, targetElements, patternIdx + 1, targetIdx + consume, filterEmpty);
503
484
  if (restMatches) {
504
- return true; // Found a valid matching
485
+ // Why earlier alternatives failed explains nothing about a match that went on
486
+ (_c = this.matcher.debug) === null || _c === void 0 ? void 0 : _c.clearExplanation();
487
+ return true;
505
488
  }
506
- // Backtrack: restore state and try next amount
507
- this.matcher.restoreState(savedState);
489
+ this.backtrack(savedState);
508
490
  }
509
491
  return false; // No consumption amount worked
510
492
  }
@@ -528,7 +510,6 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
528
510
  }
529
511
  /**
530
512
  * Visit a single element in a sequence during non-variadic matching.
531
- * Extracted to allow debug subclass to add path tracking.
532
513
  *
533
514
  * @param patternWrapper The pattern element
534
515
  * @param targetWrapper The target element
@@ -541,586 +522,12 @@ class PatternMatchingComparator extends comparator_1.JavaScriptSemanticComparato
541
522
  const savedState = this.matcher.saveState();
542
523
  await this.visitRightPadded(patternWrapper, targetWrapper);
543
524
  if (!this.match) {
544
- // Restore state on match failure
545
525
  this.match = savedMatch;
546
- this.matcher.restoreState(savedState);
526
+ this.backtrack(savedState);
547
527
  return false;
548
528
  }
549
529
  return true;
550
530
  }
551
531
  }
552
532
  exports.PatternMatchingComparator = PatternMatchingComparator;
553
- /**
554
- * Debug-instrumented version of PatternMatchingComparator.
555
- * Overrides methods to add path tracking, logging, and explanation capture.
556
- * Zero cost when not instantiated - production code uses the base class.
557
- */
558
- class DebugPatternMatchingComparator extends PatternMatchingComparator {
559
- get debug() {
560
- return this.matcher.debug;
561
- }
562
- /**
563
- * Extracts the last segment of a kind string (after the last dot).
564
- * For example: "org.openrewrite.java.tree.J.MethodInvocation" -> "MethodInvocation"
565
- */
566
- formatKind(kind) {
567
- return kind.substring(kind.lastIndexOf('.') + 1);
568
- }
569
- /**
570
- * Formats a value for display in error messages.
571
- */
572
- formatValue(value) {
573
- if (value === null)
574
- return 'null';
575
- if (value === undefined)
576
- return 'undefined';
577
- if (typeof value === 'string')
578
- return `"${value}"`;
579
- if (typeof value === 'number' || typeof value === 'boolean')
580
- return String(value);
581
- // For objects with a kind property (LST nodes)
582
- if (value && typeof value === 'object' && value.kind) {
583
- const kind = this.formatKind(value.kind);
584
- // Show key identifying properties for common node types
585
- if (value.simpleName)
586
- return `${kind}("${value.simpleName}")`;
587
- if (value.value !== undefined)
588
- return `${kind}(${this.formatValue(value.value)})`;
589
- return kind;
590
- }
591
- return String(value);
592
- }
593
- /**
594
- * Override abort to capture explanation when debug is enabled.
595
- * Only sets explanation on the first abort call (when this.match is still true).
596
- * This preserves the most specific explanation closest to the actual mismatch.
597
- */
598
- abort(t, reason, propertyName, expected, actual) {
599
- // If already aborted, don't overwrite the explanation
600
- // The first abort is typically the most specific
601
- if (!this.match) {
602
- return t;
603
- }
604
- // If we have context about the mismatch, capture it
605
- if (reason && this.debug && (expected !== undefined || actual !== undefined)) {
606
- const expectedStr = this.formatValue(expected);
607
- const actualStr = this.formatValue(actual);
608
- this.debug.setExplanation(reason, expectedStr, actualStr, 'Property values do not match');
609
- }
610
- // Set `this.match = false`
611
- return super.abort(t, reason, propertyName, expected, actual);
612
- }
613
- /**
614
- * Override helper methods to extract detailed context from cursors.
615
- */
616
- kindMismatch() {
617
- var _a, _b;
618
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
619
- const target = (_b = this.targetCursor) === null || _b === void 0 ? void 0 : _b.value;
620
- // Pass the full kind strings - formatValue() will detect and format them
621
- return this.abort(pattern, 'kind-mismatch', 'kind', this.formatKind(pattern === null || pattern === void 0 ? void 0 : pattern.kind), this.formatKind(target === null || target === void 0 ? void 0 : target.kind));
622
- }
623
- structuralMismatch(propertyName) {
624
- var _a, _b;
625
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
626
- const target = (_b = this.targetCursor) === null || _b === void 0 ? void 0 : _b.value;
627
- const expectedValue = pattern === null || pattern === void 0 ? void 0 : pattern[propertyName];
628
- const actualValue = target === null || target === void 0 ? void 0 : target[propertyName];
629
- return this.abort(pattern, 'structural-mismatch', propertyName, expectedValue, actualValue);
630
- }
631
- arrayLengthMismatch(propertyName) {
632
- var _a, _b;
633
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
634
- const target = (_b = this.targetCursor) === null || _b === void 0 ? void 0 : _b.value;
635
- const expectedArray = pattern === null || pattern === void 0 ? void 0 : pattern[propertyName];
636
- const actualArray = target === null || target === void 0 ? void 0 : target[propertyName];
637
- const expectedLen = Array.isArray(expectedArray) ? expectedArray.length : 'not an array';
638
- const actualLen = Array.isArray(actualArray) ? actualArray.length : 'not an array';
639
- return this.abort(pattern, 'array-length-mismatch', propertyName, expectedLen, actualLen);
640
- }
641
- valueMismatch(propertyName, expected, actual) {
642
- var _a, _b;
643
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
644
- const target = (_b = this.targetCursor) === null || _b === void 0 ? void 0 : _b.value;
645
- // Track number of paths pushed for cleanup
646
- let pathsPushed = 0;
647
- // Handle path tracking only if propertyName is provided
648
- if (propertyName) {
649
- // Split dotted property paths (e.g., "name.simpleName" → ["name", "simpleName"])
650
- const pathParts = propertyName.split('.');
651
- pathsPushed = pathParts.length;
652
- // Add each property to path with kind information for nested objects
653
- const kindStr = this.formatKind(pattern === null || pattern === void 0 ? void 0 : pattern.kind);
654
- this.debug.pushPath(`${kindStr}#${pathParts[0]}`);
655
- // For nested properties, try to get the kind of intermediate objects
656
- let currentObj = pattern === null || pattern === void 0 ? void 0 : pattern[pathParts[0]];
657
- for (let i = 1; i < pathParts.length; i++) {
658
- if (currentObj && typeof currentObj === 'object' && currentObj.kind) {
659
- // Include the kind of the nested object
660
- const nestedKind = this.formatKind(currentObj.kind);
661
- this.debug.pushPath(`${nestedKind}#${pathParts[i]}`);
662
- }
663
- else {
664
- // Fallback to just the property name if no kind available
665
- this.debug.pushPath(pathParts[i]);
666
- }
667
- currentObj = currentObj === null || currentObj === void 0 ? void 0 : currentObj[pathParts[i]];
668
- }
669
- }
670
- try {
671
- // If expected/actual provided, use them directly
672
- if (expected !== undefined || actual !== undefined) {
673
- return this.abort(pattern, 'value-mismatch', propertyName, expected, actual);
674
- }
675
- // Otherwise, try to extract from cursors (fallback for older code)
676
- if (propertyName) {
677
- // Navigate dotted property paths
678
- const getNestedValue = (obj, path) => {
679
- return path.split('.').reduce((current, prop) => current === null || current === void 0 ? void 0 : current[prop], obj);
680
- };
681
- const expectedValue = getNestedValue(pattern, propertyName);
682
- const actualValue = getNestedValue(target, propertyName);
683
- return this.abort(pattern, 'value-mismatch', propertyName, expectedValue, actualValue);
684
- }
685
- else {
686
- // No property name - compare whole objects
687
- return this.abort(pattern, 'value-mismatch', propertyName, pattern, target);
688
- }
689
- }
690
- finally {
691
- // Pop all the path components we pushed
692
- for (let i = 0; i < pathsPushed; i++) {
693
- this.debug.popPath();
694
- }
695
- }
696
- }
697
- async visit(j, p, parent) {
698
- const capture = this.captureAt(j, p);
699
- if (capture) {
700
- const { marker: captureMarker, target } = capture;
701
- const savedTargetCursor = this.targetCursor;
702
- const cursorAtCapturedNode = this.targetCursor !== undefined
703
- ? new __1.Cursor(target, this.targetCursor)
704
- : new __1.Cursor(target);
705
- this.targetCursor = cursorAtCapturedNode;
706
- try {
707
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
708
- this.debug.log('debug', 'constraint', `Evaluating constraint for capture: ${captureMarker.captureName}`);
709
- const constraintResult = captureMarker.constraint(target, this.buildConstraintContext(cursorAtCapturedNode));
710
- if (!constraintResult) {
711
- this.debug.log('info', 'constraint', `Constraint failed for capture: ${captureMarker.captureName}`);
712
- this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${target.kind}`, `Constraint evaluation returned false`);
713
- return this.abort(j);
714
- }
715
- this.debug.log('debug', 'constraint', `Constraint passed for capture: ${captureMarker.captureName}`);
716
- }
717
- const success = await this.matcher.handleCapture(captureMarker, target, undefined);
718
- if (!success) {
719
- return this.abort(j);
720
- }
721
- return j;
722
- }
723
- finally {
724
- this.targetCursor = savedTargetCursor;
725
- }
726
- }
727
- return await super.visit(j, p, parent);
728
- }
729
- async visitElement(j, other) {
730
- if (!this.match) {
731
- return j;
732
- }
733
- const kindStr = this.formatKind(j.kind);
734
- if (j.kind !== other.kind) {
735
- return this.abort(j, 'kind-mismatch', 'kind', kindStr, this.formatKind(other.kind));
736
- }
737
- for (const key of Object.keys(j)) {
738
- if (key.startsWith('_') || key === 'kind' || key === 'id' || key === 'markers' || key === 'prefix') {
739
- continue;
740
- }
741
- const jValue = j[key];
742
- const otherValue = other[key];
743
- if (Array.isArray(jValue)) {
744
- if (!Array.isArray(otherValue) || jValue.length !== otherValue.length) {
745
- this.debug.pushPath(`${kindStr}#${key}`);
746
- const result = this.abort(j, 'array-length-mismatch', key, jValue.length, Array.isArray(otherValue) ? otherValue.length : otherValue);
747
- this.debug.popPath();
748
- return result;
749
- }
750
- for (let i = 0; i < jValue.length; i++) {
751
- this.debug.pushPath(`${kindStr}#${key}`);
752
- this.debug.pushPath(i.toString());
753
- try {
754
- await this.visitProperty(jValue[i], otherValue[i]);
755
- if (!this.match) {
756
- return j;
757
- }
758
- }
759
- finally {
760
- this.debug.popPath();
761
- this.debug.popPath();
762
- }
763
- }
764
- }
765
- else {
766
- this.debug.pushPath(`${kindStr}#${key}`);
767
- try {
768
- await this.visitProperty(jValue, otherValue);
769
- if (!this.match) {
770
- return j;
771
- }
772
- }
773
- finally {
774
- this.debug.popPath();
775
- }
776
- }
777
- }
778
- return j;
779
- }
780
- async visitRightPadded(right, p) {
781
- if (!this.match) {
782
- return right;
783
- }
784
- const captureMarker = utils_1.PlaceholderUtils.getCaptureMarker(right);
785
- if (captureMarker) {
786
- const isRightPadded = p.kind === java_1.J.Kind.RightPadded;
787
- const targetWrapper = isRightPadded ? p : undefined;
788
- const targetElement = isRightPadded ? targetWrapper.element : p;
789
- const savedTargetCursor = this.targetCursor;
790
- const cursorAtCapturedNode = this.targetCursor !== undefined
791
- ? (targetWrapper ? new __1.Cursor(targetWrapper, this.targetCursor) : new __1.Cursor(targetElement, this.targetCursor))
792
- : (targetWrapper ? new __1.Cursor(targetWrapper) : new __1.Cursor(targetElement));
793
- this.targetCursor = cursorAtCapturedNode;
794
- try {
795
- if (captureMarker.constraint && !captureMarker.variadicOptions) {
796
- this.debug.log('debug', 'constraint', `Evaluating constraint for wrapped capture: ${captureMarker.captureName}`);
797
- const constraintResult = captureMarker.constraint(targetElement, this.buildConstraintContext(cursorAtCapturedNode));
798
- if (!constraintResult) {
799
- this.debug.log('info', 'constraint', `Constraint failed for wrapped capture: ${captureMarker.captureName}`);
800
- this.debug.setExplanation('constraint-failed', `Capture ${captureMarker.captureName} with valid constraint`, `Constraint failed for ${targetElement.kind}`, `Constraint evaluation returned false`);
801
- return this.abort(right);
802
- }
803
- this.debug.log('debug', 'constraint', `Constraint passed for wrapped capture: ${captureMarker.captureName}`);
804
- }
805
- const success = await this.matcher.handleCapture(captureMarker, targetElement, targetWrapper);
806
- if (!success) {
807
- return this.abort(right);
808
- }
809
- return right;
810
- }
811
- finally {
812
- this.targetCursor = savedTargetCursor;
813
- }
814
- }
815
- return await super.visitRightPadded(right, p);
816
- }
817
- async visitContainer(container, p) {
818
- if (!this.match) {
819
- return container;
820
- }
821
- const isContainer = p.kind === java_1.J.Kind.Container;
822
- if (!isContainer) {
823
- return this.abort(container);
824
- }
825
- const otherContainer = p;
826
- const hasVariadicCapture = container.elements.some(elem => utils_1.PlaceholderUtils.isVariadicCapture(elem));
827
- const savedCursor = this.cursor;
828
- const savedTargetCursor = this.targetCursor;
829
- this.cursor = new __1.Cursor(container, this.cursor);
830
- this.targetCursor = new __1.Cursor(otherContainer, this.targetCursor);
831
- try {
832
- if (hasVariadicCapture) {
833
- if (!await this.matchSequence(container.elements, otherContainer.elements, true)) {
834
- return this.arrayLengthMismatch('elements');
835
- }
836
- }
837
- else {
838
- // Non-variadic path - track indices
839
- if (container.elements.length !== otherContainer.elements.length) {
840
- return this.arrayLengthMismatch('elements');
841
- }
842
- for (let i = 0; i < container.elements.length; i++) {
843
- this.debug.pushPath(i.toString());
844
- try {
845
- if (!await this.visitContainerElement(container.elements[i], otherContainer.elements[i], i)) {
846
- return container;
847
- }
848
- }
849
- finally {
850
- this.debug.popPath();
851
- }
852
- }
853
- }
854
- }
855
- finally {
856
- this.cursor = savedCursor;
857
- this.targetCursor = savedTargetCursor;
858
- }
859
- return container;
860
- }
861
- /**
862
- * Override visitContainerProperty to add path tracking with property context.
863
- */
864
- async visitContainerProperty(propertyName, container, otherContainer) {
865
- // Get parent from cursor
866
- const parent = this.cursor.value;
867
- // Push path for the property
868
- const kindStr = this.formatKind(parent.kind);
869
- this.debug.pushPath(`${kindStr}#${propertyName}`);
870
- try {
871
- await this.visitContainer(container, otherContainer);
872
- return container;
873
- }
874
- finally {
875
- this.debug.popPath();
876
- }
877
- }
878
- /**
879
- * Override visitRightPaddedProperty to add path tracking with property context.
880
- */
881
- async visitRightPaddedProperty(propertyName, rightPadded, otherRightPadded) {
882
- // Get parent from cursor
883
- const parent = this.cursor.value;
884
- // Push path for the property
885
- const kindStr = this.formatKind(parent.kind);
886
- this.debug.pushPath(`${kindStr}#${propertyName}`);
887
- try {
888
- return await this.visitRightPadded(rightPadded, otherRightPadded);
889
- }
890
- finally {
891
- this.debug.popPath();
892
- }
893
- }
894
- /**
895
- * Override visitLeftPaddedProperty to add path tracking with property context.
896
- */
897
- async visitLeftPaddedProperty(propertyName, leftPadded, otherLeftPadded) {
898
- // Get parent from cursor
899
- const parent = this.cursor.value;
900
- // Push path for the property
901
- const kindStr = this.formatKind(parent.kind);
902
- this.debug.pushPath(`${kindStr}#${propertyName}`);
903
- try {
904
- return await this.visitLeftPadded(leftPadded, otherLeftPadded);
905
- }
906
- finally {
907
- this.debug.popPath();
908
- }
909
- }
910
- async visitContainerElement(element, otherElement, index) {
911
- // Don't push index here - it should be handled by the caller with proper context
912
- return await super.visitContainerElement(element, otherElement, index);
913
- }
914
- async visitArrayProperty(parent, propertyName, array1, array2, visitor) {
915
- // Push path for the property
916
- const kindStr = this.formatKind(parent.kind);
917
- this.debug.pushPath(`${kindStr}#${propertyName}`);
918
- try {
919
- // Check length mismatch (will have path context)
920
- if (array1.length !== array2.length) {
921
- this.arrayLengthMismatch(propertyName);
922
- return;
923
- }
924
- // Visit each element with index tracking
925
- for (let i = 0; i < array1.length; i++) {
926
- this.debug.pushPath(i.toString());
927
- try {
928
- await visitor(array1[i], array2[i], i);
929
- if (!this.match) {
930
- return;
931
- }
932
- }
933
- finally {
934
- this.debug.popPath();
935
- }
936
- }
937
- }
938
- finally {
939
- this.debug.popPath();
940
- }
941
- }
942
- async matchSequence(patternElements, targetElements, filterEmpty) {
943
- var _a, _b;
944
- // Push path component for the container
945
- // Extract kind from cursors if available
946
- const pattern = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.value;
947
- if (pattern && pattern.kind) {
948
- const kindStr = this.formatKind(pattern.kind);
949
- // Determine property name based on the kind
950
- let propertyName = 'elements';
951
- if (pattern.kind.includes('MethodInvocation')) {
952
- propertyName = 'arguments';
953
- }
954
- else if (pattern.kind.includes('Block')) {
955
- propertyName = 'statements';
956
- }
957
- this.debug.pushPath(`${kindStr}#${propertyName}`);
958
- }
959
- try {
960
- return await super.matchSequence(patternElements, targetElements, filterEmpty);
961
- }
962
- finally {
963
- if ((_b = this.cursor) === null || _b === void 0 ? void 0 : _b.value) {
964
- this.debug.popPath();
965
- }
966
- }
967
- }
968
- async visitSequenceElement(patternWrapper, targetWrapper, targetIdx) {
969
- this.debug.pushPath(targetIdx.toString());
970
- try {
971
- // Save current state for backtracking (both match state and capture bindings)
972
- const savedMatch = this.match;
973
- const savedState = this.matcher.saveState();
974
- await this.visitRightPadded(patternWrapper, targetWrapper);
975
- if (!this.match) {
976
- // Preserve explanation before restoring state
977
- const explanation = this.debug.getExplanation();
978
- // Restore state on match failure
979
- this.match = savedMatch;
980
- this.matcher.restoreState(savedState);
981
- // Restore the explanation if one was set during matching
982
- if (explanation) {
983
- this.debug.restoreExplanation(explanation);
984
- }
985
- return false;
986
- }
987
- return true;
988
- }
989
- finally {
990
- this.debug.popPath();
991
- }
992
- }
993
- async matchSequenceOptimized(patternElements, targetElements, patternIdx, targetIdx, filterEmpty) {
994
- var _a, _b;
995
- if (patternIdx >= patternElements.length) {
996
- return targetIdx >= targetElements.length;
997
- }
998
- const patternWrapper = patternElements[patternIdx];
999
- const captureMarker = utils_1.PlaceholderUtils.getCaptureMarker(patternWrapper);
1000
- const isVariadic = (captureMarker === null || captureMarker === void 0 ? void 0 : captureMarker.variadicOptions) !== undefined;
1001
- if (isVariadic) {
1002
- const variadicOptions = captureMarker.variadicOptions;
1003
- const min = (_a = variadicOptions === null || variadicOptions === void 0 ? void 0 : variadicOptions.min) !== null && _a !== void 0 ? _a : 0;
1004
- const max = (_b = variadicOptions === null || variadicOptions === void 0 ? void 0 : variadicOptions.max) !== null && _b !== void 0 ? _b : Infinity;
1005
- let nonVariadicRemainingPatterns = 0;
1006
- let allRemainingPatternsAreDeterministic = true;
1007
- for (let i = patternIdx + 1; i < patternElements.length; i++) {
1008
- const nextCaptureMarker = utils_1.PlaceholderUtils.getCaptureMarker(patternElements[i]);
1009
- const nextIsVariadic = (nextCaptureMarker === null || nextCaptureMarker === void 0 ? void 0 : nextCaptureMarker.variadicOptions) !== undefined;
1010
- if (!nextIsVariadic) {
1011
- nonVariadicRemainingPatterns++;
1012
- }
1013
- if (nextCaptureMarker) {
1014
- allRemainingPatternsAreDeterministic = false;
1015
- }
1016
- }
1017
- const remainingTargetElements = targetElements.length - targetIdx;
1018
- const maxPossible = Math.min(remainingTargetElements - nonVariadicRemainingPatterns, max);
1019
- let pivotDetected = false;
1020
- let pivotAt = -1;
1021
- // Skip pivot detection if we're using deterministic optimization
1022
- // (when all remaining patterns are literals, there's only ONE valid consumption amount)
1023
- const useDeterministicOptimization = allRemainingPatternsAreDeterministic && maxPossible >= min && maxPossible <= max;
1024
- if (!useDeterministicOptimization && patternIdx + 1 < patternElements.length && min <= maxPossible) {
1025
- const nextPattern = patternElements[patternIdx + 1];
1026
- for (let tryConsume = min; tryConsume <= maxPossible; tryConsume++) {
1027
- if (targetIdx + tryConsume < targetElements.length) {
1028
- const candidateElement = targetElements[targetIdx + tryConsume];
1029
- if (filterEmpty && candidateElement.element.kind === java_1.J.Kind.Empty) {
1030
- continue;
1031
- }
1032
- const savedMatch = this.match;
1033
- const savedState = this.matcher.saveState();
1034
- await this.visitRightPadded(nextPattern, candidateElement);
1035
- const matchesNext = this.match;
1036
- this.match = savedMatch;
1037
- this.matcher.restoreState(savedState);
1038
- if (matchesNext) {
1039
- pivotDetected = true;
1040
- pivotAt = tryConsume;
1041
- break;
1042
- }
1043
- }
1044
- }
1045
- }
1046
- const consumptionOrder = [];
1047
- // OPTIMIZATION: If all remaining patterns are deterministic (literals, not captures),
1048
- // there's only ONE mathematically valid consumption amount. Skip backtracking entirely.
1049
- // Example: foo(${args}, 999) matching foo(1,2,42) -> args MUST be [1,2], only try consume=2
1050
- if (useDeterministicOptimization) {
1051
- consumptionOrder.push(maxPossible);
1052
- }
1053
- else if (pivotDetected && pivotAt >= 0) {
1054
- consumptionOrder.push(pivotAt);
1055
- for (let c = maxPossible; c >= min; c--) {
1056
- if (c !== pivotAt) {
1057
- consumptionOrder.push(c);
1058
- }
1059
- }
1060
- }
1061
- else {
1062
- for (let c = maxPossible; c >= min; c--) {
1063
- consumptionOrder.push(c);
1064
- }
1065
- }
1066
- for (const consume of consumptionOrder) {
1067
- // Capture elements for this consumption amount
1068
- // For empty argument lists, there will be a single J.Empty element that we need to filter out
1069
- const rawWrappers = targetElements.slice(targetIdx, targetIdx + consume);
1070
- const capturedWrappers = filterEmpty
1071
- ? rawWrappers.filter(w => w.element.kind !== java_1.J.Kind.Empty)
1072
- : rawWrappers;
1073
- const capturedElements = capturedWrappers.map(w => w.element);
1074
- // Check min/max constraints against filtered elements
1075
- if (capturedElements.length < min || capturedElements.length > max) {
1076
- continue;
1077
- }
1078
- if (captureMarker.constraint) {
1079
- this.debug.log('debug', 'constraint', `Evaluating variadic constraint for capture: ${captureMarker.captureName} (${capturedElements.length} elements)`);
1080
- const cursor = this.targetCursor || new __1.Cursor(targetElements[0]);
1081
- const constraintResult = captureMarker.constraint(capturedElements, this.buildConstraintContext(cursor));
1082
- if (!constraintResult) {
1083
- this.debug.log('info', 'constraint', `Variadic constraint failed for capture: ${captureMarker.captureName}`);
1084
- continue;
1085
- }
1086
- this.debug.log('debug', 'constraint', `Variadic constraint passed for capture: ${captureMarker.captureName}`);
1087
- }
1088
- const savedState = this.matcher.saveState();
1089
- const success = await this.matcher.handleVariadicCapture(captureMarker, capturedElements, capturedWrappers);
1090
- if (!success) {
1091
- this.matcher.restoreState(savedState);
1092
- continue;
1093
- }
1094
- const restMatches = await this.matchSequenceOptimized(patternElements, targetElements, patternIdx + 1, targetIdx + consume, filterEmpty);
1095
- if (restMatches) {
1096
- return true;
1097
- }
1098
- // Preserve explanation from this failed attempt before restoring state
1099
- // This is especially important when using deterministic optimization (only one attempt)
1100
- const currentExplanation = this.debug.getExplanation();
1101
- this.matcher.restoreState(savedState);
1102
- // Restore the explanation if one was set during this attempt
1103
- if (currentExplanation) {
1104
- this.debug.restoreExplanation(currentExplanation);
1105
- }
1106
- }
1107
- return false;
1108
- }
1109
- else {
1110
- if (targetIdx >= targetElements.length) {
1111
- return false;
1112
- }
1113
- const targetWrapper = targetElements[targetIdx];
1114
- const targetElement = targetWrapper.element;
1115
- if (filterEmpty && targetElement.kind === java_1.J.Kind.Empty) {
1116
- return false;
1117
- }
1118
- if (!await this.visitSequenceElement(patternWrapper, targetWrapper, targetIdx)) {
1119
- return false;
1120
- }
1121
- return await this.matchSequenceOptimized(patternElements, targetElements, patternIdx + 1, targetIdx + 1, filterEmpty);
1122
- }
1123
- }
1124
- }
1125
- exports.DebugPatternMatchingComparator = DebugPatternMatchingComparator;
1126
533
  //# sourceMappingURL=comparator.js.map