cfsolve 0.1.2 → 0.1.3

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 (368) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +7 -0
  3. data/THIRD_PARTY_LICENSES/README.md +71 -254
  4. data/THIRD_PARTY_LICENSES/{derive_builder_macro-0.20.2/LICENSE-APACHE → bytecount-0.6.9/LICENSE.Apache2} +0 -1
  5. data/THIRD_PARTY_LICENSES/{darling-0.20.11/LICENSE → bytecount-0.6.9/LICENSE.MIT} +1 -3
  6. data/THIRD_PARTY_LICENSES/{ident_case-1.0.1/LICENSE → cobs-0.3.0/LICENSE-MIT} +1 -1
  7. data/THIRD_PARTY_LICENSES/cow-utils-0.1.3/LICENSE +21 -0
  8. data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → embedded-io-0.4.0}/LICENSE-MIT +1 -1
  9. data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.6.1}/LICENSE-MIT +1 -1
  10. data/THIRD_PARTY_LICENSES/{browserslist-data-0.1.4 → escape-simd-0.1.1}/LICENSE +1 -1
  11. data/THIRD_PARTY_LICENSES/escape-simd-0.1.1/NOTICE +62 -0
  12. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/LICENSE +21 -0
  13. data/THIRD_PARTY_LICENSES/{miette-7.6.0/LICENSE → json-escape-simd-3.1.3/LICENSE-APACHE} +0 -1
  14. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/NOTICE +62 -0
  15. data/THIRD_PARTY_LICENSES/memchr-2.8.3/UNLICENSE +24 -0
  16. data/THIRD_PARTY_LICENSES/{derive_builder_core-0.20.2 → nonmax-0.5.5}/LICENSE-APACHE +1 -2
  17. data/THIRD_PARTY_LICENSES/{dashmap-5.5.3/LICENSE → nonmax-0.5.5/LICENSE-MIT} +2 -4
  18. data/THIRD_PARTY_LICENSES/{rand-0.8.5 → num-bigint-0.5.1}/LICENSE-MIT +0 -1
  19. data/THIRD_PARTY_LICENSES/oxc-0.157.0/LICENSE +22 -0
  20. data/THIRD_PARTY_LICENSES/oxc-0.157.0/THIRD-PARTY-LICENSE +763 -0
  21. data/THIRD_PARTY_LICENSES/{browserslist-rs-0.19.0 → oxc-browserslist-5.0.1}/LICENSE +1 -0
  22. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/LICENSE +22 -0
  23. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/THIRD-PARTY-LICENSE +763 -0
  24. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/LICENSE +22 -0
  25. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/THIRD-PARTY-LICENSE +763 -0
  26. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/LICENSE +22 -0
  27. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/THIRD-PARTY-LICENSE +763 -0
  28. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/LICENSE +22 -0
  29. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/THIRD-PARTY-LICENSE +763 -0
  30. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/LICENSE +22 -0
  31. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/THIRD-PARTY-LICENSE +763 -0
  32. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/LICENSE +22 -0
  33. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/THIRD-PARTY-LICENSE +763 -0
  34. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/LICENSE +22 -0
  35. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/THIRD-PARTY-LICENSE +763 -0
  36. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/LICENSE +22 -0
  37. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/THIRD-PARTY-LICENSE +763 -0
  38. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/LICENSE +22 -0
  39. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/THIRD-PARTY-LICENSE +763 -0
  40. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/LICENSE +22 -0
  41. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/THIRD-PARTY-LICENSE +763 -0
  42. data/THIRD_PARTY_LICENSES/oxc_index-5.0.0/LICENSE +22 -0
  43. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/LICENSE +22 -0
  44. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/THIRD-PARTY-LICENSE +763 -0
  45. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/LICENSE +22 -0
  46. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/THIRD-PARTY-LICENSE +763 -0
  47. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/LICENSE +22 -0
  48. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/THIRD-PARTY-LICENSE +763 -0
  49. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/LICENSE +22 -0
  50. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/THIRD-PARTY-LICENSE +763 -0
  51. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/LICENSE +22 -0
  52. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/THIRD-PARTY-LICENSE +763 -0
  53. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/LICENSE +22 -0
  54. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/THIRD-PARTY-LICENSE +763 -0
  55. data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-MIT +1 -1
  56. data/THIRD_PARTY_LICENSES/{bytes-str-0.2.7/LICENSE → self_cell-1.3.0/LICENSE-APACHE} +1 -2
  57. data/THIRD_PARTY_LICENSES/self_cell-1.3.0/LICENSE-GPLv2 +339 -0
  58. data/THIRD_PARTY_LICENSES/{darling_core-0.20.11 → smawk-0.3.3}/LICENSE +1 -1
  59. data/UPSTREAM.md +7 -5
  60. data/ext/cfsolve/Cargo.lock +534 -1727
  61. data/ext/cfsolve/Cargo.toml +4 -0
  62. data/ext/cfsolve/src/main.rs +1 -1
  63. data/lib/cfsolve/profiles/safari-26-ios/answers.json +266 -265
  64. data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +312 -312
  65. data/lib/cfsolve/profiles/safari-26-ios.json +106 -152
  66. data/lib/cfsolve/version.rb +2 -2
  67. data/vendor/cfsolve/Cargo.lock +561 -1729
  68. data/vendor/cfsolve/Cargo.toml +26 -8
  69. data/vendor/cfsolve/README.md +4 -0
  70. data/vendor/cfsolve/examples/check_answers.rs +2 -2
  71. data/vendor/cfsolve/examples/compare_session.rs +1 -2
  72. data/vendor/cfsolve/examples/solver_profile.rs +84 -0
  73. data/vendor/cfsolve/examples/solver_smoke.rs +9 -8
  74. data/vendor/cfsolve/examples/stage2_snapshot.rs +2 -2
  75. data/vendor/cfsolve/examples/tls_echo.rs +3 -3
  76. data/vendor/cfsolve/examples/vm_snapshot.rs +32 -33
  77. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +266 -265
  78. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +312 -312
  79. data/vendor/cfsolve/profiles/safari-26-ios.json +106 -152
  80. data/vendor/cfsolve/src/bin/capture-proxy/main.rs +3 -2
  81. data/vendor/cfsolve/src/bin/challenge/cli.rs +8 -2
  82. data/vendor/cfsolve/src/bin/challenge/main.rs +7 -2
  83. data/vendor/cfsolve/src/capture/proxy/tests.rs +1 -1
  84. data/vendor/cfsolve/src/capture/proxy.rs +44 -13
  85. data/vendor/cfsolve/src/capture/sessions.rs +4 -3
  86. data/vendor/cfsolve/src/capture/upstream.rs +1 -1
  87. data/vendor/cfsolve/src/challenge/codec.rs +4 -2
  88. data/vendor/cfsolve/src/challenge/expression.rs +161 -117
  89. data/vendor/cfsolve/src/challenge/installed/audit.rs +11 -10
  90. data/vendor/cfsolve/src/challenge/installed.rs +13 -6
  91. data/vendor/cfsolve/src/challenge/merge.rs +120 -80
  92. data/vendor/cfsolve/src/challenge/orchestrator.rs +57 -44
  93. data/vendor/cfsolve/src/challenge/payload.rs +69 -31
  94. data/vendor/cfsolve/src/challenge/program.rs +197 -178
  95. data/vendor/cfsolve/src/challenge/reduced_timing.rs +55 -40
  96. data/vendor/cfsolve/src/challenge/source.rs +151 -96
  97. data/vendor/cfsolve/src/challenge/state.rs +180 -148
  98. data/vendor/cfsolve/src/challenge/tally.rs +64 -50
  99. data/vendor/cfsolve/src/challenge.rs +1 -0
  100. data/vendor/cfsolve/src/deobfuscate/analysis/bindings.rs +187 -185
  101. data/vendor/cfsolve/src/deobfuscate/analysis/effects.rs +42 -51
  102. data/vendor/cfsolve/src/deobfuscate/analysis/hoisting.rs +147 -228
  103. data/vendor/cfsolve/src/deobfuscate/analysis/properties.rs +250 -425
  104. data/vendor/cfsolve/src/deobfuscate/analysis/unconditional.rs +79 -0
  105. data/vendor/cfsolve/src/deobfuscate/analysis.rs +259 -41
  106. data/vendor/cfsolve/src/deobfuscate/argument_arrays.rs +70 -73
  107. data/vendor/cfsolve/src/deobfuscate/arrow_blocks.rs +91 -104
  108. data/vendor/cfsolve/src/deobfuscate/ast.rs +383 -0
  109. data/vendor/cfsolve/src/deobfuscate/bitwise.rs +44 -54
  110. data/vendor/cfsolve/src/deobfuscate/blocks.rs +36 -29
  111. data/vendor/cfsolve/src/deobfuscate/call_helpers.rs +80 -131
  112. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +239 -297
  113. data/vendor/cfsolve/src/deobfuscate/copy_propagation.rs +114 -135
  114. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +62 -61
  115. data/vendor/cfsolve/src/deobfuscate/dead_properties.rs +197 -214
  116. data/vendor/cfsolve/src/deobfuscate/dispatch.rs +238 -298
  117. data/vendor/cfsolve/src/deobfuscate/encoded_strings.rs +198 -203
  118. data/vendor/cfsolve/src/deobfuscate/function_lengths.rs +32 -38
  119. data/vendor/cfsolve/src/deobfuscate/helper_objects.rs +338 -513
  120. data/vendor/cfsolve/src/deobfuscate/hygiene.rs +197 -0
  121. data/vendor/cfsolve/src/deobfuscate/int32_helpers.rs +121 -155
  122. data/vendor/cfsolve/src/deobfuscate/literals.rs +116 -67
  123. data/vendor/cfsolve/src/deobfuscate/loops.rs +43 -43
  124. data/vendor/cfsolve/src/deobfuscate/memoized_strings.rs +127 -131
  125. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +262 -220
  126. data/vendor/cfsolve/src/deobfuscate/pipeline.rs +199 -244
  127. data/vendor/cfsolve/src/deobfuscate/register_arrays.rs +353 -327
  128. data/vendor/cfsolve/src/deobfuscate/removal.rs +83 -52
  129. data/vendor/cfsolve/src/deobfuscate/simplify.rs +147 -0
  130. data/vendor/cfsolve/src/deobfuscate/state_machines.rs +88 -110
  131. data/vendor/cfsolve/src/deobfuscate/statements.rs +228 -228
  132. data/vendor/cfsolve/src/deobfuscate/static_members.rs +46 -31
  133. data/vendor/cfsolve/src/deobfuscate/testing.rs +49 -59
  134. data/vendor/cfsolve/src/deobfuscate/unused_bindings.rs +92 -102
  135. data/vendor/cfsolve/src/deobfuscate.rs +15 -11
  136. data/vendor/cfsolve/src/embedding_page/extra_params.rs +23 -18
  137. data/vendor/cfsolve/src/embedding_page/render_sample.rs +184 -147
  138. data/vendor/cfsolve/src/error.rs +40 -5
  139. data/vendor/cfsolve/src/fingerprint.rs +8 -2
  140. data/vendor/cfsolve/src/http/client.rs +7 -10
  141. data/vendor/cfsolve/src/http/requests.rs +2 -2
  142. data/vendor/cfsolve/src/js/ast.rs +479 -263
  143. data/vendor/cfsolve/src/lib.rs +1 -0
  144. data/vendor/cfsolve/src/listing/fold.rs +19 -9
  145. data/vendor/cfsolve/src/listing/query.rs +1 -47
  146. data/vendor/cfsolve/src/performance_clock.rs +20 -1
  147. data/vendor/cfsolve/src/profiling.rs +49 -0
  148. data/vendor/cfsolve/src/script.rs +35 -24
  149. data/vendor/cfsolve/src/session/challenge_page.rs +41 -21
  150. data/vendor/cfsolve/src/session/channel.rs +2 -2
  151. data/vendor/cfsolve/src/session/initial.rs +5 -5
  152. data/vendor/cfsolve/src/session/sink.rs +26 -1
  153. data/vendor/cfsolve/src/session/tests/challenge_page.rs +36 -1
  154. data/vendor/cfsolve/src/session.rs +1 -1
  155. data/vendor/cfsolve/src/solver.rs +3 -1
  156. data/vendor/cfsolve/src/stage2/analysis/audit.rs +4 -2
  157. data/vendor/cfsolve/src/stage2/analysis/envelope.rs +2 -1
  158. data/vendor/cfsolve/src/stage2/audit_globals.rs +142 -74
  159. data/vendor/cfsolve/src/stage2/benchmark.rs +62 -31
  160. data/vendor/cfsolve/src/stage2/call_stack.rs +1415 -1025
  161. data/vendor/cfsolve/src/stage2/challenge_page.rs +3 -2
  162. data/vendor/cfsolve/src/stage2/interaction/checkbox.rs +202 -150
  163. data/vendor/cfsolve/src/stage2/interaction/click.rs +2 -2
  164. data/vendor/cfsolve/src/stage2/interaction/plan.rs +5 -4
  165. data/vendor/cfsolve/src/stage2/payload/recover.rs +2 -2
  166. data/vendor/cfsolve/src/stage2/probes/clock.rs +1 -3
  167. data/vendor/cfsolve/src/stage2/probes/performance.rs +12 -8
  168. data/vendor/cfsolve/src/stage2/queries.rs +50 -0
  169. data/vendor/cfsolve/src/stage2/syntax.rs +88 -0
  170. data/vendor/cfsolve/src/stage2/trace.rs +134 -108
  171. data/vendor/cfsolve/src/stage2/vocabulary.rs +1 -11
  172. data/vendor/cfsolve/src/stage2.rs +2 -0
  173. data/vendor/cfsolve/src/vm/disassemble.rs +7 -3
  174. data/vendor/cfsolve/src/vm/dispatch.rs +93 -65
  175. data/vendor/cfsolve/src/vm/extract.rs +347 -250
  176. data/vendor/cfsolve/src/vm/interpret/access.rs +63 -48
  177. data/vendor/cfsolve/src/vm/interpret/builtin.rs +10 -10
  178. data/vendor/cfsolve/src/vm/interpret/call.rs +116 -52
  179. data/vendor/cfsolve/src/vm/interpret/compile.rs +79 -62
  180. data/vendor/cfsolve/src/vm/interpret/copies.rs +2 -2
  181. data/vendor/cfsolve/src/vm/interpret/evaluate/tests.rs +63 -42
  182. data/vendor/cfsolve/src/vm/interpret/evaluate.rs +65 -575
  183. data/vendor/cfsolve/src/vm/interpret/explore.rs +7 -10
  184. data/vendor/cfsolve/src/vm/interpret/formula.rs +131 -0
  185. data/vendor/cfsolve/src/vm/interpret/frozen.rs +3 -5
  186. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +123 -59
  187. data/vendor/cfsolve/src/vm/interpret/mix32.rs +189 -0
  188. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +220 -0
  189. data/vendor/cfsolve/src/vm/interpret/pattern.rs +1736 -0
  190. data/vendor/cfsolve/src/vm/interpret/plan.rs +586 -338
  191. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +384 -0
  192. data/vendor/cfsolve/src/vm/interpret/run.rs +116 -45
  193. data/vendor/cfsolve/src/vm/interpret/semantics.rs +71 -46
  194. data/vendor/cfsolve/src/vm/interpret/setup.rs +80 -45
  195. data/vendor/cfsolve/src/vm/interpret/string_decoder.rs +482 -0
  196. data/vendor/cfsolve/src/vm/interpret.rs +9 -1
  197. data/vendor/cfsolve/src/vm/machine.rs +56 -49
  198. data/vendor/cfsolve/src/vm/output.rs +13 -5
  199. data/vendor/cfsolve/src/vm/packed_names.rs +11 -7
  200. data/vendor/cfsolve/src/vm/session.rs +185 -120
  201. data/vendor/cfsolve/src/vm/value.rs +22 -19
  202. data/vendor/cfsolve/src/vm.rs +2 -1
  203. data/vendor/cfsolve/vendor/btls-sys/Cargo.toml +3 -0
  204. data/vendor/cfsolve/vendor/btls-sys/build/main.rs +20 -0
  205. metadata +94 -178
  206. data/THIRD_PARTY_LICENSES/Inflector-0.11.4/LICENSE.md +0 -22
  207. data/THIRD_PARTY_LICENSES/arrayvec-0.7.6/LICENSE-MIT +0 -25
  208. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-APACHE +0 -201
  209. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-MIT +0 -22
  210. data/THIRD_PARTY_LICENSES/ast_node-5.0.0/LICENSE +0 -201
  211. data/THIRD_PARTY_LICENSES/better_scoped_tls-1.0.1/LICENSE +0 -201
  212. data/THIRD_PARTY_LICENSES/bitvec-1.0.1/LICENSE.txt +0 -21
  213. data/THIRD_PARTY_LICENSES/bstr-1.12.1/COPYING +0 -8
  214. data/THIRD_PARTY_LICENSES/bstr-1.12.1/LICENSE-MIT +0 -21
  215. data/THIRD_PARTY_LICENSES/cargo-platform-0.1.9/LICENSE-APACHE +0 -201
  216. data/THIRD_PARTY_LICENSES/cargo_metadata-0.19.2/LICENSE-MIT +0 -23
  217. data/THIRD_PARTY_LICENSES/darling_macro-0.20.11/LICENSE +0 -21
  218. data/THIRD_PARTY_LICENSES/debugid-0.8.0/LICENSE +0 -201
  219. data/THIRD_PARTY_LICENSES/derive_builder-0.20.2/LICENSE-MIT +0 -21
  220. data/THIRD_PARTY_LICENSES/derive_builder_core-0.20.2/LICENSE-MIT +0 -21
  221. data/THIRD_PARTY_LICENSES/derive_builder_macro-0.20.2/LICENSE-MIT +0 -21
  222. data/THIRD_PARTY_LICENSES/foldhash-0.1.5/LICENSE +0 -19
  223. data/THIRD_PARTY_LICENSES/from_variant-3.0.0/LICENSE +0 -201
  224. data/THIRD_PARTY_LICENSES/funty-2.0.0/LICENSE.txt +0 -21
  225. data/THIRD_PARTY_LICENSES/hashbrown-0.16.1/LICENSE-MIT +0 -25
  226. data/THIRD_PARTY_LICENSES/heck-0.5.0/LICENSE-APACHE +0 -201
  227. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-APACHE +0 -201
  228. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-MIT +0 -23
  229. data/THIRD_PARTY_LICENSES/hstr-3.0.3/LICENSE +0 -202
  230. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-APACHE +0 -201
  231. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-MIT +0 -25
  232. data/THIRD_PARTY_LICENSES/is-macro-0.3.7/LICENSE +0 -202
  233. data/THIRD_PARTY_LICENSES/itoa-1.0.17/LICENSE-MIT +0 -23
  234. data/THIRD_PARTY_LICENSES/jsonc-parser-0.26.3/LICENSE +0 -21
  235. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-APACHE +0 -201
  236. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-MIT +0 -25
  237. data/THIRD_PARTY_LICENSES/lru-0.16.2/LICENSE +0 -21
  238. data/THIRD_PARTY_LICENSES/memchr-2.7.6/COPYING +0 -3
  239. data/THIRD_PARTY_LICENSES/memchr-2.7.6/LICENSE-MIT +0 -21
  240. data/THIRD_PARTY_LICENSES/miette-derive-7.6.0/LICENSE +0 -229
  241. data/THIRD_PARTY_LICENSES/normpath-0.2.0/COPYRIGHT +0 -7
  242. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-MIT +0 -21
  243. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-THIRD-PARTY +0 -210
  244. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-APACHE +0 -201
  245. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-MIT +0 -20
  246. data/THIRD_PARTY_LICENSES/owo-colors-4.2.3/LICENSE +0 -21
  247. data/THIRD_PARTY_LICENSES/par-core-2.0.0/LICENSE +0 -202
  248. data/THIRD_PARTY_LICENSES/par-iter-2.0.0/LICENSE +0 -202
  249. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-APACHE +0 -13
  250. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-MIT +0 -18
  251. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-APACHE +0 -13
  252. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-MIT +0 -18
  253. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-APACHE +0 -201
  254. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-MIT +0 -23
  255. data/THIRD_PARTY_LICENSES/petgraph-0.7.1/LICENSE-APACHE +0 -201
  256. data/THIRD_PARTY_LICENSES/precomputed-map-0.2.0/LICENSE +0 -21
  257. data/THIRD_PARTY_LICENSES/preset_env_base-6.0.0/LICENSE +0 -201
  258. data/THIRD_PARTY_LICENSES/radium-0.7.0/LICENSE.txt +0 -21
  259. data/THIRD_PARTY_LICENSES/radix_fmt-1.0.0/LICENSE +0 -201
  260. data/THIRD_PARTY_LICENSES/rand-0.8.5/COPYRIGHT +0 -12
  261. data/THIRD_PARTY_LICENSES/rand-0.8.5/LICENSE-APACHE +0 -176
  262. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/COPYRIGHT +0 -12
  263. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-APACHE +0 -187
  264. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-MIT +0 -26
  265. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-APACHE +0 -201
  266. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-MIT +0 -21
  267. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-APACHE +0 -176
  268. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-BOOST +0 -23
  269. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-APACHE +0 -201
  270. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-MIT +0 -25
  271. data/THIRD_PARTY_LICENSES/siphasher-0.3.11/COPYING +0 -7
  272. data/THIRD_PARTY_LICENSES/smallvec-1.15.1/LICENSE-APACHE +0 -201
  273. data/THIRD_PARTY_LICENSES/smartstring-1.0.1/LICENCE.md +0 -355
  274. data/THIRD_PARTY_LICENSES/st-map-0.2.4/LICENSE +0 -202
  275. data/THIRD_PARTY_LICENSES/static-map-macro-0.3.4/LICENSE +0 -202
  276. data/THIRD_PARTY_LICENSES/string_enum-1.0.2/LICENSE +0 -201
  277. data/THIRD_PARTY_LICENSES/strsim-0.11.1/LICENSE +0 -23
  278. data/THIRD_PARTY_LICENSES/swc-52.0.0/LICENSE +0 -201
  279. data/THIRD_PARTY_LICENSES/swc_allocator-4.0.1/LICENSE +0 -201
  280. data/THIRD_PARTY_LICENSES/swc_atoms-9.0.0/LICENSE +0 -201
  281. data/THIRD_PARTY_LICENSES/swc_common-18.0.1/LICENSE +0 -201
  282. data/THIRD_PARTY_LICENSES/swc_compiler_base-45.0.0/LICENSE +0 -201
  283. data/THIRD_PARTY_LICENSES/swc_config-3.1.2/LICENSE +0 -201
  284. data/THIRD_PARTY_LICENSES/swc_config_macro-1.0.1/LICENSE +0 -201
  285. data/THIRD_PARTY_LICENSES/swc_core-54.0.0/LICENSE +0 -201
  286. data/THIRD_PARTY_LICENSES/swc_ecma_ast-19.0.0/LICENSE +0 -201
  287. data/THIRD_PARTY_LICENSES/swc_ecma_codegen-21.0.0/LICENSE +0 -201
  288. data/THIRD_PARTY_LICENSES/swc_ecma_codegen_macros-2.0.2/LICENSE +0 -201
  289. data/THIRD_PARTY_LICENSES/swc_ecma_compat_bugfixes-39.0.0/LICENSE +0 -201
  290. data/THIRD_PARTY_LICENSES/swc_ecma_compat_common-30.0.0/LICENSE +0 -201
  291. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2015-39.0.0/LICENSE +0 -201
  292. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2016-35.0.0/LICENSE +0 -201
  293. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2017-35.0.0/LICENSE +0 -201
  294. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2018-36.0.0/LICENSE +0 -201
  295. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2019-35.0.0/LICENSE +0 -201
  296. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2020-37.0.0/LICENSE +0 -201
  297. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2021-35.0.0/LICENSE +0 -201
  298. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2022-37.0.0/LICENSE +0 -201
  299. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es3-26.0.0/LICENSE +0 -201
  300. data/THIRD_PARTY_LICENSES/swc_ecma_ext_transforms-25.0.0/LICENSE +0 -201
  301. data/THIRD_PARTY_LICENSES/swc_ecma_hooks-0.3.0/LICENSE +0 -201
  302. data/THIRD_PARTY_LICENSES/swc_ecma_loader-18.0.0/LICENSE +0 -201
  303. data/THIRD_PARTY_LICENSES/swc_ecma_minifier-42.0.0/LICENSE +0 -201
  304. data/THIRD_PARTY_LICENSES/swc_ecma_parser-32.0.0/LICENSE +0 -201
  305. data/THIRD_PARTY_LICENSES/swc_ecma_preset_env-45.0.0/LICENSE +0 -201
  306. data/THIRD_PARTY_LICENSES/swc_ecma_transformer-6.0.0/LICENSE +0 -201
  307. data/THIRD_PARTY_LICENSES/swc_ecma_transforms-44.0.0/LICENSE +0 -201
  308. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_base-35.0.0/LICENSE +0 -201
  309. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_classes-35.0.0/LICENSE +0 -201
  310. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_compat-40.0.0/LICENSE +0 -201
  311. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_macros-1.0.1/LICENSE +0 -201
  312. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_module-38.0.0/LICENSE +0 -201
  313. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_optimization-37.0.0/LICENSE +0 -201
  314. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_proposal-35.0.0/LICENSE +0 -201
  315. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_react-38.0.0/LICENSE +0 -201
  316. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_typescript-38.0.0/LICENSE +0 -201
  317. data/THIRD_PARTY_LICENSES/swc_ecma_usage_analyzer-27.0.0/LICENSE +0 -201
  318. data/THIRD_PARTY_LICENSES/swc_ecma_utils-25.0.0/LICENSE +0 -201
  319. data/THIRD_PARTY_LICENSES/swc_ecma_visit-19.0.0/LICENSE +0 -201
  320. data/THIRD_PARTY_LICENSES/swc_eq_ignore_macros-1.0.1/LICENSE +0 -201
  321. data/THIRD_PARTY_LICENSES/swc_error_reporters-20.0.0/LICENSE +0 -201
  322. data/THIRD_PARTY_LICENSES/swc_macros_common-1.0.1/LICENSE +0 -201
  323. data/THIRD_PARTY_LICENSES/swc_node_comments-18.0.0/LICENSE +0 -201
  324. data/THIRD_PARTY_LICENSES/swc_timer-1.0.0/LICENSE +0 -201
  325. data/THIRD_PARTY_LICENSES/swc_trace_macro-2.0.2/LICENSE +0 -201
  326. data/THIRD_PARTY_LICENSES/swc_transform_common-12.0.0/LICENSE +0 -201
  327. data/THIRD_PARTY_LICENSES/swc_visit-2.0.1/LICENSE +0 -201
  328. data/THIRD_PARTY_LICENSES/tap-1.0.1/LICENSE.txt +0 -21
  329. data/THIRD_PARTY_LICENSES/tracing-0.1.44/LICENSE +0 -25
  330. data/THIRD_PARTY_LICENSES/tracing-attributes-0.1.31/LICENSE +0 -25
  331. data/THIRD_PARTY_LICENSES/tracing-core-0.1.36/LICENSE +0 -25
  332. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-APACHE +0 -201
  333. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-MIT +0 -27
  334. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-APACHE +0 -201
  335. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-MIT +0 -25
  336. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-APACHE +0 -201
  337. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-MIT +0 -26
  338. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-APACHE +0 -201
  339. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-MIT +0 -25
  340. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-APACHE +0 -201
  341. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-MIT +0 -25
  342. data/THIRD_PARTY_LICENSES/wyz-0.5.1/LICENSE.txt +0 -21
  343. data/vendor/cfsolve/src/deobfuscate/analysis/globals.rs +0 -33
  344. data/vendor/cfsolve/src/deobfuscate/analysis/names.rs +0 -52
  345. /data/THIRD_PARTY_LICENSES/{derive_builder-0.20.2 → cobs-0.3.0}/LICENSE-APACHE +0 -0
  346. /data/THIRD_PARTY_LICENSES/{compact_str-0.7.1 → compact_str-0.10.0}/LICENSE +0 -0
  347. /data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.4.0}/LICENSE-APACHE +0 -0
  348. /data/THIRD_PARTY_LICENSES/{arrayvec-0.7.6 → embedded-io-0.6.1}/LICENSE-APACHE +0 -0
  349. /data/THIRD_PARTY_LICENSES/{normpath-0.2.0 → escape-simd-0.1.1}/LICENSE-APACHE +0 -0
  350. /data/THIRD_PARTY_LICENSES/{bstr-1.12.1 → itertools-0.15.0}/LICENSE-APACHE +0 -0
  351. /data/THIRD_PARTY_LICENSES/{petgraph-0.7.1 → itertools-0.15.0}/LICENSE-MIT +0 -0
  352. /data/THIRD_PARTY_LICENSES/{itoa-1.0.17 → itoa-1.0.19}/LICENSE-APACHE +0 -0
  353. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → itoa-1.0.19}/LICENSE-MIT +0 -0
  354. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/COPYING +0 -0
  355. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/LICENSE-MIT +0 -0
  356. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → num-bigint-0.5.1}/LICENSE-APACHE +0 -0
  357. /data/THIRD_PARTY_LICENSES/{swc_sourcemap-9.3.4 → oxc_sourcemap-9.0.0}/LICENSE +0 -0
  358. /data/THIRD_PARTY_LICENSES/{phf-0.11.3 → phf-0.14.0}/LICENSE +0 -0
  359. /data/THIRD_PARTY_LICENSES/{phf_generator-0.11.3 → phf_generator-0.14.0}/LICENSE +0 -0
  360. /data/THIRD_PARTY_LICENSES/{phf_macros-0.11.3 → phf_macros-0.14.0}/LICENSE +0 -0
  361. /data/THIRD_PARTY_LICENSES/{phf_shared-0.11.3 → phf_shared-0.14.0}/LICENSE +0 -0
  362. /data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-APACHE +0 -0
  363. /data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → smallvec-1.16.5}/LICENSE-APACHE +0 -0
  364. /data/THIRD_PARTY_LICENSES/{smallvec-1.15.1 → smallvec-1.16.5}/LICENSE-MIT +0 -0
  365. /data/THIRD_PARTY_LICENSES/{unicode-width-0.1.14 → unicode-segmentation-1.13.3}/COPYRIGHT +0 -0
  366. /data/THIRD_PARTY_LICENSES/{hashbrown-0.16.1 → unicode-segmentation-1.13.3}/LICENSE-APACHE +0 -0
  367. /data/THIRD_PARTY_LICENSES/{heck-0.5.0 → unicode-segmentation-1.13.3}/LICENSE-MIT +0 -0
  368. /data/THIRD_PARTY_LICENSES/{cargo-platform-0.1.9 → zmij_ecma-1.0.23}/LICENSE-MIT +0 -0
@@ -14,61 +14,68 @@
14
14
 
15
15
  use std::collections::{HashMap, HashSet};
16
16
  use std::mem;
17
+ use std::sync::Arc;
17
18
 
18
19
  use anyhow::{Context, Result, bail};
19
- use serde::{Deserialize, Serialize};
20
- use swc_core::common::{BytePos, Mark, Span, Spanned, SyntaxContext};
21
- use swc_core::ecma::ast::{
22
- AssignExpr, AssignOp, AssignTarget, BinaryOp, BlockStmt, CallExpr, Callee, Class, ClassDecl,
23
- ClassMember, Decl, Expr, FnDecl, FnExpr, Function, Id, Ident, MemberExpr, MemberProp, NewExpr,
24
- ObjectLit, Pat, Program, Prop, ReturnStmt, SimpleAssignTarget, Stmt, SwitchCase, SwitchStmt,
25
- ThrowStmt, TryStmt, UnaryOp, VarDeclarator,
20
+ use oxc::ast::AstKind;
21
+ use oxc::ast::ast::{
22
+ Argument, ArrayExpression, ArrayExpressionElement, AssignmentExpression, AssignmentTarget,
23
+ BindingPattern, CallExpression, Class, ClassElement, Expression, FormalParameter, Function,
24
+ MemberExpression, MethodDefinition, MethodDefinitionKind, NewExpression, ObjectExpression,
25
+ ObjectProperty, ObjectPropertyKind, PropertyKind, Statement, SwitchCase, SwitchStatement,
26
+ ThrowStatement, TryStatement, VariableDeclarator,
26
27
  };
27
- use swc_core::ecma::visit::{Visit, VisitWith};
28
+ use oxc::ast_visit::{Visit, walk};
29
+ use oxc::semantic::SymbolId;
30
+ use oxc::span::{GetSpan, Span};
31
+ use oxc::syntax::operator::{AssignmentOperator, BinaryOperator, UnaryOperator};
32
+ use oxc::syntax::scope::ScopeFlags;
33
+ use serde::{Deserialize, Serialize};
28
34
 
35
+ use super::syntax::{
36
+ assigned_member, is_optional_call, member, plain_parameter, walk_method, walk_property,
37
+ };
29
38
  use crate::deobfuscate::{self, Deobfuscated};
30
39
  use crate::engine::{self, Engine, Lines, StackFrame, V8_STACK_LIMIT};
31
- use crate::js::ast;
40
+ use crate::js::ast::{self, Binding, ParsedScript};
32
41
  use crate::{candidates, js};
33
42
 
34
43
  /// Maps VM dispatch cases to opcodes at their original source positions. Deobfuscation resolves
35
44
  /// case labels while preserving spans. Recovery uses the resolved labels to find each opcode's
36
45
  /// case in the original script.
37
- #[derive(Clone, Debug, Default)]
38
- pub struct CaseOpcodes(HashMap<(u32, u32), u8>);
39
-
40
- /// Returns a span's offset from the parse start, stable across parses of the same script.
41
- fn offsets(span: Span, start: BytePos) -> (u32, u32) {
42
- (span.lo.0 - start.0, span.hi.0 - start.0)
46
+ #[derive(Clone, Default)]
47
+ pub struct CaseOpcodes {
48
+ opcodes: HashMap<Span, u8>,
49
+ /// The decoded program captured during deobfuscation, with the source it was decoded from,
50
+ /// shared so the cases stay cheap to clone.
51
+ decoded: Option<Arc<ParsedScript>>,
43
52
  }
44
53
 
45
54
  /// Deobfuscates `source` and maps its dispatch cases' original positions to their opcodes.
46
55
  pub fn deobfuscate_with_cases(source: String) -> Result<(Deobfuscated, CaseOpcodes)> {
47
- struct Cases {
48
- start: BytePos,
49
- opcodes: CaseOpcodes,
50
- }
51
- impl Visit for Cases {
52
- fn visit_switch_case(&mut self, case: &SwitchCase) {
56
+ // Spans are stable across parses of the same script.
57
+ struct Cases(HashMap<Span, u8>);
58
+ impl<'a> Visit<'a> for Cases {
59
+ fn visit_switch_case(&mut self, case: &SwitchCase<'a>) {
53
60
  if let Some(test) = &case.test
54
61
  && let Some(opcode) = ast::index_literal(test)
55
62
  && let Ok(opcode) = u8::try_from(opcode)
56
63
  {
57
- self.opcodes
58
- .0
59
- .insert(offsets(case.span, self.start), opcode);
64
+ self.0.insert(case.span, opcode);
60
65
  }
61
- case.visit_children_with(self);
66
+ walk::walk_switch_case(self, case);
62
67
  }
63
68
  }
64
- deobfuscate::deobfuscate_with(source, |program, start| {
65
- let mut cases = Cases {
66
- start,
67
- opcodes: CaseOpcodes::default(),
68
- };
69
- program.visit_with(&mut cases);
70
- cases.opcodes
71
- })
69
+ let (deobfuscated, opcodes, decoded) = deobfuscate::deobfuscate_capturing(source, |program| {
70
+ let mut cases = Cases(HashMap::new());
71
+ cases.visit_program(program);
72
+ Ok(cases.0)
73
+ })?;
74
+ let cases = CaseOpcodes {
75
+ opcodes,
76
+ decoded: Some(Arc::new(decoded)),
77
+ };
78
+ Ok((deobfuscated, cases))
72
79
  }
73
80
 
74
81
  /// Engine-specific function name and call position, measured from the script start in
@@ -246,71 +253,79 @@ pub struct DispatchSummary {
246
253
 
247
254
  /// Summarizes dispatch loops called by `run`, including whether each case resolves to a function.
248
255
  pub fn dispatch_summary(source: &str, cases: &CaseOpcodes) -> Result<Vec<DispatchSummary>> {
249
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
250
- let machine = Machine::new(program, start, cases)?;
251
- let script = &machine.script;
252
- let mut summaries = Vec::new();
253
- for dispatch_loop in &machine.loops {
254
- let function = script.function(&dispatch_loop.name)?;
255
- let scope = Scope::new(&dispatch_loop.name.0, function, &script.appliers);
256
- let mut opcodes = 0;
257
- let mut unresolved = Vec::new();
258
- for case in cases_of(function) {
259
- let Some(&opcode) = cases.0.get(&offsets(case.span, start)) else {
260
- continue;
261
- };
262
- opcodes += 1;
263
- let resolved = scope.target(&case.call).is_ok_and(|target| {
264
- target
265
- .callee
266
- .is_some_and(|callee| script.function(&callee).is_ok())
267
- });
268
- if !resolved {
269
- unresolved.push(opcode);
270
- }
271
- }
272
- let frames = dispatch_loop.call.frames(Name::same("run".to_owned()));
273
- summaries.push(DispatchSummary {
274
- function: dispatch_loop.name.0.to_string(),
275
- guarded: dispatch_loop.guarded,
276
- frames: frames.into_iter().map(|call| call.name.v8).collect(),
277
- opcodes,
278
- unresolved,
256
+ let decoded = deobfuscate::decode(source.to_owned())?;
257
+ let machine = Machine::new(decoded.script(), cases)?;
258
+ let script = &machine.script;
259
+ let mut summaries = Vec::new();
260
+ for dispatch_loop in &machine.loops {
261
+ let name = script.appliers.name(dispatch_loop.name);
262
+ let function = script.function(dispatch_loop.name)?;
263
+ let scope = Scope::new(name, &function, &script.appliers);
264
+ let mut opcodes = 0;
265
+ let mut unresolved = Vec::new();
266
+ for case in cases_of(script.js(), &function) {
267
+ let Some(&opcode) = cases.opcodes.get(&case.span) else {
268
+ continue;
269
+ };
270
+ opcodes += 1;
271
+ let resolved = scope.target(case.call).is_ok_and(|target| {
272
+ target
273
+ .callee
274
+ .is_some_and(|callee| script.function(callee).is_ok())
279
275
  });
276
+ if !resolved {
277
+ unresolved.push(opcode);
278
+ }
280
279
  }
281
- Ok(summaries)
282
- })
280
+ let frames = dispatch_loop.call.frames(Name::same("run".to_owned()));
281
+ summaries.push(DispatchSummary {
282
+ function: name.to_owned(),
283
+ guarded: dispatch_loop.guarded,
284
+ frames: frames.into_iter().map(|call| call.name.v8).collect(),
285
+ opcodes,
286
+ unresolved,
287
+ });
288
+ }
289
+ Ok(summaries)
283
290
  }
284
291
 
285
292
  /// Parses `source` and places the frames `recover` finds in it as each engine reports them.
286
293
  fn geometry(
287
294
  source: &str,
288
295
  cases: &CaseOpcodes,
289
- mut recover: impl FnMut(&Machine<'_>) -> Result<Chain>,
296
+ recover: impl FnOnce(&Machine<'_, '_>) -> Result<Chain>,
290
297
  ) -> Result<Geometry> {
291
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
292
- let Chain { frames, reflected } = recover(&Machine::new(program, start, cases)?)?;
293
- let frame = |function: String, at: BytePos| -> Result<Frame> {
294
- let offset = (at.0 - start.0) as usize;
295
- let prefix = source.get(..offset).context("invalid source byte offset")?;
296
- let (line, column) = engine::line_and_column(prefix, Lines::Script);
297
- Ok(Frame {
298
- function,
299
- line,
300
- column,
301
- })
302
- };
303
- let mut geometry = Geometry {
304
- frames: Vec::new(),
305
- jsc_frames: Vec::new(),
306
- reflected,
307
- };
308
- for Call { name, site } in frames {
309
- geometry.frames.push(frame(name.v8, site.v8)?);
310
- geometry.jsc_frames.push(frame(name.jsc, site.jsc)?);
298
+ // Reuse the decoded program `cases` captured if it comes from the same source.
299
+ let Chain { frames, reflected } = match &cases.decoded {
300
+ Some(decoded) if decoded.script().source == source => {
301
+ recover(&Machine::new(decoded.script(), cases)?)?
311
302
  }
312
- Ok(geometry)
313
- })
303
+ _ => recover(&Machine::new(
304
+ deobfuscate::decode(source.to_owned())?.script(),
305
+ cases,
306
+ )?)?,
307
+ };
308
+ let frame = |function: String, at: u32| -> Result<Frame> {
309
+ let prefix = source
310
+ .get(..at as usize)
311
+ .context("invalid source byte offset")?;
312
+ let (line, column) = engine::line_and_column(prefix, Lines::Script);
313
+ Ok(Frame {
314
+ function,
315
+ line,
316
+ column,
317
+ })
318
+ };
319
+ let mut geometry = Geometry {
320
+ frames: Vec::new(),
321
+ jsc_frames: Vec::new(),
322
+ reflected,
323
+ };
324
+ for Call { name, site } in frames {
325
+ geometry.frames.push(frame(name.v8, site.v8)?);
326
+ geometry.jsc_frames.push(frame(name.jsc, site.jsc)?);
327
+ }
328
+ Ok(geometry)
314
329
  }
315
330
 
316
331
  /// Calls recovered from the innermost frame outward.
@@ -344,15 +359,16 @@ impl Name {
344
359
  }
345
360
  }
346
361
 
347
- /// A call site's position for each engine: see [`call_position`] and [`arguments_position`].
362
+ /// A call site's byte offset for each engine: see [`call_position`] and
363
+ /// [`arguments_position`].
348
364
  #[derive(Clone, Copy, Debug)]
349
365
  struct Site {
350
- v8: BytePos,
351
- jsc: BytePos,
366
+ v8: u32,
367
+ jsc: u32,
352
368
  }
353
369
 
354
370
  impl Site {
355
- fn new(call: &CallExpr) -> Self {
371
+ fn new(call: &CallExpression<'_>) -> Self {
356
372
  Self {
357
373
  v8: call_position(call),
358
374
  jsc: arguments_position(call),
@@ -366,45 +382,65 @@ struct Call {
366
382
  site: Site,
367
383
  }
368
384
 
385
+ /// A function that call resolution identifies.
386
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
387
+ enum Callee<'a> {
388
+ /// A function or value held by a binding, or by a global.
389
+ Binding(Binding<'a>),
390
+ /// An original function extracted from a merged function, indexed into
391
+ /// [`Appliers::originals`].
392
+ Original(usize),
393
+ }
394
+
395
+ impl Callee<'_> {
396
+ /// The parameter or local `symbol`.
397
+ fn symbol(symbol: SymbolId) -> Self {
398
+ Self::Binding(Binding::Symbol(symbol))
399
+ }
400
+ }
401
+
369
402
  /// The VM dispatch method, its runner, and listeners that wrap the runner for each closure
370
403
  /// parameter count.
371
- struct Machine<'script> {
372
- script: Script,
373
- dispatch: DispatchMethod,
404
+ struct Machine<'a, 'cases> {
405
+ script: Script<'a>,
406
+ dispatch: DispatchMethod<'a>,
374
407
  /// The dispatch loops `run` calls.
375
- loops: Vec<DispatchLoop>,
376
- cases: &'script CaseOpcodes,
377
- start: BytePos,
408
+ loops: Vec<DispatchLoop<'a>>,
409
+ cases: &'cases CaseOpcodes,
378
410
  runner: Call,
379
- listeners: Vec<Invocation>,
411
+ listeners: Vec<Invocation<'a>>,
380
412
  }
381
413
 
382
- impl<'script> Machine<'script> {
383
- fn new(program: &Program, start: BytePos, cases: &'script CaseOpcodes) -> Result<Self> {
384
- let mut script = Script::new(program);
414
+ impl<'a, 'cases> Machine<'a, 'cases> {
415
+ fn new(js: ast::Script<'a>, cases: &'cases CaseOpcodes) -> Result<Self> {
416
+ let mut script = Script::new(js);
385
417
  let classes = mem::take(&mut script.classes);
386
418
  // The runner passes the closure's program counter, key, and arguments to `run`,
387
419
  // copying arguments when required by the VM function.
388
420
  let mut runners = Vec::new();
389
421
  for (name, function) in &script.functions {
390
- for call in calls_of(function) {
391
- let calls_run = call
392
- .callee
393
- .as_expr()
394
- .and_then(|callee| callee.as_member())
395
- .is_some_and(|member| ast::member_str(&member.prop) == Some("run"));
396
- if calls_run && call.args.len() == 3 && call.args[2].expr.is_cond() {
397
- runners.push((name, call));
422
+ for call in calls_of(js, function) {
423
+ let calls_run = member(&call.callee)
424
+ .is_some_and(|member| ast::member_str(member) == Some("run"));
425
+ if calls_run
426
+ && call.arguments.len() == 3
427
+ && matches!(
428
+ ast::argument_expression(&call.arguments[2]),
429
+ Expression::ConditionalExpression(_)
430
+ )
431
+ {
432
+ runners.push((*name, call));
398
433
  }
399
434
  }
400
435
  }
401
436
  let (runner, run_call) = candidates::exactly_one(runners, "closure-to-VM runner call")?;
437
+ let runner = Callee::Binding(runner);
402
438
  let mut listeners = Listeners {
403
439
  runner,
404
440
  appliers: &script.appliers,
405
441
  found: Vec::new(),
406
442
  };
407
- program.visit_with(&mut listeners);
443
+ listeners.visit_program(js.program);
408
444
  let listeners: Vec<Invocation> = listeners.found.into_iter().collect::<Result<_>>()?;
409
445
  let dispatches = classes.into_iter().filter_map(|dispatch| {
410
446
  let loops = dispatch_loops(&script, &dispatch.run);
@@ -413,44 +449,44 @@ impl<'script> Machine<'script> {
413
449
  let (dispatch, loops) = candidates::exactly_one(dispatches, "VM dispatch method")?;
414
450
  Ok(Self {
415
451
  runner: Call {
416
- name: Name::same(runner.0.to_string()),
417
- site: Site::new(&run_call),
452
+ name: Name::same(script.appliers.name(runner).to_owned()),
453
+ site: Site::new(run_call),
418
454
  },
419
455
  listeners,
420
456
  dispatch,
421
457
  loops,
422
458
  script,
423
459
  cases,
424
- start,
425
460
  })
426
461
  }
427
462
 
428
463
  /// Finds the handler for `opcode` in the dispatch loop with or without exception handling.
429
- fn handler(&self, opcode: u8, guarded: bool) -> Result<Handler<'_>> {
464
+ fn handler(&self, opcode: u8, guarded: bool) -> Result<Handler<'a, '_>> {
465
+ let appliers = &self.script.appliers;
430
466
  for dispatch_loop in &self.loops {
431
467
  if dispatch_loop.guarded != guarded {
432
468
  continue;
433
469
  }
434
- let function = self.script.function(&dispatch_loop.name)?;
435
- let Some(case) = cases_of(function)
470
+ let function = self.script.function(dispatch_loop.name)?;
471
+ let Some(case) = cases_of(self.script.js(), &function)
436
472
  .into_iter()
437
- .find(|case| self.cases.0.get(&offsets(case.span, self.start)) == Some(&opcode))
473
+ .find(|case| self.cases.opcodes.get(&case.span) == Some(&opcode))
438
474
  else {
439
475
  continue;
440
476
  };
441
- let scope = Scope::new(&dispatch_loop.name.0, function, &self.script.appliers);
442
- let dispatch = scope.target(&case.call)?;
477
+ let scope = Scope::new(appliers.name(dispatch_loop.name), &function, appliers);
478
+ let dispatch = scope.target(case.call)?;
443
479
  let handler = dispatch
444
480
  .callee
445
- .clone()
446
481
  .with_context(|| format!("opcode {opcode}'s dispatch calls no named handler"))?;
482
+ let name = appliers.name(handler);
447
483
  let frame = Name {
448
484
  v8: if dispatch.method {
449
- format!("{}.{}", self.dispatch.class, handler.0)
485
+ format!("{}.{name}", self.dispatch.class)
450
486
  } else {
451
- handler.0.to_string()
487
+ name.to_owned()
452
488
  },
453
- jsc: handler.0.to_string(),
489
+ jsc: name.to_owned(),
454
490
  };
455
491
  return Ok(Handler {
456
492
  dispatch,
@@ -463,17 +499,14 @@ impl<'script> Machine<'script> {
463
499
  }
464
500
 
465
501
  /// Appends frames from the call to `handler` through the dispatch loop, `run`, and the runner.
466
- fn entered(&self, handler: &Handler<'_>, mut frames: Vec<Call>) -> Vec<Call> {
502
+ fn entered(&self, handler: &Handler<'a, '_>, mut frames: Vec<Call>) -> Vec<Call> {
467
503
  let DispatchMethod { class, key, .. } = &self.dispatch;
468
504
  let dispatch_loop = handler.dispatch_loop;
469
- frames.extend(
470
- handler
471
- .dispatch
472
- .frames(Name::same(dispatch_loop.name.0.to_string())),
473
- );
505
+ let name = self.script.appliers.name(dispatch_loop.name);
506
+ frames.extend(handler.dispatch.frames(Name::same(name.to_owned())));
474
507
  frames.extend(dispatch_loop.call.frames(Name {
475
508
  v8: format!("{class}.run"),
476
- jsc: key.clone().unwrap_or_default(),
509
+ jsc: key.unwrap_or_default().to_owned(),
477
510
  }));
478
511
  frames.push(self.runner.clone());
479
512
  frames
@@ -484,21 +517,20 @@ impl<'script> Machine<'script> {
484
517
  /// arguments.
485
518
  fn construction(&self, opcode: u8, guarded: bool) -> Result<Chain> {
486
519
  let handler = self.handler(opcode, guarded)?;
487
- let function = self.script.function(&handler.name)?;
488
- let scope = Scope::new(&handler.name.0, function, &self.script.appliers);
520
+ let appliers = &self.script.appliers;
521
+ let function = self.script.function(handler.name)?;
522
+ let scope = Scope::new(appliers.name(handler.name), &function, appliers);
489
523
  let mut found = Vec::new();
490
- for call in calls_of(function) {
491
- let target = scope.target(&call)?;
524
+ for call in calls_of(self.script.js(), &function) {
525
+ let target = scope.target(call)?;
492
526
  // Find `Reflect.construct` in a binding or array slot, called directly or through a
493
527
  // helper.
494
528
  let named = target
495
529
  .callee
496
- .as_ref()
497
- .is_some_and(|callee| self.script.constructs.contains(callee));
530
+ .is_some_and(|callee| self.script.constructs.contains(&callee));
498
531
  let slotted = target
499
532
  .slot
500
- .as_ref()
501
- .is_some_and(|slot| self.script.construct_slots.contains(slot));
533
+ .is_some_and(|slot| self.script.construct_slots.contains(&slot));
502
534
  if named || slotted {
503
535
  found.push(target.frames(handler.frame.clone()));
504
536
  }
@@ -507,23 +539,26 @@ impl<'script> Machine<'script> {
507
539
  if !reflected {
508
540
  #[derive(Default)]
509
541
  struct News(Vec<Site>);
510
- impl Visit for News {
511
- fn visit_function(&mut self, _: &Function) {}
512
- fn visit_class(&mut self, _: &Class) {}
542
+ impl<'a> Visit<'a> for News {
543
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
544
+ fn visit_class(&mut self, _: &Class<'a>) {}
545
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
546
+ walk_property(self, property);
547
+ }
513
548
  // Ignore guard exceptions; they do not produce the handler's constructed value.
514
- fn visit_throw_stmt(&mut self, _: &ThrowStmt) {}
515
- fn visit_new_expr(&mut self, construction: &NewExpr) {
516
- if construction.args.as_ref().is_none_or(Vec::is_empty) {
549
+ fn visit_throw_statement(&mut self, _: &ThrowStatement<'a>) {}
550
+ fn visit_new_expression(&mut self, construction: &NewExpression<'a>) {
551
+ if construction.arguments.is_empty() {
517
552
  self.0.push(Site {
518
- v8: construction.span.lo,
519
- jsc: construction.callee.span().hi,
553
+ v8: construction.span.start,
554
+ jsc: construction.callee.span().end,
520
555
  });
521
556
  }
522
- construction.visit_children_with(self);
557
+ walk::walk_new_expression(self, construction);
523
558
  }
524
559
  }
525
560
  let mut news = News::default();
526
- function.body.visit_with(&mut news);
561
+ function.visit(&mut news);
527
562
  for site in news.0 {
528
563
  found.push(vec![Call {
529
564
  name: handler.frame.clone(),
@@ -537,7 +572,7 @@ impl<'script> Machine<'script> {
537
572
  let Some(frames) = found.pop() else {
538
573
  bail!(
539
574
  "missing original function {} with the needed shape",
540
- handler.name.0
575
+ appliers.name(handler.name)
541
576
  );
542
577
  };
543
578
  Ok(Chain {
@@ -550,13 +585,14 @@ impl<'script> Machine<'script> {
550
585
  /// passes the method, receiver, and `passed` arguments to a native apply forwarder.
551
586
  fn method_call(&self, opcode: u8, passed: usize, guarded: bool) -> Result<Vec<Call>> {
552
587
  let handler = self.handler(opcode, guarded)?;
553
- let function = self.script.function(&handler.name)?;
554
- let scope = Scope::new(&handler.name.0, function, &self.script.appliers);
588
+ let appliers = &self.script.appliers;
589
+ let function = self.script.function(handler.name)?;
590
+ let scope = Scope::new(appliers.name(handler.name), &function, appliers);
555
591
  let mut calls = Vec::new();
556
- for call in calls_of(function) {
557
- let target = scope.target(&call)?;
592
+ for call in calls_of(self.script.js(), &function) {
593
+ let target = scope.target(call)?;
558
594
  if target.passed == Some(passed + 2)
559
- && let Some(callee) = &target.callee
595
+ && let Some(callee) = target.callee
560
596
  && let Some(inner) = self.script.method_forwarder(callee)
561
597
  {
562
598
  calls.push((inner, target));
@@ -575,10 +611,7 @@ impl<'script> Machine<'script> {
575
611
  .iter()
576
612
  .filter(|target| target.passed == Some(arity))
577
613
  .collect();
578
- let sites: Vec<u32> = listeners
579
- .iter()
580
- .map(|target| target.site.v8.0 - self.start.0)
581
- .collect();
614
+ let sites: Vec<u32> = listeners.iter().map(|target| target.site.v8).collect();
582
615
  let listener = candidates::exactly_one(listeners, "listener of the closure's arity")
583
616
  .with_context(|| {
584
617
  format!("no one listener for a closure of {arity} arguments, at {sites:?}")
@@ -588,19 +621,19 @@ impl<'script> Machine<'script> {
588
621
  }
589
622
 
590
623
  /// The function `run` calls for an opcode.
591
- struct Handler<'machine> {
624
+ struct Handler<'a, 'machine> {
592
625
  /// Call from the dispatch loop to this handler.
593
- dispatch: Invocation,
594
- name: Id,
626
+ dispatch: Invocation<'a>,
627
+ name: Callee<'a>,
595
628
  frame: Name,
596
- dispatch_loop: &'machine DispatchLoop,
629
+ dispatch_loop: &'machine DispatchLoop<'a>,
597
630
  }
598
631
 
599
632
  /// Function called by `run` with the machine to dispatch opcodes.
600
- struct DispatchLoop {
601
- name: Id,
633
+ struct DispatchLoop<'a> {
634
+ name: Callee<'a>,
602
635
  /// Call from `run`, either direct or through a helper.
603
- call: Invocation,
636
+ call: Invocation<'a>,
604
637
  /// Whether the call occurs in a `try` block that handles exceptions.
605
638
  guarded: bool,
606
639
  }
@@ -610,42 +643,61 @@ struct DispatchLoop {
610
643
  const DISPATCH_CASES: usize = 40;
611
644
 
612
645
  /// Finds functions with dispatch switches that `run` calls with the machine.
613
- fn dispatch_loops(script: &Script, run: &Function) -> Vec<DispatchLoop> {
614
- #[derive(Default)]
615
- struct Calls {
616
- found: Vec<(CallExpr, bool)>,
646
+ fn dispatch_loops<'a>(script: &Script<'a>, run: &Body<'a>) -> Vec<DispatchLoop<'a>> {
647
+ struct Calls<'a> {
648
+ js: ast::Script<'a>,
649
+ found: Vec<(&'a CallExpression<'a>, bool)>,
617
650
  guarded: bool,
618
651
  }
619
- impl Visit for Calls {
620
- fn visit_function(&mut self, _: &Function) {}
621
- fn visit_class(&mut self, _: &Class) {}
652
+ impl<'a> Visit<'a> for Calls<'a> {
653
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
654
+ fn visit_class(&mut self, _: &Class<'a>) {}
655
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
656
+ walk_property(self, property);
657
+ }
622
658
  // Only a `try` with a `catch` handles exceptions.
623
- fn visit_try_stmt(&mut self, statement: &TryStmt) {
659
+ fn visit_try_statement(&mut self, statement: &TryStatement<'a>) {
624
660
  let outer = self.guarded;
625
661
  self.guarded |= statement.handler.is_some();
626
- statement.block.visit_with(self);
662
+ self.visit_block_statement(&statement.block);
627
663
  self.guarded = outer;
628
- statement.handler.visit_with(self);
629
- statement.finalizer.visit_with(self);
664
+ if let Some(handler) = &statement.handler {
665
+ self.visit_catch_clause(handler);
666
+ }
667
+ if let Some(finalizer) = &statement.finalizer {
668
+ self.visit_block_statement(finalizer);
669
+ }
630
670
  }
631
- fn visit_call_expr(&mut self, call: &CallExpr) {
632
- if call.args.iter().any(|argument| argument.expr.is_this()) {
633
- self.found.push((call.clone(), self.guarded));
671
+ fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
672
+ if !is_optional_call(call)
673
+ && call.arguments.iter().any(|argument| {
674
+ matches!(
675
+ ast::argument_expression(argument),
676
+ Expression::ThisExpression(_)
677
+ )
678
+ })
679
+ {
680
+ let call = self.js.lend(call, AstKind::as_call_expression);
681
+ self.found.push((call, self.guarded));
634
682
  }
635
- call.visit_children_with(self);
683
+ walk::walk_call_expression(self, call);
636
684
  }
637
685
  }
638
- let mut calls = Calls::default();
639
- run.body.visit_with(&mut calls);
686
+ let mut calls = Calls {
687
+ js: script.js(),
688
+ found: Vec::new(),
689
+ guarded: false,
690
+ };
691
+ run.visit(&mut calls);
640
692
  let scope = Scope::new("", run, &script.appliers);
641
693
  calls
642
694
  .found
643
695
  .into_iter()
644
696
  .filter_map(|(call, guarded)| {
645
- let call = scope.target(&call).ok()?;
646
- let name = call.callee.clone()?;
647
- let function = script.function(&name).ok()?;
648
- (cases_of(function).len() > DISPATCH_CASES).then_some(DispatchLoop {
697
+ let call = scope.target(call).ok()?;
698
+ let name = call.callee?;
699
+ let function = script.function(name).ok()?;
700
+ (cases_of(script.js(), &function).len() > DISPATCH_CASES).then_some(DispatchLoop {
649
701
  name,
650
702
  call,
651
703
  guarded,
@@ -654,148 +706,270 @@ fn dispatch_loops(script: &Script, run: &Function) -> Vec<DispatchLoop> {
654
706
  .collect()
655
707
  }
656
708
 
709
+ /// A function's parameters and statements. An original function extracted from a merged
710
+ /// function has the merged function's parameters after the selector and its case's statements.
711
+ #[derive(Clone, Copy)]
712
+ struct Body<'a> {
713
+ parameters: &'a [FormalParameter<'a>],
714
+ /// Whether a rest parameter follows `parameters`.
715
+ rest: bool,
716
+ /// Whether the body starts with a directive prologue, which no statement pattern accepts.
717
+ prologue: bool,
718
+ /// The statements, in two parts so that an original function can join its case block to the
719
+ /// statements after it.
720
+ head: &'a [Statement<'a>],
721
+ tail: &'a [Statement<'a>],
722
+ }
723
+
724
+ impl<'a> Body<'a> {
725
+ fn of(function: &'a Function<'a>) -> Self {
726
+ let (prologue, head) = match &function.body {
727
+ Some(body) => (!body.directives.is_empty(), &body.statements[..]),
728
+ None => (false, &[][..]),
729
+ };
730
+ Self {
731
+ parameters: &function.params.items,
732
+ rest: function.params.rest.is_some(),
733
+ prologue,
734
+ head,
735
+ tail: &[],
736
+ }
737
+ }
738
+
739
+ fn statements(&self) -> impl DoubleEndedIterator<Item = &'a Statement<'a>> + Clone + use<'a> {
740
+ self.head.iter().chain(self.tail)
741
+ }
742
+
743
+ /// The statements of a body without a directive prologue.
744
+ fn plain_statements(
745
+ &self,
746
+ ) -> Option<impl DoubleEndedIterator<Item = &'a Statement<'a>> + Clone + use<'a>> {
747
+ (!self.prologue).then(|| self.statements())
748
+ }
749
+
750
+ /// The only statement after leading local declarations without initializers.
751
+ fn only_statement(&self) -> Option<&'a Statement<'a>> {
752
+ let mut rest = self.plain_statements()?.skip_while(|statement| {
753
+ matches!(statement, Statement::VariableDeclaration(declaration)
754
+ if !declaration.kind.is_using()
755
+ && declaration.declarations.iter().all(|declarator| declarator.init.is_none()))
756
+ });
757
+ let only = rest.next()?;
758
+ rest.next().is_none().then_some(only)
759
+ }
760
+
761
+ /// The bindings of the parameters, if they are all plain names.
762
+ fn parameters(&self) -> Option<Vec<SymbolId>> {
763
+ if self.rest {
764
+ return None;
765
+ }
766
+ self.parameters.iter().map(plain_parameter).collect()
767
+ }
768
+
769
+ fn visit(&self, visitor: &mut impl Visit<'a>) {
770
+ for statement in self.statements() {
771
+ visitor.visit_statement(statement);
772
+ }
773
+ }
774
+ }
775
+
657
776
  /// The script's declared and assigned functions, VM dispatch methods, and aliases for
658
777
  /// `Reflect.construct` and `Reflect.apply`.
659
- struct Script {
660
- functions: Vec<(Id, Function)>,
661
- /// Original functions extracted from merged functions, each using the merged function name. See
662
- /// [`Merged`].
663
- originals: Vec<(Id, Function)>,
664
- classes: Vec<DispatchMethod>,
665
- constructs: Vec<Id>,
778
+ struct Script<'a> {
779
+ functions: Vec<(Binding<'a>, Body<'a>)>,
780
+ classes: Vec<DispatchMethod<'a>>,
781
+ constructs: Vec<Callee<'a>>,
666
782
  /// Array slots containing `Reflect.construct`, indexed by array and slot.
667
- construct_slots: Vec<(Id, usize)>,
668
- applies: Vec<Id>,
783
+ construct_slots: Vec<(Binding<'a>, usize)>,
784
+ applies: Vec<Callee<'a>>,
669
785
  /// Array slots containing `Reflect.apply`, indexed by array and slot.
670
- apply_slots: Vec<(Id, usize)>,
671
- appliers: Appliers,
786
+ apply_slots: Vec<(Binding<'a>, usize)>,
787
+ appliers: Appliers<'a>,
672
788
  }
673
789
 
674
- /// Call helpers indexed by name, including selector-based helpers, merged functions, and
790
+ /// An original function extracted from a merged function. See [`merged`].
791
+ struct Original<'a> {
792
+ /// The merged function's name, which frames of the original use.
793
+ name: &'a str,
794
+ body: Body<'a>,
795
+ }
796
+
797
+ /// Call helpers indexed by callee, including selector-based helpers, merged functions, and
675
798
  /// forwarders. Also records numeric constants used by selectors.
676
- struct Appliers {
677
- helpers: HashMap<Id, Applier>,
678
- merged: HashMap<Id, Merged>,
679
- forwarders: Forwarders,
680
- /// Bindings assigned a numeric value once, such as a shared case-label mask.
681
- constants: HashMap<Id, f64>,
799
+ struct Appliers<'a> {
800
+ helpers: HashMap<Callee<'a>, Selection<Site>>,
801
+ /// Merged functions, selecting originals indexed into `originals`.
802
+ merged: HashMap<Binding<'a>, Selection<usize>>,
803
+ /// Original functions extracted from merged functions.
804
+ originals: Vec<Original<'a>>,
805
+ forwarders: Forwarders<'a>,
806
+ constants: Constants<'a>,
807
+ }
808
+
809
+ /// Bindings assigned a numeric value once, such as a shared case-label mask, and the script
810
+ /// that binds them.
811
+ struct Constants<'a> {
812
+ js: ast::Script<'a>,
813
+ values: HashMap<SymbolId, f64>,
814
+ }
815
+
816
+ impl<'a> Constants<'a> {
817
+ fn new(js: ast::Script<'a>) -> Self {
818
+ let mut values = HashMap::new();
819
+ let mut assigned = HashSet::new();
820
+ for node in js.nodes.iter() {
821
+ match node.kind() {
822
+ AstKind::VariableDeclarator(declarator) => {
823
+ if let BindingPattern::BindingIdentifier(name) = &declarator.id
824
+ && let Some(value) = declarator
825
+ .init
826
+ .as_ref()
827
+ .and_then(|init| ast::fold_number(init, &|_| None))
828
+ {
829
+ values.insert(name.symbol_id(), value);
830
+ }
831
+ }
832
+ AstKind::AssignmentExpression(assignment) => {
833
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left
834
+ && let Some(symbol) = js.symbol(name)
835
+ {
836
+ assigned.insert(symbol);
837
+ }
838
+ }
839
+ _ => {}
840
+ }
841
+ }
842
+ values.retain(|symbol, _| !assigned.contains(symbol));
843
+ Self { js, values }
844
+ }
845
+
846
+ /// The function or value `expression` names.
847
+ fn binding(&self, expression: &Expression<'a>) -> Option<Binding<'a>> {
848
+ match expression.without_parentheses() {
849
+ Expression::Identifier(reference) => Some(self.js.binding(reference)),
850
+ _ => None,
851
+ }
852
+ }
682
853
  }
683
854
 
684
855
  /// Functions that call their first parameter with the remaining parameters, as recorded by
685
856
  /// [`Scope`].
686
857
  #[derive(Default)]
687
- struct Forwarders {
858
+ struct Forwarders<'a> {
688
859
  /// Forwarders indexed by the binding holding their object and their property key.
689
- on_objects: HashMap<(Holder, String), Forwarder>,
860
+ on_objects: HashMap<(Holder<'a>, &'a str), Forwarder>,
690
861
  /// Forwarders copied to bindings, as in `f = object.key`, with the frames produced when called
691
862
  /// through those bindings.
692
- held: HashMap<Holder, Vec<Call>>,
863
+ held: HashMap<Holder<'a>, Vec<Call>>,
693
864
  }
694
865
 
695
- impl Forwarders {
866
+ impl<'a> Forwarders<'a> {
696
867
  /// Keeps only forwarders whose object bindings are assigned once, so their values are known.
697
- fn retain_assigned_once(&mut self, assigned: &HashMap<Holder, usize>) {
868
+ fn retain_assigned_once(&mut self, assigned: &HashMap<Holder<'a>, usize>) {
698
869
  let once = |holder: &Holder| assigned.get(holder).is_none_or(|&count| count == 1);
699
870
  self.on_objects.retain(|(holder, _), _| once(holder));
700
871
  self.held.retain(|holder, _| once(holder));
701
872
  }
702
873
  }
703
874
 
704
- impl Appliers {
705
- /// Also returns original functions extracted from merged functions, using names described by
706
- /// [`Merged`].
707
- fn new(program: &Program, functions: &[(Id, Function)]) -> (Self, Vec<(Id, Function)>) {
708
- #[derive(Default)]
709
- struct Constants {
710
- values: HashMap<Id, f64>,
711
- assigned: HashSet<Id>,
712
- }
713
- impl Visit for Constants {
714
- fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
715
- if let Pat::Ident(name) = &declarator.name
716
- && let Some(value) = declarator
717
- .init
718
- .as_deref()
719
- .and_then(|init| ast::fold_number(init, &|_| None))
720
- {
721
- self.values.insert(name.to_id(), value);
722
- }
723
- declarator.visit_children_with(self);
724
- }
725
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
726
- if let Some(name) = assign.left.as_ident() {
727
- self.assigned.insert(name.to_id());
728
- }
729
- assign.visit_children_with(self);
730
- }
731
- }
732
- let mut constants = Constants::default();
733
- program.visit_with(&mut constants);
734
- constants
735
- .values
736
- .retain(|name, _| !constants.assigned.contains(name));
737
- let values = constants.values;
738
- let applier = |(name, function): &(Id, Function)| {
739
- Some((name.clone(), Applier::new(function, &values)?))
740
- };
741
- let mut helpers: HashMap<Id, Applier> = functions.iter().filter_map(applier).collect();
742
- let mut merged = HashMap::new();
875
+ impl<'a> Appliers<'a> {
876
+ fn new(js: ast::Script<'a>, functions: &[(Binding<'a>, Body<'a>)]) -> Self {
877
+ let constants = Constants::new(js);
878
+ let mut helpers: HashMap<Callee<'a>, Selection<Site>> = functions
879
+ .iter()
880
+ .filter_map(|(name, function)| {
881
+ Some((Callee::Binding(*name), applier(function, &constants)?))
882
+ })
883
+ .collect();
884
+ let mut merged_functions = HashMap::new();
743
885
  let mut originals = Vec::new();
744
886
  for (name, function) in functions {
745
- if !helpers.contains_key(name)
746
- && let Some((selection, held)) = Merged::new(name, function, &values)
887
+ if !helpers.contains_key(&Callee::Binding(*name))
888
+ && let Some(Selection { mask, cases }) = merged(function, &constants)
747
889
  {
748
- merged.insert(name.clone(), selection);
749
- originals.extend(held);
890
+ let mut indexed = Vec::new();
891
+ for (label, body) in cases {
892
+ indexed.push((label, originals.len()));
893
+ originals.push(Original {
894
+ name: js.name(*name),
895
+ body,
896
+ });
897
+ }
898
+ merged_functions.insert(
899
+ *name,
900
+ Selection {
901
+ mask,
902
+ cases: indexed,
903
+ },
904
+ );
750
905
  }
751
906
  }
752
907
  // A merged function may hold call helpers.
753
- helpers.extend(originals.iter().filter_map(applier));
908
+ for (index, original) in originals.iter().enumerate() {
909
+ if let Some(helper) = applier(&original.body, &constants) {
910
+ helpers.insert(Callee::Original(index), helper);
911
+ }
912
+ }
754
913
  let mut appliers = Self {
755
914
  helpers,
756
- merged,
915
+ merged: merged_functions,
916
+ originals,
757
917
  forwarders: Forwarders::default(),
758
- constants: values,
918
+ constants,
759
919
  };
760
- appliers.forwarders = forwarders(program, &appliers);
761
- (appliers, originals)
920
+ appliers.forwarders = forwarders(&appliers);
921
+ appliers
762
922
  }
763
923
 
764
- /// Evaluates `expression` using numeric literals and known constants.
765
- fn number(&self, expression: &Expr) -> Option<f64> {
766
- number(expression, &self.constants)
924
+ fn js(&self) -> ast::Script<'a> {
925
+ self.constants.js
926
+ }
927
+
928
+ /// The name of `callee` in the source. An original function has its merged function's name.
929
+ fn name(&self, callee: Callee<'a>) -> &'a str {
930
+ match callee {
931
+ Callee::Binding(binding) => self.js().name(binding),
932
+ Callee::Original(index) => self.originals[index].name,
933
+ }
934
+ }
935
+
936
+ /// Evaluates `operand` using numeric literals and known constants.
937
+ fn number(&self, operand: Operand<'a>) -> Option<f64> {
938
+ match operand {
939
+ Operand::Expression(expression) => number(expression, &self.constants),
940
+ Operand::Resolved(Callee::Binding(Binding::Symbol(symbol))) => {
941
+ self.constants.values.get(&symbol).copied()
942
+ }
943
+ Operand::Resolved(_) => None,
944
+ }
767
945
  }
768
946
  }
769
947
 
770
948
  /// Collects forwarders from each function via [`Scope`]. Keeps only those whose object bindings are
771
949
  /// assigned once.
772
- fn forwarders(program: &Program, appliers: &Appliers) -> Forwarders {
773
- struct Collect<'script> {
774
- appliers: &'script Appliers,
775
- found: Forwarders,
776
- assigned: HashMap<Holder, usize>,
777
- }
778
- impl Collect<'_> {
779
- fn scope(&mut self, name: &str, function: &Function) {
780
- let scope = Scope::new(name, function, self.appliers);
950
+ fn forwarders<'a>(appliers: &Appliers<'a>) -> Forwarders<'a> {
951
+ struct Collect<'a, 's> {
952
+ appliers: &'s Appliers<'a>,
953
+ found: Forwarders<'a>,
954
+ assigned: HashMap<Holder<'a>, usize>,
955
+ }
956
+ impl<'a> Visit<'a> for Collect<'a, '_> {
957
+ fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
958
+ let function = self.appliers.js().lend(function, AstKind::as_function);
959
+ let name = function.id.as_ref().map_or("", |name| name.name.as_str());
960
+ let scope = Scope::new(name, &Body::of(function), self.appliers);
781
961
  self.found.on_objects.extend(scope.forwarders.on_objects);
782
962
  self.found.held.extend(scope.forwarders.held);
783
963
  for (holder, count) in scope.assigned {
784
964
  *self.assigned.entry(holder).or_default() += count;
785
965
  }
786
- function.visit_children_with(self);
966
+ walk::walk_function(self, function, flags);
787
967
  }
788
- }
789
- impl Visit for Collect<'_> {
790
- fn visit_fn_decl(&mut self, declaration: &FnDecl) {
791
- self.scope(&declaration.ident.sym, &declaration.function);
968
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
969
+ walk_property(self, property);
792
970
  }
793
- fn visit_fn_expr(&mut self, expression: &FnExpr) {
794
- let name = expression.ident.as_ref().map_or("", |name| &*name.sym);
795
- self.scope(name, &expression.function);
796
- }
797
- fn visit_function(&mut self, function: &Function) {
798
- self.scope("", function);
971
+ fn visit_method_definition(&mut self, method: &MethodDefinition<'a>) {
972
+ walk_method(self, method);
799
973
  }
800
974
  }
801
975
  let mut collect = Collect {
@@ -803,35 +977,42 @@ fn forwarders(program: &Program, appliers: &Appliers) -> Forwarders {
803
977
  found: Forwarders::default(),
804
978
  assigned: HashMap::new(),
805
979
  };
806
- program.visit_with(&mut collect);
980
+ collect.visit_program(appliers.js().program);
807
981
  collect.found.retain_assigned_once(&collect.assigned);
808
982
  collect.found
809
983
  }
810
984
 
811
985
  /// Evaluates `expression` using literals and `constants`.
812
- fn number(expression: &Expr, constants: &HashMap<Id, f64>) -> Option<f64> {
813
- ast::fold_number(expression, &|leaf| {
814
- constants.get(&leaf.as_ident()?.to_id()).copied()
986
+ fn number<'a>(expression: &Expression<'a>, constants: &Constants<'a>) -> Option<f64> {
987
+ ast::fold_number(expression, &|leaf| match leaf {
988
+ Expression::Identifier(reference) => constants
989
+ .values
990
+ .get(&constants.js.symbol(reference)?)
991
+ .copied(),
992
+ _ => None,
815
993
  })
816
994
  }
817
995
 
818
996
  /// Finds the VM class method `run` that calls the dispatch loops.
819
- struct DispatchMethod {
820
- class: String,
821
- run: Function,
997
+ struct DispatchMethod<'a> {
998
+ class: &'a str,
999
+ run: Body<'a>,
822
1000
  /// The method's literal property key, if present.
823
- key: Option<String>,
1001
+ key: Option<&'a str>,
824
1002
  }
825
1003
 
826
- impl Script {
827
- fn new(program: &Program) -> Self {
828
- // The decoded AST retains resolver contexts, so equal names in different
829
- // lexical scopes have distinct IDs while frame names keep their original spelling.
830
- let functions = ast::named_functions(program);
831
- let (appliers, originals) = Appliers::new(program, &functions);
1004
+ impl<'a> Script<'a> {
1005
+ fn new(js: ast::Script<'a>) -> Self {
1006
+ // Semantic analysis gives equal names in different lexical scopes distinct bindings,
1007
+ // while frame names keep their original spelling.
1008
+ let functions: Vec<(Binding<'a>, Body<'a>)> = js
1009
+ .named_functions()
1010
+ .into_iter()
1011
+ .map(|(name, function)| (name, Body::of(function)))
1012
+ .collect();
1013
+ let appliers = Appliers::new(js, &functions);
832
1014
  let mut script = Self {
833
1015
  functions,
834
- originals,
835
1016
  classes: Vec::new(),
836
1017
  constructs: Vec::new(),
837
1018
  construct_slots: Vec::new(),
@@ -839,148 +1020,256 @@ impl Script {
839
1020
  apply_slots: Vec::new(),
840
1021
  appliers,
841
1022
  };
842
- program.visit_with(&mut script);
1023
+ for node in js.nodes.iter() {
1024
+ match node.kind() {
1025
+ AstKind::AssignmentExpression(assignment) => script.assignment(assignment),
1026
+ AstKind::Class(class) if class.is_declaration() => script.class(class),
1027
+ _ => {}
1028
+ }
1029
+ }
843
1030
  script
844
1031
  }
845
1032
 
846
- fn function(&self, name: &Id) -> Result<&Function> {
847
- self.functions
848
- .iter()
849
- .chain(&self.originals)
850
- .find(|(function_name, _)| function_name == name)
851
- .map(|(_, function)| function)
852
- .with_context(|| format!("missing original function {}", name.0))
1033
+ fn js(&self) -> ast::Script<'a> {
1034
+ self.appliers.js()
1035
+ }
1036
+
1037
+ /// Tracks `Reflect.construct` and `Reflect.apply` in bindings or array slots, including
1038
+ /// indirect references to `Reflect`. Each assignment in a chain records its own target.
1039
+ fn assignment(&mut self, assignment: &'a AssignmentExpression<'a>) {
1040
+ let js = self.js();
1041
+ let mut value = &assignment.right;
1042
+ while let Expression::AssignmentExpression(inner) = value.without_parentheses() {
1043
+ value = &inner.right;
1044
+ }
1045
+ let Some(member) = member(value.without_parentheses()) else {
1046
+ return;
1047
+ };
1048
+ let method = ast::member_str(member);
1049
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left {
1050
+ let name = Callee::Binding(js.binding(name));
1051
+ match method {
1052
+ Some("construct") => self.constructs.push(name),
1053
+ Some("apply") => self.applies.push(name),
1054
+ _ => {}
1055
+ }
1056
+ }
1057
+ if let Some(MemberExpression::ComputedMemberExpression(slot)) =
1058
+ assigned_member(&assignment.left)
1059
+ && let Expression::Identifier(array) = &slot.object
1060
+ && let Some(index) =
1061
+ number(&slot.expression, &self.appliers.constants).and_then(ast::array_index)
1062
+ {
1063
+ let slot = (js.binding(array), index);
1064
+ match method {
1065
+ Some("construct") => self.construct_slots.push(slot),
1066
+ Some("apply") => self.apply_slots.push(slot),
1067
+ _ => {}
1068
+ }
1069
+ }
1070
+ }
1071
+
1072
+ /// Records a class declaration's `run` method.
1073
+ fn class(&mut self, class: &'a Class<'a>) {
1074
+ let run = class.body.body.iter().find_map(|element| match element {
1075
+ ClassElement::MethodDefinition(method)
1076
+ if method.kind != MethodDefinitionKind::Constructor
1077
+ && ast::static_key_str(&method.key, method.computed) == Some("run") =>
1078
+ {
1079
+ Some(method)
1080
+ }
1081
+ _ => None,
1082
+ });
1083
+ if let Some(method) = run
1084
+ && let Some(name) = &class.id
1085
+ {
1086
+ self.classes.push(DispatchMethod {
1087
+ class: name.name.as_str(),
1088
+ run: Body::of(&method.value),
1089
+ key: ast::key_str(&method.key, method.computed),
1090
+ });
1091
+ }
853
1092
  }
854
1093
 
855
- /// Returns frames for the function bound to `name` if it forwards a method call. Allows
856
- /// local variable declarations before the return.
857
- fn method_forwarder(&self, name: &Id) -> Option<Vec<Call>> {
858
- let function = self.function(name).ok()?;
859
- let parameters = parameters(function)?;
1094
+ fn function(&self, callee: Callee<'a>) -> Result<Body<'a>> {
1095
+ match callee {
1096
+ Callee::Binding(binding) => self
1097
+ .functions
1098
+ .iter()
1099
+ .find(|(name, _)| *name == binding)
1100
+ .map(|(_, function)| *function),
1101
+ Callee::Original(index) => self
1102
+ .appliers
1103
+ .originals
1104
+ .get(index)
1105
+ .map(|original| original.body),
1106
+ }
1107
+ .with_context(|| format!("missing original function {}", self.appliers.name(callee)))
1108
+ }
1109
+
1110
+ /// Returns frames for the function `callee` if it forwards a method call. Allows local
1111
+ /// variable declarations before the return.
1112
+ fn method_forwarder(&self, callee: Callee<'a>) -> Option<Vec<Call>> {
1113
+ let function = self.function(callee).ok()?;
1114
+ let parameters = function.parameters()?;
860
1115
  let [method, receiver, ..] = parameters.as_slice() else {
861
1116
  return None;
862
1117
  };
863
- let (Stmt::Return(returned), declarations) = function.body.as_ref()?.stmts.split_last()?
864
- else {
1118
+ let mut statements = function.plain_statements()?;
1119
+ let Statement::ReturnStatement(returned) = statements.next_back()? else {
865
1120
  return None;
866
1121
  };
867
- if !declarations
868
- .iter()
869
- .all(|statement| matches!(statement, Stmt::Decl(Decl::Var(_))))
870
- {
1122
+ if !statements.all(|statement| {
1123
+ matches!(statement, Statement::VariableDeclaration(declaration)
1124
+ if !declaration.kind.is_using())
1125
+ }) {
871
1126
  return None;
872
1127
  }
873
- let mut value = returned.arg.as_deref()?.unwrap_parens();
874
- if let Expr::Seq(sequence) = value {
875
- value = sequence.exprs.last()?.unwrap_parens();
1128
+ let mut value = returned.argument.as_ref()?.without_parentheses();
1129
+ if let Expression::SequenceExpression(sequence) = value {
1130
+ value = sequence.expressions.last()?.without_parentheses();
876
1131
  }
877
- let call = value.as_call()?;
878
- let target = Scope::new(&name.0, function, &self.appliers)
1132
+ let Expression::CallExpression(call) = value else {
1133
+ return None;
1134
+ };
1135
+ let name = self.appliers.name(callee);
1136
+ let target = Scope::new(name, &function, &self.appliers)
879
1137
  .target(call)
880
1138
  .ok()?;
881
1139
  // Compare bindings so a nested function with the same name as a native apply
882
1140
  // alias cannot be mistaken for that alias. Some builds keep the alias in an array slot.
883
- let native = match (&target.callee, &target.slot) {
884
- (Some(callee), _) => self.function(callee).is_err() || self.applies.contains(callee),
885
- (None, Some(slot)) => self.apply_slots.contains(slot),
1141
+ let native = match (target.callee, target.slot) {
1142
+ (Some(callee), _) => self.function(callee).is_err() || self.applies.contains(&callee),
1143
+ (None, Some(slot)) => self.apply_slots.contains(&slot),
886
1144
  (None, None) => false,
887
1145
  };
888
1146
  if !native {
889
1147
  return None;
890
1148
  }
891
- let [first, second, ..] = handed(call, &target)?[..] else {
1149
+ let [first, second, ..] = handed(Arguments::of(call), &target)?[..] else {
892
1150
  return None;
893
1151
  };
894
- (self::name(first).as_ref() == Some(method)
895
- && self::name(second).as_ref() == Some(receiver))
896
- .then(|| target.frames(Name::same(name.0.to_string())))
1152
+ let constants = &self.appliers.constants;
1153
+ (first.callee(constants) == Some(Callee::symbol(*method))
1154
+ && second.callee(constants) == Some(Callee::symbol(*receiver)))
1155
+ .then(|| target.frames(Name::same(name.to_owned())))
897
1156
  }
898
1157
  }
899
1158
 
900
- impl Visit for Script {
901
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
902
- // Track `Reflect.construct` and `Reflect.apply` in bindings or array slots, including
903
- // indirect references to `Reflect`. Visit child expressions to record every target in a
904
- // chained assignment.
905
- let mut value = &*assign.right;
906
- while let Expr::Assign(inner) = value.unwrap_parens() {
907
- value = &inner.right;
1159
+ /// A call argument as call resolution reads it.
1160
+ #[derive(Clone, Copy)]
1161
+ enum Operand<'a> {
1162
+ Expression(&'a Expression<'a>),
1163
+ /// A function resolved without an expression that names it: a binding a forwarder reads back
1164
+ /// from an array copy, or an original function selected from a merged function.
1165
+ Resolved(Callee<'a>),
1166
+ }
1167
+
1168
+ impl<'a> Operand<'a> {
1169
+ /// The function or value the operand names.
1170
+ fn callee(self, constants: &Constants<'a>) -> Option<Callee<'a>> {
1171
+ match self {
1172
+ Self::Expression(expression) => constants.binding(expression).map(Callee::Binding),
1173
+ Self::Resolved(callee) => Some(callee),
908
1174
  }
909
- if let Expr::Member(member) = value.unwrap_parens() {
910
- let method = ast::member_str(&member.prop);
911
- match (assign.left.as_ident(), method) {
912
- (Some(name), Some("construct")) => self.constructs.push(name.to_id()),
913
- (Some(name), Some("apply")) => self.applies.push(name.to_id()),
914
- _ => {}
915
- }
916
- if let AssignTarget::Simple(SimpleAssignTarget::Member(slot)) = &assign.left
917
- && let Some(array) = slot.obj.as_ident()
918
- && let Some(index) = slot.prop.as_computed()
919
- && let Some(index) = self.appliers.number(&index.expr).and_then(ast::array_index)
920
- {
921
- match method {
922
- Some("construct") => self.construct_slots.push((array.to_id(), index)),
923
- Some("apply") => self.apply_slots.push((array.to_id(), index)),
924
- _ => {}
925
- }
926
- }
1175
+ }
1176
+ }
1177
+
1178
+ /// A call's arguments. In a forwarder, `copies` resolves arguments read back from array copies,
1179
+ /// at the top level and in array literals.
1180
+ #[derive(Clone, Copy)]
1181
+ struct Arguments<'a, 'c> {
1182
+ list: &'a [Argument<'a>],
1183
+ copies: Option<&'c Copies<'a, 'c>>,
1184
+ }
1185
+
1186
+ impl<'a, 'c> Arguments<'a, 'c> {
1187
+ fn of(call: &'a CallExpression<'a>) -> Self {
1188
+ Self {
1189
+ list: &call.arguments,
1190
+ copies: None,
927
1191
  }
928
- assign.visit_children_with(self);
929
1192
  }
930
1193
 
931
- fn visit_class_decl(&mut self, declaration: &ClassDecl) {
932
- let run = declaration
933
- .class
934
- .body
935
- .iter()
936
- .filter_map(ClassMember::as_method)
937
- .find(|method| ast::static_key_str(&method.key) == Some("run"));
938
- if let Some(method) = run {
939
- self.classes.push(DispatchMethod {
940
- class: declaration.ident.sym.to_string(),
941
- run: (*method.function).clone(),
942
- key: ast::key_str(&method.key).map(str::to_owned),
943
- });
1194
+ /// Reads an argument, resolving it through the copies unless it is an array literal.
1195
+ fn argument(&self, argument: &'a Argument<'a>) -> Operand<'a> {
1196
+ let expression = ast::argument_expression(argument);
1197
+ if let Some(copies) = self.copies
1198
+ && !matches!(
1199
+ expression.without_parentheses(),
1200
+ Expression::ArrayExpression(_)
1201
+ )
1202
+ && let Some(binding) = copies.resolve(expression)
1203
+ {
1204
+ return Operand::Resolved(Callee::Binding(binding));
944
1205
  }
945
- declaration.visit_children_with(self);
1206
+ Operand::Expression(expression)
1207
+ }
1208
+
1209
+ /// Reads an array element, or `None` for a hole.
1210
+ fn element(&self, element: &'a ArrayExpressionElement<'a>) -> Option<Operand<'a>> {
1211
+ let expression = element_expression(element)?;
1212
+ Some(
1213
+ match self.copies.and_then(|copies| copies.resolve(expression)) {
1214
+ Some(binding) => Operand::Resolved(Callee::Binding(binding)),
1215
+ None => Operand::Expression(expression),
1216
+ },
1217
+ )
946
1218
  }
947
1219
  }
948
1220
 
949
- fn name(expression: &Expr) -> Option<Id> {
950
- Some(expression.unwrap_parens().as_ident()?.to_id())
1221
+ /// The expression an array element holds, ignoring a spread, or `None` for a hole.
1222
+ fn element_expression<'b, 'a>(
1223
+ element: &'b ArrayExpressionElement<'a>,
1224
+ ) -> Option<&'b Expression<'a>> {
1225
+ match element {
1226
+ ArrayExpressionElement::SpreadElement(spread) => Some(&spread.argument),
1227
+ ArrayExpressionElement::Elision(_) => None,
1228
+ element => Some(element.to_expression()),
1229
+ }
951
1230
  }
952
1231
 
953
- /// The names of a function's parameters, if they are all plain names.
954
- fn parameters(function: &Function) -> Option<Vec<Id>> {
955
- function
956
- .params
957
- .iter()
958
- .map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
959
- .collect()
1232
+ /// An array literal, possibly parenthesized.
1233
+ fn array<'b, 'a>(expression: &'b Expression<'a>) -> Option<&'b ArrayExpression<'a>> {
1234
+ match expression.without_parentheses() {
1235
+ Expression::ArrayExpression(array) => Some(array),
1236
+ _ => None,
1237
+ }
960
1238
  }
961
1239
 
962
- /// Returns the arguments `call` forwards to the callee identified by `target`. Skips leading
1240
+ /// Returns the arguments a call forwards to the callee identified by `target`. Skips leading
963
1241
  /// selectors, callee, and receiver. The forwarded arguments are either the trailing call arguments
964
1242
  /// or the trailing elements of an apply-helper argument list.
965
- fn handed<'call>(call: &'call CallExpr, target: &Invocation) -> Option<Vec<&'call Expr>> {
966
- let arguments: Vec<&Expr> = if target.listed {
967
- let list = call.args.last()?.expr.unwrap_parens().as_array()?;
968
- list.elems
1243
+ fn handed<'a>(arguments: Arguments<'a, '_>, target: &Invocation<'a>) -> Option<Vec<Operand<'a>>> {
1244
+ let operands: Vec<Operand<'a>> = if target.listed {
1245
+ let list = array(ast::argument_expression(arguments.list.last()?))?;
1246
+ list.elements
969
1247
  .iter()
970
- .map(|element| element.as_ref().map(|element| &*element.expr))
1248
+ .map(|element| arguments.element(element))
971
1249
  .collect::<Option<_>>()?
972
1250
  } else {
973
- call.args.iter().map(|argument| &*argument.expr).collect()
1251
+ arguments
1252
+ .list
1253
+ .iter()
1254
+ .map(|argument| arguments.argument(argument))
1255
+ .collect()
974
1256
  };
975
- let start = arguments.len().checked_sub(target.passed?)?;
976
- Some(arguments[start..].to_vec())
1257
+ let start = operands.len().checked_sub(target.passed?)?;
1258
+ Some(operands[start..].to_vec())
977
1259
  }
978
1260
 
979
1261
  /// Checks whether `call` forwards two captured values followed by `function`'s leading
980
1262
  /// parameters, as a closure-factory listener does. The function may also declare trailing
981
1263
  /// parameters used as local variables.
982
- fn forwards_parameters(function: &Function, call: &CallExpr, target: &Invocation) -> bool {
983
- let (Some(handed), Some(parameters)) = (handed(call, target), parameters(function)) else {
1264
+ fn forwards_parameters<'a>(
1265
+ constants: &Constants<'a>,
1266
+ function: &Body<'a>,
1267
+ call: &'a CallExpression<'a>,
1268
+ target: &Invocation<'a>,
1269
+ ) -> bool {
1270
+ let (Some(handed), Some(parameters)) =
1271
+ (handed(Arguments::of(call), target), function.parameters())
1272
+ else {
984
1273
  return false;
985
1274
  };
986
1275
  let Some(forwarded) = handed.get(2..) else {
@@ -990,19 +1279,21 @@ fn forwards_parameters(function: &Function, call: &CallExpr, target: &Invocation
990
1279
  && forwarded
991
1280
  .iter()
992
1281
  .zip(parameters)
993
- .all(|(argument, parameter)| name(argument) == Some(parameter))
1282
+ .all(|(argument, parameter)| {
1283
+ argument.callee(constants) == Some(Callee::symbol(parameter))
1284
+ })
994
1285
  }
995
1286
 
996
1287
  /// Arrays a function fills with names before reading them back, such as `g = [f, a]` read as
997
1288
  /// `g[0]` and `g[1]`.
998
- struct Copies<'constants> {
999
- arrays: HashMap<Id, Vec<Id>>,
1289
+ struct Copies<'a, 'c> {
1290
+ arrays: HashMap<Binding<'a>, Vec<Binding<'a>>>,
1000
1291
  /// Known constants used to evaluate array indices.
1001
- constants: &'constants HashMap<Id, f64>,
1292
+ constants: &'c Constants<'a>,
1002
1293
  }
1003
1294
 
1004
- impl<'constants> Copies<'constants> {
1005
- fn new(constants: &'constants HashMap<Id, f64>) -> Self {
1295
+ impl<'a, 'c> Copies<'a, 'c> {
1296
+ fn new(constants: &'c Constants<'a>) -> Self {
1006
1297
  Self {
1007
1298
  arrays: HashMap::new(),
1008
1299
  constants,
@@ -1010,118 +1301,158 @@ impl<'constants> Copies<'constants> {
1010
1301
  }
1011
1302
 
1012
1303
  /// Records `expression` if it is `array = [name, ...]`.
1013
- fn record(&mut self, expression: &Expr) -> Option<()> {
1014
- let assign = expression.as_assign()?;
1015
- let array = assign.left.as_ident()?;
1016
- let names: Option<Vec<Id>> = assign
1017
- .right
1018
- .as_array()?
1019
- .elems
1304
+ fn record(&mut self, expression: &Expression<'a>) -> Option<()> {
1305
+ let Expression::AssignmentExpression(assignment) = expression else {
1306
+ return None;
1307
+ };
1308
+ let AssignmentTarget::AssignmentTargetIdentifier(array) = &assignment.left else {
1309
+ return None;
1310
+ };
1311
+ let Expression::ArrayExpression(list) = &assignment.right else {
1312
+ return None;
1313
+ };
1314
+ let names: Option<Vec<Binding<'a>>> = list
1315
+ .elements
1020
1316
  .iter()
1021
- .map(|element| name(&element.as_ref()?.expr))
1317
+ .map(|element| self.constants.binding(element_expression(element)?))
1022
1318
  .collect();
1023
- self.arrays.insert(array.to_id(), names?);
1319
+ self.arrays.insert(self.constants.js.binding(array), names?);
1024
1320
  Some(())
1025
1321
  }
1026
1322
 
1027
- /// The name `expression` reads, directly or through an element of a copied array.
1028
- fn resolve(&self, expression: &Expr) -> Option<Id> {
1029
- match expression.unwrap_parens() {
1030
- Expr::Ident(name) => Some(name.to_id()),
1031
- Expr::Member(member) => {
1032
- let (Expr::Ident(array), MemberProp::Computed(index)) =
1033
- (&*member.obj, &member.prop)
1034
- else {
1323
+ /// The binding `expression` reads, directly or through an element of a copied array.
1324
+ fn resolve(&self, expression: &Expression<'a>) -> Option<Binding<'a>> {
1325
+ match expression.without_parentheses() {
1326
+ Expression::Identifier(name) => Some(self.constants.js.binding(name)),
1327
+ Expression::ComputedMemberExpression(member) => {
1328
+ let Expression::Identifier(array) = &member.object else {
1035
1329
  return None;
1036
1330
  };
1037
- let index = ast::array_index(number(&index.expr, self.constants)?)?;
1038
- self.arrays.get(&array.to_id())?.get(index).cloned()
1331
+ let index = ast::array_index(number(&member.expression, self.constants)?)?;
1332
+ self.arrays
1333
+ .get(&self.constants.js.binding(array))?
1334
+ .get(index)
1335
+ .copied()
1039
1336
  }
1040
1337
  _ => None,
1041
1338
  }
1042
1339
  }
1340
+
1341
+ /// The binding `operand` reads. See [`Copies::resolve`].
1342
+ fn resolve_operand(&self, operand: Operand<'a>) -> Option<Binding<'a>> {
1343
+ match operand {
1344
+ Operand::Expression(expression) => self.resolve(expression),
1345
+ Operand::Resolved(Callee::Binding(binding)) => Some(binding),
1346
+ Operand::Resolved(Callee::Original(_)) => None,
1347
+ }
1348
+ }
1043
1349
  }
1044
1350
 
1045
1351
  /// JavaScriptCore's call position: the opening argument parenthesis, which in minified source
1046
1352
  /// immediately precedes the first argument. Decoding may change the callee's parentheses but
1047
1353
  /// preserves argument positions.
1048
- fn arguments_position(call: &CallExpr) -> BytePos {
1049
- match call.args.first() {
1050
- Some(first) => first.span().lo - BytePos(1),
1051
- None => call.span.hi - BytePos(2),
1354
+ fn arguments_position(call: &CallExpression<'_>) -> u32 {
1355
+ match call.arguments.first() {
1356
+ Some(first) => first.span().start - 1,
1357
+ None => call.span.end - 2,
1052
1358
  }
1053
1359
  }
1054
1360
 
1055
1361
  /// V8's call position: the method or function name, else JavaScriptCore's position.
1056
- fn call_position(call: &CallExpr) -> BytePos {
1362
+ fn call_position(call: &CallExpression<'_>) -> u32 {
1057
1363
  match &call.callee {
1058
- Callee::Expr(callee) => match &**callee {
1059
- Expr::Member(member) => match &member.prop {
1060
- MemberProp::Ident(property) => property.span.lo,
1061
- _ => callee.span().hi,
1062
- },
1063
- Expr::Ident(_) => call.span.lo,
1064
- _ => arguments_position(call),
1364
+ callee if let Some(member) = member(callee) => match member {
1365
+ MemberExpression::StaticMemberExpression(member) => member.property.span.start,
1366
+ _ => callee.span().end,
1065
1367
  },
1066
- _ => call.span.lo,
1368
+ Expression::Identifier(_) | Expression::Super(_) => call.span.start,
1369
+ _ => arguments_position(call),
1067
1370
  }
1068
1371
  }
1069
1372
 
1070
1373
  /// Finds the first call in a dispatch case.
1071
- struct Case {
1374
+ struct Case<'a> {
1072
1375
  span: Span,
1073
- call: CallExpr,
1376
+ call: &'a CallExpression<'a>,
1074
1377
  }
1075
1378
 
1076
- fn cases_of(function: &Function) -> Vec<Case> {
1077
- #[derive(Default)]
1078
- struct Cases(Vec<Case>);
1379
+ fn cases_of<'a>(js: ast::Script<'a>, function: &Body<'a>) -> Vec<Case<'a>> {
1380
+ struct Cases<'a> {
1381
+ js: ast::Script<'a>,
1382
+ found: Vec<Case<'a>>,
1383
+ }
1079
1384
  // Visitors inspect only the supplied body. Skip nested functions and classes, but include
1080
1385
  // arrows.
1081
- impl Visit for Cases {
1082
- fn visit_function(&mut self, _: &Function) {}
1083
- fn visit_class(&mut self, _: &Class) {}
1084
- fn visit_switch_case(&mut self, case: &SwitchCase) {
1386
+ impl<'a> Visit<'a> for Cases<'a> {
1387
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
1388
+ fn visit_class(&mut self, _: &Class<'a>) {}
1389
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
1390
+ walk_property(self, property);
1391
+ }
1392
+ fn visit_switch_case(&mut self, case: &SwitchCase<'a>) {
1085
1393
  if case.test.is_some() {
1086
- let mut calls = Calls::default();
1087
- case.cons.visit_with(&mut calls);
1088
- if let Some(call) = calls.0.into_iter().next() {
1089
- self.0.push(Case {
1394
+ let case = self.js.lend(case, AstKind::as_switch_case);
1395
+ if let Some(&call) = calls_in(self.js, &case.consequent).first() {
1396
+ self.found.push(Case {
1090
1397
  span: case.span,
1091
1398
  call,
1092
1399
  });
1093
1400
  }
1094
1401
  }
1095
- case.visit_children_with(self);
1402
+ walk::walk_switch_case(self, case);
1096
1403
  }
1097
1404
  }
1098
- let mut cases = Cases::default();
1099
- function.body.visit_with(&mut cases);
1100
- cases.0
1405
+ let mut cases = Cases {
1406
+ js,
1407
+ found: Vec::new(),
1408
+ };
1409
+ function.visit(&mut cases);
1410
+ cases.found
1101
1411
  }
1102
1412
 
1103
1413
  /// Calls made by a function's own body, excluding nested functions.
1104
- #[derive(Default)]
1105
- struct Calls(Vec<CallExpr>);
1414
+ struct Calls<'a> {
1415
+ js: ast::Script<'a>,
1416
+ found: Vec<&'a CallExpression<'a>>,
1417
+ }
1106
1418
 
1107
- impl Visit for Calls {
1108
- fn visit_function(&mut self, _: &Function) {}
1109
- fn visit_class(&mut self, _: &Class) {}
1110
- fn visit_call_expr(&mut self, call: &CallExpr) {
1111
- self.0.push(call.clone());
1112
- call.visit_children_with(self);
1419
+ impl<'a> Visit<'a> for Calls<'a> {
1420
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
1421
+ fn visit_class(&mut self, _: &Class<'a>) {}
1422
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
1423
+ walk_property(self, property);
1113
1424
  }
1425
+ fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
1426
+ if !is_optional_call(call) {
1427
+ self.found
1428
+ .push(self.js.lend(call, AstKind::as_call_expression));
1429
+ }
1430
+ walk::walk_call_expression(self, call);
1431
+ }
1432
+ }
1433
+
1434
+ /// Calls made by `statements`, excluding nested functions.
1435
+ fn calls_in<'a>(
1436
+ js: ast::Script<'a>,
1437
+ statements: impl IntoIterator<Item = &'a Statement<'a>>,
1438
+ ) -> Vec<&'a CallExpression<'a>> {
1439
+ let mut calls = Calls {
1440
+ js,
1441
+ found: Vec::new(),
1442
+ };
1443
+ for statement in statements {
1444
+ calls.visit_statement(statement);
1445
+ }
1446
+ calls.found
1114
1447
  }
1115
1448
 
1116
- fn calls_of(function: &Function) -> Vec<CallExpr> {
1117
- let mut calls = Calls::default();
1118
- function.body.visit_with(&mut calls);
1119
- calls.0
1449
+ fn calls_of<'a>(js: ast::Script<'a>, function: &Body<'a>) -> Vec<&'a CallExpression<'a>> {
1450
+ calls_in(js, function.statements())
1120
1451
  }
1121
1452
 
1122
1453
  /// A call's target, resolved through helper functions.
1123
- struct Invocation {
1124
- callee: Option<Id>,
1454
+ struct Invocation<'a> {
1455
+ callee: Option<Callee<'a>>,
1125
1456
  /// Whether it invokes `callee.call(receiver, ...)`.
1126
1457
  method: bool,
1127
1458
  /// Intermediate helper frames, innermost first.
@@ -1132,10 +1463,23 @@ struct Invocation {
1132
1463
  /// Whether the final argument is an array literal containing the arguments passed to `callee`.
1133
1464
  listed: bool,
1134
1465
  /// The array slot the called function is read from, if any.
1135
- slot: Option<(Id, usize)>,
1466
+ slot: Option<(Binding<'a>, usize)>,
1136
1467
  }
1137
1468
 
1138
- impl Invocation {
1469
+ impl Invocation<'_> {
1470
+ /// An unresolved call at `site`.
1471
+ fn at(site: Site) -> Self {
1472
+ Self {
1473
+ callee: None,
1474
+ method: false,
1475
+ helpers: Vec::new(),
1476
+ site,
1477
+ passed: None,
1478
+ listed: false,
1479
+ slot: None,
1480
+ }
1481
+ }
1482
+
1139
1483
  /// The frames of the call made from `caller`, innermost first.
1140
1484
  fn frames(&self, caller: Name) -> Vec<Call> {
1141
1485
  let mut frames = self.helpers.clone();
@@ -1147,224 +1491,186 @@ impl Invocation {
1147
1491
  }
1148
1492
  }
1149
1493
 
1150
- /// Recovers the XOR mask and call cases of a selector-based helper. Calls can use `Reflect.apply(f,
1151
- /// _, list)` or `f(a, b)` with later parameters forwarded in order.
1152
- ///
1153
- /// Handles copied selectors such as `(s = [selector], mask ^ s[0])`, indirect references to
1154
- /// `apply`, copied arguments such as `(g = [f, a], (0, g[0])(g[1]))`, and masks or labels computed
1155
- /// from constants.
1156
- struct Applier {
1494
+ /// A `switch (selector ^ mask)` whose case labels each select a `T`.
1495
+ struct Selection<T> {
1157
1496
  mask: f64,
1158
- cases: Vec<ApplierCase>,
1497
+ cases: Vec<(f64, T)>,
1159
1498
  }
1160
1499
 
1161
- struct ApplierCase {
1162
- label: f64,
1163
- site: Site,
1500
+ impl<T: Copy> Selection<T> {
1501
+ /// The case `selector` selects.
1502
+ fn select(&self, selector: f64) -> Option<T> {
1503
+ let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1504
+ self.cases
1505
+ .iter()
1506
+ .find(|(label, _)| *label == chosen)
1507
+ .map(|&(_, case)| case)
1508
+ }
1164
1509
  }
1165
1510
 
1166
- impl Applier {
1167
- fn new(function: &Function, constants: &HashMap<Id, f64>) -> Option<Self> {
1168
- let parameters = parameters(function)?;
1169
- let [selector, applied, rest @ ..] = parameters.as_slice() else {
1170
- return None;
1171
- };
1172
- let (mask, switch, copies) = selection(function, selector, constants)?;
1173
- // Match `f(a, b)` when arguments follow parameter order.
1174
- let passes_on = |call: &CallExpr| {
1175
- let Some(callee) = call.callee.as_expr() else {
1176
- return false;
1177
- };
1178
- let (callee, _) = undetached(callee, constants);
1179
- copies.resolve(callee).as_ref() == Some(applied)
1180
- && call.args.len() <= rest.len()
1181
- && call.args.iter().zip(rest).all(|(argument, parameter)| {
1182
- argument.spread.is_none()
1183
- && copies.resolve(&argument.expr).as_ref() == Some(parameter)
1511
+ /// Recovers the `Reflect.apply` call site of each case of a selector-based helper. Calls can use
1512
+ /// `Reflect.apply(f, _, list)` or `f(a, b)` with later parameters forwarded in order.
1513
+ ///
1514
+ /// Handles copied selectors such as `(s = [selector], mask ^ s[0])`, indirect references to
1515
+ /// `apply`, copied arguments such as `(g = [f, a], (0, g[0])(g[1]))`, and masks or labels computed
1516
+ /// from constants.
1517
+ fn applier<'a>(function: &Body<'a>, constants: &Constants<'a>) -> Option<Selection<Site>> {
1518
+ let parameters = function.parameters()?;
1519
+ let [selector, applied, rest @ ..] = parameters.as_slice() else {
1520
+ return None;
1521
+ };
1522
+ let (mask, switch, copies) = selection(function, *selector, constants)?;
1523
+ let is = |binding: Option<Binding<'a>>, parameter: &SymbolId| {
1524
+ binding == Some(Binding::Symbol(*parameter))
1525
+ };
1526
+ // Match `f(a, b)` when arguments follow parameter order.
1527
+ let passes_on = |call: &CallExpression<'a>| {
1528
+ let (callee, _) = undetached(&call.callee, constants);
1529
+ is(copies.resolve(callee), applied)
1530
+ && call.arguments.len() <= rest.len()
1531
+ && call
1532
+ .arguments
1533
+ .iter()
1534
+ .zip(rest)
1535
+ .all(|(argument, parameter)| match argument {
1536
+ Argument::SpreadElement(_) => false,
1537
+ argument => is(copies.resolve(argument.to_expression()), parameter),
1184
1538
  })
1539
+ };
1540
+ let applies = |call: &CallExpression<'a>| {
1541
+ let [first, _, third] = &call.arguments[..] else {
1542
+ return false;
1185
1543
  };
1186
- let applies = |call: &CallExpr| {
1187
- let [first, _, third] = &call.args[..] else {
1188
- return false;
1544
+ member(call.callee.without_parentheses()).is_some()
1545
+ && is(constants.binding(ast::argument_expression(first)), applied)
1546
+ && rest
1547
+ .first()
1548
+ .is_some_and(|list| is(constants.binding(ast::argument_expression(third)), list))
1549
+ };
1550
+ let cases: Vec<(f64, Site)> = switch
1551
+ .cases
1552
+ .iter()
1553
+ .filter_map(|case| {
1554
+ let label = number(case.test.as_ref()?, constants)?;
1555
+ let [Statement::ReturnStatement(returned)] = &case.consequent[..] else {
1556
+ return None;
1189
1557
  };
1190
- call.callee
1191
- .as_expr()
1192
- .is_some_and(|callee| callee.unwrap_parens().is_member())
1193
- && name(&first.expr).as_ref() == Some(applied)
1194
- && rest
1195
- .first()
1196
- .is_some_and(|list| name(&third.expr).as_ref() == Some(list))
1197
- };
1198
- let cases: Vec<ApplierCase> = switch
1199
- .cases
1200
- .iter()
1201
- .filter_map(|case| {
1202
- let label = number(case.test.as_deref()?, constants)?;
1203
- let [Stmt::Return(returned)] = &case.cons[..] else {
1204
- return None;
1205
- };
1206
- let Some(Expr::Call(call)) = returned.arg.as_deref().map(Expr::unwrap_parens)
1207
- else {
1208
- return None;
1209
- };
1210
- (applies(call) || passes_on(call)).then(|| ApplierCase {
1211
- label,
1212
- site: Site::new(call),
1213
- })
1214
- })
1215
- .collect();
1216
- // Other cases may call more helpers. Selectors routed there have no case in this helper.
1217
- (!cases.is_empty()).then_some(Self { mask, cases })
1218
- }
1219
-
1220
- /// The `Reflect.apply` call in the case `selector` selects.
1221
- fn call(&self, selector: f64) -> Option<Site> {
1222
- let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1223
- self.cases
1224
- .iter()
1225
- .find(|case| case.label == chosen)
1226
- .map(|case| case.site)
1227
- }
1558
+ let Expression::CallExpression(call) =
1559
+ returned.argument.as_ref()?.without_parentheses()
1560
+ else {
1561
+ return None;
1562
+ };
1563
+ (applies(call) || passes_on(call)).then(|| (label, Site::new(call)))
1564
+ })
1565
+ .collect();
1566
+ // Other cases may call more helpers. Selectors routed there have no case in this helper.
1567
+ (!cases.is_empty()).then_some(Selection { mask, cases })
1228
1568
  }
1229
1569
 
1230
1570
  /// Extracts the mask and switch from a function containing `switch (selector ^ mask)`, with
1231
1571
  /// optional leading local declarations. Also tracks arrays used to copy selector names, as in `(s =
1232
1572
  /// [selector], mask ^ s[0])`.
1233
- fn selection<'function, 'constants>(
1234
- function: &'function Function,
1235
- selector: &Id,
1236
- constants: &'constants HashMap<Id, f64>,
1237
- ) -> Option<(f64, &'function SwitchStmt, Copies<'constants>)> {
1238
- let [Stmt::Switch(switch)] = after_declarations(&function.body.as_ref()?.stmts) else {
1573
+ fn selection<'a, 'c>(
1574
+ function: &Body<'a>,
1575
+ selector: SymbolId,
1576
+ constants: &'c Constants<'a>,
1577
+ ) -> Option<(f64, &'a SwitchStatement<'a>, Copies<'a, 'c>)> {
1578
+ let Statement::SwitchStatement(switch) = function.only_statement()? else {
1239
1579
  return None;
1240
1580
  };
1241
- let mut discriminant = switch.discriminant.unwrap_parens();
1581
+ let mut discriminant = switch.discriminant.without_parentheses();
1242
1582
  let mut copies = Copies::new(constants);
1243
- if let Expr::Seq(sequence) = discriminant {
1244
- let (last, before) = sequence.exprs.split_last()?;
1583
+ if let Expression::SequenceExpression(sequence) = discriminant {
1584
+ let (last, before) = sequence.expressions.split_last()?;
1245
1585
  for expression in before {
1246
1586
  copies.record(expression);
1247
1587
  }
1248
- discriminant = last.unwrap_parens();
1588
+ discriminant = last.without_parentheses();
1589
+ }
1590
+ let Expression::BinaryExpression(xor) = discriminant else {
1591
+ return None;
1592
+ };
1593
+ if xor.operator != BinaryOperator::BitwiseXOR {
1594
+ return None;
1249
1595
  }
1250
- let xor = discriminant
1251
- .as_bin()
1252
- .filter(|xor| xor.op == BinaryOp::BitXor)?;
1253
- let is_selector = |expression: &Expr| copies.resolve(expression).as_ref() == Some(selector);
1254
- let mask = match (xor.left.unwrap_parens(), xor.right.unwrap_parens()) {
1596
+ let is_selector =
1597
+ |expression: &Expression<'a>| copies.resolve(expression) == Some(Binding::Symbol(selector));
1598
+ let mask = match (
1599
+ xor.left.without_parentheses(),
1600
+ xor.right.without_parentheses(),
1601
+ ) {
1255
1602
  (other, mask) | (mask, other) if is_selector(other) => number(mask, constants)?,
1256
1603
  _ => return None,
1257
1604
  };
1258
1605
  Some((mask, switch, copies))
1259
1606
  }
1260
1607
 
1261
- /// Returns `statements` after skipping leading local declarations without initializers.
1262
- fn after_declarations(statements: &[Stmt]) -> &[Stmt] {
1263
- let start = statements
1264
- .iter()
1265
- .position(|statement| {
1266
- !matches!(statement, Stmt::Decl(Decl::Var(declaration))
1267
- if declaration.decls.iter().all(|declarator| declarator.init.is_none()))
1268
- })
1269
- .unwrap_or(statements.len());
1270
- &statements[start..]
1271
- }
1272
-
1273
- /// A function combining several original functions, selected by its first parameter:
1608
+ /// Recovers the original functions of a function that combines several, selected by its first
1609
+ /// parameter:
1274
1610
  ///
1275
1611
  /// ```js
1276
1612
  /// function merged(selector, a) { switch (selector ^ mask) { case 1: { <original> } return; } }
1277
1613
  /// ```
1278
1614
  ///
1279
1615
  /// Both V8 and JavaScriptCore name every original function's frame after the merged function.
1280
- /// Recovery gives each original a fresh binding with that name and keeps the other parameters.
1281
- struct Merged {
1282
- mask: f64,
1283
- /// Original function for each case label, indexed into [`Script::originals`].
1284
- cases: Vec<(f64, Id)>,
1285
- }
1286
-
1287
- impl Merged {
1288
- fn new(
1289
- name: &Id,
1290
- function: &Function,
1291
- constants: &HashMap<Id, f64>,
1292
- ) -> Option<(Self, Vec<(Id, Function)>)> {
1293
- let selector = function.params.first()?.pat.as_ident()?.to_id();
1294
- let (mask, switch, _) = selection(function, &selector, constants)?;
1295
- let block = function.body.as_ref()?;
1296
- let mut cases = Vec::new();
1297
- let mut originals = Vec::new();
1298
- for (at, case) in switch.cases.iter().enumerate() {
1299
- let label = case
1300
- .test
1301
- .as_deref()
1302
- .and_then(|test| number(test, constants));
1303
- // Labels sharing a body fall through to it.
1304
- let body = switch.cases[at..]
1305
- .iter()
1306
- .map(|case| &case.cons)
1307
- .find(|body| !body.is_empty());
1308
- let (Some(label), Some(body)) = (label, body) else {
1309
- continue;
1310
- };
1311
- let mut statements: Vec<Stmt> = match &body[..] {
1312
- [Stmt::Block(original), rest @ ..] => {
1313
- original.stmts.iter().chain(rest).cloned().collect()
1314
- }
1315
- _ => body.clone(),
1316
- };
1317
- if let Some(Stmt::Return(ReturnStmt { arg: None, .. })) = statements.last() {
1318
- statements.pop();
1319
- }
1320
- let original = Function {
1321
- params: function.params[1..].to_vec(),
1322
- span: function.span,
1323
- ctxt: function.ctxt,
1324
- body: Some(BlockStmt {
1325
- span: block.span,
1326
- ctxt: block.ctxt,
1327
- stmts: statements,
1328
- }),
1329
- ..Function::default()
1330
- };
1331
- let binding = (
1332
- name.0.clone(),
1333
- SyntaxContext::empty().apply_mark(Mark::new()),
1334
- );
1335
- cases.push((label, binding.clone()));
1336
- originals.push((binding, original));
1337
- }
1338
- (!cases.is_empty()).then_some((Self { mask, cases }, originals))
1339
- }
1340
-
1341
- /// Returns the original function selected by `selector`.
1342
- fn original(&self, selector: f64) -> Option<&Id> {
1343
- let chosen = f64::from(js::int32(self.mask) ^ js::int32(selector));
1344
- self.cases
1616
+ /// Each original keeps the merged function's other parameters.
1617
+ fn merged<'a>(function: &Body<'a>, constants: &Constants<'a>) -> Option<Selection<Body<'a>>> {
1618
+ let selector = plain_parameter(function.parameters.first()?)?;
1619
+ let (mask, switch, _) = selection(function, selector, constants)?;
1620
+ let mut cases = Vec::new();
1621
+ for (at, case) in switch.cases.iter().enumerate() {
1622
+ let label = case.test.as_ref().and_then(|test| number(test, constants));
1623
+ // Labels sharing a body fall through to it.
1624
+ let body = switch.cases[at..]
1345
1625
  .iter()
1346
- .find(|(label, _)| *label == chosen)
1347
- .map(|(_, original)| original)
1626
+ .map(|case| &case.consequent)
1627
+ .find(|body| !body.is_empty());
1628
+ let (Some(label), Some(body)) = (label, body) else {
1629
+ continue;
1630
+ };
1631
+ let (mut head, mut tail): (&[Statement], &[Statement]) = match &body[..] {
1632
+ [Statement::BlockStatement(original), rest @ ..] => (&original.body[..], rest),
1633
+ body => (body, &[]),
1634
+ };
1635
+ let last = if tail.is_empty() {
1636
+ &mut head
1637
+ } else {
1638
+ &mut tail
1639
+ };
1640
+ if let [statements @ .., Statement::ReturnStatement(returned)] = *last
1641
+ && returned.argument.is_none()
1642
+ {
1643
+ *last = statements;
1644
+ }
1645
+ let body = Body {
1646
+ parameters: &function.parameters[1..],
1647
+ rest: function.rest,
1648
+ prologue: false,
1649
+ head,
1650
+ tail,
1651
+ };
1652
+ cases.push((label, body));
1348
1653
  }
1654
+ (!cases.is_empty()).then_some(Selection { mask, cases })
1349
1655
  }
1350
1656
 
1351
1657
  /// Storage location in a scope: a binding or a constant array slot.
1352
- #[derive(Clone, Debug, PartialEq, Eq, Hash)]
1353
- enum Holder {
1354
- Name(Id),
1355
- Slot(Id, usize),
1658
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1659
+ enum Holder<'a> {
1660
+ Name(Binding<'a>),
1661
+ Slot(Binding<'a>, usize),
1356
1662
  }
1357
1663
 
1358
1664
  /// A function's local aliases, string constants, and forwarders.
1359
- struct Scope<'script> {
1360
- appliers: &'script Appliers,
1665
+ struct Scope<'a, 's> {
1666
+ appliers: &'s Appliers<'a>,
1361
1667
  /// V8's name prefix for functions assigned here, such as `Owner.`.
1362
1668
  prefix: String,
1363
- forwarders: Forwarders,
1669
+ forwarders: Forwarders<'a>,
1364
1670
  /// Assignment count for each storage location. Only values assigned once are known.
1365
- assigned: HashMap<Holder, usize>,
1366
- aliases: HashMap<Id, Id>,
1367
- strings: HashMap<Id, String>,
1671
+ assigned: HashMap<Holder<'a>, usize>,
1672
+ aliases: HashMap<Binding<'a>, Binding<'a>>,
1673
+ strings: HashMap<Binding<'a>, &'a str>,
1368
1674
  }
1369
1675
 
1370
1676
  /// Frames for an object function that forwards its first parameter with the remaining arguments.
@@ -1376,14 +1682,13 @@ struct Forwarder {
1376
1682
  plain: Vec<Call>,
1377
1683
  }
1378
1684
 
1379
- impl<'script> Scope<'script> {
1685
+ impl<'a, 's> Scope<'a, 's> {
1380
1686
  /// `name` is empty for anonymous functions. V8 prefixes the names of functions assigned
1381
1687
  /// inside a capitalized function with its name, as it does for constructors.
1382
- fn new(name: &str, function: &Function, appliers: &'script Appliers) -> Self {
1383
- let constructor = name.starts_with(char::is_uppercase);
1688
+ fn new(name: &str, function: &Body<'a>, appliers: &'s Appliers<'a>) -> Self {
1384
1689
  let mut scope = Self {
1385
1690
  appliers,
1386
- prefix: if constructor {
1691
+ prefix: if name.starts_with(char::is_uppercase) {
1387
1692
  format!("{name}.")
1388
1693
  } else {
1389
1694
  String::new()
@@ -1393,157 +1698,199 @@ impl<'script> Scope<'script> {
1393
1698
  aliases: HashMap::new(),
1394
1699
  strings: HashMap::new(),
1395
1700
  };
1396
- function.body.visit_with(&mut scope);
1701
+ function.visit(&mut scope);
1397
1702
  scope.forwarders.retain_assigned_once(&scope.assigned);
1398
1703
  scope
1399
1704
  }
1400
1705
 
1401
- fn target(&self, call: &CallExpr) -> Result<Invocation> {
1402
- let mut target = Invocation {
1403
- callee: None,
1404
- method: false,
1405
- helpers: Vec::new(),
1406
- site: Site::new(call),
1407
- passed: None,
1408
- listed: false,
1409
- slot: None,
1410
- };
1411
- let Some(callee) = call.callee.as_expr() else {
1412
- return Ok(target);
1706
+ fn js(&self) -> ast::Script<'a> {
1707
+ self.appliers.js()
1708
+ }
1709
+
1710
+ fn target(&self, call: &'a CallExpression<'a>) -> Result<Invocation<'a>> {
1711
+ self.resolve(call, None)
1712
+ }
1713
+
1714
+ /// Resolves `call`, reading arguments through `copies` when given.
1715
+ fn resolve(
1716
+ &self,
1717
+ call: &'a CallExpression<'a>,
1718
+ copies: Option<&Copies<'a, '_>>,
1719
+ ) -> Result<Invocation<'a>> {
1720
+ let site = Site::new(call);
1721
+ let arguments = Arguments {
1722
+ list: &call.arguments,
1723
+ copies,
1413
1724
  };
1414
- let arguments = call.args.len();
1415
- let (callee, detached) = undetached(callee, &self.appliers.constants);
1725
+ let (callee, detached) = undetached(&call.callee, &self.appliers.constants);
1416
1726
  // Resolve the function called by `target`.
1417
- let mut function = match callee {
1418
- Expr::Ident(name) => {
1419
- if let Some(original) = self.merged_call(name, call) {
1420
- // The original function uses the merged function's frame at this call site.
1421
- let mut target = self.target(&original)?;
1422
- target.site = Site::new(call);
1423
- return Ok(target);
1424
- }
1425
- if let Some((applied, function)) = self.applier_call(name, call)? {
1426
- target = applied;
1427
- Some(function)
1428
- } else {
1429
- target.passed = Some(arguments);
1430
- Some(callee)
1431
- }
1727
+ if let Expression::Identifier(name) = callee {
1728
+ let binding = self.js().binding(name);
1729
+ if let Some((original, arguments)) = self.merged_call(binding, arguments) {
1730
+ // The original function uses the merged function's frame at this call site.
1731
+ let original = Callee::Original(original);
1732
+ return self.named(original, Operand::Resolved(original), arguments, site);
1432
1733
  }
1734
+ return self.named(
1735
+ Callee::Binding(binding),
1736
+ Operand::Expression(callee),
1737
+ arguments,
1738
+ site,
1739
+ );
1740
+ }
1741
+ let mut target = Invocation::at(site);
1742
+ let count = arguments.list.len();
1743
+ let function = match member(callee) {
1433
1744
  // Some builds keep the key in a local: `handler[c](this)` with `c = "call"`.
1434
- Expr::Member(member)
1435
- if !detached && member.obj.is_ident() && self.key(&member.prop) == Some("call") =>
1745
+ Some(member)
1746
+ if !detached
1747
+ && matches!(member.object(), Expression::Identifier(_))
1748
+ && self.key(member) == Some("call") =>
1436
1749
  {
1437
1750
  target.method = true;
1438
- target.passed = Some(arguments.saturating_sub(1));
1439
- Some(&*member.obj)
1751
+ target.passed = Some(count.saturating_sub(1));
1752
+ Some(Operand::Expression(member.object()))
1440
1753
  }
1441
1754
  // The first argument to a forwarder is the function it calls.
1442
- Expr::Member(member) if let Some(forwarder) = self.member_forwarder(member) => {
1755
+ Some(member) if let Some(forwarder) = self.member_forwarder(member) => {
1443
1756
  target.helpers = if detached {
1444
1757
  forwarder.plain.clone()
1445
1758
  } else {
1446
1759
  forwarder.method.clone()
1447
1760
  };
1448
- target.passed = Some(arguments.saturating_sub(1));
1449
- call.args.first().map(|first| &*first.expr)
1761
+ target.passed = Some(count.saturating_sub(1));
1762
+ arguments
1763
+ .list
1764
+ .first()
1765
+ .map(|first| arguments.argument(first))
1450
1766
  }
1451
1767
  // Resolve an array-stored function, as in `(0, slots[i])(f, a)`.
1452
- Expr::Member(member) if self.slot(member).is_some() => {
1453
- target.passed = Some(arguments);
1454
- Some(callee)
1768
+ Some(member) if self.slot(member).is_some() => {
1769
+ target.passed = Some(count);
1770
+ Some(Operand::Expression(callee))
1455
1771
  }
1456
1772
  _ => None,
1457
1773
  };
1774
+ Ok(self.finish(target, function, arguments))
1775
+ }
1776
+
1777
+ /// Resolves a call to the function `callee`, read as `operand`, directly or through a call
1778
+ /// helper.
1779
+ fn named(
1780
+ &self,
1781
+ callee: Callee<'a>,
1782
+ operand: Operand<'a>,
1783
+ arguments: Arguments<'a, '_>,
1784
+ site: Site,
1785
+ ) -> Result<Invocation<'a>> {
1786
+ let (target, function) = match self.applier_call(callee, arguments, site)? {
1787
+ Some(applied) => applied,
1788
+ None => {
1789
+ let mut target = Invocation::at(site);
1790
+ target.passed = Some(arguments.list.len());
1791
+ (target, operand)
1792
+ }
1793
+ };
1794
+ Ok(self.finish(target, Some(function), arguments))
1795
+ }
1796
+
1797
+ /// Follows stored forwarders from `function`, then records the resolved callee and slot.
1798
+ fn finish(
1799
+ &self,
1800
+ mut target: Invocation<'a>,
1801
+ mut function: Option<Operand<'a>>,
1802
+ arguments: Arguments<'a, '_>,
1803
+ ) -> Invocation<'a> {
1458
1804
  // A stored forwarder calls its first argument with the remaining arguments.
1459
- while let Some(expression) = function
1460
- && let Some(frames) = self.held_by(expression)
1461
- && let Some(first) = handed(call, &target).and_then(|handed| handed.first().copied())
1805
+ while let Some(operand) = function
1806
+ && let Some(frames) = self.held_by(operand)
1807
+ && let Some(first) =
1808
+ handed(arguments, &target).and_then(|handed| handed.first().copied())
1462
1809
  {
1463
1810
  function = Some(first);
1464
1811
  target.helpers = frames.iter().cloned().chain(target.helpers).collect();
1465
1812
  target.passed = target.passed.map(|passed| passed - 1);
1466
1813
  }
1467
- target.callee = function.and_then(name);
1814
+ target.callee = function.and_then(|function| function.callee(&self.appliers.constants));
1468
1815
  target.slot = function.and_then(|function| match self.holder(function)? {
1469
1816
  Holder::Slot(array, index) => Some((array, index)),
1470
1817
  Holder::Name(_) => None,
1471
1818
  });
1472
- Ok(target)
1473
- }
1474
-
1475
- /// Converts `merged(selector, a, b)` to `original(a, b)` for the selected original function.
1476
- fn merged_call(&self, callee: &Ident, call: &CallExpr) -> Option<CallExpr> {
1477
- let merged = self.appliers.merged.get(&callee.to_id())?;
1478
- let (selector, arguments) = call.args.split_first()?;
1479
- let (name, context) = merged
1480
- .original(self.appliers.number(&selector.expr)?)?
1481
- .clone();
1482
- Some(CallExpr {
1483
- callee: Callee::Expr(Box::new(Expr::Ident(Ident::new(
1484
- name,
1485
- callee.span,
1486
- context,
1487
- )))),
1488
- args: arguments.to_vec(),
1489
- ..call.clone()
1490
- })
1819
+ target
1820
+ }
1821
+
1822
+ /// Resolves `merged(selector, a, b)` to the selected original function and the arguments
1823
+ /// `a, b`.
1824
+ fn merged_call<'c>(
1825
+ &self,
1826
+ callee: Binding<'a>,
1827
+ arguments: Arguments<'a, 'c>,
1828
+ ) -> Option<(usize, Arguments<'a, 'c>)> {
1829
+ let merged = self.appliers.merged.get(&callee)?;
1830
+ let (selector, rest) = arguments.list.split_first()?;
1831
+ let original = merged.select(self.appliers.number(arguments.argument(selector))?)?;
1832
+ Some((
1833
+ original,
1834
+ Arguments {
1835
+ list: rest,
1836
+ copies: arguments.copies,
1837
+ },
1838
+ ))
1491
1839
  }
1492
1840
 
1493
1841
  /// Resolves `applier(selector, f, [args])` or `applier(selector, f, a, b)` through a call
1494
1842
  /// helper. Also returns the called function `f`.
1495
- fn applier_call<'call>(
1843
+ fn applier_call(
1496
1844
  &self,
1497
- callee: &Ident,
1498
- call: &'call CallExpr,
1499
- ) -> Result<Option<(Invocation, &'call Expr)>> {
1845
+ callee: Callee<'a>,
1846
+ arguments: Arguments<'a, '_>,
1847
+ site: Site,
1848
+ ) -> Result<Option<(Invocation<'a>, Operand<'a>)>> {
1500
1849
  let (Some(applier), [selector, function, passed @ ..]) =
1501
- (self.appliers.helpers.get(&callee.to_id()), &call.args[..])
1850
+ (self.appliers.helpers.get(&callee), arguments.list)
1502
1851
  else {
1503
1852
  return Ok(None);
1504
1853
  };
1505
- let Some(selector) = self.appliers.number(&selector.expr) else {
1854
+ let Some(selector) = self.appliers.number(arguments.argument(selector)) else {
1506
1855
  return Ok(None);
1507
1856
  };
1857
+ let name = self.appliers.name(callee);
1508
1858
  let inner = applier
1509
- .call(selector)
1510
- .with_context(|| format!("{} has no case for selector {selector}", callee.sym))?;
1859
+ .select(selector)
1860
+ .with_context(|| format!("{name} has no case for selector {selector}"))?;
1511
1861
  let (passed, listed) = match passed {
1512
- [list] if let Some(list) = list.expr.unwrap_parens().as_array() => {
1513
- (list.elems.len(), true)
1862
+ [list] if let Some(list) = array(ast::argument_expression(list)) => {
1863
+ (list.elements.len(), true)
1514
1864
  }
1515
1865
  passed => (passed.len(), false),
1516
1866
  };
1517
- let invocation = Invocation {
1518
- callee: None,
1519
- method: false,
1520
- helpers: vec![Call {
1521
- name: Name::same(callee.sym.to_string()),
1522
- site: inner,
1523
- }],
1524
- site: Site::new(call),
1525
- passed: Some(passed),
1526
- listed,
1527
- slot: None,
1528
- };
1529
- Ok(Some((invocation, &function.expr)))
1867
+ let mut invocation = Invocation::at(site);
1868
+ invocation.helpers = vec![Call {
1869
+ name: Name::same(name.to_owned()),
1870
+ site: inner,
1871
+ }];
1872
+ invocation.passed = Some(passed);
1873
+ invocation.listed = listed;
1874
+ Ok(Some((invocation, arguments.argument(function))))
1530
1875
  }
1531
1876
 
1532
1877
  /// Resolves a member key from a literal or a local string binding.
1533
- fn key<'member>(&'member self, property: &'member MemberProp) -> Option<&'member str> {
1534
- match property {
1535
- MemberProp::Computed(computed) if let Expr::Ident(name) = &*computed.expr => {
1536
- self.strings.get(&name.to_id()).map(String::as_str)
1878
+ fn key(&self, member: &MemberExpression<'a>) -> Option<&'a str> {
1879
+ match member {
1880
+ MemberExpression::ComputedMemberExpression(computed)
1881
+ if let Expression::Identifier(name) = &computed.expression =>
1882
+ {
1883
+ self.strings.get(&self.js().binding(name)).copied()
1537
1884
  }
1538
- property => ast::member_str(property),
1885
+ member => ast::member_str(member),
1539
1886
  }
1540
1887
  }
1541
1888
 
1542
1889
  /// Finds the forwarder read by `object.key`.
1543
- fn member_forwarder(&self, member: &MemberExpr) -> Option<&Forwarder> {
1890
+ fn member_forwarder(&self, member: &'a MemberExpression<'a>) -> Option<&Forwarder> {
1544
1891
  let key = (
1545
- self.holder(&member.obj)?,
1546
- self.key(&member.prop)?.to_owned(),
1892
+ self.holder(Operand::Expression(member.object()))?,
1893
+ self.key(member)?,
1547
1894
  );
1548
1895
  self.forwarders
1549
1896
  .on_objects
@@ -1551,74 +1898,85 @@ impl<'script> Scope<'script> {
1551
1898
  .or_else(|| self.appliers.forwarders.on_objects.get(&key))
1552
1899
  }
1553
1900
 
1554
- /// Returns frames for the stored forwarder read by `expression`.
1555
- fn held_by(&self, expression: &Expr) -> Option<&Vec<Call>> {
1556
- let holder = self.holder(expression)?;
1901
+ /// Returns frames for the stored forwarder read by `operand`.
1902
+ fn held_by(&self, operand: Operand<'a>) -> Option<&Vec<Call>> {
1903
+ let holder = self.holder(operand)?;
1557
1904
  self.forwarders
1558
1905
  .held
1559
1906
  .get(&holder)
1560
1907
  .or_else(|| self.appliers.forwarders.held.get(&holder))
1561
1908
  }
1562
1909
 
1563
- /// Resolves the value read by `expression`, following local aliases.
1564
- fn holder(&self, expression: &Expr) -> Option<Holder> {
1565
- match expression.unwrap_parens() {
1566
- Expr::Ident(name) => Some(Holder::Name(self.object(&name.to_id()))),
1567
- Expr::Member(member) => self.slot(member),
1568
- _ => None,
1910
+ /// Resolves the value read by `operand`, following local aliases. An original function is
1911
+ /// never stored.
1912
+ fn holder(&self, operand: Operand<'a>) -> Option<Holder<'a>> {
1913
+ match operand {
1914
+ Operand::Expression(expression) => match expression.without_parentheses() {
1915
+ Expression::Identifier(name) => {
1916
+ Some(Holder::Name(self.object(self.js().binding(name))))
1917
+ }
1918
+ expression => self.slot(member(expression)?),
1919
+ },
1920
+ Operand::Resolved(Callee::Binding(binding)) => Some(Holder::Name(self.object(binding))),
1921
+ Operand::Resolved(Callee::Original(_)) => None,
1569
1922
  }
1570
1923
  }
1571
1924
 
1572
1925
  /// Resolves `array[index]` when the index is constant.
1573
- fn slot(&self, member: &MemberExpr) -> Option<Holder> {
1574
- let array = member.obj.as_ident()?;
1575
- let index = self.appliers.number(&member.prop.as_computed()?.expr)?;
1926
+ fn slot(&self, member: &MemberExpression<'a>) -> Option<Holder<'a>> {
1927
+ let MemberExpression::ComputedMemberExpression(member) = member else {
1928
+ return None;
1929
+ };
1930
+ let Expression::Identifier(array) = &member.object else {
1931
+ return None;
1932
+ };
1933
+ let index = number(&member.expression, &self.appliers.constants)?;
1576
1934
  Some(Holder::Slot(
1577
- self.object(&array.to_id()),
1935
+ self.object(self.js().binding(array)),
1578
1936
  ast::array_index(index)?,
1579
1937
  ))
1580
1938
  }
1581
1939
 
1582
1940
  /// Resolves the object held by `name` through local copies.
1583
- fn object(&self, name: &Id) -> Id {
1941
+ fn object(&self, name: Binding<'a>) -> Binding<'a> {
1584
1942
  let mut name = name;
1585
1943
  for _ in 0..self.aliases.len() {
1586
- match self.aliases.get(name) {
1587
- Some(original) => name = original,
1944
+ match self.aliases.get(&name) {
1945
+ Some(&original) => name = original,
1588
1946
  None => break,
1589
1947
  }
1590
1948
  }
1591
- name.to_owned()
1949
+ name
1592
1950
  }
1593
1951
 
1594
1952
  /// Records the value stored by assigning `value` to `holder`.
1595
- fn bind(&mut self, holder: Holder, value: &Expr) {
1596
- *self.assigned.entry(holder.clone()).or_default() += 1;
1953
+ fn bind(&mut self, holder: Holder<'a>, value: &'a Expression<'a>) {
1954
+ *self.assigned.entry(holder).or_default() += 1;
1597
1955
  // Chained assignments store the innermost value in each target.
1598
- let mut value = value.unwrap_parens();
1599
- while let Expr::Assign(inner) = value
1600
- && inner.op == AssignOp::Assign
1956
+ let mut value = value.without_parentheses();
1957
+ while let Expression::AssignmentExpression(inner) = value
1958
+ && inner.operator == AssignmentOperator::Assign
1601
1959
  {
1602
- value = inner.right.unwrap_parens();
1960
+ value = inner.right.without_parentheses();
1603
1961
  }
1604
- let forwarder = match value {
1605
- Expr::Member(member) if let Some(forwarder) = self.member_forwarder(member) => {
1962
+ let forwarder = match member(value) {
1963
+ Some(member) if let Some(forwarder) = self.member_forwarder(member) => {
1606
1964
  Some(forwarder.plain.clone())
1607
1965
  }
1608
- value => self.held_by(value).cloned(),
1966
+ _ => self.held_by(Operand::Expression(value)).cloned(),
1609
1967
  };
1610
1968
  if let Some(frames) = forwarder {
1611
1969
  self.forwarders.held.insert(holder, frames);
1612
1970
  return;
1613
1971
  }
1614
1972
  match (holder, value) {
1615
- (Holder::Name(name), Expr::Ident(original)) => {
1616
- self.aliases.insert(name, original.to_id());
1973
+ (Holder::Name(name), Expression::Identifier(original)) => {
1974
+ self.aliases.insert(name, self.js().binding(original));
1617
1975
  }
1618
- (holder, Expr::Object(object)) => self.literal(&holder, object),
1976
+ (holder, Expression::ObjectExpression(object)) => self.literal(holder, object),
1619
1977
  (Holder::Name(name), value) => {
1620
1978
  if let Some(text) = ast::static_str(value) {
1621
- self.strings.insert(name, text.to_owned());
1979
+ self.strings.insert(name, text);
1622
1980
  }
1623
1981
  }
1624
1982
  _ => {}
@@ -1627,26 +1985,20 @@ impl<'script> Scope<'script> {
1627
1985
 
1628
1986
  /// Records forwarders defined by an object literal assigned to `holder`. Uses property keys as
1629
1987
  /// function names, including computed keys.
1630
- fn literal(&mut self, holder: &Holder, object: &ObjectLit) {
1631
- for property in &object.props {
1632
- let (key, function) = match property.as_prop().map(|property| &**property) {
1633
- Some(Prop::KeyValue(property)) if let Expr::Fn(function) = &*property.value => {
1634
- (&property.key, &*function.function)
1635
- }
1636
- Some(Prop::Method(method)) => (&method.key, &*method.function),
1637
- _ => continue,
1638
- };
1639
- let Some(key) = ast::static_key_str(key) else {
1640
- continue;
1641
- };
1642
- if let Some(frames) = self.forwarder(function, Name::same(key.to_owned())) {
1988
+ fn literal(&mut self, holder: Holder<'a>, object: &'a ObjectExpression<'a>) {
1989
+ // Matches `key: function` properties and methods, but not accessors.
1990
+ for property in &object.properties {
1991
+ if let ObjectPropertyKind::ObjectProperty(property) = property
1992
+ && let Expression::FunctionExpression(function) = &property.value
1993
+ && property.kind == PropertyKind::Init
1994
+ && let Some(key) = ast::static_key_str(&property.key, property.computed)
1995
+ && let Some(frames) = self.forwarder(function, Name::same(key.to_owned()))
1996
+ {
1643
1997
  let forwarder = Forwarder {
1644
1998
  method: frames.clone(),
1645
1999
  plain: frames,
1646
2000
  };
1647
- self.forwarders
1648
- .on_objects
1649
- .insert((holder.clone(), key.to_owned()), forwarder);
2001
+ self.forwarders.on_objects.insert((holder, key), forwarder);
1650
2002
  }
1651
2003
  }
1652
2004
  }
@@ -1655,168 +2007,168 @@ impl<'script> Scope<'script> {
1655
2007
  /// later parameters. Accepts direct calls, array copies such as `(g = [f, b], (0, g[0])(a,
1656
2008
  /// g[1]))`, and call helpers. Extra parameters can act as locals. Allows local declarations
1657
2009
  /// before the call.
1658
- fn forwarder(&self, function: &Function, frame: Name) -> Option<Vec<Call>> {
1659
- let parameters = parameters(function)?;
2010
+ fn forwarder(&self, function: &'a Function<'a>, frame: Name) -> Option<Vec<Call>> {
2011
+ let constants = &self.appliers.constants;
2012
+ let function = Body::of(function);
2013
+ let parameters = function.parameters()?;
1660
2014
  let (first, rest) = parameters.split_first()?;
1661
- let mut arrays = Copies::new(&self.appliers.constants);
1662
- let [Stmt::Return(returned)] = after_declarations(&function.body.as_ref()?.stmts) else {
2015
+ let first = Binding::Symbol(*first);
2016
+ let mut arrays = Copies::new(constants);
2017
+ let Statement::ReturnStatement(returned) = function.only_statement()? else {
1663
2018
  return None;
1664
2019
  };
1665
- let mut value = returned.arg.as_deref()?.unwrap_parens();
1666
- if let Expr::Seq(sequence) = value {
1667
- let (last, before) = sequence.exprs.split_last()?;
2020
+ let mut value = returned.argument.as_ref()?.without_parentheses();
2021
+ if let Expression::SequenceExpression(sequence) = value {
2022
+ let (last, before) = sequence.expressions.split_last()?;
1668
2023
  for expression in before {
1669
2024
  // Obfuscation leaves expressions that do nothing.
1670
- if arrays.record(expression).is_none()
1671
- && !is_inert(expression, &self.appliers.constants)
1672
- {
2025
+ if arrays.record(expression).is_none() && !is_inert(expression, constants) {
1673
2026
  return None;
1674
2027
  }
1675
2028
  }
1676
- value = last.unwrap_parens();
2029
+ value = last.without_parentheses();
1677
2030
  }
1678
2031
  // Forwarded arguments must match the parameters after the target function.
1679
- let passes_on = |arguments: &[&Expr]| {
2032
+ let passes_on = |arguments: &[Operand<'a>]| {
1680
2033
  arguments.len() <= rest.len()
1681
2034
  && arguments.iter().zip(rest).all(|(argument, parameter)| {
1682
- arrays.resolve(argument).as_ref() == Some(parameter)
2035
+ arrays.resolve_operand(*argument) == Some(Binding::Symbol(*parameter))
1683
2036
  })
1684
2037
  };
1685
- let call = value.as_call()?;
1686
- let (callee, _) = undetached(call.callee.as_expr()?, &self.appliers.constants);
1687
- if call.args.iter().any(|argument| argument.spread.is_some()) {
2038
+ let Expression::CallExpression(call) = value else {
1688
2039
  return None;
1689
- }
1690
- let arguments: Vec<&Expr> = call.args.iter().map(|argument| &*argument.expr).collect();
1691
- if arrays.resolve(callee).as_ref() == Some(first) && passes_on(&arguments) {
2040
+ };
2041
+ let (callee, _) = undetached(&call.callee, constants);
2042
+ // A spread has no expression, so it rejects the call.
2043
+ let arguments: Vec<Operand<'a>> = call
2044
+ .arguments
2045
+ .iter()
2046
+ .map(|argument| argument.as_expression().map(Operand::Expression))
2047
+ .collect::<Option<_>>()?;
2048
+ if arrays.resolve(callee) == Some(first) && passes_on(&arguments) {
1692
2049
  return Some(vec![Call {
1693
2050
  name: frame,
1694
2051
  site: Site::new(call),
1695
2052
  }]);
1696
2053
  }
1697
2054
  // Resolve copied names passed through a call helper.
1698
- let mut call = call.clone();
1699
- for argument in &mut call.args {
1700
- let copied = match argument.expr.unwrap_parens() {
1701
- Expr::Array(list) => {
1702
- let mut list = list.clone();
1703
- for element in list.elems.iter_mut().flatten() {
1704
- if let Some(name) = arrays.resolve(&element.expr) {
1705
- *element.expr =
1706
- Expr::Ident(Ident::new(name.0, element.expr.span(), name.1));
1707
- }
1708
- }
1709
- Expr::Array(list)
1710
- }
1711
- expression => match arrays.resolve(expression) {
1712
- Some(name) => Expr::Ident(Ident::new(name.0, expression.span(), name.1)),
1713
- None => continue,
1714
- },
1715
- };
1716
- *argument.expr = copied;
1717
- }
1718
- let target = self.target(&call).ok()?;
2055
+ let target = self.resolve(call, Some(&arrays)).ok()?;
2056
+ let copied = Arguments {
2057
+ list: &call.arguments,
2058
+ copies: Some(&arrays),
2059
+ };
1719
2060
  (!target.helpers.is_empty()
1720
- && target.callee.as_ref() == Some(first)
1721
- && passes_on(&handed(&call, &target)?))
2061
+ && target.callee == Some(Callee::Binding(first))
2062
+ && passes_on(&handed(copied, &target)?))
1722
2063
  .then(|| target.frames(frame))
1723
2064
  }
1724
2065
  }
1725
2066
 
1726
2067
  /// Whether `expression` has no effect, such as obfuscation's `true`, constant comparisons and
1727
- /// Matches `void` expressions, including those using numeric `constants`.
1728
- fn is_inert(expression: &Expr, constants: &HashMap<Id, f64>) -> bool {
1729
- let inert = |expression: &Expr| is_inert(expression, constants);
1730
- match expression.unwrap_parens() {
1731
- Expr::Lit(_) => true,
1732
- Expr::Ident(name) => constants.contains_key(&name.to_id()),
1733
- Expr::Bin(binary) => inert(&binary.left) && inert(&binary.right),
1734
- Expr::Unary(unary) => unary.op != UnaryOp::Delete && inert(&unary.arg),
1735
- Expr::Array(array) => array
1736
- .elems
2068
+ /// `void` expressions, including those using numeric `constants`.
2069
+ fn is_inert<'a>(expression: &Expression<'a>, constants: &Constants<'a>) -> bool {
2070
+ let inert = |expression: &Expression<'a>| is_inert(expression, constants);
2071
+ match expression.without_parentheses() {
2072
+ expression if expression.is_literal() => true,
2073
+ Expression::Identifier(name) => constants
2074
+ .js
2075
+ .symbol(name)
2076
+ .is_some_and(|symbol| constants.values.contains_key(&symbol)),
2077
+ Expression::BinaryExpression(binary) => inert(&binary.left) && inert(&binary.right),
2078
+ Expression::LogicalExpression(logical) => inert(&logical.left) && inert(&logical.right),
2079
+ Expression::UnaryExpression(unary) => {
2080
+ unary.operator != UnaryOperator::Delete && inert(&unary.argument)
2081
+ }
2082
+ Expression::ArrayExpression(array) => array
2083
+ .elements
1737
2084
  .iter()
1738
- .all(|element| element.as_ref().is_none_or(|element| inert(&element.expr))),
2085
+ .all(|element| element_expression(element).is_none_or(inert)),
1739
2086
  _ => false,
1740
2087
  }
1741
2088
  }
1742
2089
 
1743
2090
  /// Resolves the function produced by `callee` and checks whether a side-effect-free first operand
1744
2091
  /// detaches its receiver. For example, `(0, f)(a)` calls `f` without a receiver.
1745
- fn undetached<'expression>(
1746
- callee: &'expression Expr,
1747
- constants: &HashMap<Id, f64>,
1748
- ) -> (&'expression Expr, bool) {
1749
- let callee = callee.unwrap_parens();
1750
- if let Expr::Seq(sequence) = callee
1751
- && let [discarded, last] = &sequence.exprs[..]
2092
+ fn undetached<'b, 'a>(
2093
+ callee: &'b Expression<'a>,
2094
+ constants: &Constants<'a>,
2095
+ ) -> (&'b Expression<'a>, bool) {
2096
+ let callee = callee.without_parentheses();
2097
+ if let Expression::SequenceExpression(sequence) = callee
2098
+ && let [discarded, last] = &sequence.expressions[..]
1752
2099
  && is_inert(discarded, constants)
1753
2100
  {
1754
- return (last.unwrap_parens(), true);
2101
+ return (last.without_parentheses(), true);
1755
2102
  }
1756
2103
  (callee, false)
1757
2104
  }
1758
2105
 
1759
- impl Visit for Scope<'_> {
1760
- fn visit_function(&mut self, _: &Function) {}
1761
- fn visit_class(&mut self, _: &Class) {}
1762
-
1763
- fn visit_assign_expr(&mut self, assign: &AssignExpr) {
1764
- if assign.op == AssignOp::Assign {
1765
- match &assign.left {
1766
- AssignTarget::Simple(SimpleAssignTarget::Ident(name)) => {
1767
- self.bind(Holder::Name(name.to_id()), &assign.right);
1768
- }
1769
- AssignTarget::Simple(SimpleAssignTarget::Member(member)) => {
1770
- if let Some(slot) = self.slot(member) {
1771
- self.bind(slot, &assign.right);
1772
- } else if let Expr::Fn(function) = &*assign.right
1773
- && let Some(object) = self.holder(&member.obj)
1774
- && let Some(path) = inferred_path(&member.obj)
1775
- && let Some(name) = ast::member_str(&member.prop)
1776
- {
1777
- // V8 infers the name of an anonymous function from the member it is
1778
- // assigned to.
1779
- let path = format!("{}{path}", self.prefix);
1780
- let (inferred, method) = if member.prop.is_computed() {
2106
+ impl<'a> Visit<'a> for Scope<'a, '_> {
2107
+ fn visit_function(&mut self, _: &Function<'a>, _: ScopeFlags) {}
2108
+ fn visit_class(&mut self, _: &Class<'a>) {}
2109
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
2110
+ walk_property(self, property);
2111
+ }
2112
+
2113
+ fn visit_assignment_expression(&mut self, assignment: &AssignmentExpression<'a>) {
2114
+ let assignment = self
2115
+ .js()
2116
+ .lend(assignment, AstKind::as_assignment_expression);
2117
+ if assignment.operator == AssignmentOperator::Assign {
2118
+ if let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left {
2119
+ self.bind(Holder::Name(self.js().binding(name)), &assignment.right);
2120
+ } else if let Some(member) = assigned_member(&assignment.left) {
2121
+ if let Some(slot) = self.slot(member) {
2122
+ self.bind(slot, &assignment.right);
2123
+ } else if let Expression::FunctionExpression(function) = &assignment.right
2124
+ && let Some(object) = self.holder(Operand::Expression(member.object()))
2125
+ && let Some(path) = inferred_path(member.object())
2126
+ && let Some(name) = ast::member_str(member)
2127
+ {
2128
+ // V8 infers the name of an anonymous function from the member it is
2129
+ // assigned to.
2130
+ let path = format!("{}{path}", self.prefix);
2131
+ let (inferred, method) =
2132
+ if matches!(member, MemberExpression::ComputedMemberExpression(_)) {
1781
2133
  let inferred = format!("{path}.<computed>");
1782
2134
  (inferred.clone(), format!("{inferred} [as {name}]"))
1783
2135
  } else {
1784
2136
  let inferred = format!("{path}.{name}");
1785
2137
  (inferred.clone(), inferred)
1786
2138
  };
1787
- let frames = |name: String| {
1788
- self.forwarder(&function.function, Name::anonymous(name))
1789
- };
1790
- if let (Some(method), Some(plain)) = (frames(method), frames(inferred)) {
1791
- self.forwarders
1792
- .on_objects
1793
- .insert((object, name.to_owned()), Forwarder { method, plain });
1794
- }
2139
+ let frames = |name: String| self.forwarder(function, Name::anonymous(name));
2140
+ if let (Some(method), Some(plain)) = (frames(method), frames(inferred)) {
2141
+ self.forwarders
2142
+ .on_objects
2143
+ .insert((object, name), Forwarder { method, plain });
1795
2144
  }
1796
2145
  }
1797
- _ => {}
1798
2146
  }
1799
2147
  }
1800
- assign.visit_children_with(self);
2148
+ walk::walk_assignment_expression(self, assignment);
1801
2149
  }
1802
2150
 
1803
- fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
1804
- if let Pat::Ident(name) = &declarator.name
2151
+ fn visit_variable_declarator(&mut self, declarator: &VariableDeclarator<'a>) {
2152
+ let declarator = self.js().lend(declarator, AstKind::as_variable_declarator);
2153
+ if let BindingPattern::BindingIdentifier(name) = &declarator.id
1805
2154
  && let Some(init) = &declarator.init
1806
2155
  {
1807
- self.bind(Holder::Name(name.to_id()), init);
2156
+ self.bind(Holder::Name(Binding::Symbol(name.symbol_id())), init);
1808
2157
  }
1809
- declarator.visit_children_with(self);
2158
+ walk::walk_variable_declarator(self, declarator);
1810
2159
  }
1811
2160
  }
1812
2161
 
1813
2162
  /// Returns the V8 name inferred from an assignment target: `object` for an object or
1814
2163
  /// `array.<computed>` for an array slot.
1815
- fn inferred_path(object: &Expr) -> Option<String> {
1816
- match object.unwrap_parens() {
1817
- Expr::Ident(name) => Some(name.sym.to_string()),
1818
- Expr::Member(member) if member.prop.is_computed() => {
1819
- Some(format!("{}.<computed>", member.obj.as_ident()?.sym))
2164
+ fn inferred_path(object: &Expression<'_>) -> Option<String> {
2165
+ match object.without_parentheses() {
2166
+ Expression::Identifier(name) => Some(name.name.to_string()),
2167
+ Expression::ComputedMemberExpression(member) => {
2168
+ let Expression::Identifier(array) = &member.object else {
2169
+ return None;
2170
+ };
2171
+ Some(format!("{}.<computed>", array.name))
1820
2172
  }
1821
2173
  _ => None,
1822
2174
  }
@@ -1825,23 +2177,26 @@ fn inferred_path(object: &Expr) -> Option<String> {
1825
2177
  /// Finds runner calls from closure-factory listeners, including calls made through helpers, and
1826
2178
  /// records calls it cannot resolve. Each listener forwards its captured machine and layout
1827
2179
  /// followed by its own arguments.
1828
- struct Listeners<'script> {
1829
- runner: &'script Id,
1830
- appliers: &'script Appliers,
1831
- found: Vec<Result<Invocation>>,
1832
- }
1833
-
1834
- impl Visit for Listeners<'_> {
1835
- fn visit_function(&mut self, function: &Function) {
1836
- let scope = Scope::new("", function, self.appliers);
1837
- for call in calls_of(function) {
1838
- match scope.target(&call) {
2180
+ struct Listeners<'a, 's> {
2181
+ runner: Callee<'a>,
2182
+ appliers: &'s Appliers<'a>,
2183
+ found: Vec<Result<Invocation<'a>>>,
2184
+ }
2185
+
2186
+ impl<'a> Visit<'a> for Listeners<'a, '_> {
2187
+ fn visit_function(&mut self, function: &Function<'a>, flags: ScopeFlags) {
2188
+ let js = self.appliers.js();
2189
+ let function = js.lend(function, AstKind::as_function);
2190
+ let body = Body::of(function);
2191
+ let scope = Scope::new("", &body, self.appliers);
2192
+ for call in calls_of(js, &body) {
2193
+ match scope.target(call) {
1839
2194
  // A listener passes the captured machine and layout, then its own
1840
2195
  // parameters. Other scopes may reuse the runner's name for another function,
1841
2196
  // and the message handler starts the runner with computed arguments.
1842
2197
  Ok(mut target)
1843
- if target.callee.as_ref() == Some(self.runner)
1844
- && forwards_parameters(function, &call, &target) =>
2198
+ if target.callee == Some(self.runner)
2199
+ && forwards_parameters(&self.appliers.constants, &body, call, &target) =>
1845
2200
  {
1846
2201
  target.passed = target.passed.map(|passed| passed - 2);
1847
2202
  self.found.push(Ok(target));
@@ -1850,7 +2205,15 @@ impl Visit for Listeners<'_> {
1850
2205
  Err(error) => self.found.push(Err(error)),
1851
2206
  }
1852
2207
  }
1853
- function.visit_children_with(self);
2208
+ walk::walk_function(self, function, flags);
2209
+ }
2210
+
2211
+ fn visit_object_property(&mut self, property: &ObjectProperty<'a>) {
2212
+ walk_property(self, property);
2213
+ }
2214
+
2215
+ fn visit_method_definition(&mut self, method: &MethodDefinition<'a>) {
2216
+ walk_method(self, method);
1854
2217
  }
1855
2218
  }
1856
2219
 
@@ -1858,6 +2221,25 @@ impl Visit for Listeners<'_> {
1858
2221
  mod tests {
1859
2222
  use super::*;
1860
2223
 
2224
+ /// The decoded program captured during deobfuscation equals the one decoding alone
2225
+ /// produces, for a saved script named by `CFSOLVE_CAPTURE_SCRIPT`.
2226
+ #[test]
2227
+ fn captures_the_decoded_program() {
2228
+ let Some(path) = std::env::var_os("CFSOLVE_CAPTURE_SCRIPT") else {
2229
+ return;
2230
+ };
2231
+ let source = std::fs::read_to_string(path).expect("the capture script is readable");
2232
+ // The debug form includes spans and semantic IDs.
2233
+ let debug = |decoded: &ParsedScript| format!("{:?}", decoded.script().program);
2234
+ let (_, cases) = deobfuscate_with_cases(source.clone()).unwrap();
2235
+ let captured = debug(&cases.decoded.unwrap());
2236
+ let alone = debug(&deobfuscate::decode(source).unwrap());
2237
+ assert!(
2238
+ captured == alone,
2239
+ "the captured program differs from the decoded one"
2240
+ );
2241
+ }
2242
+
1861
2243
  #[test]
1862
2244
  fn appliers_may_copy_their_selector_and_name_apply_indirectly() {
1863
2245
  for source in [
@@ -1865,9 +2247,10 @@ mod tests {
1865
2247
  "function j(s,f,a,e,c,n){switch(e={},c=`apply`,n=[s],5^n[0]){case 6:return Reflect[c](f,void 0,a)}}",
1866
2248
  "var j;j=function(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}}",
1867
2249
  ] {
1868
- let (script, _) = script(source);
1869
- let applier = &script.appliers.helpers[&binding(&script, "j")];
1870
- assert!(applier.call(3.0).is_some(), "{source}");
2250
+ with_script(source, |script| {
2251
+ let applier = &script.appliers.helpers[&binding(script, "j")];
2252
+ assert!(applier.select(3.0).is_some(), "{source}");
2253
+ });
1871
2254
  }
1872
2255
  }
1873
2256
 
@@ -1882,11 +2265,11 @@ mod tests {
1882
2265
  o['k']=function(a,b,c,d,g){return g=[b,d],true,a(g[0],c,g[1])},\
1883
2266
  o['s']=function(a,b,c,g){return g=[c,a,b],(0,g[1])(g[2],g[0])},\
1884
2267
  q=o,q['k'](B,f,r,q['s'](S,arguments,2))}";
1885
- let (script, _) = script(source);
1886
- let frames = script.method_forwarder(&binding(&script, "PA")).unwrap();
1887
- let names: Vec<&str> = frames.iter().map(|call| call.name.v8.as_str()).collect();
1888
- assert_eq!(names, ["PA.o.<computed> [as k]", "PA"]);
1889
- assert!(script.method_forwarder(&binding(&script, "S")).is_none());
2268
+ with_script(source, |script| {
2269
+ let frames = script.method_forwarder(binding(script, "PA")).unwrap();
2270
+ assert_eq!(v8_names(&frames), ["PA.o.<computed> [as k]", "PA"]);
2271
+ assert!(script.method_forwarder(binding(script, "S")).is_none());
2272
+ });
1890
2273
  }
1891
2274
 
1892
2275
  /// Checks method forwarders that call a `Reflect.apply` alias kept in an array slot, directly
@@ -1898,107 +2281,108 @@ mod tests {
1898
2281
  function D(f,r,a){return(0,G[2])(f,r,[a])}\
1899
2282
  function H(f,r,a,b){return W(1,G[2],f,r,[a,b])}\
1900
2283
  function O(f,r,a){return(0,G[3])(f,r,[a])}";
1901
- let (script, _) = script(source);
1902
- let cases: [(&str, &[&str]); 2] = [("D", &["D"]), ("H", &["W", "H"])];
1903
- for (forwarder, expected) in cases {
1904
- let frames = script
1905
- .method_forwarder(&binding(&script, forwarder))
1906
- .expect("`G[2]` holds `Reflect.apply`, so the call is a method forwarder");
1907
- let names: Vec<&str> = frames.iter().map(|call| call.name.v8.as_str()).collect();
1908
- assert_eq!(names, expected, "frames of forwarder {forwarder}");
1909
- }
1910
- assert!(
1911
- script.method_forwarder(&binding(&script, "O")).is_none(),
1912
- "`G[3]` holds a plain function, not `Reflect.apply`"
1913
- );
2284
+ with_script(source, |script| {
2285
+ let cases: [(&str, &[&str]); 2] = [("D", &["D"]), ("H", &["W", "H"])];
2286
+ for (forwarder, expected) in cases {
2287
+ let frames = script
2288
+ .method_forwarder(binding(script, forwarder))
2289
+ .expect("`G[2]` holds `Reflect.apply`, so the call is a method forwarder");
2290
+ assert_eq!(
2291
+ v8_names(&frames),
2292
+ expected,
2293
+ "frames of forwarder {forwarder}"
2294
+ );
2295
+ }
2296
+ assert!(
2297
+ script.method_forwarder(binding(script, "O")).is_none(),
2298
+ "`G[3]` holds a plain function, not `Reflect.apply`"
2299
+ );
2300
+ });
1914
2301
  }
1915
2302
 
1916
2303
  #[test]
1917
2304
  fn same_named_functions_resolve_to_the_called_binding() {
1918
- let (script, _) = script(
1919
- "function outer(){function h(){wrong()} h()} function h(){right()} function caller(){h()}",
1920
- );
1921
- let target = first_target(&script, "caller");
1922
- let handler = script.function(target.callee.as_ref().unwrap()).unwrap();
1923
- assert_eq!(
1924
- name(calls_of(handler)[0].callee.as_expr().unwrap())
1925
- .unwrap()
1926
- .0,
1927
- "right"
1928
- );
2305
+ let source = "function outer(){function h(){wrong()} h()} function h(){right()} function caller(){h()}";
2306
+ with_script(source, |script| {
2307
+ let target = first_target(script, "caller");
2308
+ let handler = script.function(target.callee.unwrap()).unwrap();
2309
+ let call = calls_of(script.js(), &handler)[0];
2310
+ let callee = Operand::Expression(&call.callee)
2311
+ .callee(&script.appliers.constants)
2312
+ .unwrap();
2313
+ assert_eq!(script.appliers.name(callee), "right");
2314
+ });
1929
2315
  }
1930
2316
 
1931
2317
  #[test]
1932
2318
  fn shadowed_appliers_and_runners_are_distinct_bindings() {
1933
- let (script, _) = script(
1934
- "function runner(){} function j(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}} function outer(){function j(){} function runner(){} j(3,f,[]);return function(a){runner(vm,layout,a);j(3,f,[])}} function real(a){runner(vm,layout,a)}",
1935
- );
1936
- let runner = first_target(&script, "real").callee.unwrap();
1937
- let mut listeners = Listeners {
1938
- runner: &runner,
1939
- appliers: &script.appliers,
1940
- found: Vec::new(),
1941
- };
1942
- // Visit every collected body, including the anonymous listener inside outer.
1943
- for (_, function) in &script.functions {
1944
- function.visit_with(&mut listeners);
1945
- }
1946
- assert_eq!(listeners.found.len(), 1);
1947
- let target = first_target(&script, "outer");
1948
- assert!(target.helpers.is_empty());
1949
- assert_eq!(target.passed, Some(3));
1950
- let callee = target.callee.expect("the call has a named callee");
1951
- assert!(!script.appliers.helpers.contains_key(&callee));
2319
+ let source = "function runner(){} function j(s,f,a){switch(5^s){case 6:return Reflect.apply(f,void 0,a)}} function outer(){function j(){} function runner(){} j(3,f,[]);return function(a){runner(vm,layout,a);j(3,f,[])}} function real(a){runner(vm,layout,a)}";
2320
+ with_script(source, |script| {
2321
+ let runner = first_target(script, "real").callee.unwrap();
2322
+ let mut listeners = Listeners {
2323
+ runner,
2324
+ appliers: &script.appliers,
2325
+ found: Vec::new(),
2326
+ };
2327
+ // Visit every collected function, including the anonymous listener inside outer.
2328
+ for (_, function) in script.js().named_functions() {
2329
+ listeners.visit_function(function, ScopeFlags::Function);
2330
+ }
2331
+ assert_eq!(listeners.found.len(), 1);
2332
+ let target = first_target(script, "outer");
2333
+ assert!(target.helpers.is_empty());
2334
+ assert_eq!(target.passed, Some(3));
2335
+ let callee = target.callee.expect("the call has a named callee");
2336
+ assert!(!script.appliers.helpers.contains_key(&callee));
2337
+ });
1952
2338
  }
1953
2339
 
1954
2340
  #[test]
1955
2341
  fn native_apply_alias_does_not_match_a_shadowed_function() {
1956
- let (script, _) = script(
1957
- "var B=Reflect.apply; function outer(){function B(){} function wrong(f,r){return B(f,r,[])}} function good(f,r){return B(f,r,[])}",
1958
- );
1959
- assert!(
1960
- script
1961
- .method_forwarder(&binding(&script, "wrong"))
1962
- .is_none()
1963
- );
1964
- assert!(script.method_forwarder(&binding(&script, "good")).is_some());
2342
+ let source = "var B=Reflect.apply; function outer(){function B(){} function wrong(f,r){return B(f,r,[])}} function good(f,r){return B(f,r,[])}";
2343
+ with_script(source, |script| {
2344
+ assert!(script.method_forwarder(binding(script, "wrong")).is_none());
2345
+ assert!(script.method_forwarder(binding(script, "good")).is_some());
2346
+ });
1965
2347
  }
1966
2348
 
1967
2349
  #[test]
1968
2350
  fn block_locals_do_not_replace_an_outer_objects_forwarder() {
1969
- let (script, _) = script(
1970
- "function F(){let o={},q=o,c='k';o.k=function(f,a){return f(a)};{let o={},q=o,c='other';o.k=function(f,a){return 0};}return q[c](target,1)}",
1971
- );
1972
- let target = first_target(&script, "F");
1973
- assert_eq!(target.callee.as_ref().unwrap().0, "target");
1974
- assert_eq!(target.helpers.len(), 1);
1975
- assert_eq!(target.helpers[0].name.v8, "F.o.k");
2351
+ let source = "function F(){let o={},q=o,c='k';o.k=function(f,a){return f(a)};{let o={},q=o,c='other';o.k=function(f,a){return 0};}return q[c](target,1)}";
2352
+ with_script(source, |script| {
2353
+ let target = first_target(script, "F");
2354
+ assert_eq!(script.appliers.name(target.callee.unwrap()), "target");
2355
+ assert_eq!(target.helpers.len(), 1);
2356
+ assert_eq!(target.helpers[0].name.v8, "F.o.k");
2357
+ });
1976
2358
  }
1977
2359
 
1978
- /// Analyzes `source` and returns the script's starting position.
1979
- fn script(source: &str) -> (Script, BytePos) {
1980
- deobfuscate::read_decoded(source.to_owned(), |program, start| {
1981
- Ok((Script::new(program), start))
1982
- })
1983
- .unwrap()
2360
+ /// Decodes `source` and analyzes it.
2361
+ fn with_script<T>(source: &str, read: impl for<'a> FnOnce(&Script<'a>) -> T) -> T {
2362
+ let decoded = deobfuscate::decode(source.to_owned()).unwrap();
2363
+ read(&Script::new(decoded.script()))
1984
2364
  }
1985
2365
 
1986
- fn binding(script: &Script, name: &str) -> Id {
1987
- script
2366
+ /// The binding of the script function named `name`.
2367
+ fn binding<'a>(script: &Script<'a>, name: &str) -> Callee<'a> {
2368
+ let (binding, _) = script
1988
2369
  .functions
1989
2370
  .iter()
1990
- .find(|(id, _)| id.0 == name)
1991
- .unwrap()
1992
- .0
1993
- .clone()
2371
+ .find(|(binding, _)| script.js().name(*binding) == name)
2372
+ .unwrap();
2373
+ Callee::Binding(*binding)
2374
+ }
2375
+
2376
+ fn v8_names(calls: &[Call]) -> Vec<&str> {
2377
+ calls.iter().map(|call| call.name.v8.as_str()).collect()
1994
2378
  }
1995
2379
 
1996
2380
  /// Returns the target of the first call in the script function named `name`.
1997
- fn first_target(script: &Script, name: &str) -> Invocation {
1998
- let function = script.function(&binding(script, name)).unwrap();
1999
- let call = calls_of(function).remove(0);
2000
- Scope::new(name, function, &script.appliers)
2001
- .target(&call)
2381
+ fn first_target<'a>(script: &Script<'a>, name: &str) -> Invocation<'a> {
2382
+ let function = script.function(binding(script, name)).unwrap();
2383
+ let call = calls_of(script.js(), &function)[0];
2384
+ Scope::new(name, &function, &script.appliers)
2385
+ .target(call)
2002
2386
  .unwrap()
2003
2387
  }
2004
2388
 
@@ -2010,20 +2394,21 @@ mod tests {
2010
2394
  function e(s,t,f,a){switch(s^C){case 1:{var y;switch(y=[a],5^t){case 6:return f(y[0])}}return;case 2:{h(a)}return}}\
2011
2395
  function caller(x){return e(6,3,g,x)}\
2012
2396
  function other(x){e(5,x)}";
2013
- let (script, _) = script(source);
2014
- let target = first_target(&script, "caller");
2015
- assert_eq!(target.callee.as_ref().unwrap().0, "g");
2016
- let helpers: Vec<&str> = target
2017
- .helpers
2018
- .iter()
2019
- .map(|call| call.name.v8.as_str())
2020
- .collect();
2021
- assert_eq!(helpers, ["e"]);
2022
- assert_eq!(target.passed, Some(1));
2023
- let original = first_target(&script, "other").callee.unwrap();
2024
- assert_eq!(original.0, "e");
2025
- let calls = calls_of(script.function(&original).unwrap());
2026
- assert_eq!(name(calls[0].callee.as_expr().unwrap()).unwrap().0, "h");
2397
+ with_script(source, |script| {
2398
+ let target = first_target(script, "caller");
2399
+ assert_eq!(script.appliers.name(target.callee.unwrap()), "g");
2400
+ assert_eq!(v8_names(&target.helpers), ["e"]);
2401
+ assert_eq!(target.passed, Some(1));
2402
+ let original = first_target(script, "other").callee.unwrap();
2403
+ assert!(matches!(original, Callee::Original(_)));
2404
+ assert_eq!(script.appliers.name(original), "e");
2405
+ let function = script.function(original).unwrap();
2406
+ let call = calls_of(script.js(), &function)[0];
2407
+ let callee = Operand::Expression(&call.callee)
2408
+ .callee(&script.appliers.constants)
2409
+ .unwrap();
2410
+ assert_eq!(script.appliers.name(callee), "h");
2411
+ });
2027
2412
  }
2028
2413
 
2029
2414
  /// V8 names a forwarder copied to a binding after its assignment target, without the property
@@ -2035,31 +2420,35 @@ mod tests {
2035
2420
  function a(s,f,x,y,z){switch(s^5){case 6:return f(x,y,z)}}\
2036
2421
  function direct(m){return q(loop,m,1)}\
2037
2422
  function applied(m){return a(3,q,loop,m,1)}";
2038
- let (script, _) = script(source);
2039
- for (caller, expected) in [
2040
- ("direct", &["o.<computed>"][..]),
2041
- ("applied", &["o.<computed>", "a"]),
2042
- ] {
2043
- let target = first_target(&script, caller);
2044
- assert_eq!(target.callee.as_ref().unwrap().0, "loop", "{caller}");
2045
- let helpers: Vec<&str> = target
2046
- .helpers
2047
- .iter()
2048
- .map(|call| call.name.v8.as_str())
2049
- .collect();
2050
- assert_eq!(helpers, expected, "{caller}");
2051
- assert_eq!(target.passed, Some(2), "{caller}");
2052
- }
2423
+ with_script(source, |script| {
2424
+ for (caller, expected) in [
2425
+ ("direct", &["o.<computed>"][..]),
2426
+ ("applied", &["o.<computed>", "a"]),
2427
+ ] {
2428
+ let target = first_target(script, caller);
2429
+ assert_eq!(
2430
+ script.appliers.name(target.callee.unwrap()),
2431
+ "loop",
2432
+ "{caller}"
2433
+ );
2434
+ assert_eq!(v8_names(&target.helpers), expected, "{caller}");
2435
+ assert_eq!(target.passed, Some(2), "{caller}");
2436
+ }
2437
+ });
2053
2438
  }
2054
2439
 
2055
2440
  #[test]
2056
2441
  fn a_call_key_kept_in_a_local_still_calls_the_handler() {
2057
2442
  let source = "function run(){var c='call';switch(o){case 1:h[c](this);break}}";
2058
- let (script, _) = script(source);
2059
- let target = first_target(&script, "run");
2060
- assert_eq!(target.callee.as_ref().map(|id| id.0.as_ref()), Some("h"));
2061
- assert!(target.method);
2062
- assert_eq!(target.passed, Some(0));
2443
+ with_script(source, |script| {
2444
+ let target = first_target(script, "run");
2445
+ assert_eq!(
2446
+ target.callee.map(|callee| script.appliers.name(callee)),
2447
+ Some("h")
2448
+ );
2449
+ assert!(target.method);
2450
+ assert_eq!(target.passed, Some(0));
2451
+ });
2063
2452
  }
2064
2453
 
2065
2454
  #[test]
@@ -2098,18 +2487,19 @@ mod tests {
2098
2487
  #[test]
2099
2488
  fn jsc_frames_are_placed_at_their_arguments() {
2100
2489
  let source = "function a(s,f,l){switch(1^s){case 0:return Reflect.construct(f,void 0,l);case 3:return Reflect.apply(f,void 0,l)}}function h(){return a(1,Error,[])}";
2101
- let (script, start) = script(source);
2102
- let target = first_target(&script, "h");
2103
- let frames = target.frames(Name::same("h".to_owned()));
2104
- let names: Vec<_> = frames
2105
- .iter()
2106
- .map(|call| (call.name.v8.as_str(), call.name.jsc.as_str()))
2107
- .collect();
2108
- assert_eq!(names, [("a", "a"), ("h", "h")]);
2109
- let at = |position: BytePos| &source[(position.0 - start.0) as usize..][..2];
2110
- let (applier, handler) = (&frames[0], &frames[1]);
2111
- assert_eq!(at(handler.site.v8), "a(");
2112
- assert_eq!(at(handler.site.jsc), "(1");
2113
- assert_eq!(at(applier.site.jsc), "(f");
2490
+ with_script(source, |script| {
2491
+ let target = first_target(script, "h");
2492
+ let frames = target.frames(Name::same("h".to_owned()));
2493
+ let names: Vec<_> = frames
2494
+ .iter()
2495
+ .map(|call| (call.name.v8.as_str(), call.name.jsc.as_str()))
2496
+ .collect();
2497
+ assert_eq!(names, [("a", "a"), ("h", "h")]);
2498
+ let at = |position: u32| &source[position as usize..][..2];
2499
+ let (applier, handler) = (&frames[0], &frames[1]);
2500
+ assert_eq!(at(handler.site.v8), "a(");
2501
+ assert_eq!(at(handler.site.jsc), "(1");
2502
+ assert_eq!(at(applier.site.jsc), "(f");
2503
+ });
2114
2504
  }
2115
2505
  }