Skip to content

perf(string): zero-copy string.find, Lua 5.4 semantics, and pattern class-prefix scan - #71

Merged
esrrhs merged 2 commits into
masterfrom
perf/string-find-zerocopy-pattern
Dec 2, 2026
Merged

esrrhs merged 2 commits into
masterfrom
perf/string-find-zerocopy-pattern

Conversation

@esrrhs

@esrrhs esrrhs commented Dec 1, 2026

Copy link
Copy Markdown
Owner

What changed

P2 follow-up after PR #68 and the P1 call-dispatch work: close the remaining string.find / pattern-match gaps and a few Lua 5.4 semantic holes. Editable C runtime source remains src/compile/c_runtime_cov.h (CMake embeds it; this PR does not invent a second copy).

  1. string.find zero-copy and Lua 5.4 semantics (src/native/string/native_string.cpp)

    • Delete the unconditional std::string sub = sv.substr(...) copy that ran before the plain branch and was unused on the pattern path.
    • Plain search uses sv.substr(init_pos - 1).find(pat_view) with no heap copy.
    • nospecials: if the pattern contains none of PUC-Rio SPECIALS (^$*+?.([%-, not )), find uses the plain path. Fixes string.find("abc10)def", "10)") → 4, 6 instead of invalid pattern capture.
    • The 4th argument plain is a Lua truth value (inter::CVarToBool, only nil/false are false). Fixes string.find("a.b", ".", 1, 1).
    • string.gmatch(s, pattern [, init]) is vararg and accepts the Lua 5.4 optional 1-based init (explicit nil equals omit; same position normalization as find).
    • string.gsub replacement %1 with no captures (level == 0) is the whole match, like %0. %2 and higher still error.
  2. JIT / TCC string fast paths (src/compile/c_runtime_cov.h)

    • FlStringFindPlain uses memchr + memcmp, same idea as PR perf(string): literal-prefix memchr scan and tighter dispatch in the Lua pattern engine #68's literal-prefix Search.
    • For FAKELUA_JIT_TYPE == 0 (TCC, no -O3), FlStringLower / FlStringUpper / FlStringReverse call host -O3 helpers FlHostStringLower / Upper / Reverse defined in src/native/string/native_string.cpp and registered in src/jit/tcc_handle.cpp. GCC keeps the inlined loops (already compiled with -O3).
  3. Pattern Search class-prefix scan; gmatch/gsub reuse it (src/native/string/lua_pattern.cpp, native_string.cpp)

    • When there is no literal prefix, Search skips leading captures and, if the first required item is a character class/set (or a literal only visible after those captures), precompiles an ItemBits first-byte bitmap (or memchr for a literal) and only calls RunAt at candidate positions. Covers [0-9]+, %d+, %w+, (%d+).
    • Search takes leading_caret_is_anchor (default true). gmatch and unanchored gsub call it with false so a leftover ^ is a literal (after gsub has already stripped a leading anchor).
    • This also fixes string.gsub("^abc", "^^", "X") (Lua 5.4: Xabc), which previously stripped a second ^ via MatchAt's default anchor behavior.

Tests

New fixtures in test/lua/string/, wired through test/test_string.cpp on INTERP / TCC / GCC:

  • test_string_find_nospecials
  • test_string_find_plain_truthiness
  • test_string_gmatch_init
  • test_string_gsub_percent1_whole_match (includes %1/%0/%2 and the ^^ anchor/literal case)

C++ regressions in test_string_lua_pattern_cpp_regressions cover class-prefix Search and leading_caret_is_anchor=false.

Local run (Release unit_tests, cwd = build bin/, --gtest_filter='test_string.*:common.c_runtime_cov_matches_kCRuntimeHeader'):

  • common.c_runtime_cov_matches_kCRuntimeHeader passed.
  • Passed on all three backends: existing test_string_{len,sub,rep,case,byte_char,format,dump,lua_pattern,find,match,gmatch,gsub} plus test_string_lua_pattern_cpp_regressions and the new nospecials / plain-truthiness / gmatch-init tests.
  • During test_string_gsub_percent1_whole_match (after the first two backends had already run the expected %2 pcall), the entire build-cpm-fix tree was deleted from outside this work, so the remaining test_string.* cases were not finished locally. Please treat CI as the complete run.
  • Semantics of the four Lua 5.4 edges were also checked against PUC Lua 5.4.7 (lua on this machine; 5.4.8 was not installed).
  • No end-to-end benchmark was run (the build directory disappeared before a bench pass). Do not treat earlier master numbers as results of this branch.

Plan

No merge and no branch deletion from this PR.

…lass-prefix scan

Remove the unused subject-string copy on the string.find pattern path and
use string_view::find for plain searches. Honor PUC-Rio nospecials (so a
pattern like "10)" is a literal), treat the plain flag as a Lua truth
value, accept string.gmatch's optional init, and map %1 to the whole match
in gsub when there are no captures.

Search now precompiles a first-byte class/set bitmap (after skipping
leading captures) so patterns such as %d+ and [0-9]+ skip non-matching
bytes before entering the matcher. gmatch and unanchored gsub reuse that
Search fast path. FlStringFindPlain uses memchr+memcmp, and TCC JIT
lower/upper/reverse call host -O3 helpers instead of unoptimized loops.
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 92.02899% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.56%. Comparing base (358697f) to head (3808a60).

Files with missing lines Patch % Lines
src/native/string/native_string.cpp 84.93% 11 Missing ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #71      +/-   ##
==========================================
+ Coverage   94.55%   94.56%   +0.01%     
==========================================
  Files         130      130              
  Lines       32425    32496      +71     
==========================================
+ Hits        30659    30731      +72     
+ Misses       1766     1765       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@esrrhs
esrrhs merged commit b686d2e into master Dec 2, 2026
1 of 9 checks passed
@esrrhs
esrrhs deleted the perf/string-find-zerocopy-pattern branch December 2, 2026 02:13
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.

2 participants