react-nitro-hermes 0.0.1-alpha.8 → 0.0.1-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/hermes/CMakeLists.txt +874 -0
  2. package/hermes/android/HostObjectJniTest.cpp +178 -0
  3. package/hermes/android/build-logic/build.gradle.kts +31 -0
  4. package/hermes/android/build-logic/settings.gradle.kts +17 -0
  5. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/helpers/internal/SerializeHermesCompilerPackageJson.kt +33 -0
  6. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/plugins/internal/TestUtilsPlugin.kt +80 -0
  7. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/tasks/internal/CustomExecTask.kt +46 -0
  8. package/hermes/android/build-logic/src/main/kotlin/publish.gradle.kts +82 -0
  9. package/hermes/android/build.gradle.kts +332 -0
  10. package/hermes/android/cppruntime/build.gradle +72 -0
  11. package/hermes/android/cppruntime/src/main/AndroidManifest.xml +2 -0
  12. package/hermes/android/cppruntime/src/main/cpp/CMakeLists.txt +8 -0
  13. package/hermes/android/cppruntime/src/main/cpp/stub.cpp +12 -0
  14. package/hermes/android/cross-compile/swift-libicu.patch +13 -0
  15. package/hermes/android/cross-compile/toolchain-android-arm-api13-gnustl.cmake +13 -0
  16. package/hermes/android/cross-compile/toolchain-android-arm-api15-gnustl.cmake +14 -0
  17. package/hermes/android/gradle/libs.versions.toml +30 -0
  18. package/hermes/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  19. package/hermes/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  20. package/hermes/android/gradle.properties +3 -0
  21. package/hermes/android/gradlew +248 -0
  22. package/hermes/android/gradlew.bat +93 -0
  23. package/hermes/android/intltest/build.gradle +147 -0
  24. package/hermes/android/intltest/java/com/facebook/hermes/test/CMakeLists.txt +45 -0
  25. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.cpp +68 -0
  26. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.h +44 -0
  27. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.java +45 -0
  28. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogueTestData.java +32 -0
  29. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesInstrumentationTest.java +150 -0
  30. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlAndroidTest.java +147 -0
  31. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlTest262.java +470 -0
  32. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesRuntimeFactory.cpp +73 -0
  33. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.cpp +90 -0
  34. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.h +62 -0
  35. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.java +155 -0
  36. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.cpp +48 -0
  37. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.h +36 -0
  38. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoad.cpp +13 -0
  39. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoadEpilogue.cpp +13 -0
  40. package/hermes/android/intltest/src/main/AndroidManifest.xml +2 -0
  41. package/hermes/android/ios-artifacts/build.gradle.kts +65 -0
  42. package/hermes/android/settings.gradle.kts +27 -0
  43. package/hermes/cmake/modules/Hermes.cmake +481 -0
  44. package/hermes/cmake/modules/Lit.cmake +96 -0
  45. package/hermes/doc/Branches.md +38 -0
  46. package/hermes/doc/BuildingAndRunning.md +121 -0
  47. package/hermes/doc/CodingStandards.md +112 -0
  48. package/hermes/doc/CrossCompilation.md +79 -0
  49. package/hermes/doc/Design.md +217 -0
  50. package/hermes/doc/Emscripten.md +156 -0
  51. package/hermes/doc/Features.md +143 -0
  52. package/hermes/doc/GCSafeCoding.md +563 -0
  53. package/hermes/doc/GenGC.md +300 -0
  54. package/hermes/doc/Hades.md +344 -0
  55. package/hermes/doc/HighLevelOptimizations.md +37 -0
  56. package/hermes/doc/IR.md +1306 -0
  57. package/hermes/doc/IntlAPIs.md +196 -0
  58. package/hermes/doc/JIT.md +999 -0
  59. package/hermes/doc/LazyEvalCompilation.md +84 -0
  60. package/hermes/doc/MemoryProfilers.md +316 -0
  61. package/hermes/doc/Modules.md +144 -0
  62. package/hermes/doc/Optimizer.md +83 -0
  63. package/hermes/doc/PerfProfiling.md +29 -0
  64. package/hermes/doc/ProhibitInvoke.md +329 -0
  65. package/hermes/doc/ReactNative.md +40 -0
  66. package/hermes/doc/ReactNativeIntegration.md +94 -0
  67. package/hermes/doc/RegExp.md +24 -0
  68. package/hermes/doc/SpecIncompat.md +85 -0
  69. package/hermes/doc/Strings.md +140 -0
  70. package/hermes/doc/TypedLanguage.md +432 -0
  71. package/hermes/doc/VM.md +174 -0
  72. package/hermes/doc/blog/2024-11-09-octane-benchmark-jit-progress.md +17 -0
  73. package/hermes/doc/blog/2024-12-19-static-hermes-update-dec-2024.md +47 -0
  74. package/hermes/doc/blog/2024-12-23-compiling-javascript-to-wasm.md +267 -0
  75. package/hermes/doc/blog/2025-06-09-jsi-runtime-data-apis.md +23 -0
  76. package/hermes/doc/blog/2025-07-15-static-h-performance-june-2025.md +18 -0
  77. package/hermes/doc/blog/2025-11-02-hermes-compilation-runtime-modes.md +23 -0
  78. package/hermes/doc/blog/2025-11-06-hermes-memory-modes.md +35 -0
  79. package/hermes/doc/blog/2025-11-24-json-parsing-performance.md +17 -0
  80. package/hermes/doc/blog/2025-12-02-iserialization.md +11 -0
  81. package/hermes/doc/blog/2025-12-12-new-way-to-contribute.md +68 -0
  82. package/hermes/doc/blog/2026-06-05-new-hermes-stable-release.md +51 -0
  83. package/hermes/doc/blog/README.md +25 -0
  84. package/hermes/doc/blog/images/2024-11-09-octane-pi3.jpeg +0 -0
  85. package/hermes/doc/blog/images/2024-11-09-octane-pi5.jpeg +0 -0
  86. package/hermes/doc/blog/images/2025-07-15-perf-hv32-interpreter.jpeg +0 -0
  87. package/hermes/doc/blog/images/2025-07-15-perf-hv32-jit.jpeg +0 -0
  88. package/hermes/doc/icu_license.txt +420 -0
  89. package/hermes/doc/img/heap_snapshot_retainers.png +0 -0
  90. package/hermes/doc/img/logo.svg +1 -0
  91. package/hermes/doc/img/object_captured_by_environment.png +0 -0
  92. package/hermes/doc/img/root_categories.png +0 -0
  93. package/hermes/doc/plans/ir-type/flow-type-system.md +324 -0
  94. package/hermes/doc/plans/ir-type/ir-type-system-v2-design.md +652 -0
  95. package/hermes/doc/plans/ir-type/ir-type-system.md +220 -0
  96. package/hermes/doc/plans/ir-type/ir-type-v2-implementation.md +1187 -0
  97. package/hermes/doc/plans/ir-type/memory.md +48 -0
  98. package/hermes/doc/plans/ir-type/phase1-steps.md +512 -0
  99. package/hermes/doc/plans/ir-type/progress.md +239 -0
  100. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-design.md +203 -0
  101. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-results.md +71 -0
  102. package/hermes/doc/superpowers/plans/2026-07-28-worker-arraybuffer-input.md +597 -0
  103. package/hermes/doc/superpowers/plans/2026-08-18-jitemitter-split.md +1149 -0
  104. package/hermes/doc/superpowers/plans/2026-08-20-jit-type-asserts.md +969 -0
  105. package/hermes/doc/superpowers/plans/2026-08-23-jit-shared-compiler-driver.md +478 -0
  106. package/hermes/doc/superpowers/plans/2026-08-23-x86-64-jit-skeleton.md +797 -0
  107. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-arith.md +444 -0
  108. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-calls.md +261 -0
  109. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-props.md +240 -0
  110. package/hermes/doc/superpowers/plans/2026-10-26-regexp-bytecode-sharing.md +2197 -0
  111. package/hermes/doc/superpowers/plans/2026-10-28-regexp-start-filter-and-exec-fast-paths.md +3981 -0
  112. package/hermes/doc/superpowers/specs/2026-07-28-worker-arraybuffer-input-design.md +206 -0
  113. package/hermes/doc/superpowers/specs/2026-08-18-jitemitter-split-design.md +530 -0
  114. package/hermes/doc/superpowers/specs/2026-08-20-jit-type-asserts-design.md +360 -0
  115. package/hermes/doc/superpowers/specs/2026-08-23-x86-64-jit-design.md +246 -0
  116. package/hermes/doc/superpowers/specs/2026-08-26-icu-free-normalize-design.md +355 -0
  117. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-convert-to-case-design.md +305 -0
  118. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-locale-compare-design.md +429 -0
  119. package/hermes/doc/superpowers/specs/2026-08-29-icu-free-date-format-design.md +297 -0
  120. package/hermes/doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md +605 -0
  121. package/hermes/doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md +551 -0
  122. package/hermes/doc/typescript-stripping.md +90 -0
  123. package/hermes/external/CMakeLists.txt +20 -0
  124. package/hermes/utils/IntlGen/IntlGen.java +531 -0
  125. package/hermes/utils/bench_with_stats.py +827 -0
  126. package/hermes/utils/build-apple-framework.sh +323 -0
  127. package/hermes/utils/chrome_snapshot_parser.py +210 -0
  128. package/hermes/utils/cmake-dev-build.sh +18 -0
  129. package/hermes/utils/commons.sh +55 -0
  130. package/hermes/utils/dump-cpp-funcs.sh +3 -0
  131. package/hermes/utils/es5objects.js +198 -0
  132. package/hermes/utils/format.sh +145 -0
  133. package/hermes/utils/gen-promise-internal-bc.sh +66 -0
  134. package/hermes/utils/genUnicodeTable.py +2503 -0
  135. package/hermes/utils/hermes-lit/CMakeLists.txt +22 -0
  136. package/hermes/utils/hermes-lit/hermes-lit.in +15 -0
  137. package/hermes/utils/jit/README.md +134 -0
  138. package/hermes/utils/jit/jit-diff.sh +160 -0
  139. package/hermes/utils/jit/jit-dump.sh +193 -0
  140. package/hermes/utils/lit-expect-gen/generate.py +217 -0
  141. package/hermes/utils/promise/index.js +15 -0
  142. package/hermes/utils/promise/package.json +13 -0
  143. package/hermes/utils/promise/rollup.config.js +19 -0
  144. package/hermes/utils/promise/yarn.lock +247 -0
  145. package/hermes/utils/scripts/hermes/consts.js +26 -0
  146. package/hermes/utils/scripts/hermes/create-tarball.js +75 -0
  147. package/hermes/utils/scripts/hermes/get-hermes-version.js +57 -0
  148. package/hermes/utils/scripts/hermes/hermes-utils.js +122 -0
  149. package/hermes/utils/scripts/hermes/package.json +6 -0
  150. package/hermes/utils/scripts/hermes/prepare-artifacts.js +113 -0
  151. package/hermes/utils/scripts/hermes/publish-artifacts.js +109 -0
  152. package/hermes/utils/scripts/hermes/publish-npm.js +96 -0
  153. package/hermes/utils/scripts/hermes/scm-utils.js +41 -0
  154. package/hermes/utils/scripts/hermes/set-artifacts-version.js +64 -0
  155. package/hermes/utils/scripts/hermes/version-utils.js +98 -0
  156. package/hermes/utils/scripts/hermes/yarn.lock +240 -0
  157. package/hermes/utils/summarize_sizes.py +184 -0
  158. package/hermes/utils/symbolicate-nativecall-stats.py +112 -0
  159. package/hermes/utils/test_runner.py +13 -0
  160. package/hermes/utils/testsuite/README.facebook +3 -0
  161. package/hermes/utils/testsuite/README.md +69 -0
  162. package/hermes/utils/testsuite/cli.py +547 -0
  163. package/hermes/utils/testsuite/es_ast.py +337 -0
  164. package/hermes/utils/testsuite/external/LICENSE +28 -0
  165. package/hermes/utils/testsuite/external/README.facebook +8 -0
  166. package/hermes/utils/testsuite/external/__init__.py +0 -0
  167. package/hermes/utils/testsuite/external/_monkeyYaml.py +164 -0
  168. package/hermes/utils/testsuite/external/parse_test262.py +141 -0
  169. package/hermes/utils/testsuite/hermes.py +522 -0
  170. package/hermes/utils/testsuite/preprocess.py +365 -0
  171. package/hermes/utils/testsuite/progress.py +377 -0
  172. package/hermes/utils/testsuite/skiplist.json +4356 -0
  173. package/hermes/utils/testsuite/skiplist.py +270 -0
  174. package/hermes/utils/testsuite/test_run_defs.py +435 -0
  175. package/hermes/utils/testsuite/typing_defs.py +52 -0
  176. package/hermes/utils/testsuite/utils.py +214 -0
  177. package/hermes/utils/tidy.sh +22 -0
  178. package/hermes/utils/update-fbcode-hermes.sh +53 -0
  179. package/hermes/utils/updateErrorTest.py +193 -0
  180. package/hermes/utils/wasm-compile.sh +65 -0
  181. package/package.json +1 -1
@@ -0,0 +1,3981 @@
1
+ # RegExp Start Filter and Builtin-Exec Fast Paths Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use
4
+ > superpowers:subagent-driven-development (recommended) or
5
+ > superpowers:executing-plans to implement this plan task-by-task. Steps
6
+ > use checkbox (`- [ ]`) syntax for tracking.
7
+
8
+ **Goal:** Skip regex start positions whose first code unit cannot begin a
9
+ match (Part A), and run the builtin `RegExp.prototype.exec` without a
10
+ JS-level call or an unread result array when `exec` is the builtin
11
+ (Part B), with no observable change except the one resource-limit case
12
+ the spec accepts (A.5).
13
+
14
+ **Architecture:**
15
+ - Part A: a new virtual, `Node::addStartSet`, computes at parse time a
16
+ superset of the code units that can begin a match. `Regex::compile()`
17
+ stores it in three new header fields (`startFlags`, `startChar`,
18
+ `startASCII[16]`). `Context::match` uses it to skip positions when it
19
+ tries more than one; `memchr` handles the single-character case on
20
+ ASCII input.
21
+ - Part B: `directRegExpExec` is split into `regExpBuiltinExecMatch` (the
22
+ observable part of RegExpBuiltinExec) and the array building. The
23
+ global `@@match` loop, `@@replace` phase 1, `@@search` and
24
+ `regExpExec`'s direct dispatch run it inside a native frame for the
25
+ builtin exec, built exactly as a real call builds it. `@@replace`
26
+ phase 2 is factored per match so the fast path can feed it from match
27
+ ranges.
28
+
29
+ **Tech Stack:** C++17, lit/FileCheck, GoogleTest, ASan, MallocGC with
30
+ handle sanitization.
31
+
32
+ **Spec:**
33
+ `doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md`
34
+ (binding). Read it in full before Task 1, and read
35
+ `/home/tmikov/work/hermes-x86-jit/DESIGN-PRINCIPLES.md`. Where this plan
36
+ settles a question the spec leaves open, the task says "Plan ruling";
37
+ the last section lists them all.
38
+
39
+ ## Global Constraints
40
+
41
+ - **Repository.** The worktree is `/home/tmikov/work/hermes-regex-jit`
42
+ (branch `regexp-speedup`). The shell's working directory is a different
43
+ checkout (`/home/tmikov/work/hermes`). Every path, `git` and `cmake`
44
+ command uses `R=/home/tmikov/work/hermes-regex-jit` explicitly
45
+ (`git -C $R ...`). Never bare `cd`; use `( cd dir; cmd; )` if it cannot
46
+ be avoided.
47
+ - **Scratch.** `S` is the session scratchpad directory (the harness
48
+ gives its path). Temporary files go there, never in the repo.
49
+ - **Two parts.** Tasks 1-3 are Part A, Tasks 4-7 are Part B. They must
50
+ squash into two commits, so no Part B task touches a Part A file
51
+ except where stated, and Part A never touches `lib/VM`.
52
+ - **Non-goals** (spec, "Non-goals"):
53
+ - existing spec deviations stay: `test` never looks up `exec`
54
+ (`lib/VM/JSLib/RegExp.cpp:1239-1247`); `@@search` always sets and
55
+ restores `lastIndex` (`:1953`, `:1966`); `@@match`/`@@replace` read
56
+ `global`/`unicode`, not `flags`; no `SpeciesConstructor` in
57
+ `@@split`/`@@matchAll`;
58
+ - `@@split` gets only B.4;
59
+ - no prefixes longer than one character, no Boyer-Moore;
60
+ - no sandbox regeneration (`verify_generated.py` already fails on the
61
+ version, spec "Non-goals");
62
+ - no regex JIT.
63
+ - **Names** (spec-fixed): `Node::addStartSet(StartSet &, unsigned) const`,
64
+ `StartSetResult {Consumes, Nullable, Unknown}`,
65
+ `kMaxStartSetDepth = 64`; header fields `startFlags`, `startChar`,
66
+ `startASCII[16]`; flags `StartFilterPresent`, `StartFilterNonASCII`,
67
+ `StartFilterSingleChar`; match flag `matchNoStartFilter`;
68
+ `BYTECODE_VERSION` 101; `regExpBuiltinExecMatch`; `hasBuiltinExec`;
69
+ `RUNTIME_HV_FIELD(regExpPrototypeExec, NativeFunction)`.
70
+ - **GC-safe coding.** Every change under `lib/VM/` or `include/hermes/VM/`
71
+ is written after invoking the `gc-safe-coding` skill.
72
+ - Root every value that crosses an allocation or call; never compare
73
+ raw pointers across one.
74
+ - Every RAII object the new code creates (`LocalsRAII`, `GCScope`,
75
+ `GCScopeMarkerRAII`, `ScopedNativeCallFrame`,
76
+ `ScopedNativeDepthTracker`) spans only calls that report exceptions
77
+ through `ExecutionStatus`, exactly like the code it replaces. No new
78
+ kind of RAII crosses a call.
79
+ - **Style.** 80 columns, 2-space indent, a doc comment on every
80
+ declaration, only trivial one-line methods inside a class body, the
81
+ Meta copyright header on new files (CLAUDE.md).
82
+ - **Build trees** (configured; clang, Debug, `-O1`, JIT off):
83
+ - `$R/cmake-build-asan`: ASan, Hades; the reference tree;
84
+ - `$R/cmake-build-hsan`: ASan, MallocGC, `HERMESVM_SANITIZE_HANDLES`;
85
+ - `$R/cmake-build-hv32`: ASan, `HEAP_HV_PREFER32`;
86
+ - `$R/cmake-build-release`: Release, `-g -fno-omit-frame-pointer`, for
87
+ measurements only.
88
+
89
+ Rebuild a tree before running its tests, and after every mutation and
90
+ every restore:
91
+
92
+ ```bash
93
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes \
94
+ HermesSupportTests
95
+ ```
96
+ - **Tests.**
97
+ - Regex unit tests:
98
+ `$R/cmake-build-asan/unittests/Support/HermesSupportTests
99
+ --gtest_filter='<pattern>'`.
100
+ - One lit test, by its RUN lines through lit:
101
+ `LIT_FILTER='<regex>' cmake --build $R/cmake-build-asan --target
102
+ check-hermes`.
103
+ - One lit test, directly (faster for mutations):
104
+ `$R/cmake-build-asan/bin/hermes <args> <file> |
105
+ $R/cmake-build-asan/bin/FileCheck --match-full-lines <file>`.
106
+ - Full suite: `cmake --build $R/cmake-build-<t> --target check-hermes`.
107
+ Task 1 Step 1 records the baseline counts on `cmake-build-asan`.
108
+ - **Prove-can-fail** (DESIGN-PRINCIPLES 6). Every new test is shown to
109
+ fail before the feature, or, for a regression guard, under each
110
+ mutation the task names. A mutation is a concrete code edit. Apply it,
111
+ rebuild, run the named command, record the failure, restore the code
112
+ (`git -C $R diff` must show only the task's change), rebuild and re-run
113
+ green.
114
+ - **Mutation diff** (Part B). FileCheck stops at the first mismatch, but
115
+ one mutation can change several cases. So Part B mutations compare the
116
+ whole output: Task 4 Step 3 writes the unmutated output to
117
+ `$S/fast-path.expected`, and a mutation is run as
118
+
119
+ ```bash
120
+ timeout 120 $R/cmake-build-asan/bin/hermes \
121
+ $R/test/hermes/regexp-exec-fast-path.js > $S/fast-path.out 2>&1
122
+ echo "exit $?"; diff $S/fast-path.expected $S/fast-path.out
123
+ ```
124
+
125
+ The task names the lines that must differ. Record every differing
126
+ line.
127
+ - **Commits.**
128
+ - One commit per task, from a message file:
129
+ `git -C $R commit -F $S/commit-<N>.txt`. The message text is given
130
+ in the task. Code in a message goes in ``` fences, never in indented
131
+ blocks. Every message ends with exactly:
132
+ ```
133
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
134
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
135
+ ```
136
+ - Stage by explicit path only: never `git add -A`, never
137
+ `git add dz/issues`.
138
+ - Never push.
139
+ - **Reporting.** Each task's report lists: the commit hash, the trees
140
+ built, every suite run with its pass/unsupported/fail counts, and each
141
+ mutation with the failure it produced.
142
+ - **BASE.** Record `git -C $R rev-parse HEAD` before Task 1 as BASE
143
+ (Task 1 Step 1). Task 8 measures it.
144
+
145
+ ## Review Focus
146
+
147
+ Inputs the spec implies but its test list does not name, most likely to
148
+ bite first. Each has a test in the owning task.
149
+
150
+ 1. **UTF-16 strings whose units are all ASCII.** A string can be stored
151
+ as UTF-16 and still hold only ASCII units, and then it takes the
152
+ `char16_t` path without `matchInputAllAscii`
153
+ (`lib/VM/JSRegExp.cpp:357-374`). The filter must behave as on the
154
+ ASCII path. Test: the differential input `u"abcAB 1\nxyz"` (Task 3).
155
+ 2. **Unicode property escapes in brackets.** `\p{Lu}`, `\P{Lu}` and
156
+ `\p{Lu}` under `/iu` are ranges added while parsing
157
+ (`lib/Regex/RegexParser.cpp:1344-1366`), not classes. Their ASCII bits
158
+ and non-ASCII bit must be right. Tests: header expectations and corpus
159
+ entries, guarded by `HERMES_ENABLE_UNICODE_REGEXP_PROPERTY_ESCAPES`
160
+ (Tasks 1, 3).
161
+ 3. **Empty and full brackets.** `[]` matches nothing and `[^]` matches
162
+ any unit. The first gives a present but empty filter that must reject
163
+ every position; the second must not lose non-ASCII units. Tests:
164
+ header expectations and corpus entries (Tasks 1, 3).
165
+ 4. **A `unicode` property that disagrees with the flag.** `@@match` and
166
+ `@@replace` advance past an empty match by `Get(rx, "unicode")`
167
+ (`RegExp.cpp:1825-1830`, `:2056-2061`), not by the regexp's flag. The
168
+ fast loops must keep using the value they read. Test: `unicodeGetter`
169
+ in `regexp-exec-fast-path.js` (Tasks 6, 7).
170
+ 5. **A replace callback that uses the same global regexp.** The
171
+ callback runs in phase 2 and resets `lastIndex` and the statics. The
172
+ matches stored by phase 1 must be unaffected. Test:
173
+ `reentrantCallback` in `regexp-exec-fast-path.js` (Task 7).
174
+
175
+ ---
176
+
177
+ ## File Structure
178
+
179
+ - Part A, `lib/Regex` and its headers:
180
+ - `include/hermes/Regex/RegexBytecode.h`: header fields, flag enum,
181
+ `startSetHasASCII()`;
182
+ - `include/hermes/Regex/RegexNode.h`: `StartSet`, `StartSetResult`,
183
+ `addStartSet` per node, the bracket closure helper;
184
+ - `include/hermes/Regex/RegexTraits.h`: `bracketMatchesCodePoint`,
185
+ shared by the executor and the analysis;
186
+ - `include/hermes/Regex/Regex.h`: computing and storing the set;
187
+ - `include/hermes/Regex/RegexTypes.h`: `matchNoStartFilter`;
188
+ - `lib/Regex/Executor.cpp`: the filter;
189
+ - `lib/Regex/RegexSerialization.cpp`: the `StartSet:` dump line;
190
+ - `include/hermes/BCGen/HBC/BytecodeVersion.h`: 100 to 101;
191
+ - tests: `unittests/Support/RegexTest.cpp`,
192
+ `test/hermes/regexp_bytecode.js`, `test/BCGen/HBC/store_to_env.js`.
193
+ - Part B, `lib/VM`:
194
+ - `include/hermes/VM/Callable.h`: `NativeFunction::runNativeCallBody`;
195
+ - `include/hermes/VM/RuntimeHermesValueFields.def`:
196
+ `regExpPrototypeExec`;
197
+ - `include/hermes/VM/Runtime.h`: `regExpSearchCaptures`;
198
+ - `lib/VM/JSRegExp.cpp`: `performSearch` uses the buffer;
199
+ - `lib/VM/JSLib/RegExp.cpp`: everything else;
200
+ - test: `test/hermes/regexp-exec-fast-path.js` (new).
201
+
202
+ ---
203
+
204
+ ### Task 1: Start-set analysis and header fields
205
+
206
+ **Files:**
207
+ - Modify: `include/hermes/Regex/RegexBytecode.h:284-299`
208
+ - Modify: `include/hermes/Regex/RegexTraits.h` (after `:154`)
209
+ - Modify: `include/hermes/Regex/RegexNode.h` (includes `:21-30`; before
210
+ `class Node` at `:47`; every node class `:47-978`; after `:1000`)
211
+ - Modify: `include/hermes/Regex/Regex.h:73-74`, `:142-158`, `:347-372`
212
+ - Modify: `lib/Regex/Executor.cpp:719-757`
213
+ - Modify: `include/hermes/BCGen/HBC/BytecodeVersion.h:21-22`
214
+ - Test: `unittests/Support/RegexTest.cpp` (append before `:824`)
215
+
216
+ **Interfaces:**
217
+ - **Produces:**
218
+ - `enum StartFilterFlags : uint8_t {StartFilterPresent = 1,
219
+ StartFilterNonASCII = 2, StartFilterSingleChar = 4}` and
220
+ `bool startSetHasASCII(const RegexBytecodeHeader &, uint32_t u)` in
221
+ `RegexBytecode.h`;
222
+ - `RegexBytecodeHeader::startFlags`, `startChar`, `startASCII[16]`;
223
+ `sizeof(RegexBytecodeHeader) == 24`;
224
+ - `class StartSet` with `addASCII`, `addNonASCII`, `hasASCII`,
225
+ `hasNonASCII`, `writeTo(RegexBytecodeHeader &)`;
226
+ - `enum class StartSetResult`, `kMaxStartSetDepth`,
227
+ `Node::addStartSetForList(const NodeList &, StartSet &, unsigned)`;
228
+ - `template <class Traits> bool bracketMatchesCodePoint(...)` in
229
+ `RegexTraits.h`.
230
+ - Tasks 2 and 3 read the header fields and `startSetHasASCII`.
231
+
232
+ **Facts this task relies on** (read before coding):
233
+ - Node fields are private and there is no RTTI or kind enum
234
+ (`RegexNode.h:47-148`), so the analysis is a virtual.
235
+ - The root list starts with a no-op `Node` and ends with a `GoalNode`
236
+ (`Regex.h:349`, `:362`); coalescing runs before the constraints
237
+ (`Regex.h:363`, `:370`).
238
+ - `icase_` is node-local (`Regex.h:49-54`); `pushChar` canonicalizes
239
+ icase characters (`Regex.h:406-411`); `unicode` is global
240
+ (`Regex.h:407`, `:436`, `:473`).
241
+ - The executor accepts an icase unit `c` for instruction char `k` iff
242
+ `c == k || canonicalize(c) == k` (`Executor.cpp:892-904`,
243
+ `:648-660`).
244
+ - Bracket ranges are closed with `makeCanonicallyEquivalent` at emit time
245
+ (`RegexNode.h:828-831`); the executor tests the closed ranges raw and
246
+ canonicalizes the input for classes only under `/iu`
247
+ (`Executor.cpp:738-755`).
248
+ - Lookbehind bodies are reversed (`Regex.h:478-491`).
249
+ - `parse()` may call `parseWithBackRefLimit` twice (`Regex.h:317-335`).
250
+ - Instruction offsets exclude the header (`RegexBytecode.h:371-377`,
251
+ `Executor.cpp:1073`), so growing the header moves nothing.
252
+
253
+ - [ ] **Step 1: Record BASE and the baseline suite**
254
+
255
+ ```bash
256
+ git -C $R rev-parse HEAD # record as BASE
257
+ cmake --build $R/cmake-build-asan --target check-hermes
258
+ ```
259
+
260
+ Record BASE and the counts (expected passes, expected failures,
261
+ unsupported, failures). There must be 0 failures; if not, STOP and
262
+ report.
263
+
264
+ - [ ] **Step 2: Write the header-contents test**
265
+
266
+ Append to `unittests/Support/RegexTest.cpp`, just before
267
+ `} // end anonymous namespace` (`:824`). Add `#include <cstdio>` and
268
+ `#include <cstring>` after `#include <string>` (`:12`).
269
+
270
+ ```cpp
271
+ /// \return the start filter in the header of \p bytecode as a string:
272
+ /// "none" if absent; otherwise the ASCII members as hex ranges in
273
+ /// increasing order, then "nonascii" if StartFilterNonASCII is set, then
274
+ /// "single" if StartFilterSingleChar is set; "empty" for a present filter
275
+ /// with no members. Checks that StartFilterSingleChar and startChar agree
276
+ /// with the bitmap.
277
+ std::string describeStartFilter(const std::vector<uint8_t> &bytecode) {
278
+ RegexBytecodeHeader header;
279
+ EXPECT_GE(bytecode.size(), sizeof(header));
280
+ std::memcpy(&header, bytecode.data(), sizeof(header));
281
+ if (!(header.startFlags & StartFilterPresent)) {
282
+ EXPECT_EQ(0u, header.startFlags);
283
+ return "none";
284
+ }
285
+ std::string out;
286
+ unsigned count = 0;
287
+ for (uint32_t u = 0; u < 128;) {
288
+ if (!startSetHasASCII(header, u)) {
289
+ ++u;
290
+ continue;
291
+ }
292
+ uint32_t last = u;
293
+ while (last + 1 < 128 && startSetHasASCII(header, last + 1))
294
+ ++last;
295
+ char buf[16];
296
+ if (last == u)
297
+ snprintf(buf, sizeof(buf), "0x%02x", u);
298
+ else
299
+ snprintf(buf, sizeof(buf), "0x%02x-0x%02x", u, last);
300
+ if (!out.empty())
301
+ out += ' ';
302
+ out += buf;
303
+ count += last - u + 1;
304
+ u = last + 1;
305
+ }
306
+ if (header.startFlags & StartFilterNonASCII) {
307
+ if (!out.empty())
308
+ out += ' ';
309
+ out += "nonascii";
310
+ }
311
+ const bool single = header.startFlags & StartFilterSingleChar;
312
+ EXPECT_EQ(count == 1, single) << out;
313
+ if (single) {
314
+ EXPECT_TRUE(startSetHasASCII(header, header.startChar)) << out;
315
+ out += " single";
316
+ }
317
+ return out.empty() ? "empty" : out;
318
+ }
319
+
320
+ /// \return describeStartFilter() of the regex \p pattern with \p flags.
321
+ std::string startFilterOf(
322
+ const std::u16string &pattern,
323
+ const char16_t *flags = u"") {
324
+ cregex re(pattern.c_str(), flags);
325
+ EXPECT_TRUE(re.valid());
326
+ if (!re.valid())
327
+ return "invalid";
328
+ return describeStartFilter(re.compile());
329
+ }
330
+
331
+ /// \return \p depth nested capture groups around the pattern "a".
332
+ std::u16string nestedGroups(unsigned depth) {
333
+ return std::u16string(depth, u'(') + u"a" + std::u16string(depth, u')');
334
+ }
335
+
336
+ TEST(Regex, StartFilterHeader) {
337
+ // Literals. /abc/ is coalesced into one MatchCharNode.
338
+ EXPECT_EQ("0x61 single", startFilterOf(u"abc"));
339
+ EXPECT_EQ("0x61 single", startFilterOf(u"(){999999999}a"));
340
+
341
+ // Case folding: both cases of an ASCII letter; under /iu also every
342
+ // non-ASCII unit, for U+017F -> 's' and U+212A -> 'k'.
343
+ EXPECT_EQ("0x41 0x61", startFilterOf(u"a", u"i"));
344
+ EXPECT_EQ("0x41 0x61 nonascii", startFilterOf(u"a", u"iu"));
345
+ EXPECT_EQ("0x53 0x73 nonascii", startFilterOf(u"s", u"iu"));
346
+ EXPECT_EQ("0x4b 0x6b nonascii", startFilterOf(u"k", u"iu"));
347
+ EXPECT_EQ("0x53 0x73", startFilterOf(u"s", u"i"));
348
+ EXPECT_EQ("nonascii", startFilterOf(u"\\u017f", u"i"));
349
+ EXPECT_EQ("0x53 0x73 nonascii", startFilterOf(u"\\u017f", u"iu"));
350
+
351
+ // Alternation, including an empty alternative.
352
+ EXPECT_EQ("0x61 0x63", startFilterOf(u"ab|cd"));
353
+ EXPECT_EQ("none", startFilterOf(u"a|"));
354
+
355
+ // Loops.
356
+ EXPECT_EQ("0x78-0x79", startFilterOf(u"x*y"));
357
+ EXPECT_EQ("0x78 single", startFilterOf(u"x+y"));
358
+
359
+ // Zero-width nodes are transparent; lookarounds are not descended into.
360
+ EXPECT_EQ("0x61 single", startFilterOf(u"^a"));
361
+ EXPECT_EQ("0x61 single", startFilterOf(u"\\ba"));
362
+ EXPECT_EQ("0x61 single", startFilterOf(u"(?=b)a"));
363
+ EXPECT_EQ("0x61 single", startFilterOf(u"(?!b)a"));
364
+ EXPECT_EQ("0x61 single", startFilterOf(u"(?<=b)a"));
365
+ EXPECT_EQ("none", startFilterOf(u"\\b"));
366
+
367
+ // A back-reference first gives up; after a consuming node it is never
368
+ // reached.
369
+ EXPECT_EQ("none", startFilterOf(u"\\1(a)"));
370
+ EXPECT_EQ("none", startFilterOf(u"(?=(a))\\1"));
371
+ EXPECT_EQ("0x61 single", startFilterOf(u"(a)\\1"));
372
+
373
+ // Any character.
374
+ EXPECT_EQ("0x00-0x09 0x0b-0x0c 0x0e-0x7f nonascii", startFilterOf(u"."));
375
+ EXPECT_EQ("0x00-0x7f nonascii", startFilterOf(u".", u"s"));
376
+
377
+ // Brackets and classes: exact on ASCII, a superset on non-ASCII.
378
+ EXPECT_EQ("0x61-0x63", startFilterOf(u"[a-c]"));
379
+ EXPECT_EQ("0x00-0x60 0x62-0x7f nonascii", startFilterOf(u"[^a]"));
380
+ EXPECT_EQ("0x30-0x39", startFilterOf(u"\\d"));
381
+ EXPECT_EQ("0x30-0x39", startFilterOf(u"[\\d]"));
382
+ EXPECT_EQ("0x00-0x2f 0x3a-0x7f nonascii", startFilterOf(u"\\D"));
383
+ EXPECT_EQ(
384
+ "0x30-0x39 0x41-0x5a 0x5f 0x61-0x7a nonascii", startFilterOf(u"\\w"));
385
+ EXPECT_EQ("0x09-0x0d 0x20 nonascii", startFilterOf(u"\\s"));
386
+ EXPECT_EQ(
387
+ "0x00-0x2f 0x3a-0x40 0x5b-0x5e 0x60 0x7b-0x7f nonascii",
388
+ startFilterOf(u"\\W", u"iu"));
389
+ EXPECT_EQ("0x61 nonascii single", startFilterOf(u"[a\\u00e9]"));
390
+ EXPECT_EQ("0x41-0x5a 0x61-0x7a", startFilterOf(u"[a-z]", u"i"));
391
+ EXPECT_EQ("0x41-0x5a 0x61-0x7a nonascii", startFilterOf(u"[a-z]", u"iu"));
392
+ // Review Focus 3.
393
+ EXPECT_EQ("empty", startFilterOf(u"[]"));
394
+ EXPECT_EQ("0x00-0x7f nonascii", startFilterOf(u"[^]"));
395
+ #ifdef HERMES_ENABLE_UNICODE_REGEXP_PROPERTY_ESCAPES
396
+ // Review Focus 2.
397
+ EXPECT_EQ("0x41-0x5a nonascii", startFilterOf(u"\\p{Lu}", u"u"));
398
+ EXPECT_EQ("0x00-0x40 0x5b-0x7f nonascii", startFilterOf(u"\\P{Lu}", u"u"));
399
+ EXPECT_EQ("0x41-0x5a 0x61-0x7a nonascii", startFilterOf(u"\\p{Lu}", u"iu"));
400
+ #endif
401
+
402
+ // Surrogates under /u: an astral literal starts with its high surrogate;
403
+ // a lone surrogate is itself non-ASCII.
404
+ EXPECT_EQ("nonascii", startFilterOf(u"\\u{1F600}", u"u"));
405
+ EXPECT_EQ("nonascii", startFilterOf(u"\\uD83D", u"u"));
406
+
407
+ // Modifier groups make icase node-local.
408
+ EXPECT_EQ("0x41 0x61", startFilterOf(u"(?i:a)b"));
409
+ EXPECT_EQ("0x61 single", startFilterOf(u"a(?i:b)"));
410
+
411
+ // The depth cap: the innermost list of N nested groups is at depth N.
412
+ EXPECT_EQ("0x61 single", startFilterOf(nestedGroups(63)));
413
+ EXPECT_EQ("none", startFilterOf(nestedGroups(64)));
414
+ EXPECT_EQ("none", startFilterOf(nestedGroups(100)));
415
+ }
416
+ ```
417
+
418
+ Derivations, for the reviewer:
419
+ - `/a/i`: `pushChar` stores `canonicalize('a', false) == 'A'`; the ASCII
420
+ units with `canonicalize(u, false) == 'A'` are 0x41 and 0x61.
421
+ - `/\u017f/i`: legacy canonicalization never maps non-ASCII to ASCII, so
422
+ the char stays 0x17f; no ASCII unit canonicalizes to it.
423
+ - `/\u017f/iu`: `canonicalize(0x17f, true) == 's'`.
424
+ - `\s`: `isWhiteSpaceChar` and `isLineTerminatorChar` give 0x09-0x0d and
425
+ 0x20 in ASCII (`RegexTraits.h:52-62`).
426
+ - `[a-z]/iu`: the closure adds A-Z, U+017F and U+212A (a range of 0x80 or
427
+ more sets `nonascii`).
428
+ - `\W/iu`: the negative class matches the ASCII non-word units; the
429
+ class sets `nonascii`.
430
+
431
+ - [ ] **Step 3: See it fail**
432
+
433
+ ```bash
434
+ cmake --build $R/cmake-build-asan --target HermesSupportTests
435
+ ```
436
+
437
+ Expected: compile errors, `StartFilterPresent`, `startSetHasASCII` and
438
+ `startFlags` undeclared.
439
+
440
+ - [ ] **Step 4: Header fields** (`include/hermes/Regex/RegexBytecode.h`)
441
+
442
+ Replace `RegexBytecodeHeader` (`:284-297`) with:
443
+
444
+ ```cpp
445
+ /// A header that appears at the beginning of a bytecode stream.
446
+ struct RegexBytecodeHeader {
447
+ /// Number of capture groups.
448
+ uint16_t markedCount;
449
+
450
+ /// Number of loops.
451
+ uint16_t loopCount;
452
+
453
+ /// Syntax flags used to construct the regex.
454
+ uint8_t syntaxFlags;
455
+
456
+ /// Constraints on what strings can match this regex.
457
+ MatchConstraintSet constraints;
458
+
459
+ /// The start filter: a set of StartFilterFlags.
460
+ uint8_t startFlags;
461
+
462
+ /// The only ASCII member of the start set when StartFilterSingleChar is
463
+ /// set, 0 otherwise.
464
+ uint8_t startChar;
465
+
466
+ /// The ASCII members of the start set: bit u % 8 of startASCII[u / 8] is
467
+ /// set if a match can begin with code unit u.
468
+ uint8_t startASCII[16];
469
+ };
470
+ ```
471
+
472
+ After `LLVM_PACKED_END;` (`:299`) add:
473
+
474
+ ```cpp
475
+ static_assert(
476
+ sizeof(RegexBytecodeHeader) == 24,
477
+ "RegexBytecodeHeader must stay packed");
478
+
479
+ /// Flags of RegexBytecodeHeader::startFlags.
480
+ enum StartFilterFlags : uint8_t {
481
+ /// The header holds a start filter: every match begins with a code unit
482
+ /// of the start set. Such a regex cannot match the empty string.
483
+ StartFilterPresent = 1 << 0,
484
+
485
+ /// A match may begin with any code unit >= 0x80.
486
+ StartFilterNonASCII = 1 << 1,
487
+
488
+ /// The start set has exactly one ASCII member, startChar.
489
+ StartFilterSingleChar = 1 << 2,
490
+ };
491
+
492
+ /// \return whether the ASCII code unit \p u is in the start set of
493
+ /// \p header.
494
+ inline bool startSetHasASCII(const RegexBytecodeHeader &header, uint32_t u) {
495
+ assert(u < 128 && "not an ASCII code unit");
496
+ return (header.startASCII[u >> 3] >> (u & 7)) & 1;
497
+ }
498
+ ```
499
+
500
+ Add `#include <cassert>` after `#include <cstdint>` (`:15`).
501
+
502
+ - [ ] **Step 5: The shared bracket predicate**
503
+ (`include/hermes/Regex/RegexTraits.h`, after `ASCIIRegexTraits`,
504
+ `:154`)
505
+
506
+ ```cpp
507
+ /// \return whether the code point \p ch matches a bracket whose character
508
+ /// classes are \p positiveClasses and \p negativeClasses (sets of
509
+ /// CharacterClass::Type bits), whose ranges are \p ranges (closed under
510
+ /// canonical equivalence when \p icase), and which is negated if \p negate.
511
+ /// \p unicode is the regex's unicode flag. The executor and the start-set
512
+ /// analysis both call this, so that they agree on every code unit.
513
+ template <class Traits>
514
+ bool bracketMatchesCodePoint(
515
+ const Traits &traits,
516
+ uint8_t positiveClasses,
517
+ uint8_t negativeClasses,
518
+ bool negate,
519
+ llvh::ArrayRef<BracketRange32> ranges,
520
+ typename Traits::CodePoint ch,
521
+ bool icase,
522
+ bool unicode) {
523
+ // When both ignoreCase and unicode are set (/iu), canonicalize the
524
+ // character before testing, because per ES spec 22.2.2.9.2
525
+ // (WordCharacters), \w with /iu must match any character whose canonical
526
+ // form is a word character (e.g. U+212A KELVIN SIGN canonicalizes to 'k').
527
+ if (positiveClasses || negativeClasses) {
528
+ auto testCh = icase && unicode ? Traits::canonicalize(ch, true) : ch;
529
+ for (auto charClass :
530
+ {CharacterClass::Digits,
531
+ CharacterClass::Spaces,
532
+ CharacterClass::Words}) {
533
+ if ((positiveClasses & charClass) &&
534
+ traits.characterHasType(testCh, charClass))
535
+ return !negate;
536
+ if ((negativeClasses & charClass) &&
537
+ !traits.characterHasType(testCh, charClass))
538
+ return !negate;
539
+ }
540
+ }
541
+ return traits.rangesContain(ranges, ch) != negate;
542
+ }
543
+ ```
544
+
545
+ In `lib/Regex/Executor.cpp`, replace the body of `bracketMatchesChar`
546
+ (`:729-756`) with:
547
+
548
+ ```cpp
549
+ return bracketMatchesCodePoint(
550
+ ctx.traits_,
551
+ insn->positiveCharClasses,
552
+ insn->negativeCharClasses,
553
+ insn->negate,
554
+ llvh::makeArrayRef(ranges, insn->rangeCount),
555
+ ch,
556
+ icase,
557
+ ctx.syntaxFlags_.unicode);
558
+ ```
559
+
560
+ Keep its doc comment (`:719-721`). `true ^ insn->negate` was `!negate`
561
+ and `contained ^ insn->negate` was `contained != negate` for the 1-bit
562
+ `negate`, so the executor is unchanged.
563
+
564
+ - [ ] **Step 6: `StartSet`, `StartSetResult` and the list walk**
565
+ (`include/hermes/Regex/RegexNode.h`)
566
+
567
+ Add `#include "hermes/Regex/RegexTraits.h"` after
568
+ `#include "hermes/Regex/RegexBytecode.h"` (`:24`), and `#include <cstring>`
569
+ after `#include <string>` (`:29`).
570
+
571
+ Before `/// Base class representing some part...` (`:42`) add:
572
+
573
+ ```cpp
574
+ /// The result of Node::addStartSet().
575
+ enum class StartSetResult : uint8_t {
576
+ /// Every match of the node consumes input and begins with a code unit of
577
+ /// the set.
578
+ Consumes,
579
+ /// The node can match without consuming input, so what follows it also
580
+ /// contributes to the start set.
581
+ Nullable,
582
+ /// The analysis cannot bound the first code unit: no filter.
583
+ Unknown,
584
+ };
585
+
586
+ /// The nesting depth of node lists at which the start-set analysis gives
587
+ /// up. The node tree has no depth limit (test/hermes/regexp.js:94 nests
588
+ /// 50000 groups), so the recursive analysis is bounded instead.
589
+ constexpr unsigned kMaxStartSetDepth = 64;
590
+
591
+ /// A superset of the code units that can begin a match: exact for ASCII
592
+ /// code units, and one bit standing for every code unit >= 0x80. Treating
593
+ /// every non-ASCII unit alike keeps a /u search from stopping on a low
594
+ /// surrogate whose high surrogate it skipped.
595
+ class StartSet {
596
+ public:
597
+ /// Add the ASCII code unit \p u.
598
+ inline void addASCII(uint32_t u);
599
+
600
+ /// Add every code unit >= 0x80.
601
+ void addNonASCII() {
602
+ nonASCII_ = true;
603
+ }
604
+
605
+ /// \return whether the ASCII code unit \p u is in the set.
606
+ inline bool hasASCII(uint32_t u) const;
607
+
608
+ /// \return whether the code units >= 0x80 are in the set.
609
+ bool hasNonASCII() const {
610
+ return nonASCII_;
611
+ }
612
+
613
+ /// Store this set as the start filter of \p header.
614
+ inline void writeTo(RegexBytecodeHeader &header) const;
615
+
616
+ private:
617
+ /// Bit u % 8 of ascii_[u / 8] is set if the ASCII unit u is in the set.
618
+ uint8_t ascii_[16] = {};
619
+
620
+ /// Whether every code unit >= 0x80 is in the set.
621
+ bool nonASCII_ = false;
622
+ };
623
+
624
+ void StartSet::addASCII(uint32_t u) {
625
+ assert(u < 128 && "not an ASCII code unit");
626
+ ascii_[u >> 3] |= 1u << (u & 7);
627
+ }
628
+
629
+ bool StartSet::hasASCII(uint32_t u) const {
630
+ assert(u < 128 && "not an ASCII code unit");
631
+ return (ascii_[u >> 3] >> (u & 7)) & 1;
632
+ }
633
+
634
+ void StartSet::writeTo(RegexBytecodeHeader &header) const {
635
+ header.startFlags = StartFilterPresent;
636
+ if (nonASCII_)
637
+ header.startFlags |= StartFilterNonASCII;
638
+ unsigned count = 0;
639
+ uint32_t only = 0;
640
+ for (uint32_t u = 0; u < 128; ++u) {
641
+ if (hasASCII(u)) {
642
+ ++count;
643
+ only = u;
644
+ }
645
+ }
646
+ if (count == 1) {
647
+ header.startFlags |= StartFilterSingleChar;
648
+ header.startChar = static_cast<uint8_t>(only);
649
+ }
650
+ static_assert(
651
+ sizeof(header.startASCII) == sizeof(ascii_), "bitmap size mismatch");
652
+ std::memcpy(header.startASCII, ascii_, sizeof(ascii_));
653
+ }
654
+ ```
655
+
656
+ In `class Node`, after `optimizeNodeList`'s declaration (`:89-92`), add:
657
+
658
+ ```cpp
659
+ /// Add to \p set the start sets of the nodes of \p nodes, in order, up to
660
+ /// and including the first node that consumes input. \p depth is the
661
+ /// nesting depth of \p nodes: 0 for the root list.
662
+ /// \return Consumes if a node of the list consumes, Nullable if none
663
+ /// does, Unknown if the analysis gave up.
664
+ inline static StartSetResult
665
+ addStartSetForList(const NodeList &nodes, StartSet &set, unsigned depth);
666
+ ```
667
+
668
+ In the `protected:` section of `Node`, after `matchConstraints()`
669
+ (`:117-119`), add:
670
+
671
+ ```cpp
672
+ /// Add to \p set every code unit that can begin a match of this node.
673
+ /// \p depth is the nesting depth of the list holding this node; a node
674
+ /// that descends into a child list passes depth + 1.
675
+ /// \return Nullable if the node can match without consuming input, so
676
+ /// the caller must also add the start set of what follows; Consumes if
677
+ /// every match consumes; Unknown to give up (no filter).
678
+ /// The base Node is the leading no-op node: it is nullable and adds
679
+ /// nothing. Every subclass overrides this.
680
+ virtual StartSetResult addStartSet(StartSet &set, unsigned depth) const {
681
+ return StartSetResult::Nullable;
682
+ }
683
+ ```
684
+
685
+ After `Node::reverseNodeList` (`:980-1000`) add:
686
+
687
+ ```cpp
688
+ StartSetResult Node::addStartSetForList(
689
+ const NodeList &nodes,
690
+ StartSet &set,
691
+ unsigned depth) {
692
+ if (depth >= kMaxStartSetDepth)
693
+ return StartSetResult::Unknown;
694
+ for (const Node *node : nodes) {
695
+ StartSetResult result = node->addStartSet(set, depth);
696
+ if (result != StartSetResult::Nullable)
697
+ return result;
698
+ }
699
+ return StartSetResult::Nullable;
700
+ }
701
+ ```
702
+
703
+ - [ ] **Step 7: The per-node rules** (`RegexNode.h`; one override per
704
+ class, added to the class's `protected:` section, creating one where the
705
+ class has none)
706
+
707
+ `GoalNode` (`:151-162`):
708
+
709
+ ```cpp
710
+ /// Reaching the goal means the list can match the empty string.
711
+ StartSetResult addStartSet(StartSet &, unsigned) const override {
712
+ return StartSetResult::Nullable;
713
+ }
714
+ ```
715
+
716
+ `LoopNode` (`:164-306`):
717
+
718
+ ```cpp
719
+ /// The loopee's set is added even for {0}: a superset is safe. The loop is
720
+ /// nullable if it may run zero times or its loopee is nullable.
721
+ StartSetResult addStartSet(StartSet &set, unsigned depth) const override {
722
+ StartSetResult result = addStartSetForList(loopee_, set, depth + 1);
723
+ if (result == StartSetResult::Unknown)
724
+ return result;
725
+ return min_ == 0 ? StartSetResult::Nullable : result;
726
+ }
727
+ ```
728
+
729
+ `AlternationNode` (`:309-422`):
730
+
731
+ ```cpp
732
+ /// The union over the alternatives. An alternative may be empty (/a|/).
733
+ StartSetResult addStartSet(StartSet &set, unsigned depth) const override {
734
+ StartSetResult result = StartSetResult::Consumes;
735
+ for (const NodeList &alternative : alternatives_) {
736
+ StartSetResult altResult =
737
+ addStartSetForList(alternative, set, depth + 1);
738
+ if (altResult == StartSetResult::Unknown)
739
+ return altResult;
740
+ if (altResult == StartSetResult::Nullable)
741
+ result = StartSetResult::Nullable;
742
+ }
743
+ return result;
744
+ }
745
+ ```
746
+
747
+ `MarkedSubexpressionNode` (`:425-469`):
748
+
749
+ ```cpp
750
+ /// A capture group matches what its contents match.
751
+ StartSetResult addStartSet(StartSet &set, unsigned depth) const override {
752
+ return addStartSetForList(contents_, set, depth + 1);
753
+ }
754
+ ```
755
+
756
+ `BackRefNode` (`:472-495`):
757
+
758
+ ```cpp
759
+ /// A back-reference can repeat text captured inside a lookahead, e.g.
760
+ /// /(?=(a))\1/, so its first unit is unknown.
761
+ StartSetResult addStartSet(StartSet &, unsigned) const override {
762
+ return StartSetResult::Unknown;
763
+ }
764
+ ```
765
+
766
+ `WordBoundaryNode` (`:498-518`), `LeftAnchorNode` (`:521-547`),
767
+ `RightAnchorNode` (`:550-566`), each:
768
+
769
+ ```cpp
770
+ /// A zero-width assertion consumes nothing.
771
+ StartSetResult addStartSet(StartSet &, unsigned) const override {
772
+ return StartSetResult::Nullable;
773
+ }
774
+ ```
775
+
776
+ `LookaroundNode` (`:898-978`):
777
+
778
+ ```cpp
779
+ /// Every lookaround is zero-width at the match start. Its body is not
780
+ /// descended into: a lookbehind body is reversed and reads the text to
781
+ /// the left.
782
+ StartSetResult addStartSet(StartSet &, unsigned) const override {
783
+ return StartSetResult::Nullable;
784
+ }
785
+ ```
786
+
787
+ `MatchAnyNode` (`:570-609`):
788
+
789
+ ```cpp
790
+ /// Without dotAll, '.' rejects the line terminators: 0x0A and 0x0D in
791
+ /// ASCII, U+2028 and U+2029 beyond (Executor.cpp isLineTerminator).
792
+ StartSetResult addStartSet(StartSet &set, unsigned) const override {
793
+ for (uint32_t u = 0; u < 128; ++u) {
794
+ if (dotAll_ || (u != u'\n' && u != u'\r'))
795
+ set.addASCII(u);
796
+ }
797
+ set.addNonASCII();
798
+ return StartSetResult::Consumes;
799
+ }
800
+ ```
801
+
802
+ `MatchCharNode` (`:613-756`):
803
+
804
+ ```cpp
805
+ /// The first unit of a match is the first unit of chars_[0], which is
806
+ /// already canonical when icase_ (Regex::pushChar).
807
+ StartSetResult addStartSet(StartSet &set, unsigned) const override {
808
+ assert(!chars_.empty() && "MatchCharNode without characters");
809
+ const CodePoint c = chars_.front();
810
+ if (!isASCII(c)) {
811
+ // An astral character starts with its high surrogate, a lone
812
+ // surrogate is non-ASCII, and no ASCII unit canonicalizes to a
813
+ // non-ASCII character.
814
+ set.addNonASCII();
815
+ } else if (!icase_) {
816
+ set.addASCII(c);
817
+ } else {
818
+ // Every ASCII unit the executor accepts for c: u == c or
819
+ // canonicalize(u) == c (MatchCharICase8, MatchNCharICase8).
820
+ for (uint32_t u = 0; u < 128; ++u) {
821
+ if (u == c || UTF16RegexTraits::canonicalize(u, unicode_) == c)
822
+ set.addASCII(u);
823
+ }
824
+ // Under /iu, U+017F and U+212A canonicalize to 's' and 'k'. Setting
825
+ // the bit for every /iu character is a deliberate superset.
826
+ if (unicode_)
827
+ set.addNonASCII();
828
+ }
829
+ return StartSetResult::Consumes;
830
+ }
831
+ ```
832
+
833
+ `BracketNode<Traits>` (`:759-895`). Add, before `populateInstruction`
834
+ (`:814`):
835
+
836
+ ```cpp
837
+ /// \return the code point set this bracket emits: the parsed set, closed
838
+ /// under canonical equivalence when icase_. emitStep() and addStartSet()
839
+ /// both use it, so they cannot diverge.
840
+ CodePointSet emittedCodePointSet() const {
841
+ return icase_ ? makeCanonicallyEquivalent(codePointSet_, unicode_)
842
+ : codePointSet_;
843
+ }
844
+ ```
845
+
846
+ In `populateInstruction`, replace `:828-831` with:
847
+
848
+ ```cpp
849
+ CodePointSet cps = emittedCodePointSet();
850
+ ```
851
+
852
+ Add to the class (a `protected:` section after `matchesExactlyOneCharacter`,
853
+ `:875-878`):
854
+
855
+ ```cpp
856
+ /// The ASCII bits are the executor's own answers: bracketMatchesCodePoint
857
+ /// on the emitted ranges. Non-ASCII units are a superset: they are in the
858
+ /// set unless the bracket is not negated, has no class other than a
859
+ /// positive \d, and has no emitted range reaching 0x80.
860
+ StartSetResult addStartSet(StartSet &set, unsigned) const override {
861
+ const CodePointSet cps = emittedCodePointSet();
862
+ llvh::SmallVector<BracketRange32, 8> ranges;
863
+ for (const CodePointRange &range : cps.ranges())
864
+ ranges.push_back(
865
+ BracketRange32{range.first, range.first + range.length - 1});
866
+ uint8_t positive = 0;
867
+ uint8_t negative = 0;
868
+ for (CharacterClass cc : classes_) {
869
+ if (cc.inverted_)
870
+ negative |= cc.type_;
871
+ else
872
+ positive |= cc.type_;
873
+ }
874
+ for (uint32_t u = 0; u < 128; ++u) {
875
+ if (bracketMatchesCodePoint(
876
+ traits_,
877
+ positive,
878
+ negative,
879
+ negate_,
880
+ ranges,
881
+ u,
882
+ icase_,
883
+ unicode_))
884
+ set.addASCII(u);
885
+ }
886
+ if (negate_ || negative != 0 ||
887
+ (positive & ~uint8_t(CharacterClass::Digits)) != 0 ||
888
+ (!cps.ranges().empty() && cps.end() > 0x80))
889
+ set.addNonASCII();
890
+ return StartSetResult::Consumes;
891
+ }
892
+ ```
893
+
894
+ - [ ] **Step 8: Compute, store and write the set** (`Regex.h`)
895
+
896
+ After `matchConstraints_` (`:73-74`) add:
897
+
898
+ ```cpp
899
+ /// The code units that can begin a match, or None if there is no start
900
+ /// filter: the regex can match the empty string, or the analysis gave up.
901
+ llvh::Optional<StartSet> startSet_;
902
+ ```
903
+
904
+ In `parseWithBackRefLimit`, after `nodes_.clear();` (`:348`) add
905
+ `startSet_ = llvh::None;`, and after
906
+ `matchConstraints_ = Node::matchConstraintsForList(nodes_);` (`:370`) add:
907
+
908
+ ```cpp
909
+ // Compute the start-position filter.
910
+ if (result == constants::ErrorType::None) {
911
+ StartSet set;
912
+ if (Node::addStartSetForList(nodes_, set, 0) == StartSetResult::Consumes)
913
+ startSet_ = set;
914
+ }
915
+ ```
916
+
917
+ In `compile()`, replace the header construction (`:150-154`) with:
918
+
919
+ ```cpp
920
+ RegexBytecodeHeader header{};
921
+ header.markedCount = markedCount_;
922
+ header.loopCount = static_cast<uint16_t>(loopCount_);
923
+ header.syntaxFlags = globalFlags_.toByte();
924
+ header.constraints = matchConstraints_;
925
+ if (startSet_)
926
+ startSet_->writeTo(header);
927
+ ```
928
+
929
+ - [ ] **Step 9: Bump the bytecode version**
930
+ (`include/hermes/BCGen/HBC/BytecodeVersion.h:21-22`)
931
+
932
+ ```cpp
933
+ // Bytecode version generated by this version of the compiler.
934
+ // Updated: Oct 28, 2026
935
+ const static uint32_t BYTECODE_VERSION = 101;
936
+ ```
937
+
938
+ - [ ] **Step 10: Build and run**
939
+
940
+ ```bash
941
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes \
942
+ HermesSupportTests
943
+ $R/cmake-build-asan/unittests/Support/HermesSupportTests \
944
+ --gtest_filter='Regex.*'
945
+ ```
946
+
947
+ Expected: every `Regex.*` test passes, including `StartFilterHeader`.
948
+ If an expectation differs, re-derive it from the rules above before
949
+ changing the code or the expectation; report any expectation changed.
950
+
951
+ - [ ] **Step 11: Prove the header test can fail** (rebuild
952
+ `HermesSupportTests` after each edit and each restore; run the Step 10
953
+ command)
954
+ - M1, drop the other case: in `MatchCharNode::addStartSet` change
955
+ `if (u == c || UTF16RegexTraits::canonicalize(u, unicode_) == c)` to
956
+ `if (u == c)`. Fails: `startFilterOf(u"a", u"i")` gives
957
+ `"0x41 single"`.
958
+ - M2, no `nonascii` for `/iu`: delete
959
+ `if (unicode_) set.addNonASCII();` in `MatchCharNode`. Fails:
960
+ `u"s", u"iu"` gives `"0x53 0x73"`.
961
+ - M3, lookaround body as consuming: make `LookaroundNode::addStartSet`
962
+ `{ addStartSetForList(exp_, set, depth + 1); return
963
+ StartSetResult::Consumes; }` (name the parameters). Fails:
964
+ `u"(?=b)a"` gives `"0x62 single"`.
965
+ - M4, `.` without non-ASCII: in `MatchAnyNode`, change
966
+ `set.addNonASCII();` to `if (dotAll_) set.addNonASCII();`. Fails:
967
+ `u"."`.
968
+ - M5, depth cap: change `kMaxStartSetDepth` to 65. Fails:
969
+ `nestedGroups(64)` gives `"0x61 single"`.
970
+ - M6, back-reference as nullable: return `StartSetResult::Nullable` in
971
+ `BackRefNode`. Fails: `u"\\1(a)"` gives `"0x61 single"`.
972
+ - M7, negation ignored on the non-ASCII side: drop `negate_ ||` from
973
+ the `addNonASCII` condition in `BracketNode`. Fails: `u"[^a]"`.
974
+
975
+ - [ ] **Step 12: Full suite**
976
+
977
+ ```bash
978
+ cmake --build $R/cmake-build-asan --target check-hermes
979
+ ```
980
+
981
+ Expected: 0 failures, and the Step 1 counts with one more expected pass:
982
+ check-hermes runs `unittests/` too and counts each GoogleTest case, and
983
+ this task adds `Regex.StartFilterHeader`. The header grows silently: no
984
+ offset moves and the dump is unchanged until Task 2. The 50000-deep
985
+ nesting in `test/hermes/regexp.js:94` must pass (the analysis stops at
986
+ depth 64).
987
+
988
+ - [ ] **Step 13: Commit**
989
+
990
+ ```bash
991
+ git -C $R add include/hermes/Regex/RegexBytecode.h \
992
+ include/hermes/Regex/RegexTraits.h include/hermes/Regex/RegexNode.h \
993
+ include/hermes/Regex/Regex.h lib/Regex/Executor.cpp \
994
+ include/hermes/BCGen/HBC/BytecodeVersion.h unittests/Support/RegexTest.cpp
995
+ git -C $R commit -F $S/commit-1.txt
996
+ ```
997
+
998
+ `$S/commit-1.txt`:
999
+
1000
+ ````
1001
+ Regex: compute a start set per regex and store it in the header
1002
+
1003
+ Each regex now records at compile time which code units can begin a
1004
+ match: an exact bitmap of the ASCII units and one bit for all units of
1005
+ 0x80 and above. A regex that can match the empty string, or whose first
1006
+ unit cannot be bounded, has no set.
1007
+
1008
+ A new virtual, Node::addStartSet, walks the node tree with a depth cap
1009
+ of 64, since the tree has no nesting limit:
1010
+
1011
+ ```
1012
+ virtual StartSetResult addStartSet(StartSet &set, unsigned depth) const;
1013
+ ```
1014
+
1015
+ Zero-width nodes are transparent, lookarounds are not descended into,
1016
+ and a back-reference gives up. Case-insensitive characters add every
1017
+ ASCII unit the executor accepts for them, and under /iu also the
1018
+ non-ASCII bit, for U+017F and U+212A. A bracket's ASCII bits come from
1019
+ the executor's own predicate, now shared as bracketMatchesCodePoint, on
1020
+ the ranges it emits, now computed by one helper for emission and
1021
+ analysis.
1022
+
1023
+ RegexBytecodeHeader grows from 6 to 24 bytes: startFlags, startChar and
1024
+ startASCII[16]. Instruction offsets exclude the header, so no jump
1025
+ target or dumped offset moves. The bytes format changes, so
1026
+ BYTECODE_VERSION goes from 100 to 101. SH-generated C must be rebuilt.
1027
+ Nothing reads the set yet.
1028
+
1029
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1030
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
1031
+ ````
1032
+
1033
+ ---
1034
+
1035
+ ### Task 2: Print the start set in bytecode dumps
1036
+
1037
+ **Files:**
1038
+ - Modify: `lib/Regex/RegexSerialization.cpp:343-353`
1039
+ - Modify: `test/hermes/regexp_bytecode.js` (21 `Header:` lines),
1040
+ `test/BCGen/HBC/store_to_env.js:108`
1041
+
1042
+ **Interfaces:**
1043
+ - **Consumes:** Task 1's header fields and `startSetHasASCII`.
1044
+ - **Produces:** the dump line
1045
+ ` StartSet: <hex ranges>[ nonascii]` after ` Header:` when a filter
1046
+ is present (spec, "Storing it").
1047
+
1048
+ - [ ] **Step 1: Update the expected dumps**
1049
+
1050
+ The test uses `--match-full-lines` and `CHECK-NEXT`
1051
+ (`test/hermes/regexp_bytecode.js:8`), so a new line must be expected
1052
+ wherever a filter exists. FileCheck ignores leading whitespace here.
1053
+ Run this script; it inserts after the given 1-based line numbers of the
1054
+ current file, bottom-up:
1055
+
1056
+ ```bash
1057
+ python3 - $R/test/hermes/regexp_bytecode.js <<'EOF'
1058
+ import sys
1059
+ path = sys.argv[1]
1060
+ lines = open(path).read().split('\n')
1061
+ # line number of the case's Header CHECK -> StartSet value
1062
+ inserts = {
1063
+ 15: "0x41 0x61", # 0: /a\x01\u017f/i
1064
+ 23: "0x61", # 1: /^a\u017f\x01$/
1065
+ 33: "0x61-0x62", # 2: /^a|b/
1066
+ 43: "0x61-0x7a", # 3: /[a-z].../
1067
+ 52: "0x61", # 4: /a(b(c)(d))e\1\2/
1068
+ 76: "0x41 0x61", # 6: /abc(?=^)(?!def)/i
1069
+ 88: "0x61", # 7: /ab*c+d{3,5}/
1070
+ 100: "0x61", # 8: /a((b+){3})*/
1071
+ 116: "0x62", # 9: /(^b)+(c)*?/
1072
+ 132: "nonascii", # 10: /[\u017f]/i
1073
+ 145: "0x61", # 12: /a+/
1074
+ 191: "0x41 0x61", # 18: /(a)(?=(.))/i
1075
+ 204: "0x41 0x61", # 19: /(a)(?<!(.))/i
1076
+ 218: "0x61", # 20: /a{255}overflow/
1077
+ 225: "0x41 0x61", # 21: /a{255}overflow/i
1078
+ 232: "0x00-0x09 0x0b-0x0c 0x0e-0x7f nonascii", # 22: /./
1079
+ 238: "0x00-0x09 0x0b-0x0c 0x0e-0x7f nonascii", # 23: /./u
1080
+ 244: "0x00-0x7f nonascii", # 24: /./s
1081
+ 250: "0x00-0x7f nonascii", # 25: /./us
1082
+ 256: "0x61-0x66", # 26: /a|b|c|d|e|f/
1083
+ 277: "0x61 0x64", # 27: /(abc|def)/
1084
+ }
1085
+ for n in sorted(inserts, reverse=True):
1086
+ assert 'Header:' in lines[n - 1], (n, lines[n - 1])
1087
+ lines.insert(n, '// CHECK-NEXT: StartSet: ' + inserts[n])
1088
+ open(path, 'w').write('\n'.join(lines))
1089
+ EOF
1090
+ ```
1091
+
1092
+ Cases 5 (`/\b\B/`), 11 (`/a*/`), 13, 14, 15, 16 and 17 can match the
1093
+ empty string and get no line. Derivations: icase letters are stored
1094
+ uppercase without `/u`, so `'A'` gives 0x41 and 0x61; `/[\u017f]/i`
1095
+ emits only `[0x17f]` (`:133`); `.` excludes 0x0A and 0x0D unless `s`.
1096
+
1097
+ In `test/BCGen/HBC/store_to_env.js`, after line 108
1098
+ (`// CHECK-NEXT: Header: marked: 0 loops: 0 flags: 1 constraints: 4`,
1099
+ for `/Hermes/i`) insert:
1100
+
1101
+ ```js
1102
+ // CHECK-NEXT: StartSet: 0x48 0x68
1103
+ ```
1104
+
1105
+ - [ ] **Step 2: See them fail**
1106
+
1107
+ ```bash
1108
+ LIT_FILTER='regexp_bytecode|store_to_env' \
1109
+ cmake --build $R/cmake-build-asan --target check-hermes
1110
+ ```
1111
+
1112
+ Expected: 2 failures, each `CHECK-NEXT: expected string not found in
1113
+ input` on the first `StartSet:` line.
1114
+
1115
+ - [ ] **Step 3: Print the line** (`lib/Regex/RegexSerialization.cpp`,
1116
+ after the `Header:` print, `:352`)
1117
+
1118
+ ```cpp
1119
+ if (header->startFlags & regex::StartFilterPresent) {
1120
+ // ASCII members as hex ranges in increasing order.
1121
+ OS << " StartSet:";
1122
+ for (uint32_t u = 0; u < 128;) {
1123
+ if (!regex::startSetHasASCII(*header, u)) {
1124
+ ++u;
1125
+ continue;
1126
+ }
1127
+ uint32_t last = u;
1128
+ while (last + 1 < 128 && regex::startSetHasASCII(*header, last + 1))
1129
+ ++last;
1130
+ OS << llvh::format(" 0x%02x", u);
1131
+ if (last != u)
1132
+ OS << llvh::format("-0x%02x", last);
1133
+ u = last + 1;
1134
+ }
1135
+ if (header->startFlags & regex::StartFilterNonASCII)
1136
+ OS << " nonascii";
1137
+ OS << '\n';
1138
+ }
1139
+ ```
1140
+
1141
+ - [ ] **Step 4: Run**
1142
+
1143
+ ```bash
1144
+ cmake --build $R/cmake-build-asan --target hermes hermesc
1145
+ LIT_FILTER='regexp_bytecode|store_to_env' \
1146
+ cmake --build $R/cmake-build-asan --target check-hermes
1147
+ ```
1148
+
1149
+ Expected: 2 passes.
1150
+
1151
+ - [ ] **Step 5: Prove it can fail.** Delete the whole statement
1152
+ `if (header->startFlags & regex::StartFilterNonASCII) OS << " nonascii";`
1153
+ (both lines; deleting only its body would leave the `if` controlling
1154
+ `OS << '\n';`). Rebuild, re-run Step 4. Expected: `regexp_bytecode.js`
1155
+ fails at case 10, the first case with `nonascii` in file order: the
1156
+ line prints `StartSet:` where `StartSet: nonascii` is expected.
1157
+ Restore, rebuild, re-run green.
1158
+
1159
+ - [ ] **Step 6: Full suite** on `cmake-build-asan`: 0 failures; expected
1160
+ passes still baseline + 1 (this task adds no test; it changes two
1161
+ existing lit files).
1162
+
1163
+ - [ ] **Step 7: Commit**
1164
+
1165
+ ```bash
1166
+ git -C $R add lib/Regex/RegexSerialization.cpp \
1167
+ test/hermes/regexp_bytecode.js test/BCGen/HBC/store_to_env.js
1168
+ git -C $R commit -F $S/commit-2.txt
1169
+ ```
1170
+
1171
+ `$S/commit-2.txt`:
1172
+
1173
+ ````
1174
+ Regex: print the start set in regex bytecode dumps
1175
+
1176
+ dumpRegexBytecode prints a line after the header when the regex has a
1177
+ start filter, with the ASCII members as hex ranges and "nonascii" when
1178
+ non-ASCII units may begin a match:
1179
+
1180
+ ```
1181
+ Header: marked: 0 loops: 0 flags: 0 constraints: 4
1182
+ StartSet: 0x61-0x63 0x6b nonascii
1183
+ ```
1184
+
1185
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1186
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
1187
+ ````
1188
+
1189
+ ---
1190
+
1191
+ ### Task 3: Skip start positions in the executor
1192
+
1193
+ **Files:**
1194
+ - Modify: `include/hermes/Regex/RegexTypes.h:33-48`
1195
+ - Modify: `lib/Regex/Executor.cpp` (includes `:8-15`; before `match`,
1196
+ `:1063`; `match`, `:1063-1120`)
1197
+ - Test: `unittests/Support/RegexTest.cpp`
1198
+
1199
+ **Interfaces:**
1200
+ - **Consumes:** Task 1's header fields and `startSetHasASCII`.
1201
+ - **Produces:** `constants::matchNoStartFilter = 1 << 4`, which disables
1202
+ the filter (tests only).
1203
+
1204
+ **Facts this task relies on:**
1205
+ - `match` resets only the cursor and `ip_` per position
1206
+ (`Executor.cpp:1116-1120`); an exhausted position drains its backtrack
1207
+ records (`:803-871`); `backtracksRemaining_` is shared (`:404`).
1208
+ - `onlyAtStart` is true for sticky, `AnchoredAtStart`
1209
+ (`:1665-1668`) and every lookaround recursion (`:1437`), which also
1210
+ runs backwards cursors (`:1089-1093`).
1211
+ - The loop checks `1 + charsToRight` positions (`:1087`); a filtered
1212
+ regex cannot match empty, so the last one needs no attempt.
1213
+ - `advanceStringIndex` steps over a surrogate pair under `/u`
1214
+ (`:1035-1061`).
1215
+ - ASCII-path input is 7-bit (`lib/VM/JSRegExp.cpp:357-365`).
1216
+ - `operator~` on `MatchFlagType` masks to 12 bits (`RegexTypes.h:50-52`),
1217
+ so `1 << 4` is safe.
1218
+
1219
+ - [ ] **Step 1: Write the differential and resource-limit tests**
1220
+
1221
+ Append to `unittests/Support/RegexTest.cpp`, before
1222
+ `} // end anonymous namespace`:
1223
+
1224
+ ```cpp
1225
+ /// \return the outcome of searching \p text (\p length units) for
1226
+ /// \p bytecode from \p start with \p flags: "nomatch", "overflow", or
1227
+ /// "match" and the captures.
1228
+ template <typename CharT>
1229
+ std::string searchOutcome(
1230
+ const std::vector<uint8_t> &bytecode,
1231
+ const CharT *text,
1232
+ uint32_t length,
1233
+ uint32_t start,
1234
+ constants::MatchFlagType flags) {
1235
+ cmatch m;
1236
+ switch (searchWithBytecode(bytecode, text, start, length, &m, flags)) {
1237
+ case MatchRuntimeResult::Match:
1238
+ return "match " + flatten(m);
1239
+ case MatchRuntimeResult::NoMatch:
1240
+ return "nomatch";
1241
+ case MatchRuntimeResult::StackOverflow:
1242
+ return "overflow";
1243
+ }
1244
+ return "?";
1245
+ }
1246
+
1247
+ /// \return \p s with each non-ASCII code unit written as \uXXXX.
1248
+ std::string printable(const std::u16string &s) {
1249
+ std::string out;
1250
+ for (char16_t c : s) {
1251
+ if (c < 0x80) {
1252
+ out += static_cast<char>(c);
1253
+ } else {
1254
+ char buf[8];
1255
+ snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(c));
1256
+ out += buf;
1257
+ }
1258
+ }
1259
+ return out;
1260
+ }
1261
+
1262
+ /// Check that the start filter of \p pattern with \p flags never changes a
1263
+ /// search result: over UTF-16 and ASCII inputs, at every start index, with
1264
+ /// and without matchOnlyAtStart (sticky), the filtered search and the
1265
+ /// unfiltered one (matchNoStartFilter) give the same outcome, unless the
1266
+ /// unfiltered one overflows (spec A.5).
1267
+ void expectStartFilterTransparent(
1268
+ const std::u16string &pattern,
1269
+ const std::u16string &flags) {
1270
+ // Case folds to ASCII (U+017F, U+212A), line terminators, a surrogate
1271
+ // pair, lone surrogates, Latin-1, and ASCII units held as UTF-16
1272
+ // (Review Focus 1). \x escapes are split so no hex digit follows them.
1273
+ static const std::u16string utf16Inputs[] = {
1274
+ u"xaAbsSkK\u017f\u212a",
1275
+ u"b\u2028a\nc\rd e\tf_9",
1276
+ u"\xD83D\xDE00" u"a" u"\xD83D\xDE00",
1277
+ u"a\xD83D" u"b\xDE00" u"c",
1278
+ u"\u00e9\u00c9x1_9",
1279
+ u"abcAB 1\nxyz",
1280
+ u"",
1281
+ };
1282
+ static const std::string asciiInputs[] = {
1283
+ "xaAbsSkK",
1284
+ "b a\nc\rd\te_9",
1285
+ "abcabd012_",
1286
+ "",
1287
+ };
1288
+ cregex re(pattern.c_str(), flags.c_str());
1289
+ ASSERT_TRUE(re.valid()) << printable(pattern);
1290
+ const std::vector<uint8_t> bytecode = re.compile();
1291
+ for (constants::MatchFlagType mode :
1292
+ {constants::matchDefault, constants::matchOnlyAtStart}) {
1293
+ for (const std::u16string &in : utf16Inputs) {
1294
+ const uint32_t len = in.size();
1295
+ for (uint32_t start = 0; start <= len; ++start) {
1296
+ std::string unfiltered = searchOutcome(
1297
+ bytecode,
1298
+ in.data(),
1299
+ len,
1300
+ start,
1301
+ mode | constants::matchNoStartFilter);
1302
+ if (unfiltered == "overflow")
1303
+ continue;
1304
+ EXPECT_EQ(
1305
+ unfiltered, searchOutcome(bytecode, in.data(), len, start, mode))
1306
+ << "/" << printable(pattern) << "/" << printable(flags)
1307
+ << " on \"" << printable(in) << "\" from " << start
1308
+ << (mode ? " sticky" : "");
1309
+ }
1310
+ }
1311
+ for (const std::string &in : asciiInputs) {
1312
+ const uint32_t len = in.size();
1313
+ const constants::MatchFlagType asciiMode =
1314
+ mode | constants::matchInputAllAscii;
1315
+ for (uint32_t start = 0; start <= len; ++start) {
1316
+ std::string unfiltered = searchOutcome(
1317
+ bytecode,
1318
+ in.data(),
1319
+ len,
1320
+ start,
1321
+ asciiMode | constants::matchNoStartFilter);
1322
+ if (unfiltered == "overflow")
1323
+ continue;
1324
+ EXPECT_EQ(
1325
+ unfiltered,
1326
+ searchOutcome(bytecode, in.data(), len, start, asciiMode))
1327
+ << "/" << printable(pattern) << "/" << printable(flags)
1328
+ << " on ascii \"" << in << "\" from " << start
1329
+ << (mode ? " sticky" : "");
1330
+ }
1331
+ }
1332
+ }
1333
+ }
1334
+
1335
+ TEST(Regex, StartFilterTransparent) {
1336
+ const std::pair<std::u16string, std::u16string> corpus[] = {
1337
+ {u"abc", u""},
1338
+ {u"a", u""},
1339
+ {u"a", u"i"},
1340
+ {u"a", u"iu"},
1341
+ {u"s", u"iu"},
1342
+ {u"k", u"iu"},
1343
+ {u"s", u"i"},
1344
+ {u"K", u"i"},
1345
+ {u"\\u017f", u"i"},
1346
+ {u"\\u017f", u"iu"},
1347
+ {u"\\u212a", u"iu"},
1348
+ {u"ab|cd", u""},
1349
+ {u"a|", u""},
1350
+ {u"x*y", u""},
1351
+ {u"x+y", u""},
1352
+ {u"^a", u""},
1353
+ {u"^b", u"m"},
1354
+ {u"a$", u"m"},
1355
+ {u"\\ba", u""},
1356
+ {u"\\bb", u"i"},
1357
+ {u"(?=b)a", u""},
1358
+ {u"(?<=a)b", u""},
1359
+ {u"(?!a)b", u""},
1360
+ {u"(?!a)\\w", u""},
1361
+ {u"(?<!a)\\w", u"u"},
1362
+ {u"\\1(a)", u""},
1363
+ {u"(?=(a))\\1", u""},
1364
+ {u"(a)\\1", u"i"},
1365
+ {u".", u""},
1366
+ {u".", u"s"},
1367
+ {u".", u"u"},
1368
+ {u".a", u"su"},
1369
+ {u"[a-c]", u""},
1370
+ {u"[^a]", u""},
1371
+ {u"[^a]", u"u"},
1372
+ {u"\\d", u""},
1373
+ {u"\\D", u""},
1374
+ {u"\\w", u""},
1375
+ {u"\\w", u"iu"},
1376
+ {u"\\W", u"iu"},
1377
+ {u"\\s", u""},
1378
+ {u"\\s+x", u""},
1379
+ {u"[\\s\\S]a", u""},
1380
+ {u"\\S", u""},
1381
+ {u"[a-z]", u"i"},
1382
+ {u"[a-z]", u"iu"},
1383
+ {u"[a\\u00e9]", u""},
1384
+ {u"[]", u""},
1385
+ {u"[^]", u""},
1386
+ {u"\\u{1F600}", u"u"},
1387
+ {u"[\\u{1F600}x]", u"u"},
1388
+ {u"\\uD83D", u"u"},
1389
+ {u"\\uDE00", u"u"},
1390
+ {u"\\uD83D", u""},
1391
+ {u"\\u2028|\\n", u""},
1392
+ {u"(?i:a)b", u""},
1393
+ {u"a(?i:b)", u""},
1394
+ #ifdef HERMES_ENABLE_UNICODE_REGEXP_PROPERTY_ESCAPES
1395
+ {u"\\p{Lu}", u"u"},
1396
+ {u"\\P{Lu}", u"u"},
1397
+ {u"\\p{Lu}", u"iu"},
1398
+ #endif
1399
+ {nestedGroups(63), u""},
1400
+ {nestedGroups(64), u""},
1401
+ };
1402
+ for (const auto &entry : corpus)
1403
+ expectStartFilterTransparent(entry.first, entry.second);
1404
+ }
1405
+
1406
+ TEST(Regex, StartFilterAvoidsOverflow) {
1407
+ // Spec A.5: unfiltered, position 0 enters the loop and overflows the
1408
+ // backtrack stack before testing 'a'; filtered, no position is tried. It
1409
+ // runs once each way: an unfiltered run builds 2^24 backtrack records.
1410
+ const std::vector<uint8_t> bytecode = cregex(u"(){999999999}a").compile();
1411
+ const char16_t text[] = u"b";
1412
+ cmatch m;
1413
+ EXPECT_EQ(
1414
+ MatchRuntimeResult::StackOverflow,
1415
+ searchWithBytecode(
1416
+ bytecode, text, 0, 1, &m, constants::matchNoStartFilter));
1417
+ EXPECT_EQ(
1418
+ MatchRuntimeResult::NoMatch,
1419
+ searchWithBytecode(bytecode, text, 0, 1, &m, constants::matchDefault));
1420
+ }
1421
+ ```
1422
+
1423
+ - [ ] **Step 2: See it fail**
1424
+
1425
+ ```bash
1426
+ cmake --build $R/cmake-build-asan --target HermesSupportTests
1427
+ ```
1428
+
1429
+ Expected: compile error, `matchNoStartFilter` is not a member of
1430
+ `constants`.
1431
+
1432
+ - [ ] **Step 3: The flag** (`include/hermes/Regex/RegexTypes.h`, after
1433
+ `matchOnlyAtStart = 1 << 3,` at `:47`)
1434
+
1435
+ ```cpp
1436
+
1437
+ /// Do not use the start-position filter. Only tests use it, to compare
1438
+ /// filtered and unfiltered searches.
1439
+ matchNoStartFilter = 1 << 4,
1440
+ ```
1441
+
1442
+ - [ ] **Step 4: The filter** (`lib/Regex/Executor.cpp`)
1443
+
1444
+ Add `#include <cstring>` after the `llvh` includes (`:15`). Before
1445
+ `template <class Traits> auto Context<Traits>::match` (`:1063`) add:
1446
+
1447
+ ```cpp
1448
+ /// \return the first index i in [\p from, \p length) such that the code
1449
+ /// unit \p start[i] can begin a match according to the start filter of
1450
+ /// \p header, or \p length if there is none. This is the ASCII-path
1451
+ /// overload: every unit is 7-bit, so the non-ASCII bit is irrelevant.
1452
+ static inline size_t findStartCandidate(
1453
+ const RegexBytecodeHeader &header,
1454
+ const char *start,
1455
+ size_t from,
1456
+ size_t length) {
1457
+ if (header.startFlags & StartFilterSingleChar) {
1458
+ const void *found =
1459
+ std::memchr(start + from, header.startChar, length - from);
1460
+ return found ? static_cast<const char *>(found) - start : length;
1461
+ }
1462
+ for (size_t i = from; i < length; ++i) {
1463
+ const uint8_t u = static_cast<uint8_t>(start[i]);
1464
+ assert(u < 128 && "ASCII-path input must be 7-bit");
1465
+ if (startSetHasASCII(header, u))
1466
+ return i;
1467
+ }
1468
+ return length;
1469
+ }
1470
+
1471
+ /// \return the first index i in [\p from, \p length) such that the code
1472
+ /// unit \p start[i] can begin a match according to the start filter of
1473
+ /// \p header, or \p length if there is none. A unit >= 0x80 passes iff
1474
+ /// StartFilterNonASCII is set.
1475
+ static inline size_t findStartCandidate(
1476
+ const RegexBytecodeHeader &header,
1477
+ const char16_t *start,
1478
+ size_t from,
1479
+ size_t length) {
1480
+ const bool nonASCII = header.startFlags & StartFilterNonASCII;
1481
+ if (header.startFlags & StartFilterSingleChar) {
1482
+ const char16_t only = header.startChar;
1483
+ for (size_t i = from; i < length; ++i) {
1484
+ const char16_t u = start[i];
1485
+ if (u == only || (u >= 0x80 && nonASCII))
1486
+ return i;
1487
+ }
1488
+ return length;
1489
+ }
1490
+ for (size_t i = from; i < length; ++i) {
1491
+ const char16_t u = start[i];
1492
+ if (u >= 0x80 ? nonASCII : startSetHasASCII(header, u))
1493
+ return i;
1494
+ }
1495
+ return length;
1496
+ }
1497
+ ```
1498
+
1499
+ In `match`, after `const size_t locsToCheckCount = ...;` (`:1087`) add:
1500
+
1501
+ ```cpp
1502
+ // The start-position filter. Only a search that tries several positions
1503
+ // uses it: sticky and anchored searches and every lookaround recursion
1504
+ // (which may run a backwards cursor) pass onlyAtStart.
1505
+ const auto *header =
1506
+ reinterpret_cast<const RegexBytecodeHeader *>(bytecodeStream_.data());
1507
+ const bool useStartFilter = !onlyAtStart &&
1508
+ (header->startFlags & StartFilterPresent) &&
1509
+ !(flags_ & constants::matchNoStartFilter);
1510
+ ```
1511
+
1512
+ At the top of the loop body (`:1118`, before
1513
+ `const CodeUnit *potentialMatchLocation = ...`) add:
1514
+
1515
+ ```cpp
1516
+ if (useStartFilter) {
1517
+ // Skip to the first position whose unit can begin a match. A filtered
1518
+ // regex cannot match the empty string, so the position at the end of
1519
+ // the input needs no attempt. Under /u, every non-ASCII unit is
1520
+ // treated alike, so the scan stops on a high surrogate before its low
1521
+ // surrogate, and advanceStringIndex then steps over the pair.
1522
+ locIndex = findStartCandidate(*header, startLoc, locIndex, charsToRight);
1523
+ if (locIndex >= charsToRight)
1524
+ return nullptr;
1525
+ }
1526
+ ```
1527
+
1528
+ The `backtrackingSucceeded:` label (`:1121`) stays after these lines:
1529
+ `BACKTRACK()` jumps there within the same position, past the skip.
1530
+
1531
+ - [ ] **Step 5: Run**
1532
+
1533
+ ```bash
1534
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes \
1535
+ HermesSupportTests
1536
+ $R/cmake-build-asan/unittests/Support/HermesSupportTests \
1537
+ --gtest_filter='Regex.*'
1538
+ ```
1539
+
1540
+ Expected: all pass, including `StartFilterTransparent` and
1541
+ `StartFilterAvoidsOverflow`.
1542
+
1543
+ - [ ] **Step 6: Prove the tests can fail** (rebuild after each edit and
1544
+ restore; run the Step 5 command). These are the spec's mutations
1545
+ ("Tests", Part A, "Mutations it must catch"):
1546
+ - M1 (Task 1 Step 11). Fails `StartFilterTransparent`, e.g. `/a/i` on
1547
+ `"xaAbsSkK..."` from 0: unfiltered `match (1-2)`, filtered
1548
+ `match (2-3)`.
1549
+ - M2. Fails: `/s/iu` on `"xaAbsSkK\u017f\u212a"` from 6: unfiltered
1550
+ `match (8-9)`, filtered `nomatch`.
1551
+ - M3. Fails: `/(?!a)b/` on `"xaAbsSkK..."` from 0: unfiltered
1552
+ `match (3-4)`, filtered `nomatch`.
1553
+ - M4. Fails: `/./` on `"\u00e9\u00c9x1_9"` from 0: unfiltered
1554
+ `match (0-1)`, filtered `match (2-3)`.
1555
+ - M8, filter when `onlyAtStart`: change the `useStartFilter`
1556
+ initializer to start `(header->startFlags & StartFilterPresent) &&`,
1557
+ dropping `!onlyAtStart &&`. Fails: `/a/i` sticky on `"xaAbsSkK..."`
1558
+ from 0: unfiltered `nomatch`, filtered `match (1-2)`.
1559
+ - M9, no filter: change the `useStartFilter` initializer to `false`.
1560
+ Fails `StartFilterAvoidsOverflow`: the second search is
1561
+ `StackOverflow`.
1562
+
1563
+ - [ ] **Step 7: Full suite** on `cmake-build-asan`: 0 failures; expected
1564
+ passes baseline + 3 (this task adds `Regex.StartFilterTransparent` and
1565
+ `Regex.StartFilterAvoidsOverflow`). This covers
1566
+ `test/hermes/regexp*.js`, `regex*.js`,
1567
+ `regress-regexp-*.js` and `test/shermes/regexp-aot.js`.
1568
+
1569
+ - [ ] **Step 8: Commit**
1570
+
1571
+ ```bash
1572
+ git -C $R add include/hermes/Regex/RegexTypes.h lib/Regex/Executor.cpp \
1573
+ unittests/Support/RegexTest.cpp
1574
+ git -C $R commit -F $S/commit-3.txt
1575
+ ```
1576
+
1577
+ `$S/commit-3.txt` (Task 8 adds the measurements):
1578
+
1579
+ ````
1580
+ Regex: skip start positions that cannot begin a match
1581
+
1582
+ Context::match ran the whole instruction loop at every start position.
1583
+ Over one Octane RegExp run, 278M of 282M positions failed, most after
1584
+ one instruction, and failed positions took 95% of dispatched
1585
+ instructions.
1586
+
1587
+ When a search tries more than one position and the regex has a start
1588
+ filter, the loop now advances to the first position whose code unit is
1589
+ in the start set, and returns no match when there is none. ASCII input
1590
+ uses memchr for a single start character and the bitmap otherwise;
1591
+ UTF-16 input accepts a unit of 0x80 or more iff the non-ASCII bit is
1592
+ set. Sticky and anchored searches and lookaround recursion never use
1593
+ it.
1594
+
1595
+ A position the filter skips could only have failed. It ran with no more
1596
+ budget than the positions after it, so results change only where the
1597
+ unfiltered search hit the regex resource limit: the filter may avoid a
1598
+ "Maximum regex stack depth reached" RangeError, never cause one, e.g.
1599
+
1600
+ ```
1601
+ /(){999999999}a/.exec("b") // was RangeError, now null
1602
+ ```
1603
+
1604
+ A new match flag, matchNoStartFilter, disables the filter; the unit
1605
+ tests compare filtered and unfiltered searches over a corpus.
1606
+
1607
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1608
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
1609
+ ````
1610
+
1611
+ ---
1612
+
1613
+ ### Task 4: Split the builtin exec core from the result array
1614
+
1615
+ **Files:**
1616
+ - Modify: `lib/VM/JSLib/RegExp.cpp:898-1111` (`directRegExpExec`),
1617
+ `:1235-1246` (`regExpPrototypeTest`), `:2531` (`@@split`)
1618
+ - Modify: `include/hermes/VM/Runtime.h` (includes `:11-45`; after
1619
+ `regExpLastMatch`, `:935`)
1620
+ - Modify: `lib/VM/JSRegExp.cpp:293-309` (`performSearch`)
1621
+ - Create: `test/hermes/regexp-exec-fast-path.js`
1622
+
1623
+ **Interfaces:**
1624
+ - **Produces:**
1625
+ ```cpp
1626
+ static CallResult<bool> regExpBuiltinExecMatch(
1627
+ Handle<JSRegExp> regexp, Runtime &runtime, Handle<StringPrimitive> S,
1628
+ RegExpMatch &match);
1629
+ ```
1630
+ in `RegExp.cpp`, defined before `directRegExpExec`; and
1631
+ `std::vector<regex::CapturedRange> Runtime::regExpSearchCaptures`.
1632
+ Tasks 5-7 call `regExpBuiltinExecMatch`.
1633
+
1634
+ **Facts this task relies on:**
1635
+ - The observable operations of `directRegExpExec` are the `Get` and
1636
+ `ToLength` of `lastIndex` (`RegExp.cpp:917-927`) and one `Set` of
1637
+ `lastIndex` to 0 or `e` (`:977-1011`); the statics are written by
1638
+ `JSRegExp::search` on success (`lib/VM/JSRegExp.cpp:376-383`).
1639
+ - `test` already requires a `JSRegExp`, never looks up `exec`, and runs
1640
+ `ToString` on its argument (`RegExp.cpp:1198-1246`).
1641
+ - `performSearch` allocates a `std::vector<regex::CapturedRange>` per
1642
+ search (`JSRegExp.cpp:301`), and the executor clears and refills it
1643
+ (`lib/Regex/Executor.cpp:1676-1686`) without running JS or allocating
1644
+ on the GC heap.
1645
+ - `@@split` copies its `RegExpMatch` (`RegExp.cpp:2531`).
1646
+
1647
+ **GC safety.** `regexp` and `S` are handles; `RegExpMatch` holds only
1648
+ integers (`include/hermes/VM/RegExpMatch.h:18-30`). The core keeps the
1649
+ `GCScope` that `directRegExpExec` opened (`:912`), so handles created by
1650
+ `toLengthU64` and `JSRegExp::search` are freed on return.
1651
+
1652
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
1653
+
1654
+ - [ ] **Step 2: Write the regression test**
1655
+
1656
+ Create `test/hermes/regexp-exec-fast-path.js`:
1657
+
1658
+ ```js
1659
+ /**
1660
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1661
+ *
1662
+ * This source code is licensed under the MIT license found in the
1663
+ * LICENSE file in the root directory of this source tree.
1664
+ */
1665
+
1666
+ // RUN: %hermes %s | %FileCheck --match-full-lines %s
1667
+ // RUN: %hermes -lazy %s | %FileCheck --match-full-lines %s
1668
+ // RUN: %hermes -gc-sanitize-handles=1 %s | %FileCheck --match-full-lines %s
1669
+ // RUN: %shermes -exec %s | %FileCheck --match-full-lines %s
1670
+
1671
+ // The RegExp library skips the JS-level call of RegExp.prototype.exec when
1672
+ // exec is the builtin. Every observable effect of the call must remain: user
1673
+ // replacements of exec, the exec lookups, lastIndex coercion and writes,
1674
+ // the legacy statics, and the native exec frame in stack traces.
1675
+
1676
+ /// \return a printable form of \p v: strings quoted with non-ASCII escaped,
1677
+ /// arrays bracketed, undefined and null by name.
1678
+ function show(v) {
1679
+ if (v === undefined) return "undefined";
1680
+ if (v === null) return "null";
1681
+ if (typeof v === "string") {
1682
+ var out = '"';
1683
+ for (var i = 0; i < v.length; ++i) {
1684
+ var c = v.charCodeAt(i);
1685
+ out += c < 0x20 || c > 0x7e
1686
+ ? "\\u" + c.toString(16).padStart(4, "0") : v[i];
1687
+ }
1688
+ return out + '"';
1689
+ }
1690
+ if (Array.isArray(v)) return "[" + v.map(show).join(",") + "]";
1691
+ if (typeof v === "object") {
1692
+ return "{" + Object.keys(v).map(function (k) {
1693
+ return k + ":" + show(v[k]);
1694
+ }).join(",") + "}";
1695
+ }
1696
+ return String(v);
1697
+ }
1698
+
1699
+ /// \return whether the stack trace \p stack has a frame for the native exec.
1700
+ function hasExecFrame(stack) {
1701
+ return stack.indexOf("at exec (native)") >= 0;
1702
+ }
1703
+
1704
+ /// Run \p body with RegExp.prototype.exec replaced by \p exec, restoring
1705
+ /// the builtin afterwards.
1706
+ function withProtoExec(exec, body) {
1707
+ var saved = RegExp.prototype.exec;
1708
+ RegExp.prototype.exec = exec;
1709
+ try {
1710
+ body();
1711
+ } finally {
1712
+ RegExp.prototype.exec = saved;
1713
+ }
1714
+ }
1715
+
1716
+ function replacedExec(builtinExec) {
1717
+ print("replaced exec");
1718
+ var log = [];
1719
+ function counting(s) {
1720
+ log.push(this.source + "@" + this.lastIndex + ":" + s);
1721
+ return builtinExec.call(this, s);
1722
+ }
1723
+ withProtoExec(counting, function () {
1724
+ log = [];
1725
+ print(show("abab".match(/ab/g)), show(log));
1726
+ log = [];
1727
+ print(show("abab".replace(/ab/g, "x")), show(log));
1728
+ log = [];
1729
+ print(show("abab".replace(/ab/g, function (m) { return m.toUpperCase(); })),
1730
+ show(log));
1731
+ log = [];
1732
+ print("abab".search(/b/), show(log));
1733
+ log = [];
1734
+ print(show("abab".match(/b/)), show(log));
1735
+ });
1736
+ }
1737
+ // CHECK-LABEL: replaced exec
1738
+ // CHECK-NEXT: ["ab","ab"] ["ab@0:abab","ab@2:abab","ab@4:abab"]
1739
+ // CHECK-NEXT: "xx" ["ab@0:abab","ab@2:abab","ab@4:abab"]
1740
+ // CHECK-NEXT: "ABAB" ["ab@0:abab","ab@2:abab","ab@4:abab"]
1741
+ // CHECK-NEXT: 1 ["b@0:abab"]
1742
+ // CHECK-NEXT: ["b"] ["b@0:abab"]
1743
+
1744
+ function ownAndSubclassExec(builtinExec) {
1745
+ print("own and subclass exec");
1746
+ var n = 0;
1747
+ var re = /a/g;
1748
+ re.exec = function (s) { ++n; return builtinExec.call(this, s); };
1749
+ print(show("aa".match(re)), show("aa".replace(re, "b")), "aa".search(re), n);
1750
+ class Sub extends RegExp {
1751
+ exec(s) { ++n; return super.exec(s); }
1752
+ }
1753
+ n = 0;
1754
+ var sub = new Sub("a", "g");
1755
+ print(show("aa".match(sub)), show("aa".replace(sub, "b")), "aa".search(sub),
1756
+ n);
1757
+ }
1758
+ // CHECK-LABEL: own and subclass exec
1759
+ // CHECK-NEXT: ["a","a"] "bb" 0 7
1760
+ // CHECK-NEXT: ["a","a"] "bb" 0 7
1761
+
1762
+ function execAccessor(builtinExec) {
1763
+ print("exec accessor");
1764
+ var gets = 0;
1765
+ Object.defineProperty(RegExp.prototype, "exec", {
1766
+ get: function () { ++gets; return builtinExec; },
1767
+ configurable: true,
1768
+ });
1769
+ try {
1770
+ print(show("abab".match(/ab/g)), gets);
1771
+ gets = 0;
1772
+ print(show("abab".replace(/ab/g, "x")), gets);
1773
+ gets = 0;
1774
+ print("abab".search(/b/), gets);
1775
+ } finally {
1776
+ Object.defineProperty(RegExp.prototype, "exec", {
1777
+ value: builtinExec,
1778
+ writable: true,
1779
+ configurable: true,
1780
+ });
1781
+ }
1782
+ }
1783
+ // CHECK-LABEL: exec accessor
1784
+ // CHECK-NEXT: ["ab","ab"] 3
1785
+ // CHECK-NEXT: "xx" 3
1786
+ // CHECK-NEXT: 1 1
1787
+
1788
+ function proxyPrototype() {
1789
+ print("proxy prototype");
1790
+ var log = [];
1791
+ var proxy = new Proxy(RegExp.prototype, {
1792
+ get: function (target, key, receiver) {
1793
+ if (key === "exec") log.push("exec");
1794
+ return Reflect.get(target, key, receiver);
1795
+ },
1796
+ });
1797
+ var re = /ab/g;
1798
+ Object.setPrototypeOf(re, proxy);
1799
+ print(show(RegExp.prototype[Symbol.match].call(re, "abab")), log.length);
1800
+ log = [];
1801
+ print(show(RegExp.prototype[Symbol.replace].call(re, "abab", "x")),
1802
+ log.length);
1803
+ log = [];
1804
+ print(RegExp.prototype[Symbol.search].call(re, "abab"), log.length);
1805
+ }
1806
+ // CHECK-LABEL: proxy prototype
1807
+ // CHECK-NEXT: ["ab","ab"] 3
1808
+ // CHECK-NEXT: "xx" 3
1809
+ // CHECK-NEXT: 0 1
1810
+
1811
+ function frozen() {
1812
+ print("frozen");
1813
+ var re = Object.freeze(/a/g);
1814
+ try {
1815
+ "aa".match(re);
1816
+ } catch (e) {
1817
+ print(e.name, hasExecFrame(e.stack));
1818
+ }
1819
+ try {
1820
+ "aa".replace(re, "b");
1821
+ } catch (e) {
1822
+ print(e.name, hasExecFrame(e.stack));
1823
+ }
1824
+ }
1825
+ // CHECK-LABEL: frozen
1826
+ // CHECK-NEXT: TypeError false
1827
+ // CHECK-NEXT: TypeError false
1828
+
1829
+ function lastIndexValueOf() {
1830
+ print("lastIndex valueOf");
1831
+ var n = 0;
1832
+ var re = /a/;
1833
+ re.lastIndex = { valueOf: function () { ++n; return 0; } };
1834
+ re.exec("a");
1835
+ re.test("a");
1836
+ "a".match(re);
1837
+ "a".replace(re, "b");
1838
+ "a".search(re);
1839
+ print(n, typeof re.lastIndex);
1840
+ }
1841
+ // CHECK-LABEL: lastIndex valueOf
1842
+ // CHECK-NEXT: 4 object
1843
+
1844
+ function statics() {
1845
+ print("statics");
1846
+ function dump() {
1847
+ return [RegExp.$1, RegExp.lastMatch, RegExp.leftContext,
1848
+ RegExp.rightContext].join("|");
1849
+ }
1850
+ /(z)/.exec("z");
1851
+ /(\d)(\d)/.test("x12y");
1852
+ print(dump(), RegExp.$2);
1853
+ "a1b2c".match(/(\d)/g);
1854
+ print(dump());
1855
+ "xx3y".search(/(\d)/);
1856
+ print(dump());
1857
+ "p4q5r".replace(/(\d)/g, "-");
1858
+ print(dump());
1859
+ var seen = [];
1860
+ "p6q7r".replace(/(\d)/g, function (m) { seen.push(RegExp.$1); return m; });
1861
+ print(seen.join(","), dump());
1862
+ }
1863
+ // CHECK-LABEL: statics
1864
+ // CHECK-NEXT: 1|12|x|y 2
1865
+ // CHECK-NEXT: 2|2|a1b|c
1866
+ // CHECK-NEXT: 3|3|xx|y
1867
+ // CHECK-NEXT: 5|5|p4q|r
1868
+ // CHECK-NEXT: 7,7 7|7|p6q|r
1869
+
1870
+ function emptyMatches() {
1871
+ print("empty matches");
1872
+ // Under /u the loop steps over the pair. The \uDE00 alternative matches
1873
+ // only a lone low surrogate, which a search started inside the pair sees:
1874
+ // so a loop that stepped by one code unit would match the pair (index
1875
+ // moved back by GetStringIndex) instead of looping on /(?:)/gu forever.
1876
+ var s = "\uD83D\uDE00x";
1877
+ print(show(s.match(/\uDE00|(?:)/gu)), show(s.match(/(?:)/g)));
1878
+ print(show(s.replace(/\uDE00|(?:)/gu, "-")), show(s.replace(/(?:)/g, "-")));
1879
+ }
1880
+ // CHECK-LABEL: empty matches
1881
+ // CHECK-NEXT: ["","",""] ["","","",""]
1882
+ // CHECK-NEXT: "-\ud83d\ude00-x-" "-\ud83d-\ude00-x-"
1883
+
1884
+ function stickyGlobal() {
1885
+ print("sticky global");
1886
+ print(show("aab".match(/a/gy)), show("baa".match(/a/gy)));
1887
+ print(show("aaba".replace(/a/gy, "x")), show("baa".replace(/a/gy, "x")));
1888
+ }
1889
+ // CHECK-LABEL: sticky global
1890
+ // CHECK-NEXT: ["a","a"] null
1891
+ // CHECK-NEXT: "xxba" "baa"
1892
+
1893
+ function replacements() {
1894
+ print("replacements");
1895
+ print(show("John Smith".replace(/(?<first>\w+)\s(?<last>\w+)/,
1896
+ "$<last>, $<first> [$1|$2|$&|$`|$']")));
1897
+ print(show("x-ab-y".replace(/(a)(z)?(b)/, "[$1|$2|$3|$&|$`|$']")));
1898
+ print(show("ab".replace(/(a)|(b)/g, "[$1|$2]")));
1899
+ "x-ab-y".replace(/(a)(z)?(b)/, function () {
1900
+ print(show(Array.prototype.slice.call(arguments)));
1901
+ return "";
1902
+ });
1903
+ "x-ab-y".replace(/(?<p>a)(?<q>z)?b/g, function () {
1904
+ print(show(Array.prototype.slice.call(arguments)));
1905
+ return "";
1906
+ });
1907
+ }
1908
+ // CHECK-LABEL: replacements
1909
+ // CHECK-NEXT: "Smith, John [John|Smith|John Smith||]"
1910
+ // CHECK-NEXT: "x-[a||b|ab|x-|-y]-y"
1911
+ // CHECK-NEXT: "[a|][|b]"
1912
+ // CHECK-NEXT: ["ab","a",undefined,"b",2,"x-ab-y"]
1913
+ // CHECK-NEXT: ["ab","a",undefined,2,"x-ab-y",{p:"a",q:undefined}]
1914
+
1915
+ function hasIndices() {
1916
+ print("hasIndices");
1917
+ var m = "xab".match(/a(b)/d);
1918
+ print(show(m), m.index, show(m.indices));
1919
+ }
1920
+ // CHECK-LABEL: hasIndices
1921
+ // CHECK-NEXT: ["ab","b"] 1 {{\[}}[1,3],[2,3]]
1922
+
1923
+ function unicodeGetter() {
1924
+ print("unicode getter");
1925
+ // @@match and @@replace advance past an empty match by Get(rx, "unicode"),
1926
+ // not by the regexp's own flag.
1927
+ var re = /(?:)/g;
1928
+ Object.defineProperty(re, "unicode", { value: true });
1929
+ var s = "\uD83D\uDE00x";
1930
+ print(show(s.match(re)), show(s.replace(re, "-")));
1931
+ }
1932
+ // CHECK-LABEL: unicode getter
1933
+ // CHECK-NEXT: ["","",""] "-\ud83d\ude00-x-"
1934
+
1935
+ function reentrantCallback() {
1936
+ print("reentrant callback");
1937
+ // The callback runs after every exec of phase 1, and may use the same
1938
+ // regexp.
1939
+ var re = /\d/g;
1940
+ var out = "a1b2c".replace(re, function (d) {
1941
+ var inner = "7z8".replace(re, "q");
1942
+ return "<" + d + inner + re.lastIndex + RegExp.lastMatch + ">";
1943
+ });
1944
+ print(out, re.lastIndex, RegExp.lastMatch);
1945
+ }
1946
+ // CHECK-LABEL: reentrant callback
1947
+ // CHECK-NEXT: a<1qzq08>b<2qzq08>c 0 8
1948
+
1949
+ function stacks() {
1950
+ print("stacks");
1951
+ var stack = "";
1952
+ var re = /a/;
1953
+ re.lastIndex = {
1954
+ valueOf: function () { stack = new Error().stack; return 0; },
1955
+ };
1956
+ "xa".match(re);
1957
+ print("match", hasExecFrame(stack));
1958
+ stack = "";
1959
+ "xa".replace(re, "b");
1960
+ print("replace", hasExecFrame(stack));
1961
+ stack = "";
1962
+ re.test("xa");
1963
+ print("test", hasExecFrame(stack));
1964
+ try {
1965
+ Object.freeze(/a/y)[Symbol.match]("a");
1966
+ } catch (e) {
1967
+ print("sticky", e.name, hasExecFrame(e.stack));
1968
+ }
1969
+ try {
1970
+ "b".match(/(){999999999}/g);
1971
+ } catch (e) {
1972
+ print("global match limit", e.name, hasExecFrame(e.stack));
1973
+ }
1974
+ try {
1975
+ "b".search(/(){999999999}/);
1976
+ } catch (e) {
1977
+ print("search limit", e.name, hasExecFrame(e.stack));
1978
+ }
1979
+ }
1980
+ // CHECK-LABEL: stacks
1981
+ // CHECK-NEXT: match true
1982
+ // CHECK-NEXT: replace true
1983
+ // CHECK-NEXT: test false
1984
+ // CHECK-NEXT: sticky TypeError true
1985
+ // CHECK-NEXT: global match limit RangeError true
1986
+ // CHECK-NEXT: search limit RangeError true
1987
+
1988
+ function main() {
1989
+ var builtinExec = RegExp.prototype.exec;
1990
+ replacedExec(builtinExec);
1991
+ ownAndSubclassExec(builtinExec);
1992
+ execAccessor(builtinExec);
1993
+ proxyPrototype();
1994
+ frozen();
1995
+ lastIndexValueOf();
1996
+ statics();
1997
+ emptyMatches();
1998
+ stickyGlobal();
1999
+ replacements();
2000
+ hasIndices();
2001
+ unicodeGetter();
2002
+ reentrantCallback();
2003
+ stacks();
2004
+ }
2005
+
2006
+ main();
2007
+ ```
2008
+
2009
+ Notes for the reviewer:
2010
+ - The expected lines are today's output. This exact file, extracted
2011
+ from this plan, was run through FileCheck at BASE's code (b2e83b329,
2012
+ which has no source change from BASE) on `cmake-build-asan` under
2013
+ every RUN line (`hermes`, `-lazy`, `-gc-sanitize-handles=1`,
2014
+ `shermes -exec`, and also `-O`) and on `cmake-build-hsan` with
2015
+ `-gc-sanitize-handles=1`; all passed. Every string is printed through
2016
+ `show()`, which escapes each code unit above 0x7e, so no expected line
2017
+ holds non-ASCII. The test is a regression guard: it passes before Part B
2018
+ and must still pass after it.
2019
+ - `(){999999999}` can match the empty string, so it has no start filter
2020
+ and still hits the limit inside exec after Part A.
2021
+ - `@@search` overwrites `lastIndex` with 0 before exec
2022
+ (`RegExp.cpp:1953`), so its `lastIndex.valueOf` never runs: the count
2023
+ is 4 (exec, test, match, replace).
2024
+ - `{{\[}}` keeps FileCheck from reading `[[` as a variable.
2025
+ - The callbacks in `statics` see `7,7`: phase 2 runs after every exec.
2026
+
2027
+ - [ ] **Step 3: Run it at BASE and save the expected output**
2028
+
2029
+ ```bash
2030
+ LIT_FILTER='regexp-exec-fast-path' \
2031
+ cmake --build $R/cmake-build-asan --target check-hermes
2032
+ $R/cmake-build-asan/bin/hermes $R/test/hermes/regexp-exec-fast-path.js \
2033
+ > $S/fast-path.expected
2034
+ ```
2035
+
2036
+ Expected: 1 pass. `$S/fast-path.expected` is the reference for every
2037
+ Part B mutation diff.
2038
+
2039
+ - [ ] **Step 4: Split `directRegExpExec`** (`lib/VM/JSLib/RegExp.cpp`)
2040
+
2041
+ Insert before `// ES6 21.2.5.2.2` (`:898`):
2042
+
2043
+ ```cpp
2044
+ /// ES6 21.2.5.2.2 RegExpBuiltinExec ( R, S ) up to, but not including,
2045
+ /// building the result array: the Get and ToLength of lastIndex, the
2046
+ /// search, the Set of lastIndex, and the unicode adjustment of the ranges.
2047
+ /// \return false on no match; on a match, set \p match to its ranges
2048
+ /// (element 0 is the whole match) and \return true.
2049
+ static CallResult<bool> regExpBuiltinExecMatch(
2050
+ Handle<JSRegExp> regexp,
2051
+ Runtime &runtime,
2052
+ Handle<StringPrimitive> S,
2053
+ RegExpMatch &match) {
2054
+ struct : public Locals {
2055
+ PinnedValue<> propHandle;
2056
+ } lv;
2057
+ LocalsRAII lraii(runtime, &lv);
2058
+
2059
+ GCScope gcScope{runtime};
2060
+
2061
+ // Let length be the number of code units in S.
2062
+ const uint32_t length = S->getStringLength();
2063
+
2064
+ // Let lastIndex be ? ToLength(? Get(R, "lastIndex")).
2065
+ auto propRes = runtime.getNamed(regexp, PropCacheID::RegExpLastIndex);
2066
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
2067
+ return ExecutionStatus::EXCEPTION;
2068
+ }
2069
+ lv.propHandle = std::move(*propRes);
2070
+ auto lengthRes = toLengthU64(runtime, lv.propHandle);
2071
+ if (LLVM_UNLIKELY(lengthRes == ExecutionStatus::EXCEPTION)) {
2072
+ return ExecutionStatus::EXCEPTION;
2073
+ }
2074
+ uint64_t lastIndex = *lengthRes;
2075
+
2076
+ // Let flags be R.[[OriginalFlags]]
2077
+ const regex::SyntaxFlags flags = JSRegExp::getSyntaxFlags(regexp.get());
2078
+
2079
+ // If flags contains "g", let global be true, else let global be false
2080
+ // If flags contains "y", let sticky be true, else let sticky be false.
2081
+ // If flags contains "u", let fullUnicode be true, else let fullUnicode be
2082
+ // false.
2083
+ const bool global = flags.global;
2084
+ const bool sticky = flags.sticky;
2085
+ const bool fullUnicode = flags.unicode;
2086
+
2087
+ // If global is false and sticky is false, set lastIndex to 0.
2088
+ if (!global && !sticky) {
2089
+ lastIndex = 0;
2090
+ }
2091
+
2092
+ // The ES6 spec is cast in terms of a loop on "matchSucceeded". This is
2093
+ // handled internally by JSRegExp::search for efficiency reasons.
2094
+ // (Note that lastIndex == length is allowed: it may match an empty range at
2095
+ // the end of the string.)
2096
+ match.clear();
2097
+ if (lastIndex <= length) {
2098
+ assert(
2099
+ lastIndex <= UINT32_MAX &&
2100
+ "lastIndex should fit in u32 because it is <= a string length");
2101
+ uint32_t searchStartOffset = static_cast<uint32_t>(lastIndex);
2102
+ auto matchResult = JSRegExp::search(regexp, runtime, S, searchStartOffset);
2103
+ if (LLVM_UNLIKELY(matchResult == ExecutionStatus::EXCEPTION))
2104
+ return ExecutionStatus::EXCEPTION;
2105
+ match = std::move(*matchResult);
2106
+ }
2107
+
2108
+ if (match.empty()) {
2109
+ // No match. The following implements both:
2110
+ // If lastIndex > length, then
2111
+ // If global is true or sticky is true, then
2112
+ // Let setStatus be Set(R, "lastIndex", 0, true);
2113
+ // ReturnIfAbrupt(setStatus)
2114
+ // return null
2115
+ // and also:
2116
+ // If r is failure, then
2117
+ // If sticky is true, then
2118
+ // Let setStatus be Set(R, "lastIndex", 0, true);
2119
+ // ReturnIfAbrupt(setStatus)
2120
+ // Return null
2121
+ if (global || sticky) {
2122
+ if (LLVM_UNLIKELY(
2123
+ setLastIndex(regexp, runtime, 0) == ExecutionStatus::EXCEPTION)) {
2124
+ return ExecutionStatus::EXCEPTION;
2125
+ }
2126
+ }
2127
+ return false;
2128
+ }
2129
+
2130
+ // We have a match!
2131
+ // If using unicode, ensure that no indices can be set to a trailing
2132
+ // surrogate.
2133
+ if (fullUnicode) {
2134
+ for (auto &mg : match) {
2135
+ if (!mg)
2136
+ continue;
2137
+ auto captureStart = getStringIndex(S, mg->location);
2138
+ auto captureEnd = getStringIndex(S, mg->location + mg->length);
2139
+ mg = RegExpMatchRange{captureStart, captureEnd - captureStart};
2140
+ }
2141
+ }
2142
+
2143
+ // "If global is true or sticky is true, Let setStatus be Set(R, "lastIndex",
2144
+ // e, true)."
2145
+ // Here 'e' is the end of the total match.
2146
+ if (global || sticky) {
2147
+ auto totalMatch = *match.front();
2148
+ uint32_t e = totalMatch.location + totalMatch.length;
2149
+ if (LLVM_UNLIKELY(
2150
+ setLastIndex(regexp, runtime, e) == ExecutionStatus::EXCEPTION)) {
2151
+ return ExecutionStatus::EXCEPTION;
2152
+ }
2153
+ }
2154
+ return true;
2155
+ }
2156
+ ```
2157
+
2158
+ Then make `directRegExpExec` the core followed by the array building.
2159
+ Replace its Locals and everything from `GCScope gcScope{runtime};`
2160
+ (`:912`) through the `lastIndex` `Set` (`:1012`) with:
2161
+
2162
+ ```cpp
2163
+ struct : public Locals {
2164
+ PinnedValue<JSArray> A;
2165
+ PinnedValue<StringPrimitive> strHandle;
2166
+ PinnedValue<JSArray> indicesArray;
2167
+ } lv;
2168
+ LocalsRAII lraii(runtime, &lv);
2169
+
2170
+ GCScope gcScope{runtime};
2171
+
2172
+ RegExpMatch match;
2173
+ auto matchRes = regExpBuiltinExecMatch(regexp, runtime, S, match);
2174
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION))
2175
+ return ExecutionStatus::EXCEPTION;
2176
+ if (!*matchRes) {
2177
+ resultOut.clear();
2178
+ return ExecutionStatus::RETURNED;
2179
+ }
2180
+
2181
+ // If flags contains "d", let hasIndices be true, else let hasIndices be
2182
+ // false.
2183
+ const bool hasIndices = JSRegExp::getSyntaxFlags(regexp.get()).hasIndices;
2184
+ ```
2185
+
2186
+ Everything from `auto arrRes = JSArray::createAndAllocPropStorage(`
2187
+ (`:1014`) to the end of the function stays as it is (it uses `match`,
2188
+ `hasIndices`, `lv.A`, `lv.strHandle`, `lv.indicesArray` and `gcScope`).
2189
+ `lv.propHandle` moved into the core.
2190
+
2191
+ - [ ] **Step 5: `test` uses the core unframed** (replace
2192
+ `regExpPrototypeTest`, `:1235-1246`)
2193
+
2194
+ ```cpp
2195
+ /// Implementation of RegExp.prototype.test
2196
+ /// Returns true if a match is found, false otherwise. It runs the effects
2197
+ /// of the builtin exec (lastIndex, the statics) without building the
2198
+ /// result array. As before, it never looks up exec.
2199
+ CallResult<HermesValue> regExpPrototypeTest(void *context, Runtime &runtime) {
2200
+ struct : public Locals {
2201
+ PinnedValue<StringPrimitive> S;
2202
+ } lv;
2203
+ LocalsRAII lraii(runtime, &lv);
2204
+
2205
+ NativeArgs args = runtime.getCurrentFrame().getNativeArgs();
2206
+ Handle<JSRegExp> regexp = args.dyncastThis<JSRegExp>();
2207
+ if (!regexp) {
2208
+ return runtime.raiseTypeError(
2209
+ "RegExp function called on non-RegExp object");
2210
+ }
2211
+
2212
+ auto strRes = toString_RJS(runtime, args.getArgHandle(0));
2213
+ if (strRes == ExecutionStatus::EXCEPTION) {
2214
+ return ExecutionStatus::EXCEPTION;
2215
+ }
2216
+ lv.S = std::move(*strRes);
2217
+
2218
+ RegExpMatch match;
2219
+ auto matchRes = regExpBuiltinExecMatch(regexp, runtime, lv.S, match);
2220
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION))
2221
+ return ExecutionStatus::EXCEPTION;
2222
+ return HermesValue::encodeBoolValue(*matchRes);
2223
+ }
2224
+ ```
2225
+
2226
+ - [ ] **Step 6: The Runtime-owned capture buffer** (B.4)
2227
+
2228
+ In `include/hermes/VM/Runtime.h`, add
2229
+ `#include "hermes/Regex/Executor.h"` before
2230
+ `#include "hermes/Support/Compiler.h"` (`:15`), and after
2231
+ `RegExpMatch regExpLastMatch{};` (`:935`):
2232
+
2233
+ ```cpp
2234
+ /// The capture ranges of the latest regex search, reused by every search
2235
+ /// so that it keeps its capacity. It is used only between the executor's
2236
+ /// return and the copy into a RegExpMatch (performSearch in
2237
+ /// JSRegExp.cpp); the executor runs no JS and allocates nothing on the GC
2238
+ /// heap, so it is never in use twice at once.
2239
+ std::vector<regex::CapturedRange> regExpSearchCaptures{};
2240
+ ```
2241
+
2242
+ In `lib/VM/JSRegExp.cpp`, `performSearch`, replace
2243
+ `std::vector<regex::CapturedRange> nativeMatchRanges;` (`:301`) with:
2244
+
2245
+ ```cpp
2246
+ std::vector<regex::CapturedRange> &nativeMatchRanges =
2247
+ runtime.regExpSearchCaptures;
2248
+ ```
2249
+
2250
+ In `@@split` (`RegExp.cpp:2531`), replace `auto match = *matchResult;`
2251
+ with:
2252
+
2253
+ ```cpp
2254
+ RegExpMatch match = std::move(*matchResult);
2255
+ ```
2256
+
2257
+ - [ ] **Step 7: Build and run**
2258
+
2259
+ ```bash
2260
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes
2261
+ LIT_FILTER='regexp|regex|string-functions' \
2262
+ cmake --build $R/cmake-build-asan --target check-hermes
2263
+ ```
2264
+
2265
+ Expected: 0 failures, including `regexp-exec-fast-path.js`.
2266
+
2267
+ - [ ] **Step 8: Prove the guard can fail** (mutation diff; rebuild
2268
+ `hermes` after each edit and restore)
2269
+ - `lastIndex.valueOf` count: in `regExpBuiltinExecMatch`, move
2270
+ `const regex::SyntaxFlags flags = ...` above the `Get`, declare
2271
+ `uint64_t lastIndex = 0;`, and wrap the `Get`/`ToLength` block in
2272
+ `if (flags.global || flags.sticky) { ... lastIndex = *lengthRes; }`.
2273
+ Expected diff: `4 object` becomes `0 object`; `match true` and
2274
+ `replace true` become `false` (the `valueOf` never runs).
2275
+ - statics after `test`: in `regExpPrototypeTest`, around the core call,
2276
+ save and restore the statics:
2277
+ ```cpp
2278
+ struct : public Locals {
2279
+ PinnedValue<StringPrimitive> savedInput;
2280
+ } lvm;
2281
+ LocalsRAII lraiim(runtime, &lvm);
2282
+ lvm.savedInput = runtime.regExpLastInput;
2283
+ RegExpMatch savedMatch = runtime.regExpLastMatch;
2284
+ // ... the regExpBuiltinExecMatch call ...
2285
+ runtime.regExpLastInput = lvm.savedInput;
2286
+ runtime.regExpLastMatch = savedMatch;
2287
+ ```
2288
+ Expected diff: `1|12|x|y 2` changes to the statics of `/(z)/.exec("z")`
2289
+ (`z|z||` followed by an empty `$2`).
2290
+
2291
+ - [ ] **Step 9: Full suite** on `cmake-build-asan`: 0 failures; expected
2292
+ passes baseline + 4 (lit counts `regexp-exec-fast-path.js` once, whatever
2293
+ its number of RUN lines). Tasks 5-7 add no test: each later full suite
2294
+ expects baseline + 4.
2295
+
2296
+ - [ ] **Step 10: Commit**
2297
+
2298
+ ```bash
2299
+ git -C $R add lib/VM/JSLib/RegExp.cpp include/hermes/VM/Runtime.h \
2300
+ lib/VM/JSRegExp.cpp test/hermes/regexp-exec-fast-path.js
2301
+ git -C $R commit -F $S/commit-4.txt
2302
+ ```
2303
+
2304
+ `$S/commit-4.txt`:
2305
+
2306
+ ````
2307
+ VM: split RegExpBuiltinExec from building the exec result array
2308
+
2309
+ directRegExpExec did the observable part of RegExpBuiltinExec (Get and
2310
+ ToLength of lastIndex, the search, the Set of lastIndex) and then built
2311
+ a result array. The first part is now its own function, which the fast
2312
+ paths that follow will use:
2313
+
2314
+ ```
2315
+ static CallResult<bool> regExpBuiltinExecMatch(
2316
+ Handle<JSRegExp> regexp, Runtime &runtime, Handle<StringPrimitive> S,
2317
+ RegExpMatch &match);
2318
+ ```
2319
+
2320
+ RegExp.prototype.test calls it and no longer builds an array it throws
2321
+ away. It still never looks up exec.
2322
+
2323
+ Each search also allocated a vector of capture ranges and copied it into
2324
+ the RegExpMatch. The vector is now a Runtime buffer that keeps its
2325
+ capacity, and the @@split loop moves its RegExpMatch instead of copying
2326
+ it.
2327
+
2328
+ A new test, regexp-exec-fast-path.js, pins what the fast paths must not
2329
+ change: replaced, own, subclass and accessor exec, a Proxy prototype,
2330
+ lastIndex coercion and writes, the legacy statics, empty and sticky
2331
+ matches, replacement patterns and callback arguments, hasIndices, and
2332
+ the native exec frame in stack traces.
2333
+
2334
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2335
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
2336
+ ````
2337
+
2338
+ ---
2339
+
2340
+ ### Task 5: The exec frame and direct dispatch in `regExpExec`
2341
+
2342
+ **Files:**
2343
+ - Modify: `include/hermes/VM/Callable.h:727-765` and after the
2344
+ `NativeFunction` class
2345
+ - Modify: `include/hermes/VM/RuntimeHermesValueFields.def:71`
2346
+ - Modify: `lib/VM/JSLib/RegExp.cpp:82-88`, after `:1146`, `:1164-1165`
2347
+
2348
+ **Interfaces:**
2349
+ - **Consumes:** none from Part B beyond Task 4.
2350
+ - **Produces:**
2351
+ - `template <typename Body> static CallResult<PseudoHandle<>>
2352
+ NativeFunction::runNativeCallBody(NativeFunction *self, Runtime &,
2353
+ const Body &body)`; `body()` returns `CallResult<HermesValue>`;
2354
+ - `runtime.regExpPrototypeExec` (`PinnedValue<NativeFunction>`);
2355
+ - in `RegExp.cpp`:
2356
+ ```cpp
2357
+ template <typename Body>
2358
+ static CallResult<HermesValue> runInBuiltinExecFrame(
2359
+ Runtime &runtime, Handle<JSObject> R, Handle<StringPrimitive> S,
2360
+ const Body &body);
2361
+ ```
2362
+ - Tasks 6 and 7 call `runInBuiltinExecFrame`.
2363
+
2364
+ **Facts this task relies on:**
2365
+ - A real call builds: a `ScopedNativeCallFrame` with one argument and its
2366
+ overflow check (`lib/VM/Callable.cpp:322-339`); `potentiallyMoveHeap()`
2367
+ before dispatch (`include/hermes/VM/Callable.h:279-287`); then the body
2368
+ of `_nativeCall` (`Callable.h:730-765`). `NativeFunction::_callImpl`
2369
+ only forwards to `_nativeCall` (`lib/VM/Callable.cpp:1189-1193`).
2370
+ - Stack traces record native frames from the runtime frames
2371
+ (`lib/VM/JSError.cpp:355`, `:708-712`); the debugger and the sampling
2372
+ profiler walk the same frames.
2373
+ - The builtin exec runs `ToString` on its argument, a no-op on a string,
2374
+ then `directRegExpExec` (`RegExp.cpp:1198-1228`); its result is an
2375
+ object or null, so `regExpExec`'s type check (`:1175-1178`) always
2376
+ passes for it.
2377
+ - The precedent for saving a builtin is `runtime.arrayPrototypeValues =
2378
+ defineMethod(...)` (`lib/VM/JSLib/Array.cpp:146`).
2379
+
2380
+ **GC safety.**
2381
+ - `R` and `S` are handles owned by the caller.
2382
+ - `runtime.regExpPrototypeExec` is a root. `runInBuiltinExecFrame` reads
2383
+ it once for the frame and again after `potentiallyMoveHeap()`, so the
2384
+ callee pointer passed on is current.
2385
+ - `runNativeCallBody` never uses `self` after `body()` without reloading
2386
+ it: in `HERMESVM_PROFILER_NATIVECALL` builds it reloads the callee from
2387
+ the native frame's callee slot (`getCalleeClosureOrCBRef()`,
2388
+ `include/hermes/VM/StackFrame.h:112`), a root the GC updates, before
2389
+ updating the counters (Plan ruling 9). This also fixes the stale `self`
2390
+ that `_nativeCall` dereferenced after the native returned.
2391
+ - The direct-dispatch comparison is between two rooted values, with no
2392
+ allocation between the reads.
2393
+
2394
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
2395
+
2396
+ - [ ] **Step 2: Split `_nativeCall`** (`include/hermes/VM/Callable.h`)
2397
+
2398
+ Replace `_nativeCall` (`:727-765`) with:
2399
+
2400
+ ```cpp
2401
+ /// Run \p body, which takes no arguments and returns
2402
+ /// CallResult<HermesValue>, as the body of a call of \p self: inside the
2403
+ /// native depth check and the frame setup and teardown that every call of
2404
+ /// a NativeFunction performs. The caller has pushed the frame (callee
2405
+ /// \p self, this and arguments), as for _nativeCall.
2406
+ template <typename Body>
2407
+ static inline CallResult<PseudoHandle<>> runNativeCallBody(
2408
+ NativeFunction *self,
2409
+ Runtime &runtime,
2410
+ const Body &body);
2411
+
2412
+ /// This is a lightweight and unsafe wrapper intended to be used only by the
2413
+ /// interpreter. Its purpose is to avoid needlessly exposing the private
2414
+ /// fields.
2415
+ static CallResult<PseudoHandle<>> _nativeCall(
2416
+ NativeFunction *self,
2417
+ Runtime &runtime) {
2418
+ NativeFunctionPtr functionPtr = self->functionPtr_;
2419
+ void *context = self->context_;
2420
+ return runNativeCallBody(self, runtime, [functionPtr, context, &runtime]() {
2421
+ return functionPtr(context, runtime);
2422
+ });
2423
+ }
2424
+ ```
2425
+
2426
+ After the closing `};` of `class NativeFunction`, add:
2427
+
2428
+ ```cpp
2429
+ template <typename Body>
2430
+ inline CallResult<PseudoHandle<>> NativeFunction::runNativeCallBody(
2431
+ NativeFunction *self,
2432
+ Runtime &runtime,
2433
+ const Body &body) {
2434
+ ScopedNativeDepthTracker depthTracker{runtime};
2435
+ if (LLVM_UNLIKELY(depthTracker.overflowed())) {
2436
+ return runtime.raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
2437
+ }
2438
+
2439
+ // Ensure the IP was correctly saved before we create the new frame.
2440
+ runtime.validateSavedIPBeforeCall();
2441
+ auto newFrame = runtime.setCurrentFrameToTopOfStack();
2442
+ // We don't need to allocate CalleeExtraRegistersAtStart here because the
2443
+ // only register is DebugEnvironment, which is not useful in a
2444
+ // NativeFunction.
2445
+ static_assert(
2446
+ StackFrameLayout::FirstLocal - 1 == StackFrameLayout::DebugEnvironment &&
2447
+ StackFrameLayout::CalleeExtraRegistersAtStart == 1);
2448
+
2449
+ #ifdef HERMESVM_PROFILER_NATIVECALL
2450
+ auto t1 = HERMESVM_RDTSC();
2451
+ #endif
2452
+
2453
+ CallResult<HermesValue> res = body();
2454
+
2455
+ #ifdef HERMESVM_PROFILER_NATIVECALL
2456
+ // body() may have moved the heap, so \p self may be stale. Reload the
2457
+ // callee from the frame's callee slot, which the GC updates.
2458
+ self = vmcast<NativeFunction>(newFrame.getCalleeClosureOrCBRef());
2459
+ self->callDuration_ = HERMESVM_RDTSC() - t1;
2460
+ ++self->callCount_;
2461
+ #else
2462
+ (void)self;
2463
+ #endif
2464
+ runtime.restoreStackAndPreviousFrame(newFrame);
2465
+ if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
2466
+ return ExecutionStatus::EXCEPTION;
2467
+ }
2468
+ return createPseudoHandle(*res);
2469
+ }
2470
+ ```
2471
+
2472
+ - [ ] **Step 3: Save the builtin exec**
2473
+
2474
+ In `include/hermes/VM/RuntimeHermesValueFields.def`, after
2475
+ `RUNTIME_HV_FIELD(regExpPrototype, JSObject)` (`:71`):
2476
+
2477
+ ```
2478
+ // RegExp.prototype.exec as defined, to recognize the builtin.
2479
+ RUNTIME_HV_FIELD(regExpPrototypeExec, NativeFunction)
2480
+ ```
2481
+
2482
+ In `RegExp.cpp` (`:82-88`), change the `exec` definition to:
2483
+
2484
+ ```cpp
2485
+ runtime.regExpPrototypeExec = defineMethod(
2486
+ runtime,
2487
+ proto,
2488
+ Predefined::getSymbolID(Predefined::exec),
2489
+ nullptr,
2490
+ regExpPrototypeExec,
2491
+ 1);
2492
+ ```
2493
+
2494
+ - [ ] **Step 4: The exec frame** (`RegExp.cpp`, after `advanceStringIndex`,
2495
+ `:1146`)
2496
+
2497
+ ```cpp
2498
+ /// Run \p body as the body of a call of the builtin RegExp.prototype.exec
2499
+ /// with this \p R and the argument \p S: inside a native frame for
2500
+ /// runtime.regExpPrototypeExec built as Callable::executeCall1,
2501
+ /// Callable::call and NativeFunction::_nativeCall build it. Stack traces,
2502
+ /// the debugger and the sampling profiler then see the same exec frame as
2503
+ /// for a real call. \p body returns CallResult<HermesValue>.
2504
+ template <typename Body>
2505
+ static CallResult<HermesValue> runInBuiltinExecFrame(
2506
+ Runtime &runtime,
2507
+ Handle<JSObject> R,
2508
+ Handle<StringPrimitive> S,
2509
+ const Body &body) {
2510
+ // As Callable::executeCall1.
2511
+ ScopedNativeCallFrame newFrame{
2512
+ runtime,
2513
+ 1,
2514
+ runtime.regExpPrototypeExec.getHermesValue(),
2515
+ HermesValue::encodeUndefinedValue(),
2516
+ R.getHermesValue()};
2517
+ if (LLVM_UNLIKELY(newFrame.overflowed()))
2518
+ return runtime.raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
2519
+ newFrame->getArgRef(0) = S.getHermesValue();
2520
+ // As Callable::call. The callee is read again from its root below.
2521
+ runtime.potentiallyMoveHeap();
2522
+ // As NativeFunction::_nativeCall.
2523
+ auto res = NativeFunction::runNativeCallBody(
2524
+ *runtime.regExpPrototypeExec, runtime, body);
2525
+ if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
2526
+ return ExecutionStatus::EXCEPTION;
2527
+ return res->get();
2528
+ }
2529
+ ```
2530
+
2531
+ - [ ] **Step 5: Direct dispatch in `regExpExec`** (`RegExp.cpp`, inside
2532
+ `if (auto execCallable = ...) {` at `:1165`, before the existing
2533
+ `// a. Let result be Call(exec, R, «S»).`)
2534
+
2535
+ ```cpp
2536
+ // The builtin exec on a JSRegExp would run ToString(S), a no-op on a
2537
+ // string, and then RegExpBuiltinExec, whose result is an object or null.
2538
+ // Run that in the exec frame without the dispatch through
2539
+ // Callable::call.
2540
+ if (lv.exec.getHermesValue().getRaw() ==
2541
+ runtime.regExpPrototypeExec.getHermesValue().getRaw()) {
2542
+ if (auto regExpObj = Handle<JSRegExp>::dyn_vmcast(R)) {
2543
+ return runInBuiltinExecFrame(runtime, R, S, [&]() {
2544
+ return regExpBuiltinExec(runtime, regExpObj, S);
2545
+ });
2546
+ }
2547
+ }
2548
+ ```
2549
+
2550
+ A builtin exec on a non-`JSRegExp` still goes through `executeCall1`,
2551
+ where the builtin raises its TypeError inside its frame, as today. The
2552
+ non-callable fallback (`:1182-1192`) still calls `regExpBuiltinExec`
2553
+ with no frame, as today.
2554
+
2555
+ - [ ] **Step 6: Build and run**
2556
+
2557
+ ```bash
2558
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes
2559
+ LIT_FILTER='regexp|regex|string-functions|stacktrace' \
2560
+ cmake --build $R/cmake-build-asan --target check-hermes
2561
+ ```
2562
+
2563
+ Expected: 0 failures.
2564
+
2565
+ - [ ] **Step 7: Prove the guard can fail** (mutation diff; rebuild after
2566
+ each edit and restore)
2567
+ - Direct dispatch unframed: replace the `return runInBuiltinExecFrame(
2568
+ ...);` statement with `return regExpBuiltinExec(runtime, regExpObj,
2569
+ S);`. Expected diff: in `stacks`, `match`, `replace`, `sticky`,
2570
+ `global match limit` and `search limit` become `false` (every site
2571
+ still reaches exec through `regExpExec` at this task).
2572
+ - `test` given a frame: in `regExpPrototypeTest`, replace the core call
2573
+ with
2574
+ ```cpp
2575
+ bool matched = false;
2576
+ auto frameRes = runInBuiltinExecFrame(runtime, regexp, lv.S, [&]()
2577
+ -> CallResult<HermesValue> {
2578
+ auto r = regExpBuiltinExecMatch(regexp, runtime, lv.S, match);
2579
+ if (r == ExecutionStatus::EXCEPTION)
2580
+ return ExecutionStatus::EXCEPTION;
2581
+ matched = *r;
2582
+ return HermesValue::encodeUndefinedValue();
2583
+ });
2584
+ if (frameRes == ExecutionStatus::EXCEPTION)
2585
+ return ExecutionStatus::EXCEPTION;
2586
+ return HermesValue::encodeBoolValue(matched);
2587
+ ```
2588
+ (move `runInBuiltinExecFrame` above `regExpPrototypeTest` for the
2589
+ mutation if needed). Expected diff: `test false` becomes `test true`.
2590
+ - Builtin recognized by mistake: change the raw comparison to `true`.
2591
+ Expected diff: every line of `replaced exec` and `own and subclass
2592
+ exec` loses the user exec's calls (the logs are `[]`, the counts 0).
2593
+
2594
+ - [ ] **Step 8: Full suite** on `cmake-build-asan`: 0 failures.
2595
+
2596
+ - [ ] **Step 9: Commit**
2597
+
2598
+ ```bash
2599
+ git -C $R add include/hermes/VM/Callable.h \
2600
+ include/hermes/VM/RuntimeHermesValueFields.def lib/VM/JSLib/RegExp.cpp
2601
+ git -C $R commit -F $S/commit-5.txt
2602
+ ```
2603
+
2604
+ `$S/commit-5.txt`:
2605
+
2606
+ ````
2607
+ VM: run the builtin exec directly in its own frame from RegExpExec
2608
+
2609
+ RegExpExec called the exec it looked up through executeCall1 even when
2610
+ it was the builtin, which then ran ToString on a string and
2611
+ directRegExpExec. When exec is the builtin and R is a JSRegExp, it now
2612
+ runs regExpBuiltinExec directly.
2613
+
2614
+ Stack traces, the debugger and the sampling profiler must still see the
2615
+ native exec frame: user code can run inside exec (ToLength of a
2616
+ lastIndex object), and errors can be raised there. So the call runs in
2617
+ a frame for the builtin, built as executeCall1, Callable::call and
2618
+ _nativeCall build it. _nativeCall is split so that both share the frame
2619
+ code:
2620
+
2621
+ ```
2622
+ template <typename Body>
2623
+ static CallResult<PseudoHandle<>> runNativeCallBody(
2624
+ NativeFunction *self, Runtime &runtime, const Body &body);
2625
+ ```
2626
+
2627
+ Runtime saves the builtin as regExpPrototypeExec. Every caller of
2628
+ RegExpExec benefits; for non-global @@match and the matchAll iterator,
2629
+ which need the result array, this is the whole fast path.
2630
+
2631
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2632
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
2633
+ ````
2634
+
2635
+ ---
2636
+
2637
+ ### Task 6: `hasBuiltinExec`, the global `@@match` loop and `@@search`
2638
+
2639
+ **Files:**
2640
+ - Modify: `lib/VM/JSLib/RegExp.cpp` (new helpers before `:1779`;
2641
+ `regExpPrototypeSymbolMatch` `:1781-1917`;
2642
+ `regExpPrototypeSymbolSearch` `:1920-1985`)
2643
+
2644
+ **Interfaces:**
2645
+ - **Consumes:** `regExpBuiltinExecMatch` (Task 4),
2646
+ `runInBuiltinExecFrame` and `runtime.regExpPrototypeExec` (Task 5).
2647
+ - **Produces** (in `RegExp.cpp`, before `regExpPrototypeSymbolMatch`):
2648
+ - `static bool hasBuiltinExec(Runtime &runtime, Handle<JSObject> R);`
2649
+ - `static CallResult<bool> execMatchInBuiltinExecFrame(Runtime &runtime,
2650
+ Handle<JSRegExp> R, Handle<StringPrimitive> S, RegExpMatch &match);`
2651
+ - `static ExecutionStatus advanceLastIndexAfterEmptyMatch(Runtime
2652
+ &runtime, Handle<JSObject> rx, Handle<StringPrimitive> S, bool
2653
+ fullUnicode);`
2654
+ - Task 7 uses all three.
2655
+
2656
+ **Facts this task relies on:**
2657
+ - `getNamedDescriptorPredefined` returns the owner and sets
2658
+ `proxyObject`/`hostObject` instead of a slot for proxies and host
2659
+ objects (`lib/VM/JSObject.cpp:1028-1065`); `getNamedSlotValueUnsafe`
2660
+ asserts it is not given either (`include/hermes/VM/JSObject.h:641-654`).
2661
+ - Writing `RegExp.prototype.exec = f` rewrites the slot without a new
2662
+ class (`lib/VM/JSObject.cpp:3254-3283`), so the value must be compared.
2663
+ - The precedents check `proxyObject` and compare the slot value with the
2664
+ saved builtin (`lib/VM/JSLib/HermesBuiltin.cpp:595-605`,
2665
+ `lib/VM/Interpreter-slowpaths.cpp:327-348`).
2666
+ - Global `@@match` runs `Get global`, `Get unicode` and `Set lastIndex =
2667
+ 0` before its loop (`RegExp.cpp:1811-1836`). In the loop, the only
2668
+ steps besides exec are `ToString` of a string from the builtin and the
2669
+ `Get`/`ToLength`/`Set` of a number `lastIndex` holds (`:1873-1911`):
2670
+ no user code, so `exec` cannot change during the loop.
2671
+ - `@@search` reads only `index` of the result (`:1976-1984`).
2672
+
2673
+ **Counterexamples tried** (DESIGN-PRINCIPLES 3):
2674
+ - A `lastIndex.valueOf` changing `exec` mid-loop: the pre-loop `Set`
2675
+ overwrote `lastIndex` with 0, and exec writes only numbers.
2676
+ - An `exec` accessor that returns the builtin: rejected by
2677
+ `desc.flags.accessor`; the slow path runs the getter per iteration.
2678
+ - A Proxy prototype: rejected by `proxyObject`; its `get` trap sees each
2679
+ lookup.
2680
+ - An own `exec` holding the builtin: accepted; the builtin runs, as a
2681
+ `Get` would return it.
2682
+
2683
+ **GC safety.** `hasBuiltinExec` keeps the raw owner pointer only until
2684
+ it reads the slot, with no allocation in between.
2685
+ `getNamedDescriptorPredefined` may allocate (a lazy object), but `R` is
2686
+ a handle. In the loops, `RegExpMatch` holds integers; the slice comes
2687
+ from `S`, which `JSRegExp::search` flattened, and `slice` reads the
2688
+ characters after it allocates (`lib/VM/StringPrimitive.cpp:350-382`).
2689
+ The loop keeps its `flushToMarker` per iteration.
2690
+
2691
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
2692
+
2693
+ - [ ] **Step 2: The helpers** (`RegExp.cpp`, before
2694
+ `// TODO: consider writing this in JS.` at `:1779`)
2695
+
2696
+ ```cpp
2697
+ /// \return true if \p R is a JSRegExp and Get(R, "exec") would return the
2698
+ /// builtin exec from a plain data property, with no proxy, host object or
2699
+ /// accessor on the lookup path. Such a Get runs no user code, so skipping
2700
+ /// it is unobservable.
2701
+ static bool hasBuiltinExec(Runtime &runtime, Handle<JSObject> R) {
2702
+ if (!vmisa<JSRegExp>(R.getHermesValue()))
2703
+ return false;
2704
+ NamedPropertyDescriptor desc;
2705
+ JSObject *owner = JSObject::getNamedDescriptorPredefined(
2706
+ R, runtime, Predefined::exec, desc);
2707
+ if (!owner || desc.flags.proxyObject || desc.flags.hostObject ||
2708
+ desc.flags.accessor)
2709
+ return false;
2710
+ SmallHermesValue slot =
2711
+ JSObject::getNamedSlotValueUnsafe(owner, runtime, desc);
2712
+ return slot.isObject() &&
2713
+ slot.getObject(runtime) == *runtime.regExpPrototypeExec;
2714
+ }
2715
+
2716
+ /// Run regExpBuiltinExecMatch(\p R, \p S, \p match) inside a frame for the
2717
+ /// builtin exec, as a call of RegExp.prototype.exec would. \return whether
2718
+ /// it matched.
2719
+ static CallResult<bool> execMatchInBuiltinExecFrame(
2720
+ Runtime &runtime,
2721
+ Handle<JSRegExp> R,
2722
+ Handle<StringPrimitive> S,
2723
+ RegExpMatch &match) {
2724
+ bool matched = false;
2725
+ auto res = runInBuiltinExecFrame(
2726
+ runtime, R, S, [&]() -> CallResult<HermesValue> {
2727
+ auto matchRes = regExpBuiltinExecMatch(R, runtime, S, match);
2728
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION))
2729
+ return ExecutionStatus::EXCEPTION;
2730
+ matched = *matchRes;
2731
+ return HermesValue::encodeUndefinedValue();
2732
+ });
2733
+ if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
2734
+ return ExecutionStatus::EXCEPTION;
2735
+ return matched;
2736
+ }
2737
+
2738
+ /// After an empty match in the loop of @@match or @@replace: set lastIndex
2739
+ /// of \p rx to AdvanceStringIndex(\p S, ToLength(Get(rx, "lastIndex")),
2740
+ /// \p fullUnicode).
2741
+ static ExecutionStatus advanceLastIndexAfterEmptyMatch(
2742
+ Runtime &runtime,
2743
+ Handle<JSObject> rx,
2744
+ Handle<StringPrimitive> S,
2745
+ bool fullUnicode) {
2746
+ struct : public Locals {
2747
+ PinnedValue<> lastIndex;
2748
+ } lv;
2749
+ LocalsRAII lraii(runtime, &lv);
2750
+
2751
+ // a. Let thisIndex be ToLength(Get(rx, "lastIndex")).
2752
+ // b. ReturnIfAbrupt(thisIndex).
2753
+ auto propRes = runtime.getNamed(rx, PropCacheID::RegExpLastIndex);
2754
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION))
2755
+ return ExecutionStatus::EXCEPTION;
2756
+ lv.lastIndex = std::move(*propRes);
2757
+ auto thisIndex = toLength(runtime, lv.lastIndex);
2758
+ if (LLVM_UNLIKELY(thisIndex == ExecutionStatus::EXCEPTION))
2759
+ return ExecutionStatus::EXCEPTION;
2760
+ // c. Let nextIndex be AdvanceStringIndex(S, thisIndex, fullUnicode).
2761
+ double nextIndex = advanceStringIndex(
2762
+ S.get(), thisIndex->getNumberAs<uint64_t>(), fullUnicode);
2763
+ // d. Let setStatus be Set(rx, "lastIndex", nextIndex, true).
2764
+ // e. ReturnIfAbrupt(setStatus).
2765
+ return setLastIndex(rx, runtime, nextIndex);
2766
+ }
2767
+ ```
2768
+
2769
+ - [ ] **Step 3: The global `@@match` loop**
2770
+ (`regExpPrototypeSymbolMatch`; everything up to `uint32_t n = 0;`,
2771
+ `:1844`, stays; replace from `// g. Repeat,` (`:1846`) to the end of
2772
+ the loop (`:1914`) with:)
2773
+
2774
+ ```cpp
2775
+ // Whether exec is the builtin. Besides exec, every step of the loop below
2776
+ // runs no user code (ToString of a string, Get and ToLength of the number
2777
+ // that lastIndex holds, Set of lastIndex), so exec cannot change during
2778
+ // the loop and one check covers every iteration.
2779
+ const bool fast = hasBuiltinExec(runtime, rx);
2780
+
2781
+ // g. Repeat,
2782
+ auto marker = gcScope.createMarker();
2783
+ RegExpMatch match;
2784
+ while (true) {
2785
+ gcScope.flushToMarker(marker);
2786
+ // i. Let result be RegExpExec(rx, S).
2787
+ // ii. ReturnIfAbrupt(result).
2788
+ bool matched;
2789
+ if (fast) {
2790
+ auto matchRes = execMatchInBuiltinExecFrame(
2791
+ runtime, Handle<JSRegExp>::vmcast(rx), lv.S, match);
2792
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION)) {
2793
+ return ExecutionStatus::EXCEPTION;
2794
+ }
2795
+ matched = *matchRes;
2796
+ } else {
2797
+ auto callRes = regExpExec(runtime, rx, lv.S);
2798
+ if (LLVM_UNLIKELY(callRes == ExecutionStatus::EXCEPTION)) {
2799
+ return ExecutionStatus::EXCEPTION;
2800
+ }
2801
+ lv.result = callRes.getValue();
2802
+ matched = !lv.result->isNull();
2803
+ }
2804
+ // iii. If result is null, then
2805
+ if (!matched) {
2806
+ if (n == 0) {
2807
+ return HermesValue::encodeNullValue();
2808
+ } else {
2809
+ if (LLVM_UNLIKELY(
2810
+ JSArray::setLengthProperty(lv.A, runtime, n) ==
2811
+ ExecutionStatus::EXCEPTION))
2812
+ return ExecutionStatus::EXCEPTION;
2813
+ return lv.A.getHermesValue();
2814
+ }
2815
+ }
2816
+ // iv. Else result is not null,
2817
+ // 1. Let matchStr be ToString(Get(result, "0")).
2818
+ // 2. ReturnIfAbrupt(matchStr).
2819
+ if (fast) {
2820
+ // Element 0 of the builtin's result is this slice of S.
2821
+ auto strRes = StringPrimitive::slice(
2822
+ runtime, lv.S, match[0]->location, match[0]->length);
2823
+ if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
2824
+ return ExecutionStatus::EXCEPTION;
2825
+ }
2826
+ lv.matchStr.castAndSetHermesValue<StringPrimitive>(*strRes);
2827
+ } else {
2828
+ auto resultObj = Handle<JSObject>::vmcast(&lv.result);
2829
+ auto propRes2 = getIndexed_RJS(runtime, resultObj, 0);
2830
+ if (propRes2 == ExecutionStatus::EXCEPTION) {
2831
+ return ExecutionStatus::EXCEPTION;
2832
+ }
2833
+ lv.propValue = std::move(propRes2.getValue());
2834
+ auto strRes2 = toString_RJS(runtime, lv.propValue);
2835
+ if (strRes2 == ExecutionStatus::EXCEPTION) {
2836
+ return ExecutionStatus::EXCEPTION;
2837
+ }
2838
+ lv.matchStr = strRes2->get();
2839
+ }
2840
+ // 3. Let status be CreateDataProperty(A, ToString(n), matchStr).
2841
+ // 4. Assert: status is true.
2842
+ if (LLVM_UNLIKELY(
2843
+ JSArray::setElementAt(lv.A, runtime, n, lv.matchStr) ==
2844
+ ExecutionStatus::EXCEPTION))
2845
+ return ExecutionStatus::EXCEPTION;
2846
+ // 5. If matchStr is the empty String, then
2847
+ // a-e. Set lastIndex to AdvanceStringIndex(S, thisIndex, fullUnicode).
2848
+ if (lv.matchStr->getStringLength() == 0) {
2849
+ if (LLVM_UNLIKELY(
2850
+ advanceLastIndexAfterEmptyMatch(
2851
+ runtime, rx, lv.S, fullUnicode) ==
2852
+ ExecutionStatus::EXCEPTION)) {
2853
+ return ExecutionStatus::EXCEPTION;
2854
+ }
2855
+ }
2856
+ // 6. Increment n.
2857
+ n++;
2858
+ }
2859
+ ```
2860
+
2861
+ The `llvm_unreachable` after the loop stays. `propRes` is still used by
2862
+ the `Get global` above the loop, so it stays declared.
2863
+
2864
+ - [ ] **Step 4: `@@search`** (`regExpPrototypeSymbolSearch`; replace from
2865
+ `// 9. Let result be RegExpExec(rx, S).` (`:1958`) to the end of the
2866
+ function with:)
2867
+
2868
+ ```cpp
2869
+ // 9. Let result be RegExpExec(rx, S).
2870
+ // 10. ReturnIfAbrupt(result).
2871
+ // When exec is the builtin, only the position of the match is needed.
2872
+ const bool fast = hasBuiltinExec(runtime, rx);
2873
+ RegExpMatch match;
2874
+ bool matched;
2875
+ if (fast) {
2876
+ auto matchRes = execMatchInBuiltinExecFrame(
2877
+ runtime, Handle<JSRegExp>::vmcast(rx), lv.S, match);
2878
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION)) {
2879
+ return ExecutionStatus::EXCEPTION;
2880
+ }
2881
+ matched = *matchRes;
2882
+ } else {
2883
+ auto execRes = regExpExec(runtime, rx, lv.S);
2884
+ if (LLVM_UNLIKELY(execRes == ExecutionStatus::EXCEPTION)) {
2885
+ return ExecutionStatus::EXCEPTION;
2886
+ }
2887
+ lv.result = execRes.getValue();
2888
+ matched = !lv.result.getHermesValue().isNull();
2889
+ }
2890
+ // 11. Let status be Set(rx, "lastIndex", previousLastIndex, true).
2891
+ auto previousLastIndexSHV = SmallHermesValue::encodeHermesValue(
2892
+ lv.previousLastIndex.getHermesValue(), runtime);
2893
+ status = setLastIndex(rx, runtime, previousLastIndexSHV);
2894
+ // 12. ReturnIfAbrupt(status).
2895
+ if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
2896
+ return ExecutionStatus::EXCEPTION;
2897
+ }
2898
+ // 13. If result is null, return -1.
2899
+ if (!matched) {
2900
+ return HermesValue::encodeTrustedNumberValue(-1);
2901
+ }
2902
+ // 14. Return Get(result, "index").
2903
+ if (fast) {
2904
+ // The builtin's index is the start of the whole match.
2905
+ return HermesValue::encodeTrustedNumberValue(match[0]->location);
2906
+ }
2907
+ auto resultObj = Handle<JSObject>::dyn_vmcast(Handle<>{lv.result});
2908
+ if (LLVM_UNLIKELY(!resultObj)) {
2909
+ return ExecutionStatus::EXCEPTION;
2910
+ }
2911
+ return JSObject::getNamed_RJS(
2912
+ resultObj, runtime, Predefined::getSymbolID(Predefined::index))
2913
+ .toCallResultHermesValue();
2914
+ }
2915
+ ```
2916
+
2917
+ The check sits between the two `Set`s of `lastIndex`, as the spec
2918
+ requires; the first `Set` writes an own data property of a `JSRegExp`
2919
+ and runs no user code.
2920
+
2921
+ - [ ] **Step 5: Build and run**
2922
+
2923
+ ```bash
2924
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes
2925
+ LIT_FILTER='regexp|regex|string-functions' \
2926
+ cmake --build $R/cmake-build-asan --target check-hermes
2927
+ ```
2928
+
2929
+ Expected: 0 failures.
2930
+
2931
+ - [ ] **Step 6: Prove the guard can fail** (spec table; mutation diff;
2932
+ rebuild after each edit and restore)
2933
+ - `hasBuiltinExec` always true: replace everything after the
2934
+ `vmisa<JSRegExp>` test with `return true;`. Expected diff: the global
2935
+ `match` and `search` lines of `replaced exec` and `own and subclass
2936
+ exec` lose the user exec's calls.
2937
+ - Accessor accepted and hoisted: replace the body after the
2938
+ `vmisa<JSRegExp>` test with
2939
+ ```cpp
2940
+ auto res = JSObject::getNamed_RJS(
2941
+ R, runtime, Predefined::getSymbolID(Predefined::exec));
2942
+ if (res == ExecutionStatus::EXCEPTION) {
2943
+ runtime.clearThrownValue();
2944
+ return false;
2945
+ }
2946
+ return res->get().getRaw() ==
2947
+ runtime.regExpPrototypeExec.getHermesValue().getRaw();
2948
+ ```
2949
+ Expected diff: `exec accessor` line 1 becomes `["ab","ab"] 1`. (The
2950
+ `search` line stays `1 1`: one hoisted `Get` replaces one exec
2951
+ `Get`.) Deleting only `desc.flags.accessor` is masked: the slot then
2952
+ holds a `PropertyAccessor`, never the builtin
2953
+ (`lib/VM/JSObject.cpp:3278`).
2954
+ - Proxy check removed: delete `desc.flags.proxyObject ||`. Expected: the
2955
+ run aborts in `proxy prototype` with the Debug assertion
2956
+ `getNamedSlotValueUnsafe called on a Proxy`
2957
+ (`include/hermes/VM/JSObject.h:645-648`); `exit` is non-zero.
2958
+ - Frozen, pre-loop `Set` skipped: move
2959
+ `const bool fast = hasBuiltinExec(runtime, rx);` above step c of
2960
+ `@@match`, and make the `Set` `if (!fast && setLastIndex(rx, runtime,
2961
+ 0) == ExecutionStatus::EXCEPTION)`. Expected diff: `frozen` line 1
2962
+ becomes `TypeError true` (the TypeError now comes from inside exec).
2963
+ - Empty matches by code unit: in the `@@match` loop pass
2964
+ `fast ? false : fullUnicode` to `advanceLastIndexAfterEmptyMatch`.
2965
+ Expected diff: `empty matches` line 1 becomes
2966
+ `["","\ud83d\ude00","",""] ["","","",""]`, and `unicode getter`
2967
+ line 1 becomes `["","","",""] ...`. Derivation: after the empty match
2968
+ at 0, lastIndex becomes 1; the search from 1 matches the lone
2969
+ `\uDE00` at 1, which GetStringIndex reports as index 0 and length 2
2970
+ with lastIndex 2 (`RegExp.cpp:413-417`, `:995-1011`; checked at BASE
2971
+ with `re.lastIndex = 1; re.exec(s)` giving index 0, length 2,
2972
+ lastIndex 2); then empty matches at 2 and 3. The run terminates, so
2973
+ every later case stays visible. (The old `/(?:)/gu` loops forever
2974
+ under this mutation: the search from 1 moves lastIndex back to 0.)
2975
+ - Flag instead of `Get unicode` (Review Focus 4): pass
2976
+ `fast ? JSRegExp::getSyntaxFlags(vmcast<JSRegExp>(rx.get())).unicode
2977
+ : fullUnicode`. Expected diff: only `unicode getter` line 1, which
2978
+ becomes `["","","",""] ...` (the regexp has no `u` flag, so it steps
2979
+ by one unit and stops at the end). `empty matches` is unchanged: there
2980
+ the flag and `Get unicode` agree. So this case is observed
2981
+ independently of the code-unit mutation above.
2982
+ - Sticky cleared: before the `@@match` loop add
2983
+ `if (fast) { auto f = JSRegExp::getSyntaxFlags(vmcast<JSRegExp>(
2984
+ rx.get())); f.sticky = false; JSRegExp::setSyntaxFlags(
2985
+ vmcast<JSRegExp>(rx.get()), f); }`. Expected diff: `sticky global`
2986
+ line 1 becomes `["a","a"] ["a","a"]`.
2987
+ - `@@match` unframed: in the loop, call
2988
+ `regExpBuiltinExecMatch(Handle<JSRegExp>::vmcast(rx), runtime, lv.S,
2989
+ match)` instead of `execMatchInBuiltinExecFrame(...)`. Expected
2990
+ diff: `global match limit RangeError false`.
2991
+ - `@@search` unframed: the same edit in `@@search`. Expected diff:
2992
+ `search limit RangeError false`.
2993
+ - `hasIndices`, array-free non-global match: in `@@match`, before
2994
+ `return regExpExec(runtime, rx, lv.S);` (step 7.a) add
2995
+ ```cpp
2996
+ if (hasBuiltinExec(runtime, rx)) {
2997
+ RegExpMatch m1;
2998
+ auto r = regExpBuiltinExecMatch(
2999
+ Handle<JSRegExp>::vmcast(rx), runtime, lv.S, m1);
3000
+ if (r == ExecutionStatus::EXCEPTION)
3001
+ return ExecutionStatus::EXCEPTION;
3002
+ if (!*r)
3003
+ return HermesValue::encodeNullValue();
3004
+ auto s1 = StringPrimitive::slice(
3005
+ runtime, lv.S, m1[0]->location, m1[0]->length);
3006
+ if (s1 == ExecutionStatus::EXCEPTION)
3007
+ return ExecutionStatus::EXCEPTION;
3008
+ lv.matchStr.castAndSetHermesValue<StringPrimitive>(*s1);
3009
+ auto a1 = JSArray::create(runtime, 1, 1);
3010
+ if (a1 == ExecutionStatus::EXCEPTION)
3011
+ return ExecutionStatus::EXCEPTION;
3012
+ lv.A = std::move(*a1);
3013
+ if (JSArray::setElementAt(lv.A, runtime, 0, lv.matchStr) ==
3014
+ ExecutionStatus::EXCEPTION)
3015
+ return ExecutionStatus::EXCEPTION;
3016
+ return lv.A.getHermesValue();
3017
+ }
3018
+ ```
3019
+ Expected diff: `hasIndices` becomes `["ab"] undefined undefined`.
3020
+
3021
+ - [ ] **Step 7: Full suite** on `cmake-build-asan`: 0 failures.
3022
+
3023
+ - [ ] **Step 8: Commit**
3024
+
3025
+ ```bash
3026
+ git -C $R add lib/VM/JSLib/RegExp.cpp
3027
+ git -C $R commit -F $S/commit-6.txt
3028
+ ```
3029
+
3030
+ `$S/commit-6.txt`:
3031
+
3032
+ ````
3033
+ VM: builtin-exec fast paths for global @@match and @@search
3034
+
3035
+ A global @@match ran RegExpExec per match: an uncached Get of exec, a
3036
+ call to the native exec and a full result array with index, input and
3037
+ groups, of which it read only element 0. @@search read only index.
3038
+
3039
+ When exec is the builtin, both now run regExpBuiltinExecMatch in the
3040
+ exec frame and take the slice or position from the match ranges. The
3041
+ check reads exec's descriptor and compares the value with the saved
3042
+ builtin; a proxy, host object or accessor on the lookup path falls back
3043
+ to the generic path:
3044
+
3045
+ ```
3046
+ static bool hasBuiltinExec(Runtime &runtime, Handle<JSObject> R);
3047
+ ```
3048
+
3049
+ One check before the loop covers every iteration: the only other steps
3050
+ of an iteration are ToString of a string and the Get, ToLength and Set
3051
+ of a number in lastIndex, so no user code can change exec. lastIndex is
3052
+ read and written exactly as before.
3053
+
3054
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3055
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
3056
+ ````
3057
+
3058
+ ---
3059
+
3060
+ ### Task 7: The `@@replace` fast path
3061
+
3062
+ **Files:**
3063
+ - Modify: `lib/VM/JSLib/RegExp.cpp` (`buildGroupsObject` `:691-763` and
3064
+ its callers `:790`, `:871`; new helpers before
3065
+ `regExpPrototypeSymbolReplace`, `:1987`; its body `:1989-2374`)
3066
+
3067
+ **Interfaces:**
3068
+ - **Consumes:** `hasBuiltinExec`, `execMatchInBuiltinExecFrame`,
3069
+ `advanceLastIndexAfterEmptyMatch` (Task 6).
3070
+ - **Produces** (all `static` in `RegExp.cpp`):
3071
+ - `template <typename GetCapture> CallResult<PseudoHandle<JSObject>>
3072
+ buildGroupsObject(Runtime &, Handle<JSObject> mappingObj, const
3073
+ GetCapture &getCapture)`, where `getCapture(uint32_t i)` returns the
3074
+ `SmallHermesValue` of element `i` of the match (0 = whole match);
3075
+ - `ExecutionStatus replaceOneMatch(...)`: steps 16.m-p for one match;
3076
+ - `ExecutionStatus replaceBuiltinMatch(...)`: builds `matched`, the
3077
+ captures and the groups object from a `RegExpMatch`, then calls
3078
+ `replaceOneMatch`.
3079
+
3080
+ **Facts this task relies on:**
3081
+ - `@@replace` runs `ToString(S)`, `ToString(replaceValue)` when not
3082
+ callable, `Get global`, `Get unicode` and the `Set` before its loop
3083
+ (`RegExp.cpp:2020-2069`), keeps every result array
3084
+ (`:2099-2103`), and reads them back in phase 2 through `Get`s on own
3085
+ properties of arrays user code never sees (`:2156-2264`). The callback
3086
+ runs in phase 2 (`:2266-2316`).
3087
+ - The group-name mapping maps a name to its index in the full match
3088
+ array (`include/hermes/Regex/Regex.h:497-503`;
3089
+ `lib/VM/JSRegExp.cpp:261-267`), which is what `buildGroupsObject`
3090
+ indexes (`RegExp.cpp:718-722`).
3091
+ - `getSubstitution` takes captures as an `ArrayStorageSmall` and named
3092
+ captures as an object (`lib/VM/JSLib/JSLibInternal.h:282-289`).
3093
+ - `stringView` holds a handle and survives allocations
3094
+ (`include/hermes/VM/StringView.h:38-57`); it is only sliced and
3095
+ appended (`RegExp.cpp:2356-2358`).
3096
+
3097
+ **Counterexamples tried:**
3098
+ - A non-global `@@replace` has no pre-loop `Set`, so `lastIndex` may hold
3099
+ an object whose `valueOf` changes `exec`. There is one exec, and the
3100
+ slow path has already fetched `exec` before `valueOf` runs too, so both
3101
+ paths run the builtin once.
3102
+ - A callback that reuses the regexp (Review Focus 5) runs after phase 1
3103
+ in both paths, on stored matches.
3104
+
3105
+ **GC safety.**
3106
+ - `fastMatches` is a malloc'd vector of integers, unreachable from the
3107
+ GC.
3108
+ - Every string is a slice of the flat `S`, made by `slice`, which reads
3109
+ the characters after allocating.
3110
+ - `buildGroupsObject`'s `getCapture` reads through a handle and does not
3111
+ allocate.
3112
+ - Phase 2 keeps `marker1` per match and a marker per capture
3113
+ (`:2154`, `:2226`).
3114
+ - No raw pointer or `StringView` iterator is held across an allocation
3115
+ or call.
3116
+
3117
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
3118
+
3119
+ - [ ] **Step 2: Generalize `buildGroupsObject`** (`:691-763`)
3120
+
3121
+ Change its doc comment, signature and the two reads:
3122
+
3123
+ ```cpp
3124
+ /// Build an object whose property keys are identical to \p mappingObj. Each
3125
+ /// value for a given property key `k` in this object is
3126
+ /// `getCapture(mappingObj[k])`: \p getCapture maps an index of the match
3127
+ /// (0 is the whole match, n the n-th group) to that element as a
3128
+ /// SmallHermesValue, and must not allocate. The result has a null
3129
+ /// prototype.
3130
+ template <typename GetCapture>
3131
+ static CallResult<PseudoHandle<JSObject>> buildGroupsObject(
3132
+ Runtime &runtime,
3133
+ Handle<JSObject> mappingObj,
3134
+ const GetCapture &getCapture) {
3135
+ ```
3136
+
3137
+ In the non-dictionary path (`:718-722`):
3138
+
3139
+ ```cpp
3140
+ auto idx = static_cast<uint32_t>(
3141
+ JSObject::getNamedSlotValueUnsafe(
3142
+ *mappingObj, runtime, desc.slot)
3143
+ .getNumber(runtime));
3144
+ JSObject::setNamedSlotValueUnsafe(
3145
+ lv.groupsObj.get(), runtime, desc.slot, getCapture(idx));
3146
+ ```
3147
+
3148
+ In the dictionary path (`:744-747`):
3149
+
3150
+ ```cpp
3151
+ auto idx = static_cast<uint32_t>(
3152
+ JSObject::getNamedSlotValueUnsafe(*mappingObj, runtime, desc.slot)
3153
+ .getNumber(runtime));
3154
+ lv.tmpVal = getCapture(idx).unboxToHV(runtime);
3155
+ ```
3156
+
3157
+ Callers: in `setMatchGroups` (`:790`):
3158
+
3159
+ ```cpp
3160
+ auto groupsRes = buildGroupsObject(
3161
+ runtime, mappingObj, [&](uint32_t i) -> SmallHermesValue {
3162
+ return matchObj->at(runtime, i);
3163
+ });
3164
+ ```
3165
+
3166
+ and in `makeMatchIndicesIndexPairArray` (`:871`):
3167
+
3168
+ ```cpp
3169
+ auto groupsRes = buildGroupsObject(
3170
+ runtime, mappingObj, [&](uint32_t i) -> SmallHermesValue {
3171
+ return lv.A->at(runtime, i);
3172
+ });
3173
+ ```
3174
+
3175
+ - [ ] **Step 3: The per-match phase-2 helpers** (before
3176
+ `/// ES6.0 21.2.5.8` at `:1987`)
3177
+
3178
+ ```cpp
3179
+ /// ES6.0 21.2.5.8 steps 16.m-p of RegExp.prototype[@@replace], for one
3180
+ /// match: compute the replacement of the match \p matched at \p position of
3181
+ /// \p S, whose captures are \p captures (each a string or undefined) and
3182
+ /// whose named captures are \p namedCaptures (undefined if none), by calling
3183
+ /// \p replaceFn if it is not null and by GetSubstitution with
3184
+ /// \p replaceValueStr otherwise. If \p position is not before
3185
+ /// \p nextSourcePosition, append the text of \p stringView (a view of S)
3186
+ /// from nextSourcePosition up to position, and the replacement, to
3187
+ /// \p accumulatedResult, and move \p nextSourcePosition past the match.
3188
+ static ExecutionStatus replaceOneMatch(
3189
+ Runtime &runtime,
3190
+ Handle<StringPrimitive> S,
3191
+ const StringView &stringView,
3192
+ Handle<Callable> replaceFn,
3193
+ Handle<StringPrimitive> replaceValueStr,
3194
+ Handle<StringPrimitive> matched,
3195
+ uint32_t position,
3196
+ Handle<ArrayStorageSmall> captures,
3197
+ Handle<> namedCaptures,
3198
+ SmallU16String<32> &accumulatedResult,
3199
+ uint32_t &nextSourcePosition) {
3200
+ struct : public Locals {
3201
+ PinnedValue<HermesValue> namedCapturesObj;
3202
+ PinnedValue<> replValue;
3203
+ PinnedValue<StringPrimitive> replacement;
3204
+ } lv;
3205
+ LocalsRAII lraii(runtime, &lv);
3206
+
3207
+ const bool hasNamedCaptures = !namedCaptures->isUndefined();
3208
+ // f. Let matchLength be the number of code units in matched.
3209
+ const uint32_t matchLength = matched->getStringLength();
3210
+
3211
+ // m. If functionalReplace is true, then
3212
+ if (replaceFn) {
3213
+ CallResult<PseudoHandle<>> callRes{ExecutionStatus::EXCEPTION};
3214
+ {
3215
+ // i. Let replacerArgs be «matched».
3216
+ // Arguments: matched, captures, position, S (, groups).
3217
+ size_t replacerArgsCount =
3218
+ 1 + (size_t)captures->size() + 2 + hasNamedCaptures;
3219
+ if (LLVM_UNLIKELY(replacerArgsCount >= UINT32_MAX))
3220
+ return runtime.raiseStackOverflow(
3221
+ Runtime::StackOverflowKind::JSRegisterStack);
3222
+ ScopedNativeCallFrame newFrame{
3223
+ runtime,
3224
+ static_cast<uint32_t>(replacerArgsCount),
3225
+ *replaceFn,
3226
+ false,
3227
+ HermesValue::encodeUndefinedValue()};
3228
+ if (LLVM_UNLIKELY(newFrame.overflowed()))
3229
+ return runtime.raiseStackOverflow(
3230
+ Runtime::StackOverflowKind::NativeStack);
3231
+
3232
+ uint32_t argIdx = 0;
3233
+ newFrame->getArgRef(argIdx++) = matched.getHermesValue();
3234
+ // ii. Append in list order the elements of captures to the end of the
3235
+ // List replacerArgs.
3236
+ for (; argIdx <= captures->size(); ++argIdx) {
3237
+ newFrame->getArgRef(argIdx) =
3238
+ captures->at(argIdx - 1).unboxToHV(runtime);
3239
+ }
3240
+ // iii. Append position and S.
3241
+ newFrame->getArgRef(argIdx++) =
3242
+ HermesValue::encodeTrustedNumberValue(position);
3243
+ newFrame->getArgRef(argIdx++) = S.getHermesValue();
3244
+ // iv. If namedCaptures is not undefined, then
3245
+ if (hasNamedCaptures) {
3246
+ newFrame->getArgRef(argIdx++) = namedCaptures.getHermesValue();
3247
+ }
3248
+ // v. Let replValue be Call(replaceValue, undefined, replacerArgs).
3249
+ callRes = Callable::call(replaceFn, runtime);
3250
+ if (callRes == ExecutionStatus::EXCEPTION) {
3251
+ return ExecutionStatus::EXCEPTION;
3252
+ }
3253
+ }
3254
+ // vi. Let replacement be ToString(replValue).
3255
+ lv.replValue = std::move(callRes.getValue());
3256
+ auto strRes = toString_RJS(runtime, lv.replValue);
3257
+ if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
3258
+ return ExecutionStatus::EXCEPTION;
3259
+ }
3260
+ lv.replacement = strRes->get();
3261
+ } else {
3262
+ // n. Else,
3263
+ // i. If namedCaptures is not undefined, then
3264
+ if (hasNamedCaptures) {
3265
+ // 1. Set namedCaptures to ? ToObject(namedCaptures).
3266
+ auto objRes = toObject(runtime, namedCaptures);
3267
+ if (LLVM_UNLIKELY(objRes == ExecutionStatus::EXCEPTION)) {
3268
+ return ExecutionStatus::EXCEPTION;
3269
+ }
3270
+ lv.namedCapturesObj = *objRes;
3271
+ }
3272
+ // ii. Let replacement be GetSubstitution(matched, S, position, captures,
3273
+ // replaceValue).
3274
+ auto callRes = getSubstitution(
3275
+ runtime,
3276
+ matched,
3277
+ S,
3278
+ position,
3279
+ captures,
3280
+ hasNamedCaptures ? Handle<JSObject>::vmcast(&lv.namedCapturesObj)
3281
+ : Runtime::makeNullHandle<JSObject>(),
3282
+ replaceValueStr);
3283
+ if (LLVM_UNLIKELY(callRes == ExecutionStatus::EXCEPTION)) {
3284
+ return ExecutionStatus::EXCEPTION;
3285
+ }
3286
+ lv.replacement.castAndSetHermesValue<StringPrimitive>(callRes.getValue());
3287
+ }
3288
+ // o. ReturnIfAbrupt(replacement).
3289
+ // p. If position ≥ nextSourcePosition, then
3290
+ if (position >= nextSourcePosition) {
3291
+ // i. NOTE position should not normally move backwards. If it does, it is
3292
+ // an indication of an ill-behaving RegExp subclass or use of an access
3293
+ // triggered side-effect to change the global flag or other
3294
+ // characteristics of rx. In such cases, the corresponding substitution is
3295
+ // ignored.
3296
+ // ii. Let accumulatedResult be the String formed by concatenating the
3297
+ // code units of the current value of accumulatedResult with the substring
3298
+ // of S consisting of the code units from nextSourcePosition (inclusive) up
3299
+ // to position (exclusive) and with the code units of replacement.
3300
+ stringView.slice(nextSourcePosition, position - nextSourcePosition)
3301
+ .appendUTF16String(accumulatedResult);
3302
+ lv.replacement->appendUTF16String(accumulatedResult);
3303
+ // iii. Let nextSourcePosition be position + matchLength.
3304
+ nextSourcePosition = position + matchLength;
3305
+ }
3306
+ return ExecutionStatus::RETURNED;
3307
+ }
3308
+
3309
+ /// Phase 2 of RegExp.prototype[@@replace] for a match \p match of the
3310
+ /// builtin exec on \p S: build matched, the captures and the groups object
3311
+ /// (from \p groupNames, the regexp's group-name mapping, if not null) as
3312
+ /// the builtin's result array would hold them, then run replaceOneMatch().
3313
+ /// The Gets this replaces read own properties of an array user code never
3314
+ /// sees, so skipping them is unobservable.
3315
+ static ExecutionStatus replaceBuiltinMatch(
3316
+ Runtime &runtime,
3317
+ Handle<StringPrimitive> S,
3318
+ const StringView &stringView,
3319
+ Handle<Callable> replaceFn,
3320
+ Handle<StringPrimitive> replaceValueStr,
3321
+ Handle<JSObject> groupNames,
3322
+ const RegExpMatch &match,
3323
+ SmallU16String<32> &accumulatedResult,
3324
+ uint32_t &nextSourcePosition) {
3325
+ struct : public Locals {
3326
+ PinnedValue<StringPrimitive> matched;
3327
+ PinnedValue<ArrayStorageSmall> captures;
3328
+ PinnedValue<> capN;
3329
+ PinnedValue<> namedCaptures;
3330
+ } lv;
3331
+ LocalsRAII lraii(runtime, &lv);
3332
+
3333
+ // matched: element 0, the whole match.
3334
+ const RegExpMatchRange whole = *match[0];
3335
+ auto matchedRes =
3336
+ StringPrimitive::slice(runtime, S, whole.location, whole.length);
3337
+ if (LLVM_UNLIKELY(matchedRes == ExecutionStatus::EXCEPTION))
3338
+ return ExecutionStatus::EXCEPTION;
3339
+ lv.matched.castAndSetHermesValue<StringPrimitive>(*matchedRes);
3340
+
3341
+ // captures: a string per matched group, undefined per unmatched one.
3342
+ const uint32_t nCaptures = match.size() - 1;
3343
+ auto capturesRes = ArrayStorageSmall::create(runtime, nCaptures);
3344
+ if (LLVM_UNLIKELY(capturesRes == ExecutionStatus::EXCEPTION))
3345
+ return ExecutionStatus::EXCEPTION;
3346
+ lv.captures.castAndSetHermesValue<ArrayStorageSmall>(*capturesRes);
3347
+ MutableHandle<ArrayStorageSmall> captures{lv.captures};
3348
+ for (uint32_t n = 1; n <= nCaptures; ++n) {
3349
+ GCScopeMarkerRAII marker{runtime};
3350
+ if (!match[n]) {
3351
+ lv.capN = HermesValue::encodeUndefinedValue();
3352
+ } else {
3353
+ auto capRes = StringPrimitive::slice(
3354
+ runtime, S, match[n]->location, match[n]->length);
3355
+ if (LLVM_UNLIKELY(capRes == ExecutionStatus::EXCEPTION))
3356
+ return ExecutionStatus::EXCEPTION;
3357
+ lv.capN = *capRes;
3358
+ }
3359
+ if (LLVM_UNLIKELY(
3360
+ ArrayStorageSmall::push_back(captures, runtime, lv.capN) ==
3361
+ ExecutionStatus::EXCEPTION))
3362
+ return ExecutionStatus::EXCEPTION;
3363
+ }
3364
+
3365
+ // namedCaptures: the groups object, or undefined without named groups.
3366
+ if (groupNames) {
3367
+ auto groupsRes = buildGroupsObject(
3368
+ runtime, groupNames, [&](uint32_t i) -> SmallHermesValue {
3369
+ return captures->at(i - 1);
3370
+ });
3371
+ if (LLVM_UNLIKELY(groupsRes == ExecutionStatus::EXCEPTION))
3372
+ return ExecutionStatus::EXCEPTION;
3373
+ lv.namedCaptures = groupsRes->getHermesValue();
3374
+ } else {
3375
+ lv.namedCaptures = HermesValue::encodeUndefinedValue();
3376
+ }
3377
+
3378
+ return replaceOneMatch(
3379
+ runtime,
3380
+ S,
3381
+ stringView,
3382
+ replaceFn,
3383
+ replaceValueStr,
3384
+ lv.matched,
3385
+ whole.location,
3386
+ captures,
3387
+ lv.namedCaptures,
3388
+ accumulatedResult,
3389
+ nextSourcePosition);
3390
+ }
3391
+ ```
3392
+
3393
+ - [ ] **Step 4: The `@@replace` body**
3394
+
3395
+ In the Locals of `regExpPrototypeSymbolReplace` (`:1989-2005`), delete
3396
+ `PinnedValue<StringPrimitive> replacement;` and
3397
+ `PinnedValue<> replValueHandle;` (now in `replaceOneMatch`). Keep
3398
+ everything up to the end of `if (global) { ... }` (`:2069`). Replace
3399
+ from `// 11. Let results be a new empty List.` (`:2070`) to the end of
3400
+ the function (`:2374`) with:
3401
+
3402
+ ```cpp
3403
+ // Whether exec is the builtin. From here to the end of phase 1 no user
3404
+ // code runs outside exec (ToString of a string, Get and ToLength of the
3405
+ // number that lastIndex holds, Set of lastIndex), so one check covers
3406
+ // every exec; callbacks run in phase 2, after the last exec.
3407
+ const bool fast = hasBuiltinExec(runtime, rx);
3408
+ // The matches of phase 1 when fast.
3409
+ std::vector<RegExpMatch> fastMatches;
3410
+ MutableHandle<ArrayStorageSmall> resultsHandle{lv.resultsHandle};
3411
+ if (!fast) {
3412
+ // 11. Let results be a new empty List.
3413
+ auto arrRes = ArrayStorageSmall::create(runtime, 16 /* capacity */);
3414
+ if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {
3415
+ return ExecutionStatus::EXCEPTION;
3416
+ }
3417
+ lv.resultsHandle.castAndSetHermesValue<ArrayStorageSmall>(
3418
+ arrRes.getValue());
3419
+ }
3420
+
3421
+ // 12. Let done be false.
3422
+ // 13. Repeat, while done is false
3423
+ auto stringView = StringPrimitive::createStringView(runtime, lv.S);
3424
+ while (true) {
3425
+ GCScopeMarkerRAII marker{runtime};
3426
+ bool emptyMatch = false;
3427
+ // a. Let result be RegExpExec(rx, S).
3428
+ // b. ReturnIfAbrupt(result).
3429
+ if (fast) {
3430
+ RegExpMatch match;
3431
+ auto matchRes = execMatchInBuiltinExecFrame(
3432
+ runtime, Handle<JSRegExp>::vmcast(rx), lv.S, match);
3433
+ if (LLVM_UNLIKELY(matchRes == ExecutionStatus::EXCEPTION)) {
3434
+ return ExecutionStatus::EXCEPTION;
3435
+ }
3436
+ // c. If result is null, set done to true.
3437
+ if (!*matchRes)
3438
+ break;
3439
+ // Element 0 of the builtin's result is this range of S.
3440
+ emptyMatch = match[0]->length == 0;
3441
+ // d.i. Append result to the end of results.
3442
+ fastMatches.push_back(std::move(match));
3443
+ // ii. If global is false, set done to true.
3444
+ if (!global)
3445
+ break;
3446
+ } else {
3447
+ auto execRes = regExpExec(runtime, rx, lv.S);
3448
+ if (LLVM_UNLIKELY(execRes == ExecutionStatus::EXCEPTION)) {
3449
+ return ExecutionStatus::EXCEPTION;
3450
+ }
3451
+ // c. If result is null, set done to true.
3452
+ if (execRes->isNull())
3453
+ break;
3454
+ // d. Else result is not null,
3455
+ // If result is not null, it must be an object.
3456
+ lv.result.castAndSetHermesValue<JSObject>(execRes.getValue());
3457
+ // i. Append result to the end of results.
3458
+ if (LLVM_UNLIKELY(
3459
+ ArrayStorageSmall::push_back(resultsHandle, runtime, lv.result) ==
3460
+ ExecutionStatus::EXCEPTION)) {
3461
+ return ExecutionStatus::EXCEPTION;
3462
+ }
3463
+ // ii. If global is false, set done to true.
3464
+ if (!global)
3465
+ break;
3466
+ // iii. Else,
3467
+ // 1. Let matchStr be ToString(Get(result, "0")).
3468
+ // 2. ReturnIfAbrupt(matchStr).
3469
+ propRes = getIndexed_RJS(runtime, lv.result, 0);
3470
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
3471
+ return ExecutionStatus::EXCEPTION;
3472
+ }
3473
+ lv.propValue = propRes->get();
3474
+ auto strRes = toString_RJS(runtime, lv.propValue);
3475
+ if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
3476
+ return ExecutionStatus::EXCEPTION;
3477
+ }
3478
+ lv.matchStr = strRes->get();
3479
+ emptyMatch = lv.matchStr->getStringLength() == 0;
3480
+ }
3481
+ // iii.3. If matchStr is the empty String, then
3482
+ // a-e. Set lastIndex to AdvanceStringIndex(S, thisIndex, fullUnicode).
3483
+ if (emptyMatch) {
3484
+ if (LLVM_UNLIKELY(
3485
+ advanceLastIndexAfterEmptyMatch(
3486
+ runtime, rx, lv.S, fullUnicode) ==
3487
+ ExecutionStatus::EXCEPTION)) {
3488
+ return ExecutionStatus::EXCEPTION;
3489
+ }
3490
+ }
3491
+ }
3492
+
3493
+ // 14. Let accumulatedResult be the empty String value.
3494
+ SmallU16String<32> accumulatedResult{};
3495
+ // 15. Let nextSourcePosition be 0.
3496
+ uint32_t nextSourcePosition = 0;
3497
+ // 16. Repeat, for each result in results,
3498
+ if (fast) {
3499
+ Handle<JSObject> groupNames =
3500
+ Handle<JSRegExp>::vmcast(rx)->getGroupNameMappings(runtime);
3501
+ for (const RegExpMatch &match : fastMatches) {
3502
+ GCScopeMarkerRAII marker1{runtime};
3503
+ if (LLVM_UNLIKELY(
3504
+ replaceBuiltinMatch(
3505
+ runtime,
3506
+ lv.S,
3507
+ stringView,
3508
+ replaceFn,
3509
+ lv.replaceValueStr,
3510
+ groupNames,
3511
+ match,
3512
+ accumulatedResult,
3513
+ nextSourcePosition) == ExecutionStatus::EXCEPTION)) {
3514
+ return ExecutionStatus::EXCEPTION;
3515
+ }
3516
+ }
3517
+ } else {
3518
+ for (uint32_t i = 0, size = resultsHandle->size(); i < size; ++i) {
3519
+ GCScopeMarkerRAII marker1{runtime};
3520
+ lv.result = vmcast<JSObject>(resultsHandle->at(i).getObject(runtime));
3521
+ // a. Let nCaptures be ToLength(Get(result, "length")).
3522
+ // b. ReturnIfAbrupt(nCaptures).
3523
+ propRes = JSObject::getNamed_RJS(
3524
+ lv.result, runtime, Predefined::getSymbolID(Predefined::length));
3525
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
3526
+ return ExecutionStatus::EXCEPTION;
3527
+ }
3528
+ lv.valueHandle = std::move(propRes.getValue());
3529
+ auto lengthRes = toLength(runtime, lv.valueHandle);
3530
+ if (LLVM_UNLIKELY(lengthRes == ExecutionStatus::EXCEPTION)) {
3531
+ return ExecutionStatus::EXCEPTION;
3532
+ }
3533
+ // Use uint64_t so it can fit the result of toLength.
3534
+ uint64_t nCaptures = lengthRes->getNumberAs<uint64_t>();
3535
+ // c. Let nCaptures be max(nCaptures − 1, 0).
3536
+ nCaptures = nCaptures > 0 ? nCaptures - 1 : 0;
3537
+
3538
+ // Throw RangeError if nCaptures exceeds uint32_t, since
3539
+ // ArrayStorageSmall::create() takes uint32_t capacity and the loop
3540
+ // below would run for an impractical number of iterations.
3541
+ if (LLVM_UNLIKELY(nCaptures > UINT32_MAX)) {
3542
+ return runtime.raiseRangeError(
3543
+ "Too many capture groups in exec result");
3544
+ }
3545
+ // d. Let matched be ToString(Get(result, "0")).
3546
+ // e. ReturnIfAbrupt(matched).
3547
+ propRes = getIndexed_RJS(runtime, lv.result, 0);
3548
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
3549
+ return ExecutionStatus::EXCEPTION;
3550
+ }
3551
+ lv.indexedPropValue = std::move(propRes.getValue());
3552
+ auto strRes = toString_RJS(runtime, lv.indexedPropValue);
3553
+ if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) {
3554
+ return ExecutionStatus::EXCEPTION;
3555
+ }
3556
+ lv.matched = std::move(*strRes);
3557
+ // g. Let position be ToIntegerOrInfinity(Get(result, "index")).
3558
+ // h. ReturnIfAbrupt(position).
3559
+ propRes = JSObject::getNamed_RJS(
3560
+ lv.result, runtime, Predefined::getSymbolID(Predefined::index));
3561
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
3562
+ return ExecutionStatus::EXCEPTION;
3563
+ }
3564
+ lv.indexPropValue = std::move(propRes.getValue());
3565
+ auto intRes = toIntegerOrInfinity(runtime, lv.indexPropValue);
3566
+ if (LLVM_UNLIKELY(intRes == ExecutionStatus::EXCEPTION)) {
3567
+ return ExecutionStatus::EXCEPTION;
3568
+ }
3569
+ // position could potentially be negative or Infinity here, so use
3570
+ // double.
3571
+ double positionDouble = intRes->getNumber();
3572
+ // i. Let position be max(min(position, lengthS), 0).
3573
+ // Now we can clamp to uint32_t because we've bounds checked
3574
+ // and `lengthS` is `uint32_t`.
3575
+ uint32_t position = (int64_t)std::fmax(
3576
+ std::fmin(positionDouble, (double)lengthS), (double)0);
3577
+ // j. Let n be 1.
3578
+ // Match the type of nCaptures.
3579
+ uint64_t n = 1;
3580
+ // k. Let captures be an empty List.
3581
+ auto capturesRes =
3582
+ ArrayStorageSmall::create(runtime, static_cast<uint32_t>(nCaptures));
3583
+ if (LLVM_UNLIKELY(capturesRes == ExecutionStatus::EXCEPTION)) {
3584
+ return ExecutionStatus::EXCEPTION;
3585
+ }
3586
+ lv.capturesHandle.castAndSetHermesValue<ArrayStorageSmall>(
3587
+ capturesRes.getValue());
3588
+ MutableHandle<ArrayStorageSmall> capturesHandle{lv.capturesHandle};
3589
+ // l. Repeat while n ≤ nCaptures
3590
+ while (n <= nCaptures) {
3591
+ GCScopeMarkerRAII marker2{runtime};
3592
+ // i. Let capN be Get(result, ToString(n)).
3593
+ // ii. ReturnIfAbrupt(capN).
3594
+ propRes = getIndexed_RJS(runtime, lv.result, n);
3595
+ if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
3596
+ return ExecutionStatus::EXCEPTION;
3597
+ }
3598
+ lv.capN = std::move(propRes.getValue());
3599
+ // iii. If capN is not undefined, then
3600
+ if (!lv.capN->isUndefined()) {
3601
+ // 1. Let capN be ToString(capN).
3602
+ // 2. ReturnIfAbrupt(capN).
3603
+ auto capStrRes = toString_RJS(runtime, lv.capN);
3604
+ if (LLVM_UNLIKELY(capStrRes == ExecutionStatus::EXCEPTION)) {
3605
+ return ExecutionStatus::EXCEPTION;
3606
+ }
3607
+ lv.capN = capStrRes->getHermesValue();
3608
+ }
3609
+ // iv. Append capN as the last element of captures.
3610
+ if (LLVM_UNLIKELY(
3611
+ ArrayStorageSmall::push_back(
3612
+ capturesHandle, runtime, lv.capN) ==
3613
+ ExecutionStatus::EXCEPTION)) {
3614
+ return ExecutionStatus::EXCEPTION;
3615
+ }
3616
+ // v. Let n be n+1
3617
+ n++;
3618
+ }
3619
+
3620
+ // j. Let namedCaptures be ? Get(result, "groups").
3621
+ auto namedCapturesRes = JSObject::getNamed_RJS(
3622
+ lv.result, runtime, Predefined::getSymbolID(Predefined::groups));
3623
+ if (LLVM_UNLIKELY(namedCapturesRes == ExecutionStatus::EXCEPTION)) {
3624
+ return ExecutionStatus::EXCEPTION;
3625
+ }
3626
+ lv.namedCaptures = std::move(*namedCapturesRes);
3627
+
3628
+ // m-p.
3629
+ if (LLVM_UNLIKELY(
3630
+ replaceOneMatch(
3631
+ runtime,
3632
+ lv.S,
3633
+ stringView,
3634
+ replaceFn,
3635
+ lv.replaceValueStr,
3636
+ lv.matched,
3637
+ position,
3638
+ capturesHandle,
3639
+ lv.namedCaptures,
3640
+ accumulatedResult,
3641
+ nextSourcePosition) == ExecutionStatus::EXCEPTION)) {
3642
+ return ExecutionStatus::EXCEPTION;
3643
+ }
3644
+ }
3645
+ }
3646
+
3647
+ // 17. If nextSourcePosition ≥ lengthS, return accumulatedResult.
3648
+ if (nextSourcePosition >= lengthS) {
3649
+ return StringPrimitive::createEfficient(runtime, accumulatedResult);
3650
+ }
3651
+ // 18. Return the String formed by concatenating the code units of
3652
+ // accumulatedResult with the substring of S consisting of the code units from
3653
+ // nextSourcePosition (inclusive) up through the final code unit of S
3654
+ // (inclusive).
3655
+ stringView.slice(nextSourcePosition).appendUTF16String(accumulatedResult);
3656
+ return StringPrimitive::createEfficient(runtime, accumulatedResult);
3657
+ }
3658
+ ```
3659
+
3660
+ The slow path is today's code (`:2083-2361`) with three changes: the
3661
+ empty-match block calls `advanceLastIndexAfterEmptyMatch`, steps m-p
3662
+ call `replaceOneMatch`, and `namedCaptures` is passed as a value
3663
+ (undefined when absent) instead of a flag plus a value.
3664
+
3665
+ - [ ] **Step 5: Build and run**
3666
+
3667
+ ```bash
3668
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes
3669
+ LIT_FILTER='regexp|regex|string-functions|string-replace' \
3670
+ cmake --build $R/cmake-build-asan --target check-hermes
3671
+ ```
3672
+
3673
+ Expected: 0 failures, including `regexp-replace-truncation.js` (the
3674
+ generic path's `length` RangeError) and `regexp.js:586-590` (an own
3675
+ `exec` returning a huge `index`).
3676
+
3677
+ - [ ] **Step 6: Moving GC** (`-gc-sanitize-handles` coverage)
3678
+
3679
+ ```bash
3680
+ cmake --build $R/cmake-build-hsan --target hermes hermesc shermes
3681
+ LIT_FILTER='regexp|regex|string-functions' \
3682
+ cmake --build $R/cmake-build-hsan --target check-hermes
3683
+ ```
3684
+
3685
+ Expected: 0 failures, no ASan report. The `-gc-sanitize-handles=1` RUN
3686
+ line moves the heap at every allocation in this tree.
3687
+
3688
+ - [ ] **Step 7: Prove the guard can fail** (spec table; mutation diff on
3689
+ `cmake-build-asan`; rebuild after each edit and restore)
3690
+ - Replace fast path taken for any JSRegExp: change
3691
+ `const bool fast = hasBuiltinExec(runtime, rx);` in `@@replace` to
3692
+ `const bool fast = vmisa<JSRegExp>(rx.getHermesValue());`. Expected
3693
+ diff: `replaced exec` lines 2-3 have empty logs; `own and subclass
3694
+ exec` counts drop.
3695
+ - Frozen, pre-loop `Set` skipped: move the `fast` check above the
3696
+ `if (global)` block and make the `Set` `if (!fast)`-guarded. Expected
3697
+ diff: `frozen` line 2 becomes `TypeError true`.
3698
+ - Empty matches by code unit: pass `fast ? false : fullUnicode` in the
3699
+ `@@replace` loop. Expected diff: `empty matches` line 2 becomes
3700
+ `"---x-" "-\ud83d-\ude00-x-"`, and `unicode getter` becomes
3701
+ `["","",""] "-\ud83d-\ude00-x-"`. Derivation: phase 1 records
3702
+ (0,0), (0,2), (2,0), (3,0) (see the Task 6 derivation); phase 2
3703
+ appends `-` for each and the text before it, and the last append
3704
+ brings in `x`. The run terminates.
3705
+ - Flag instead of `Get unicode`: the Task 6 edit in the `@@replace`
3706
+ loop. Expected diff: only `unicode getter`, whose replace result
3707
+ becomes `"-\ud83d-\ude00-x-"`.
3708
+ - Sticky cleared: before the `@@replace` loop, clear `sticky` on the
3709
+ regexp when `fast` (the Task 6 edit). Expected diff: `sticky global`
3710
+ line 2 becomes `"xxbx" "bxx"`. Derivation: without sticky, the global
3711
+ search of `/a/g` on `"aaba"` finds `a` at 0, 1 and 3 (it skips the
3712
+ `b` at 2), and on `"baa"` at 1 and 2.
3713
+ - `@@replace` unframed: call `regExpBuiltinExecMatch(
3714
+ Handle<JSRegExp>::vmcast(rx), runtime, lv.S, match)` instead of
3715
+ `execMatchInBuiltinExecFrame(...)`. Expected diff: `replace false` in
3716
+ `stacks`.
3717
+ - Range 0 for every capture: in `replaceBuiltinMatch`, use `match[0]`
3718
+ in place of `match[n]` (both uses). Expected diff: `replacements`
3719
+ lines 1, 2, 4 and 5 change (every `$n`, `$<name>`, capture argument
3720
+ and group becomes the whole match).
3721
+ - Unmatched groups as `""`: in `replaceBuiltinMatch`, replace
3722
+ `lv.capN = HermesValue::encodeUndefinedValue();` with
3723
+ `lv.capN = HermesValue::encodeStringValue(
3724
+ runtime.getPredefinedString(Predefined::emptyString));`. Expected
3725
+ diff: `replacements` lines 4-5 show `""` for `undefined` (also
3726
+ `q:""`); line 2 is unchanged because `$2` substitutes `""` either
3727
+ way.
3728
+ - Callbacks interleaved with execs (Review Focus 5): move
3729
+ `SmallU16String<32> accumulatedResult{};` and
3730
+ `uint32_t nextSourcePosition = 0;` above the phase-1 loop, and in the
3731
+ fast branch replace `fastMatches.push_back(std::move(match));` with
3732
+ a call to `replaceBuiltinMatch(runtime, lv.S, stringView, replaceFn,
3733
+ lv.replaceValueStr, Handle<JSRegExp>::vmcast(rx)->
3734
+ getGroupNameMappings(runtime), match, accumulatedResult,
3735
+ nextSourcePosition)` (returning on exception). Expected: `statics`
3736
+ line 5 becomes `6,7 7|7|p6q|r`, and the run then loops in
3737
+ `reentrant callback` (the inner replace resets `lastIndex`) until
3738
+ `timeout` kills it (`exit 124`).
3739
+
3740
+ - [ ] **Step 8: Full suite** on `cmake-build-asan`: 0 failures.
3741
+
3742
+ - [ ] **Step 9: Commit**
3743
+
3744
+ ```bash
3745
+ git -C $R add lib/VM/JSLib/RegExp.cpp
3746
+ git -C $R commit -F $S/commit-7.txt
3747
+ ```
3748
+
3749
+ `$S/commit-7.txt` (Task 8 adds the measurements):
3750
+
3751
+ ````
3752
+ VM: builtin-exec fast path for @@replace
3753
+
3754
+ @@replace kept every exec result array until phase 2, then read each
3755
+ back through generic Gets of length, 0, index, every capture and
3756
+ groups.
3757
+
3758
+ When exec is the builtin, phase 1 runs regExpBuiltinExecMatch in the
3759
+ exec frame and keeps each match's ranges in a C++ vector. Phase 2 is
3760
+ factored into one step per match that takes matched, position, the
3761
+ captures and the named captures:
3762
+
3763
+ ```
3764
+ static ExecutionStatus replaceOneMatch(
3765
+ Runtime &runtime, Handle<StringPrimitive> S,
3766
+ const StringView &stringView, Handle<Callable> replaceFn,
3767
+ Handle<StringPrimitive> replaceValueStr,
3768
+ Handle<StringPrimitive> matched, uint32_t position,
3769
+ Handle<ArrayStorageSmall> captures, Handle<> namedCaptures,
3770
+ SmallU16String<32> &accumulatedResult, uint32_t &nextSourcePosition);
3771
+ ```
3772
+
3773
+ The generic path still extracts them with today's Gets. The fast path
3774
+ builds them from the ranges: slices of S, undefined for unmatched
3775
+ groups, and a groups object from the regexp's group-name mapping;
3776
+ buildGroupsObject now takes a function that reads a capture. The
3777
+ callback still runs in phase 2, after every exec.
3778
+
3779
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3780
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
3781
+ ````
3782
+
3783
+ ---
3784
+
3785
+ ### Task 8: Cross-configuration suites and measurements
3786
+
3787
+ **Files:**
3788
+ - No source change. Amends the messages of the Task 3 and Task 7
3789
+ commits.
3790
+
3791
+ - [ ] **Step 1: Full suites**
3792
+
3793
+ ```bash
3794
+ for t in asan hsan hv32; do
3795
+ cmake --build $R/cmake-build-$t --target check-hermes
3796
+ done
3797
+ $R/cmake-build-asan/unittests/Support/HermesSupportTests \
3798
+ --gtest_filter='Regex.*'
3799
+ ```
3800
+
3801
+ Expected: 0 failures in every tree. On `cmake-build-asan`, expected
3802
+ passes are the Task 1 baseline + 4 (unless a test is unsupported there).
3803
+ `cmake-build-hsan` and `cmake-build-hv32` have no recorded baseline;
3804
+ record their counts.
3805
+
3806
+ - [ ] **Step 2: The measurement script**
3807
+
3808
+ Write `$S/measure.sh`:
3809
+
3810
+ ```bash
3811
+ #!/bin/bash
3812
+ # Usage: measure.sh <label>. Rebuilds the release hermes for the current
3813
+ # checkout and runs each benchmark of the spec's Problem section 3 times.
3814
+ set -e
3815
+ R=/home/tmikov/work/hermes-regex-jit
3816
+ cmake --build $R/cmake-build-release --target hermes > /dev/null
3817
+ H=$R/cmake-build-release/bin/hermes
3818
+ M=$R/benchmarks/bench-runner/resource/test-suites/micros
3819
+ echo "== $1 ($(git -C $R rev-parse --short HEAD))"
3820
+ for i in 1 2 3; do
3821
+ $H -O $R/benchmarks/octane/regexp.js | grep '^RegExp '
3822
+ done
3823
+ for b in stringMatch stringSearch regExpSearch regExpMatch regExpSplit \
3824
+ regExpReplace; do
3825
+ for i in 1 2 3; do
3826
+ echo "$b $($H -O $M/$b.js | grep '^Time:')"
3827
+ done
3828
+ done
3829
+ ```
3830
+
3831
+ Best of three is the highest Octane score and the lowest micro time.
3832
+
3833
+ - [ ] **Step 3: Measure BASE, end of Part A, end of Part B**
3834
+
3835
+ The tree must be clean apart from untracked files
3836
+ (`git -C $R status --short` shows only `??` lines). `A_END` is the Task 3
3837
+ commit, `B_END` the Task 7 commit (HEAD).
3838
+
3839
+ ```bash
3840
+ A_END=$(git -C $R log --format=%H -1 \
3841
+ --grep='^Regex: skip start positions that cannot begin a match')
3842
+ B_END=$(git -C $R rev-parse HEAD)
3843
+ git -C $R checkout --detach <BASE>
3844
+ bash $S/measure.sh BASE | tee $S/measure-base.txt
3845
+ git -C $R checkout --detach $A_END
3846
+ bash $S/measure.sh "Part A" | tee $S/measure-a.txt
3847
+ git -C $R checkout regexp-speedup
3848
+ bash $S/measure.sh "Part B" | tee $S/measure-b.txt
3849
+ ```
3850
+
3851
+ `<BASE>` is the hash recorded in Task 1 Step 1. Each checkout makes the
3852
+ next build of the Debug trees rebuild more; that is expected.
3853
+
3854
+ - [ ] **Step 4: Record the numbers in the two commit messages**
3855
+
3856
+ Each part gets a block from its best-of-three numbers (no pass/fail
3857
+ threshold, spec "Measurements"). The two blocks compare against
3858
+ different revisions:
3859
+
3860
+ | Block | Message of | "Before" column | "After" column | `<REF>` |
3861
+ |--------|-----------|-----------------|----------------|---------|
3862
+ | Part A | Task 3 commit | `measure-base.txt` | `measure-a.txt` | `BASE <BASE short hash>` |
3863
+ | Part B | Task 7 commit | `measure-a.txt` | `measure-b.txt` | `the start-filter commit ("Regex: skip start positions that cannot begin a match")` |
3864
+
3865
+ Part B's reference names the Part A commit by subject, not by hash: the
3866
+ rewrite below and the later squash both change that hash, while BASE is
3867
+ an existing commit whose hash does not change. Template:
3868
+
3869
+ ````
3870
+ Measured on a release build (-g -fno-omit-frame-pointer, x86-64), best
3871
+ of three, hermes -O, against <REF>:
3872
+
3873
+ ```
3874
+ Benchmark Before After
3875
+ Octane RegExp (score) ... ...
3876
+ micros/stringMatch.js ... ms ... ms
3877
+ micros/stringSearch.js ... ms ... ms
3878
+ micros/regExpSearch.js ... ms ... ms
3879
+ micros/regExpMatch.js ... ms ... ms
3880
+ micros/regExpSplit.js ... ms ... ms
3881
+ micros/regExpReplace.js ... ms ... ms
3882
+ ```
3883
+ ````
3884
+
3885
+ Insert each block before the `Co-Authored-By:` line of its message.
3886
+ Rewrite the Part A message first, then the Part B message (HEAD after
3887
+ the rebase):
3888
+
3889
+ ```bash
3890
+ git -C $R log -1 --format=%B $A_END > $S/msg-a.txt
3891
+ # edit $S/msg-a.txt: insert the Part A block before the trailers
3892
+ GIT_SEQUENCE_EDITOR="sed -i '/^pick ${A_END:0:7}/a exec git commit --amend -F $S/msg-a.txt'" \
3893
+ git -C $R rebase -i ${A_END}~1
3894
+ git -C $R log -1 --format=%B HEAD > $S/msg-b.txt
3895
+ # edit $S/msg-b.txt: insert the Part B block before the trailers
3896
+ git -C $R commit --amend -F $S/msg-b.txt
3897
+ git -C $R diff $B_END HEAD --stat # must be empty: only messages changed
3898
+ git -C $R log -7 --format='%h %s' # record the new hashes
3899
+ ```
3900
+
3901
+ See the `non-interactive-git-rebase` skill if the rebase stops. The
3902
+ final `diff` must print nothing.
3903
+
3904
+ - [ ] **Step 5: Report**
3905
+
3906
+ The report lists: the per-tree suite counts; the three measurement
3907
+ tables; the new hashes of all seven commits; every mutation and the
3908
+ failure it produced (from Tasks 1-7); and every plan ruling used,
3909
+ including any taken during implementation.
3910
+
3911
+ ---
3912
+
3913
+ ## Plan rulings
3914
+
3915
+ 1. The executor's bracket predicate moves into
3916
+ `bracketMatchesCodePoint` (`RegexTraits.h`), shared by the executor
3917
+ and `BracketNode::addStartSet`. Beyond the spec's shared closure
3918
+ helper, this makes the ASCII bits the executor's own answers (spec,
3919
+ Risks) (Task 1).
3920
+ 2. The base `Node::addStartSet` returns `Nullable`, because the base
3921
+ `Node` is the leading no-op node; every subclass overrides it,
3922
+ including the zero-width ones, so each states its rule (Task 1).
3923
+ 3. `startSet_` is reset at the start of `parseWithBackRefLimit` and
3924
+ computed only on success, so a reparse (`Regex.h:317-335`) never
3925
+ keeps a stale set (Task 1).
3926
+ 4. `StartSet` is a class with an out-of-line `writeTo`; one helper,
3927
+ `startSetHasASCII`, reads the header bitmap for the executor, the
3928
+ dump and the tests; a `static_assert` pins the 24-byte header
3929
+ (Task 1).
3930
+ 5. The header test describes a filter as a string ("none", hex ranges,
3931
+ "nonascii", "single", "empty"), so one table checks flags, bitmap and
3932
+ `startChar` (Task 1).
3933
+ 6. A present filter with no members (only `[]`) dumps as `StartSet:`
3934
+ with nothing after it (Task 2).
3935
+ 7. The A.5 case `/(){999999999}a/` over `"b"` runs as its own test, once
3936
+ each way, not inside the corpus loop: an unfiltered run builds 2^24
3937
+ backtrack records (Task 3).
3938
+ 8. The differential corpus adds lookbehind, astral, multiline, `\s`,
3939
+ property-escape, `[]`/`[^]` and nested-group patterns, and a UTF-16
3940
+ input with only ASCII units (Review Focus 1-3) (Task 3).
3941
+ 9. Spec B.3 requires the callee rooted and reloaded across the body. In
3942
+ `HERMESVM_PROFILER_NATIVECALL` builds, `runNativeCallBody` reloads
3943
+ `self` from the native frame's callee slot after `body()` before
3944
+ updating the counters; `_nativeCall` gets the same fix. No tree here
3945
+ builds the profiler, so Task 5's report states that this path was
3946
+ compiled only by inspection, or, if the executor configures a scratch
3947
+ tree with `-DHERMESVM_PROFILER_NATIVECALL=ON`, that it built (Task 5).
3948
+ 10. `regExpBuiltinExecMatch` keeps the `GCScope` that `directRegExpExec`
3949
+ opened (`RegExp.cpp:912`), so the handles of `toLengthU64` and
3950
+ `JSRegExp::search` are freed in every caller, including `test` and
3951
+ the frame body (Task 4).
3952
+ 11. The empty-match `lastIndex` advance becomes
3953
+ `advanceLastIndexAfterEmptyMatch`, shared by the generic and fast
3954
+ loops of `@@match` and `@@replace`; each loop has one body with
3955
+ `fast` branches, so the steps cannot drift apart (Tasks 6, 7).
3956
+ 12. Phase 2 is `replaceOneMatch` (steps 16.m-p), shared by both paths;
3957
+ `replaceBuiltinMatch` builds its inputs from ranges.
3958
+ `buildGroupsObject` takes a capture-reading callable (Task 7).
3959
+ 13. The `@@replace` fast path does not create the results
3960
+ `ArrayStorageSmall` (Task 7).
3961
+ 14. Part B mutations are checked by diffing the whole test output against
3962
+ the unmutated output, since one mutation can change several cases
3963
+ and FileCheck stops at the first (Global Constraints).
3964
+ 15. The proxy mutation's failure is the Debug assertion in
3965
+ `getNamedSlotValueUnsafe` (`JSObject.h:645-648`), which every Debug
3966
+ tree here enables (Task 6).
3967
+ 16. The Part B test adds two Review Focus cases (`unicodeGetter`,
3968
+ `reentrantCallback`) and a mutation that interleaves callbacks with
3969
+ execs, beyond the spec's table (Tasks 4, 7).
3970
+ 17. Measurements use `hermes -O` and re-measure BASE in the same session,
3971
+ so before and after are compared like for like. Part A is compared
3972
+ with BASE, Part B with the end of Part A, which its message names by
3973
+ subject because rewriting and squashing change the hash. The numbers
3974
+ go into the last commit of each part (Tasks 3 and 7) by a
3975
+ non-interactive rebase, so the two-commit squash carries them
3976
+ (Task 8).
3977
+ 18. `Runtime.h` includes `hermes/Regex/Executor.h` for
3978
+ `regex::CapturedRange`, the buffer's element type (Task 4).
3979
+ 19. Header expectations for `\p{Lu}` sit under
3980
+ `HERMES_ENABLE_UNICODE_REGEXP_PROPERTY_ESCAPES` (on in every tree
3981
+ here), as the parser's support does (Tasks 1, 3).