Repository navigation
Fix String.endsWith for overlapping regex matches - #1880
Conversation
The regex overload looped over `Matcher.find()` and checked whether the
last match ended at the end of the string. `find()` skips matches that
overlap an earlier one, so `"aaa".endsWith(Regex("aa"))` returned false.
Try each suffix with `matches()` on a region instead. Transparent bounds
keep lookbehind and `\b` looking at the text before the suffix, and
non-anchoring bounds keep `^` from matching at the region start.
bioball
left a comment
There was a problem hiding this comment.
Thanks for the PR, and for spotting this bug!
I think a better fix here is to create a derived pattern and adding the $ anchor.
This should also perform better; the current solution (and your PR) are both linear.
I played around with this, and I think this should do it. Note the usage of cacheing when computing the derived pattern.
diff --git a/pkl-core/src/main/java/org/pkl/core/stdlib/base/StringNodes.java b/pkl-core/src/main/java/org/pkl/core/stdlib/base/StringNodes.java
index c125bd7b..a4e9dcdf 100644
--- a/pkl-core/src/main/java/org/pkl/core/stdlib/base/StringNodes.java
+++ b/pkl-core/src/main/java/org/pkl/core/stdlib/base/StringNodes.java
@@ -17,6 +17,7 @@ package org.pkl.core.stdlib.base;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
+import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.LoopNode;
import java.io.UnsupportedEncodingException;
@@ -332,14 +333,28 @@ public final class StringNodes {
}
@TruffleBoundary
- @Specialization
- protected boolean eval(String self, VmRegex regex) {
- // try every suffix; `find()` would skip matches that overlap an earlier one
- var matcher = regex.matcher(self).useTransparentBounds(true).useAnchoringBounds(false);
- for (var start = self.length(); ; start = self.offsetByCodePoints(start, -1)) {
- if (matcher.region(start, self.length()).matches()) return true;
- if (start == 0) return false;
+ @Specialization(guards = "regex.equals(cachedRegex)")
+ protected boolean evalRegexCached(
+ String self,
+ VmRegex regex,
+ @Cached("regex") VmRegex cachedRegex,
+ @Cached("computedPattern(cachedRegex)") Pattern computedPattern) {
+ return computedPattern.matcher(self).find();
+ }
+
+ @Specialization(replaces = "evalRegexCached")
+ protected boolean evalRegex(String self, VmRegex regex) {
+ var computedPattern = computedPattern(regex);
+ return computedPattern.matcher(self).matches();
+ }
+
+ protected Pattern computedPattern(VmRegex regex) {
+ var existingPattern = regex.getPattern();
+ if (existingPattern.pattern().endsWith("$")) {
+ return existingPattern;
}
+ //noinspection RegExpUnnecessaryNonCapturingGroup
+ return Pattern.compile("(?:" + existingPattern.pattern() + ")$", existingPattern.flags());
}
}
This doesn't appear to work in the general case, particularly when the multiline regex flag is enabled ( res =
"""
bb
cc
bb
cc
dd
""".endsWith(Regex("(?m)^bb\ncc\nbb"))
// res = trueThis optimization may still be worthwhile if the regex doesn't have the multiline flag set (most typical case in my experience), but we may need to fall back on the linear implementation when it is enabled. |
|
Ah yeah, good point with the multiline flag. I'm okay with getting this PR in as-is, then, and we can follow up with optimizations. WDYT? |
* Compute a derived regex expression with `\z` anchor * Ensure derived regex can't be messed up with comments (in extended mode) or quote start Follow up to #1880
Root cause
The regex overload of
String.endsWithloops overMatcher.find()and checks whether the last match ends at the end of the string.find()only returns non-overlapping matches, and only one alternative per start position, so a suffix that starts inside an earlier match (or needs another alternative, likeRegex("a|ab")on"ab") is never tried:The
Stringoverload already gets this right ("aaa".endsWith("aa")istrue).Fix
Try each suffix, starting from the end, with
matches()on a region of the string, stepping by code point. Transparent bounds keep lookbehind and\blooking at the text before the suffix, and non-anchoring bounds keep^from matching at the start of the region, so^,\band lookbehind behave as before.Test
Added
endsWith()facts with regex patterns to theapi/stringlanguage snippet test, including\band^cases. Before the fix,LanguageSnippetTestsfails onapi/string.pklbecause"aaa".endsWith(Regex("aa"))isfalse. After the fix it passes, and./gradlew :pkl-core:spotlessCheckis clean.