From f6e9075a73a780803386246d18f8482b09405f34 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 18 Nov 2026 19:29:25 +0100 Subject: [PATCH] fix(scripting): a %b counts the way it walks along the subject A %bxy at the end of a pattern (or before what always matches) was costed as one pass over the subject, but matchbalance walks to the end of the subject from every opening character nothing closes: ("("):rep(1e6):find("%b()") was let through and ran for hours in C, past the instruction hook. A %b now multiplies wherever it stands. With the subject at hand it counts the longest way from an opening character to its closing one, or, when it is tried once from each position, the ways from all of them over the positions: a long text of short balanced pairs stays cheap, one that doesn't balance is refused. --- scripting/scriptscreenrules.cpp | 87 ++++++++++++++++++++++++++ scripting/scriptscreenrules.h | 6 ++ tests/unit/test_script_screen_host.cpp | 8 ++- tests/unit/test_script_screens.cpp | 44 +++++++++++++ 4 files changed, 144 insertions(+), 1 deletion(-) diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index e8df2692e..5aa71cdd4 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -309,6 +309,84 @@ std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item return longest; } +// the characters Lua's matchbalance goes along for a %bxy tried in the subject: from each opening character to the one +// that closes it, or to the end of the subject when nothing does +struct balance_walks +{ + double longest{0.0}; // of one try + double total{0.0}; // of a try at every opening character +}; + +// the openings held while their closing characters are looked for; a subject nested deeper counts as never closed +constexpr std::size_t max_balance_depth{65536}; + +balance_walks balance_walks_of(char const Open, char const Close, std::string_view const Subject) +{ + balance_walks walks; + auto const size{Subject.size()}; + auto const add{[&walks](std::size_t const Walk) { + walks.longest = std::max(walks.longest, static_cast(Walk)); + walks.total += static_cast(Walk); + }}; + if (Open == Close) + { + // the next one closes it, and opens the try that starts there + auto previous{Subject.find(Open)}; + while (previous != std::string_view::npos) + { + auto const next{Subject.find(Open, previous + 1)}; + add((next != std::string_view::npos ? next : size) - previous); + previous = next; + } + return walks; + } + std::vector open; + for (std::size_t idx{0}; idx < size; ++idx) + { + if (Subject[idx] == Close) + { + if (false == open.empty()) + { + add(idx - open.back()); + open.pop_back(); + } + } + else if (Subject[idx] == Open) + { + if (open.size() >= max_balance_depth) + { + auto const openings{static_cast(std::count(Subject.begin(), Subject.end(), Open))}; + return {static_cast(size), openings * static_cast(size)}; + } + open.push_back(idx); + } + } + for (auto const idx : open) + { + add(size - idx); + } + return walks; +} + +// how many times over a %bxy counts: it goes along the subject on its own, whatever follows it, so it counts where it +// ends the pattern as well. without the subject, as many times as the subject has positions. with it: the longest walk +// of one try (plus one); or, when nothing but captures is before it in a pattern tried from every position, each +// opening character is tried once, and it's the walks of all of them over the positions (plus one) +double balance_cost(std::string_view const Pattern, pattern_item const &Item, std::string_view const *Subject, double const Positions, bool const Once) +{ + if (Subject == nullptr) + { + return Positions; + } + if (Item.begin + 3 >= Pattern.size()) + { + // malformed: the function raises its error + return 1.0; + } + auto const walks{balance_walks_of(Pattern[Item.begin + 2], Pattern[Item.begin + 3], *Subject)}; + return Once ? 1.0 + walks.total / Positions : 1.0 + walks.longest; +} + double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable) { auto const length{static_cast(std::max(Pattern.size(), 1))}; @@ -324,12 +402,21 @@ double pattern_cost(std::string_view const Pattern, std::size_t const Size, std: // from the end: what follows each item, and whether that's only the end of the subject auto rest{rest_match::always}; auto only_end{true}; + // the first item that isn't a capture: a %bxy there is tried once from each position + auto const first{std::find_if(items.begin(), items.end(), [](pattern_item const &Item) { return Item.type != pattern_item::kind::paren; })}; for (auto item{items.rbegin()}; item != items.rend(); ++item) { if (item->type == pattern_item::kind::single && item->quantifier == '?') { cost *= 2.0; } + if (item->type == pattern_item::kind::scan && Pattern[item->begin + 1] == 'b') + { + cost *= balance_cost(Pattern, *item, Subject, positions, false == anchored && first != items.end() && &*item == &*first); + only_end = false; + rest = rest_match::maybe; + continue; + } auto const repeated{item->type == pattern_item::kind::scan || (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')}; // a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index 889f7e9c3..bd751e50b 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -92,11 +92,17 @@ constexpr double max_pattern_cost{1e8}; // or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last // repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step // (a set is gone through item by item) +// - a %bxy goes along the subject on its own, whatever follows it, so it counts where it ends the pattern as well: +// ("("):rep(1e6):find("%b()") walks to the end of the subject from each of its characters // a malformed pattern costs nothing here: the function raises its error itself double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); // as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts // as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or // gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces +// a %bxy counts as many times as the longest way from an opening character to the one that closes it (to the end of +// the subject when nothing does), plus one; when only captures are before it in a pattern tried from every position, +// each opening character is tried once, and it's the ways from all of them over the positions of the subject. so +// "%b()" on a long text of short balanced pairs is cheap, and on one that doesn't balance it's the subject squared double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); } // namespace script_screens diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 7c7130f85..c4226da40 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -1171,6 +1171,11 @@ local slow = refused(string.find, long, ".-b") and refused(function() for x in long:gmatch("a-b") do end end) and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- %b walks to the end of the subject from each opening character that nothing closes +local open = ("("):rep(1000000) +slow = slow and refused(string.find, open, '%b()') + and refused(string.gsub, open, '%b()', "") + and refused(function() for x in open:gmatch('%b()') do end end) -- what a screen does: lines of a file, fields of a line, a plain search, short subjects local text = ("key=value\n"):rep(10000) local lines = 0 @@ -1178,7 +1183,8 @@ for line in text:gmatch("[^\n]+") do lines = lines + 1 end local key, value = ("speed=120"):match("^(%w+)=(%d+)$") local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 -local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found +local calls = select(2, (("call(a, b) "):rep(10000)):gsub('%b()', "")) +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found and calls == 10000 and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" return { render = function(state) diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 59aa19560..af8678f2e 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -136,6 +136,10 @@ TEST_CASE("script screens: the steps a Lua pattern function may take at worst") CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // %b goes along the subject on its own: it counts where it ends the pattern too + CHECK(lua_pattern_cost("%b()", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); + CHECK(lua_pattern_cost("(%b())", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%b().*", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); // '?' doubles @@ -173,6 +177,46 @@ TEST_CASE("script screens: a repetition followed by what always matches doesn't CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); } +TEST_CASE("script screens: %b counts the way from an opening character to the one that closes it") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // nothing closes: from each character to the end of the subject, the subject squared; whatever follows the %b + auto const open{std::string(1'000'000, '(')}; + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, false) > max_pattern_cost); + CHECK(lua_pattern_cost("(%b())", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b().*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()x*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open + open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 10'000), false, true) > max_pattern_cost); + // the same with a hundred thousand of them, more than the openings held at a time + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 100'000), false, true) > max_pattern_cost); + // tried once from each position: the positions and the ways from the three openings, 2 + 5 + 2 + std::string_view const calls{"a(b)c(d(e))"}; + CHECK(lua_pattern_cost("%b()", calls, false, true) == doctest::Approx((12.0 + 9.0) * 4)); + CHECK(lua_pattern_cost("(%b())", calls, false, true) == doctest::Approx((12.0 + 9.0) * 6)); + // tried from the first position only, or after a repetition: the longest way of one try, and one + CHECK(lua_pattern_cost("^%b()", calls, false, true) == doctest::Approx(6.0 * 5)); + CHECK(lua_pattern_cost(".-%b()", calls, false, true) == doctest::Approx(12.0 * 12 * 6 * 6)); + // the same character opens and closes: to the next one + CHECK(lua_pattern_cost("%b\"\"", std::string_view{"a\"b\"c\""}, false, true) == doctest::Approx((7.0 + 5.0) * 4)); + // none in the subject: nothing to go along + CHECK(lua_pattern_cost("%b()", std::string_view{"abc"}, false, true) == doctest::Approx(4.0 * 4)); + // a long text of short calls is cheap, and so is one opening left unclosed in it + std::string text; + while (text.size() < 100'000) { + text += "call(a, b) "; + } + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + text[9] = ' '; + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + // nested deep, the ways add up to the subject squared again + auto const nested{std::string(20'000, '(') + std::string(20'000, ')')}; + CHECK(lua_pattern_cost("%b()x", std::string_view{nested}, false, true) > max_pattern_cost); + // malformed: the function raises its error + CHECK(lua_pattern_cost("%b(", std::string_view{open}, false, true) > 0.0); +} + TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") { using script_screens::lua_pattern_cost; using script_screens::max_pattern_cost;