Repository navigation
Perf improvements for String.endWith(Regex) - #1884
Conversation
* Compute a derived regex expression with `$` anchor * Keep around current implementation if multiline flag is set * Ensure derived regex can't be messed up with comments (in extended mode)
fd17d5d to
d6607b8
Compare
There was a problem hiding this comment.
There are a couple problems with the current implementation:
// unclosed \Q, which is valid
res = "x)".endsWith(Regex(#"x\Q)"#))errors with
java.util.regex.PatternSyntaxException%3A%20Unclosed%20group%20near%20index%2010%0A%28%3F%3Ax%5CQ%29%29%24
–– Pkl Error ––
Unclosed group near index 10
(?:x\Q))$
Here a bunch of cases that are failing:
amends "pkl:test"
facts {
["comment mode"] {
"zz".endsWith(Regex("(?x)zz"))
"zz".endsWith(Regex("(?x) zz # comment"))
}
["unicode"] {
"a\né".endsWith(Regex(#"(?x)\w"#))
"a\nÉ".endsWith(Regex("(?x)(?i)é"))
"é".endsWith(Regex(#"\w"#)) // this works
}
["trailing new lines"] {
!"foo\n".endsWith(Regex("foo"))
!"foo\r\n".endsWith(Regex("foo"))
!"foo\n".endsWith("foo") // this works
}
["overlap multiline"] {
"a\nb".endsWith(Regex(#"(?m)a(?:\nb)??"#))
}
}All of these pass on current main. They should be added to the tests.
There was a problem hiding this comment.
Great catches, all fixed!
I switched to using the \z anchor, which also means that we can get rid of the special-cased (?m) flag handling, which is great.
There was a problem hiding this comment.
Inline flags are now applying to the whole pattern, so flags at the middle/end of a pattern affect the whole thing:
amends "pkl:test"
facts {
["global flags"] {
!"Ab".endsWith(Regex("a(?i)b"))
!"x\n".endsWith(Regex("x.(?s)"))
"a b".endsWith(Regex("a b(?x)"))
}
}They were all passing before.
| String self, | ||
| VmRegex regex, | ||
| @Cached("regex") VmRegex cachedRegex, | ||
| @Cached("computePattern(cachedRegex)") Pattern pattern) { |
There was a problem hiding this comment.
nit: truffle only caches up to 3 values by default, so if you have code like function hasSuffix(s, r: Regex) = s.endsWith(r) you can easily run out of cache space and recompile all the time.
I think it'd be better to cache the pattern in the VmRegex itself. Which is how it works in Java and most languages (compile once, use everywhere).
There was a problem hiding this comment.
Now sure what you mean by Java? Java's Pattern.compile compiles every time.
Our existing Regex() constructor has the same limitation; i.e. this code can possibly re-compile all the time once it gets past three instances of the cached version:
function makeRegex(r: String) = Regex(r)It's a tradeoff between memory and CPU here; we can adjust the specialization limit if we need to. But I think the 99% case here is that these regexes will be declared literally, e.g.
foo.endsWith(Regex("bar|baz"))So, I'm not too concerned about the uncached-variant.
\zanchorFollow up to #1880