Skip to content

Fix String.endsWith for overlapping regex matches - #1880

Merged
HT154 merged 1 commit into
apple:mainfrom
kwy404:fix-string-endswith-regex
Sep 30, 2026
Merged

HT154 merged 1 commit into
apple:mainfrom
kwy404:fix-string-endswith-regex

Conversation

@kwy404

@kwy404 kwy404 commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Root cause

The regex overload of String.endsWith loops over Matcher.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, like Regex("a|ab") on "ab") is never tried:

"aaa".endsWith(Regex("aa"))          // false, expected true
"1.2.3".endsWith(Regex(#"\d\.\d"#))  // false, expected true

The String overload already gets this right ("aaa".endsWith("aa") is true).

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 \b looking at the text before the suffix, and non-anchoring bounds keep ^ from matching at the start of the region, so ^, \b and lookbehind behave as before.

Test

Added endsWith() facts with regex patterns to the api/string language snippet test, including \b and ^ cases. Before the fix, LanguageSnippetTests fails on api/string.pkl because "aaa".endsWith(Regex("aa")) is false. After the fix it passes, and ./gradlew :pkl-core:spotlessCheck is clean.

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 bioball left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());
     }
   }

@HT154

HT154 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

I think a better fix here is to create a derived pattern and adding the $ anchor.

This doesn't appear to work in the general case, particularly when the multiline regex flag is enabled ((?m) in the pattern). With your impl:

res =
  """
  bb
  cc
  bb
  cc
  dd
  """.endsWith(Regex("(?m)^bb\ncc\nbb"))
// res = true

This 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.

@bioball

bioball commented Sep 30, 2026

Copy link
Copy Markdown
Member

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?

@HT154 HT154 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm okay with getting this PR in as-is, then, and we can follow up with optimizations. WDYT?

Sounds good to me!

Thanks again for the fix @kwy404

@HT154
HT154 merged commit 8331570 into apple:main Sep 30, 2026
25 checks passed
bioball added a commit that referenced this pull request Oct 5, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants