(n: number, k: number)
| 909 | } else { |
| 910 | // OptionalSequence |
| 911 | optionalSeqWildcards.push(op); |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | // Early termination: check if we have enough elements |
| 916 | const minNeeded = |
| 917 | anchors.length + universalWildcards.length + sequenceWildcards.length; |
| 918 | const maxAllowed = |
| 919 | anchors.length + |
| 920 | universalWildcards.length + |
| 921 | (sequenceWildcards.length + optionalSeqWildcards.length > 0 ? Infinity : 0); |
| 922 | |
| 923 | if (exprOps.length < minNeeded) return null; |
| 924 | if ( |
| 925 | sequenceWildcards.length === 0 && |
| 926 | optionalSeqWildcards.length === 0 && |
| 927 | exprOps.length > maxAllowed |
| 928 | ) |
| 929 | return null; |
| 930 | |
| 931 | // Sort anchors by specificity (most specific first) |
| 932 | // This reduces backtracking by pruning impossible branches early |
| 933 | const sortedAnchors = [...anchors].sort( |
| 934 | (a, b) => anchorSpecificity(b) - anchorSpecificity(a) |
| 935 | ); |
| 936 | |
| 937 | // Try to match anchors against expression elements using backtracking |
| 938 | return tryMatchAnchors(0, exprOps, substitution); |
| 939 | |
| 940 | function tryMatchAnchors( |
| 941 | anchorIndex: number, |
| 942 | remainingOps: Expression[], |
| 943 | sub: BoxedSubstitution |
| 944 | ): BoxedSubstitution | null { |
| 945 | // All anchors matched - now assign remaining ops to wildcards |
| 946 | if (anchorIndex >= sortedAnchors.length) { |
| 947 | return assignWildcards(remainingOps, sub); |
no test coverage detected