cfsolve 0.1.1 → 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 (404) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +18 -0
  3. data/README.md +10 -9
  4. data/THIRD_PARTY_LICENSES/README.md +71 -254
  5. data/THIRD_PARTY_LICENSES/{derive_builder_macro-0.20.2/LICENSE-APACHE → bytecount-0.6.9/LICENSE.Apache2} +0 -1
  6. data/THIRD_PARTY_LICENSES/{darling-0.20.11/LICENSE → bytecount-0.6.9/LICENSE.MIT} +1 -3
  7. data/THIRD_PARTY_LICENSES/{ident_case-1.0.1/LICENSE → cobs-0.3.0/LICENSE-MIT} +1 -1
  8. data/THIRD_PARTY_LICENSES/cow-utils-0.1.3/LICENSE +21 -0
  9. data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → embedded-io-0.4.0}/LICENSE-MIT +1 -1
  10. data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.6.1}/LICENSE-MIT +1 -1
  11. data/THIRD_PARTY_LICENSES/{browserslist-data-0.1.4 → escape-simd-0.1.1}/LICENSE +1 -1
  12. data/THIRD_PARTY_LICENSES/escape-simd-0.1.1/NOTICE +62 -0
  13. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/LICENSE +21 -0
  14. data/THIRD_PARTY_LICENSES/{miette-7.6.0/LICENSE → json-escape-simd-3.1.3/LICENSE-APACHE} +0 -1
  15. data/THIRD_PARTY_LICENSES/json-escape-simd-3.1.3/NOTICE +62 -0
  16. data/THIRD_PARTY_LICENSES/memchr-2.8.3/UNLICENSE +24 -0
  17. data/THIRD_PARTY_LICENSES/{derive_builder_core-0.20.2 → nonmax-0.5.5}/LICENSE-APACHE +1 -2
  18. data/THIRD_PARTY_LICENSES/{dashmap-5.5.3/LICENSE → nonmax-0.5.5/LICENSE-MIT} +2 -4
  19. data/THIRD_PARTY_LICENSES/{rand-0.8.5 → num-bigint-0.5.1}/LICENSE-MIT +0 -1
  20. data/THIRD_PARTY_LICENSES/oxc-0.157.0/LICENSE +22 -0
  21. data/THIRD_PARTY_LICENSES/oxc-0.157.0/THIRD-PARTY-LICENSE +763 -0
  22. data/THIRD_PARTY_LICENSES/{browserslist-rs-0.19.0 → oxc-browserslist-5.0.1}/LICENSE +1 -0
  23. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/LICENSE +22 -0
  24. data/THIRD_PARTY_LICENSES/oxc_allocator-0.157.0/THIRD-PARTY-LICENSE +763 -0
  25. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/LICENSE +22 -0
  26. data/THIRD_PARTY_LICENSES/oxc_ast-0.157.0/THIRD-PARTY-LICENSE +763 -0
  27. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/LICENSE +22 -0
  28. data/THIRD_PARTY_LICENSES/oxc_ast_macros-0.157.0/THIRD-PARTY-LICENSE +763 -0
  29. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/LICENSE +22 -0
  30. data/THIRD_PARTY_LICENSES/oxc_ast_visit-0.157.0/THIRD-PARTY-LICENSE +763 -0
  31. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/LICENSE +22 -0
  32. data/THIRD_PARTY_LICENSES/oxc_codegen-0.157.0/THIRD-PARTY-LICENSE +763 -0
  33. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/LICENSE +22 -0
  34. data/THIRD_PARTY_LICENSES/oxc_compat-0.157.0/THIRD-PARTY-LICENSE +763 -0
  35. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/LICENSE +22 -0
  36. data/THIRD_PARTY_LICENSES/oxc_data_structures-0.157.0/THIRD-PARTY-LICENSE +763 -0
  37. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/LICENSE +22 -0
  38. data/THIRD_PARTY_LICENSES/oxc_diagnostics-0.157.0/THIRD-PARTY-LICENSE +763 -0
  39. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/LICENSE +22 -0
  40. data/THIRD_PARTY_LICENSES/oxc_ecmascript-0.157.0/THIRD-PARTY-LICENSE +763 -0
  41. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/LICENSE +22 -0
  42. data/THIRD_PARTY_LICENSES/oxc_estree-0.157.0/THIRD-PARTY-LICENSE +763 -0
  43. data/THIRD_PARTY_LICENSES/oxc_index-5.0.0/LICENSE +22 -0
  44. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/LICENSE +22 -0
  45. data/THIRD_PARTY_LICENSES/oxc_parser-0.157.0/THIRD-PARTY-LICENSE +763 -0
  46. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/LICENSE +22 -0
  47. data/THIRD_PARTY_LICENSES/oxc_regular_expression-0.157.0/THIRD-PARTY-LICENSE +763 -0
  48. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/LICENSE +22 -0
  49. data/THIRD_PARTY_LICENSES/oxc_semantic-0.157.0/THIRD-PARTY-LICENSE +763 -0
  50. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/LICENSE +22 -0
  51. data/THIRD_PARTY_LICENSES/oxc_span-0.157.0/THIRD-PARTY-LICENSE +763 -0
  52. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/LICENSE +22 -0
  53. data/THIRD_PARTY_LICENSES/oxc_str-0.157.0/THIRD-PARTY-LICENSE +763 -0
  54. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/LICENSE +22 -0
  55. data/THIRD_PARTY_LICENSES/oxc_syntax-0.157.0/THIRD-PARTY-LICENSE +763 -0
  56. data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-MIT +1 -1
  57. data/THIRD_PARTY_LICENSES/{bytes-str-0.2.7/LICENSE → self_cell-1.3.0/LICENSE-APACHE} +1 -2
  58. data/THIRD_PARTY_LICENSES/self_cell-1.3.0/LICENSE-GPLv2 +339 -0
  59. data/THIRD_PARTY_LICENSES/{darling_core-0.20.11 → smawk-0.3.3}/LICENSE +1 -1
  60. data/UPSTREAM.md +10 -8
  61. data/ext/cfsolve/Cargo.lock +534 -1727
  62. data/ext/cfsolve/Cargo.toml +4 -0
  63. data/ext/cfsolve/src/main.rs +1 -1
  64. data/lib/cfsolve/profiles/safari-26-ios/answers.json +2570 -1894
  65. data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +1867 -1192
  66. data/lib/cfsolve/profiles/safari-26-ios.json +102 -156
  67. data/lib/cfsolve/version.rb +2 -2
  68. data/vendor/cfsolve/Cargo.lock +561 -1729
  69. data/vendor/cfsolve/Cargo.toml +26 -8
  70. data/vendor/cfsolve/README.md +4 -35
  71. data/vendor/cfsolve/examples/build_profile.rs +17 -15
  72. data/vendor/cfsolve/examples/capture_session.rs +37 -0
  73. data/vendor/cfsolve/examples/check_answers.rs +66 -0
  74. data/vendor/cfsolve/examples/compare_session.rs +189 -0
  75. data/vendor/cfsolve/examples/solver_profile.rs +84 -0
  76. data/vendor/cfsolve/examples/solver_smoke.rs +9 -8
  77. data/vendor/cfsolve/examples/stage2_snapshot.rs +6 -3
  78. data/vendor/cfsolve/examples/tls_echo.rs +3 -3
  79. data/vendor/cfsolve/examples/vm_snapshot.rs +32 -33
  80. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +2570 -1894
  81. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +1867 -1192
  82. data/vendor/cfsolve/profiles/safari-26-ios.json +102 -156
  83. data/vendor/cfsolve/scripts/capture_cssom.mjs +42 -0
  84. data/vendor/cfsolve/scripts/serve_cssom.py +111 -0
  85. data/vendor/cfsolve/src/bin/capture-proxy/main.rs +3 -2
  86. data/vendor/cfsolve/src/bin/challenge/cli.rs +8 -2
  87. data/vendor/cfsolve/src/bin/challenge/main.rs +7 -2
  88. data/vendor/cfsolve/src/capture/profile.rs +7 -18
  89. data/vendor/cfsolve/src/capture/proxy/tests.rs +1 -1
  90. data/vendor/cfsolve/src/capture/proxy.rs +44 -13
  91. data/vendor/cfsolve/src/capture/recorded.rs +42 -7
  92. data/vendor/cfsolve/src/capture/sessions.rs +4 -3
  93. data/vendor/cfsolve/src/capture/upstream.rs +1 -1
  94. data/vendor/cfsolve/src/challenge/codec.rs +4 -2
  95. data/vendor/cfsolve/src/challenge/expression.rs +161 -117
  96. data/vendor/cfsolve/src/challenge/installed/audit.rs +132 -0
  97. data/vendor/cfsolve/src/challenge/installed.rs +127 -269
  98. data/vendor/cfsolve/src/challenge/merge.rs +120 -80
  99. data/vendor/cfsolve/src/challenge/orchestrator.rs +57 -44
  100. data/vendor/cfsolve/src/challenge/payload.rs +175 -35
  101. data/vendor/cfsolve/src/challenge/program.rs +197 -178
  102. data/vendor/cfsolve/src/challenge/reduced_timing.rs +55 -40
  103. data/vendor/cfsolve/src/challenge/source.rs +151 -96
  104. data/vendor/cfsolve/src/challenge/state.rs +236 -122
  105. data/vendor/cfsolve/src/challenge/tally.rs +64 -50
  106. data/vendor/cfsolve/src/challenge.rs +1 -0
  107. data/vendor/cfsolve/src/deobfuscate/analysis/bindings.rs +187 -185
  108. data/vendor/cfsolve/src/deobfuscate/analysis/effects.rs +42 -51
  109. data/vendor/cfsolve/src/deobfuscate/analysis/hoisting.rs +147 -228
  110. data/vendor/cfsolve/src/deobfuscate/analysis/properties.rs +250 -425
  111. data/vendor/cfsolve/src/deobfuscate/analysis/unconditional.rs +79 -0
  112. data/vendor/cfsolve/src/deobfuscate/analysis.rs +259 -41
  113. data/vendor/cfsolve/src/deobfuscate/argument_arrays.rs +70 -73
  114. data/vendor/cfsolve/src/deobfuscate/arrow_blocks.rs +91 -104
  115. data/vendor/cfsolve/src/deobfuscate/ast.rs +383 -0
  116. data/vendor/cfsolve/src/deobfuscate/bitwise.rs +44 -54
  117. data/vendor/cfsolve/src/deobfuscate/blocks.rs +36 -29
  118. data/vendor/cfsolve/src/deobfuscate/call_helpers.rs +80 -131
  119. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +239 -297
  120. data/vendor/cfsolve/src/deobfuscate/copy_propagation.rs +114 -135
  121. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +62 -61
  122. data/vendor/cfsolve/src/deobfuscate/dead_properties.rs +197 -214
  123. data/vendor/cfsolve/src/deobfuscate/dispatch.rs +238 -298
  124. data/vendor/cfsolve/src/deobfuscate/encoded_strings.rs +201 -205
  125. data/vendor/cfsolve/src/deobfuscate/function_lengths.rs +32 -38
  126. data/vendor/cfsolve/src/deobfuscate/helper_objects.rs +346 -536
  127. data/vendor/cfsolve/src/deobfuscate/hygiene.rs +197 -0
  128. data/vendor/cfsolve/src/deobfuscate/int32_helpers.rs +121 -155
  129. data/vendor/cfsolve/src/deobfuscate/literals.rs +116 -67
  130. data/vendor/cfsolve/src/deobfuscate/loops.rs +43 -43
  131. data/vendor/cfsolve/src/deobfuscate/memoized_strings.rs +127 -131
  132. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +262 -220
  133. data/vendor/cfsolve/src/deobfuscate/pipeline.rs +199 -244
  134. data/vendor/cfsolve/src/deobfuscate/register_arrays.rs +361 -322
  135. data/vendor/cfsolve/src/deobfuscate/removal.rs +83 -52
  136. data/vendor/cfsolve/src/deobfuscate/simplify.rs +147 -0
  137. data/vendor/cfsolve/src/deobfuscate/state_machines.rs +88 -110
  138. data/vendor/cfsolve/src/deobfuscate/statements.rs +228 -228
  139. data/vendor/cfsolve/src/deobfuscate/static_members.rs +46 -31
  140. data/vendor/cfsolve/src/deobfuscate/testing.rs +49 -59
  141. data/vendor/cfsolve/src/deobfuscate/unused_bindings.rs +92 -102
  142. data/vendor/cfsolve/src/deobfuscate.rs +15 -11
  143. data/vendor/cfsolve/src/embedding_page/extra_params.rs +23 -32
  144. data/vendor/cfsolve/src/embedding_page/page.rs +28 -2
  145. data/vendor/cfsolve/src/embedding_page/render_sample.rs +184 -147
  146. data/vendor/cfsolve/src/error.rs +40 -5
  147. data/vendor/cfsolve/src/fingerprint.rs +8 -2
  148. data/vendor/cfsolve/src/http/client.rs +9 -1
  149. data/vendor/cfsolve/src/http/requests.rs +2 -2
  150. data/vendor/cfsolve/src/js/ast.rs +479 -254
  151. data/vendor/cfsolve/src/js/objects.rs +9 -2
  152. data/vendor/cfsolve/src/lib.rs +1 -0
  153. data/vendor/cfsolve/src/listing/fold.rs +19 -92
  154. data/vendor/cfsolve/src/listing/query.rs +26 -291
  155. data/vendor/cfsolve/src/listing.rs +0 -1
  156. data/vendor/cfsolve/src/performance_clock.rs +20 -1
  157. data/vendor/cfsolve/src/profiling.rs +49 -0
  158. data/vendor/cfsolve/src/script.rs +35 -24
  159. data/vendor/cfsolve/src/session/challenge_page.rs +41 -21
  160. data/vendor/cfsolve/src/session/channel.rs +2 -2
  161. data/vendor/cfsolve/src/session/initial.rs +19 -10
  162. data/vendor/cfsolve/src/session/probes.rs +160 -125
  163. data/vendor/cfsolve/src/session/sink.rs +26 -1
  164. data/vendor/cfsolve/src/session/tests/challenge_page.rs +36 -1
  165. data/vendor/cfsolve/src/session/timing.rs +58 -53
  166. data/vendor/cfsolve/src/session/widget.rs +5 -6
  167. data/vendor/cfsolve/src/session.rs +1 -1
  168. data/vendor/cfsolve/src/solver.rs +3 -1
  169. data/vendor/cfsolve/src/stage2/analysis/analyze.rs +50 -33
  170. data/vendor/cfsolve/src/stage2/analysis/audit.rs +4 -2
  171. data/vendor/cfsolve/src/stage2/analysis/discovery.rs +61 -66
  172. data/vendor/cfsolve/src/stage2/analysis/envelope.rs +33 -22
  173. data/vendor/cfsolve/src/stage2/analysis/recognize.rs +3 -5
  174. data/vendor/cfsolve/src/stage2/analysis.rs +0 -1
  175. data/vendor/cfsolve/src/stage2/audit_globals.rs +378 -0
  176. data/vendor/cfsolve/src/stage2/benchmark.rs +66 -38
  177. data/vendor/cfsolve/src/stage2/call_stack.rs +1463 -1017
  178. data/vendor/cfsolve/src/stage2/challenge_page.rs +3 -2
  179. data/vendor/cfsolve/src/stage2/interaction/checkbox.rs +202 -150
  180. data/vendor/cfsolve/src/stage2/interaction/click.rs +2 -2
  181. data/vendor/cfsolve/src/stage2/interaction/native.rs +2 -1
  182. data/vendor/cfsolve/src/stage2/interaction/plan.rs +5 -7
  183. data/vendor/cfsolve/src/stage2/payload/recover.rs +56 -25
  184. data/vendor/cfsolve/src/stage2/probes/clock.rs +1 -3
  185. data/vendor/cfsolve/src/stage2/probes/ice.rs +11 -10
  186. data/vendor/cfsolve/src/stage2/probes/media.rs +47 -33
  187. data/vendor/cfsolve/src/stage2/probes/performance.rs +13 -8
  188. data/vendor/cfsolve/src/stage2/probes/rects.rs +12 -17
  189. data/vendor/cfsolve/src/stage2/probes/stack.rs +50 -103
  190. data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +17 -86
  191. data/vendor/cfsolve/src/stage2/probes.rs +0 -1
  192. data/vendor/cfsolve/src/stage2/queries.rs +50 -0
  193. data/vendor/cfsolve/src/stage2/records.rs +4 -13
  194. data/vendor/cfsolve/src/stage2/reference.json +1 -1
  195. data/vendor/cfsolve/src/stage2/reference.rs +98 -100
  196. data/vendor/cfsolve/src/stage2/registry.rs +41 -34
  197. data/vendor/cfsolve/src/stage2/replay.rs +182 -254
  198. data/vendor/cfsolve/src/stage2/stylesheets.rs +176 -0
  199. data/vendor/cfsolve/src/stage2/syntax.rs +88 -0
  200. data/vendor/cfsolve/src/stage2/trace.rs +152 -108
  201. data/vendor/cfsolve/src/stage2/vocabulary.rs +103 -403
  202. data/vendor/cfsolve/src/stage2.rs +4 -1
  203. data/vendor/cfsolve/src/vm/disassemble.rs +46 -13
  204. data/vendor/cfsolve/src/vm/dispatch.rs +93 -65
  205. data/vendor/cfsolve/src/vm/extract.rs +347 -250
  206. data/vendor/cfsolve/src/vm/interpret/access.rs +67 -68
  207. data/vendor/cfsolve/src/vm/interpret/builtin.rs +16 -63
  208. data/vendor/cfsolve/src/vm/interpret/call.rs +192 -51
  209. data/vendor/cfsolve/src/vm/interpret/compile.rs +643 -0
  210. data/vendor/cfsolve/src/vm/interpret/copies.rs +232 -120
  211. data/vendor/cfsolve/src/vm/interpret/evaluate/tests.rs +149 -40
  212. data/vendor/cfsolve/src/vm/interpret/evaluate.rs +189 -572
  213. data/vendor/cfsolve/src/vm/interpret/explore.rs +159 -46
  214. data/vendor/cfsolve/src/vm/interpret/formula.rs +131 -0
  215. data/vendor/cfsolve/src/vm/interpret/frozen.rs +169 -0
  216. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +414 -0
  217. data/vendor/cfsolve/src/vm/interpret/mix32.rs +189 -0
  218. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +220 -0
  219. data/vendor/cfsolve/src/vm/interpret/pattern.rs +1736 -0
  220. data/vendor/cfsolve/src/vm/interpret/plan.rs +605 -330
  221. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +384 -0
  222. data/vendor/cfsolve/src/vm/interpret/run.rs +314 -54
  223. data/vendor/cfsolve/src/vm/interpret/semantics.rs +71 -46
  224. data/vendor/cfsolve/src/vm/interpret/setup.rs +80 -45
  225. data/vendor/cfsolve/src/vm/interpret/string_decoder.rs +482 -0
  226. data/vendor/cfsolve/src/vm/interpret.rs +16 -3
  227. data/vendor/cfsolve/src/vm/machine.rs +58 -47
  228. data/vendor/cfsolve/src/vm/output.rs +13 -5
  229. data/vendor/cfsolve/src/vm/packed_names.rs +311 -0
  230. data/vendor/cfsolve/src/vm/session.rs +197 -110
  231. data/vendor/cfsolve/src/vm/value.rs +35 -19
  232. data/vendor/cfsolve/src/vm.rs +3 -1
  233. data/vendor/cfsolve/vendor/btls-sys/Cargo.toml +3 -0
  234. data/vendor/cfsolve/vendor/btls-sys/build/main.rs +20 -0
  235. data/vendor/cfsolve/vendor/btls-sys/src/lib.rs +3 -0
  236. metadata +106 -183
  237. data/THIRD_PARTY_LICENSES/Inflector-0.11.4/LICENSE.md +0 -22
  238. data/THIRD_PARTY_LICENSES/arrayvec-0.7.6/LICENSE-MIT +0 -25
  239. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-APACHE +0 -201
  240. data/THIRD_PARTY_LICENSES/ascii-1.1.0/LICENSE-MIT +0 -22
  241. data/THIRD_PARTY_LICENSES/ast_node-5.0.0/LICENSE +0 -201
  242. data/THIRD_PARTY_LICENSES/better_scoped_tls-1.0.1/LICENSE +0 -201
  243. data/THIRD_PARTY_LICENSES/bitvec-1.0.1/LICENSE.txt +0 -21
  244. data/THIRD_PARTY_LICENSES/bstr-1.12.1/COPYING +0 -8
  245. data/THIRD_PARTY_LICENSES/bstr-1.12.1/LICENSE-MIT +0 -21
  246. data/THIRD_PARTY_LICENSES/cargo-platform-0.1.9/LICENSE-APACHE +0 -201
  247. data/THIRD_PARTY_LICENSES/cargo_metadata-0.19.2/LICENSE-MIT +0 -23
  248. data/THIRD_PARTY_LICENSES/darling_macro-0.20.11/LICENSE +0 -21
  249. data/THIRD_PARTY_LICENSES/debugid-0.8.0/LICENSE +0 -201
  250. data/THIRD_PARTY_LICENSES/derive_builder-0.20.2/LICENSE-MIT +0 -21
  251. data/THIRD_PARTY_LICENSES/derive_builder_core-0.20.2/LICENSE-MIT +0 -21
  252. data/THIRD_PARTY_LICENSES/derive_builder_macro-0.20.2/LICENSE-MIT +0 -21
  253. data/THIRD_PARTY_LICENSES/foldhash-0.1.5/LICENSE +0 -19
  254. data/THIRD_PARTY_LICENSES/from_variant-3.0.0/LICENSE +0 -201
  255. data/THIRD_PARTY_LICENSES/funty-2.0.0/LICENSE.txt +0 -21
  256. data/THIRD_PARTY_LICENSES/hashbrown-0.16.1/LICENSE-MIT +0 -25
  257. data/THIRD_PARTY_LICENSES/heck-0.5.0/LICENSE-APACHE +0 -201
  258. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-APACHE +0 -201
  259. data/THIRD_PARTY_LICENSES/hermit-abi-0.5.2/LICENSE-MIT +0 -23
  260. data/THIRD_PARTY_LICENSES/hstr-3.0.3/LICENSE +0 -202
  261. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-APACHE +0 -201
  262. data/THIRD_PARTY_LICENSES/if_chain-1.0.3/LICENSE-MIT +0 -25
  263. data/THIRD_PARTY_LICENSES/is-macro-0.3.7/LICENSE +0 -202
  264. data/THIRD_PARTY_LICENSES/itoa-1.0.17/LICENSE-MIT +0 -23
  265. data/THIRD_PARTY_LICENSES/jsonc-parser-0.26.3/LICENSE +0 -21
  266. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-APACHE +0 -201
  267. data/THIRD_PARTY_LICENSES/lazy_static-1.5.0/LICENSE-MIT +0 -25
  268. data/THIRD_PARTY_LICENSES/lru-0.16.2/LICENSE +0 -21
  269. data/THIRD_PARTY_LICENSES/memchr-2.7.6/COPYING +0 -3
  270. data/THIRD_PARTY_LICENSES/memchr-2.7.6/LICENSE-MIT +0 -21
  271. data/THIRD_PARTY_LICENSES/miette-derive-7.6.0/LICENSE +0 -229
  272. data/THIRD_PARTY_LICENSES/normpath-0.2.0/COPYRIGHT +0 -7
  273. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-MIT +0 -21
  274. data/THIRD_PARTY_LICENSES/normpath-0.2.0/LICENSE-THIRD-PARTY +0 -210
  275. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-APACHE +0 -201
  276. data/THIRD_PARTY_LICENSES/num_cpus-1.17.0/LICENSE-MIT +0 -20
  277. data/THIRD_PARTY_LICENSES/owo-colors-4.2.3/LICENSE +0 -21
  278. data/THIRD_PARTY_LICENSES/par-core-2.0.0/LICENSE +0 -202
  279. data/THIRD_PARTY_LICENSES/par-iter-2.0.0/LICENSE +0 -202
  280. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-APACHE +0 -13
  281. data/THIRD_PARTY_LICENSES/path-clean-0.1.0/LICENSE-MIT +0 -18
  282. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-APACHE +0 -13
  283. data/THIRD_PARTY_LICENSES/path-clean-1.0.1/LICENSE-MIT +0 -18
  284. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-APACHE +0 -201
  285. data/THIRD_PARTY_LICENSES/pathdiff-0.2.3/LICENSE-MIT +0 -23
  286. data/THIRD_PARTY_LICENSES/petgraph-0.7.1/LICENSE-APACHE +0 -201
  287. data/THIRD_PARTY_LICENSES/precomputed-map-0.2.0/LICENSE +0 -21
  288. data/THIRD_PARTY_LICENSES/preset_env_base-6.0.0/LICENSE +0 -201
  289. data/THIRD_PARTY_LICENSES/radium-0.7.0/LICENSE.txt +0 -21
  290. data/THIRD_PARTY_LICENSES/radix_fmt-1.0.0/LICENSE +0 -201
  291. data/THIRD_PARTY_LICENSES/rand-0.8.5/COPYRIGHT +0 -12
  292. data/THIRD_PARTY_LICENSES/rand-0.8.5/LICENSE-APACHE +0 -176
  293. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/COPYRIGHT +0 -12
  294. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-APACHE +0 -187
  295. data/THIRD_PARTY_LICENSES/rand_core-0.6.4/LICENSE-MIT +0 -26
  296. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-APACHE +0 -201
  297. data/THIRD_PARTY_LICENSES/regress-0.10.5/LICENSE-MIT +0 -21
  298. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-APACHE +0 -176
  299. data/THIRD_PARTY_LICENSES/ryu-1.0.22/LICENSE-BOOST +0 -23
  300. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-APACHE +0 -201
  301. data/THIRD_PARTY_LICENSES/scoped-tls-1.0.1/LICENSE-MIT +0 -25
  302. data/THIRD_PARTY_LICENSES/siphasher-0.3.11/COPYING +0 -7
  303. data/THIRD_PARTY_LICENSES/smallvec-1.15.1/LICENSE-APACHE +0 -201
  304. data/THIRD_PARTY_LICENSES/smartstring-1.0.1/LICENCE.md +0 -355
  305. data/THIRD_PARTY_LICENSES/st-map-0.2.4/LICENSE +0 -202
  306. data/THIRD_PARTY_LICENSES/static-map-macro-0.3.4/LICENSE +0 -202
  307. data/THIRD_PARTY_LICENSES/string_enum-1.0.2/LICENSE +0 -201
  308. data/THIRD_PARTY_LICENSES/strsim-0.11.1/LICENSE +0 -23
  309. data/THIRD_PARTY_LICENSES/swc-52.0.0/LICENSE +0 -201
  310. data/THIRD_PARTY_LICENSES/swc_allocator-4.0.1/LICENSE +0 -201
  311. data/THIRD_PARTY_LICENSES/swc_atoms-9.0.0/LICENSE +0 -201
  312. data/THIRD_PARTY_LICENSES/swc_common-18.0.1/LICENSE +0 -201
  313. data/THIRD_PARTY_LICENSES/swc_compiler_base-45.0.0/LICENSE +0 -201
  314. data/THIRD_PARTY_LICENSES/swc_config-3.1.2/LICENSE +0 -201
  315. data/THIRD_PARTY_LICENSES/swc_config_macro-1.0.1/LICENSE +0 -201
  316. data/THIRD_PARTY_LICENSES/swc_core-54.0.0/LICENSE +0 -201
  317. data/THIRD_PARTY_LICENSES/swc_ecma_ast-19.0.0/LICENSE +0 -201
  318. data/THIRD_PARTY_LICENSES/swc_ecma_codegen-21.0.0/LICENSE +0 -201
  319. data/THIRD_PARTY_LICENSES/swc_ecma_codegen_macros-2.0.2/LICENSE +0 -201
  320. data/THIRD_PARTY_LICENSES/swc_ecma_compat_bugfixes-39.0.0/LICENSE +0 -201
  321. data/THIRD_PARTY_LICENSES/swc_ecma_compat_common-30.0.0/LICENSE +0 -201
  322. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2015-39.0.0/LICENSE +0 -201
  323. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2016-35.0.0/LICENSE +0 -201
  324. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2017-35.0.0/LICENSE +0 -201
  325. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2018-36.0.0/LICENSE +0 -201
  326. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2019-35.0.0/LICENSE +0 -201
  327. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2020-37.0.0/LICENSE +0 -201
  328. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2021-35.0.0/LICENSE +0 -201
  329. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es2022-37.0.0/LICENSE +0 -201
  330. data/THIRD_PARTY_LICENSES/swc_ecma_compat_es3-26.0.0/LICENSE +0 -201
  331. data/THIRD_PARTY_LICENSES/swc_ecma_ext_transforms-25.0.0/LICENSE +0 -201
  332. data/THIRD_PARTY_LICENSES/swc_ecma_hooks-0.3.0/LICENSE +0 -201
  333. data/THIRD_PARTY_LICENSES/swc_ecma_loader-18.0.0/LICENSE +0 -201
  334. data/THIRD_PARTY_LICENSES/swc_ecma_minifier-42.0.0/LICENSE +0 -201
  335. data/THIRD_PARTY_LICENSES/swc_ecma_parser-32.0.0/LICENSE +0 -201
  336. data/THIRD_PARTY_LICENSES/swc_ecma_preset_env-45.0.0/LICENSE +0 -201
  337. data/THIRD_PARTY_LICENSES/swc_ecma_transformer-6.0.0/LICENSE +0 -201
  338. data/THIRD_PARTY_LICENSES/swc_ecma_transforms-44.0.0/LICENSE +0 -201
  339. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_base-35.0.0/LICENSE +0 -201
  340. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_classes-35.0.0/LICENSE +0 -201
  341. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_compat-40.0.0/LICENSE +0 -201
  342. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_macros-1.0.1/LICENSE +0 -201
  343. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_module-38.0.0/LICENSE +0 -201
  344. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_optimization-37.0.0/LICENSE +0 -201
  345. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_proposal-35.0.0/LICENSE +0 -201
  346. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_react-38.0.0/LICENSE +0 -201
  347. data/THIRD_PARTY_LICENSES/swc_ecma_transforms_typescript-38.0.0/LICENSE +0 -201
  348. data/THIRD_PARTY_LICENSES/swc_ecma_usage_analyzer-27.0.0/LICENSE +0 -201
  349. data/THIRD_PARTY_LICENSES/swc_ecma_utils-25.0.0/LICENSE +0 -201
  350. data/THIRD_PARTY_LICENSES/swc_ecma_visit-19.0.0/LICENSE +0 -201
  351. data/THIRD_PARTY_LICENSES/swc_eq_ignore_macros-1.0.1/LICENSE +0 -201
  352. data/THIRD_PARTY_LICENSES/swc_error_reporters-20.0.0/LICENSE +0 -201
  353. data/THIRD_PARTY_LICENSES/swc_macros_common-1.0.1/LICENSE +0 -201
  354. data/THIRD_PARTY_LICENSES/swc_node_comments-18.0.0/LICENSE +0 -201
  355. data/THIRD_PARTY_LICENSES/swc_timer-1.0.0/LICENSE +0 -201
  356. data/THIRD_PARTY_LICENSES/swc_trace_macro-2.0.2/LICENSE +0 -201
  357. data/THIRD_PARTY_LICENSES/swc_transform_common-12.0.0/LICENSE +0 -201
  358. data/THIRD_PARTY_LICENSES/swc_visit-2.0.1/LICENSE +0 -201
  359. data/THIRD_PARTY_LICENSES/tap-1.0.1/LICENSE.txt +0 -21
  360. data/THIRD_PARTY_LICENSES/tracing-0.1.44/LICENSE +0 -25
  361. data/THIRD_PARTY_LICENSES/tracing-attributes-0.1.31/LICENSE +0 -25
  362. data/THIRD_PARTY_LICENSES/tracing-core-0.1.36/LICENSE +0 -25
  363. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-APACHE +0 -201
  364. data/THIRD_PARTY_LICENSES/triomphe-0.1.15/LICENSE-MIT +0 -27
  365. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-APACHE +0 -201
  366. data/THIRD_PARTY_LICENSES/unicode-width-0.1.14/LICENSE-MIT +0 -25
  367. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-APACHE +0 -201
  368. data/THIRD_PARTY_LICENSES/uuid-1.19.0/LICENSE-MIT +0 -26
  369. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-APACHE +0 -201
  370. data/THIRD_PARTY_LICENSES/vergen-9.0.6/LICENSE-MIT +0 -25
  371. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-APACHE +0 -201
  372. data/THIRD_PARTY_LICENSES/vergen-lib-0.1.6/LICENSE-MIT +0 -25
  373. data/THIRD_PARTY_LICENSES/wyz-0.5.1/LICENSE.txt +0 -21
  374. data/vendor/cfsolve/src/deobfuscate/analysis/globals.rs +0 -33
  375. data/vendor/cfsolve/src/deobfuscate/analysis/names.rs +0 -52
  376. data/vendor/cfsolve/src/listing/normalize.rs +0 -264
  377. data/vendor/cfsolve/src/stage2/analysis/outputs.rs +0 -327
  378. data/vendor/cfsolve/src/stage2/probes/stylesheets.rs +0 -249
  379. data/vendor/cfsolve/src/stage2/reference-expanded.json +0 -42
  380. data/vendor/cfsolve/src/stage2/session_names.rs +0 -470
  381. /data/THIRD_PARTY_LICENSES/{derive_builder-0.20.2 → cobs-0.3.0}/LICENSE-APACHE +0 -0
  382. /data/THIRD_PARTY_LICENSES/{compact_str-0.7.1 → compact_str-0.10.0}/LICENSE +0 -0
  383. /data/THIRD_PARTY_LICENSES/{ahash-0.8.12 → embedded-io-0.4.0}/LICENSE-APACHE +0 -0
  384. /data/THIRD_PARTY_LICENSES/{arrayvec-0.7.6 → embedded-io-0.6.1}/LICENSE-APACHE +0 -0
  385. /data/THIRD_PARTY_LICENSES/{normpath-0.2.0 → escape-simd-0.1.1}/LICENSE-APACHE +0 -0
  386. /data/THIRD_PARTY_LICENSES/{bstr-1.12.1 → itertools-0.15.0}/LICENSE-APACHE +0 -0
  387. /data/THIRD_PARTY_LICENSES/{petgraph-0.7.1 → itertools-0.15.0}/LICENSE-MIT +0 -0
  388. /data/THIRD_PARTY_LICENSES/{itoa-1.0.17 → itoa-1.0.19}/LICENSE-APACHE +0 -0
  389. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → itoa-1.0.19}/LICENSE-MIT +0 -0
  390. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/COPYING +0 -0
  391. /data/THIRD_PARTY_LICENSES/{globset-0.4.18 → memchr-2.8.3}/LICENSE-MIT +0 -0
  392. /data/THIRD_PARTY_LICENSES/{camino-1.2.2 → num-bigint-0.5.1}/LICENSE-APACHE +0 -0
  393. /data/THIRD_PARTY_LICENSES/{swc_sourcemap-9.3.4 → oxc_sourcemap-9.0.0}/LICENSE +0 -0
  394. /data/THIRD_PARTY_LICENSES/{phf-0.11.3 → phf-0.14.0}/LICENSE +0 -0
  395. /data/THIRD_PARTY_LICENSES/{phf_generator-0.11.3 → phf_generator-0.14.0}/LICENSE +0 -0
  396. /data/THIRD_PARTY_LICENSES/{phf_macros-0.11.3 → phf_macros-0.14.0}/LICENSE +0 -0
  397. /data/THIRD_PARTY_LICENSES/{phf_shared-0.11.3 → phf_shared-0.14.0}/LICENSE +0 -0
  398. /data/THIRD_PARTY_LICENSES/{fixedbitset-0.5.7 → postcard-1.1.3}/LICENSE-APACHE +0 -0
  399. /data/THIRD_PARTY_LICENSES/{hashbrown-0.14.5 → smallvec-1.16.5}/LICENSE-APACHE +0 -0
  400. /data/THIRD_PARTY_LICENSES/{smallvec-1.15.1 → smallvec-1.16.5}/LICENSE-MIT +0 -0
  401. /data/THIRD_PARTY_LICENSES/{unicode-width-0.1.14 → unicode-segmentation-1.13.3}/COPYRIGHT +0 -0
  402. /data/THIRD_PARTY_LICENSES/{hashbrown-0.16.1 → unicode-segmentation-1.13.3}/LICENSE-APACHE +0 -0
  403. /data/THIRD_PARTY_LICENSES/{heck-0.5.0 → unicode-segmentation-1.13.3}/LICENSE-MIT +0 -0
  404. /data/THIRD_PARTY_LICENSES/{cargo-platform-0.1.9 → zmij_ecma-1.0.23}/LICENSE-MIT +0 -0
@@ -0,0 +1,1736 @@
1
+ //! Structural matching of script functions against JavaScript templates, for native versions
2
+ //! of functions whose shape the obfuscator varies only superficially.
3
+ //!
4
+ //! A template matches a function exactly, up to:
5
+ //!
6
+ //! - consistent renaming of locals (each template local names one function local, and the
7
+ //! reverse);
8
+ //! - names beginning with `$`, which match one free binding of the function each, consistently;
9
+ //! - names beginning with `$c_`, which match a numeric literal and capture its value;
10
+ //! - names beginning with `$e_`, which match any [`Formula`] over locals already matched, and
11
+ //! capture it with each local named as in the template;
12
+ //! - operand order of `*`, `===`, `!==`, `==`, and `!=`, and the order of operands in chains of
13
+ //! `&`, `|`, or `^`;
14
+ //! - declarations without initializers, which only scope names;
15
+ //! - the function's dead helper-object statements (see [`dead_statements`]);
16
+ //! - mixed boolean-arithmetic forms of `|`, `^` and `&`, with their operands bound to
17
+ //! temporaries nothing else reads (see [`Matcher::normalized`]);
18
+ //! - calls to [`BinaryHelper`]s, which return one operator applied to their two parameters;
19
+ //! - statements after a `return` or `throw`, except function and initialized declarations;
20
+ //! - blocks that declare nothing block-scoped, which only group statements.
21
+ //!
22
+ //! Other free names, such as `Error`, must be the same globals. Reordering operands changes
23
+ //! evaluation order, so callers must only rely on a match where every operand is free of side
24
+ //! effects, which the templates' native versions check by matching each function they call.
25
+ //!
26
+ //! Normal forms are built in the matcher's own arena from copies of the function's nodes. The
27
+ //! copies keep their semantic IDs, so their references still resolve in the function's script.
28
+
29
+ use std::cell::RefCell;
30
+ use std::collections::{BTreeMap, BTreeSet};
31
+ use std::{ptr, slice};
32
+
33
+ use oxc::allocator::{Allocator, CloneIn};
34
+ use oxc::ast::AstKind;
35
+ use oxc::ast::ast::{
36
+ Argument, ArrayExpressionElement, AssignmentOperator, AssignmentTarget,
37
+ AssignmentTargetPropertyIdentifier, BinaryExpression, BindingIdentifier, BindingPattern, Class,
38
+ Expression, ForStatement, ForStatementInit, Function, IdentifierReference, LogicalExpression,
39
+ MemberExpression, ObjectPropertyKind, PropertyKey, PropertyKind, SequenceExpression,
40
+ SimpleAssignmentTarget, Statement, UpdateExpression, VariableDeclaration,
41
+ VariableDeclarationKind, VariableDeclarator,
42
+ };
43
+ use oxc::ast::builder::AstBuilder;
44
+ use oxc::ast_visit::{Visit, VisitMut, walk, walk_mut};
45
+ use oxc::semantic::{ScopeFlags, SymbolId};
46
+ use oxc::span::{ContentEq, SPAN};
47
+ use oxc::syntax::operator::{BinaryOperator, LogicalOperator};
48
+
49
+ use super::formula::Formula;
50
+ use super::plan::Routine;
51
+ use crate::js;
52
+ use crate::js::ast::{Binding, ParsedScript, Script};
53
+ use crate::vm::session::Session;
54
+ use crate::vm::value::{Callable, Value};
55
+ use crate::vm::{HashMap, HashSet, extract};
56
+
57
+ /// What a match bound, by template name: free bindings, constants, and formulas.
58
+ #[derive(Clone, Default)]
59
+ pub(super) struct Captures<'a> {
60
+ names: BTreeMap<String, Binding<'a>>,
61
+ constants: BTreeMap<String, f64>,
62
+ formulas: BTreeMap<String, Formula>,
63
+ /// The binary helpers inlined by any attempted match, a superset of those the match relies
64
+ /// on. They must still name the same functions wherever the match is relied on.
65
+ pub(super) helpers: BTreeSet<Binding<'a>>,
66
+ }
67
+
68
+ impl<'a> Captures<'a> {
69
+ pub(super) fn name(&self, placeholder: &str) -> Option<Binding<'a>> {
70
+ self.names.get(placeholder).copied()
71
+ }
72
+
73
+ pub(super) fn constant(&self, placeholder: &str) -> Option<f64> {
74
+ self.constants.get(placeholder).copied()
75
+ }
76
+
77
+ pub(super) fn formula(&self, placeholder: &str) -> Option<Formula> {
78
+ self.formulas.get(placeholder).cloned()
79
+ }
80
+ }
81
+
82
+ /// An operator a [`BinaryHelper`] applies.
83
+ #[derive(Clone, Copy)]
84
+ enum Operator {
85
+ Binary(BinaryOperator),
86
+ Logical(LogicalOperator),
87
+ }
88
+
89
+ /// A free function `function (p, q) { return p <op> q; }`, or `q <op> p` if `swapped`. A call to
90
+ /// one with two arguments computes the operator on them.
91
+ #[derive(Clone, Copy)]
92
+ pub(super) struct BinaryHelper {
93
+ operator: Operator,
94
+ swapped: bool,
95
+ }
96
+
97
+ pub(super) type BinaryHelpers<'a> = HashMap<Binding<'a>, BinaryHelper>;
98
+
99
+ /// The session's binary helpers: functions declared beside the class that no binding shadows,
100
+ /// and bindings holding script functions.
101
+ pub(super) fn binary_helpers<'a>(session: &Session<'a>) -> BinaryHelpers<'a> {
102
+ let script = session.script;
103
+ let mut helpers = BinaryHelpers::default();
104
+ for (&symbol, function) in &session.functions {
105
+ let binding = Binding::Symbol(symbol);
106
+ if !session.bindings.contains_key(&binding)
107
+ && let Some(helper) = binary_helper(script, function)
108
+ {
109
+ helpers.insert(binding, helper);
110
+ }
111
+ }
112
+ for (&binding, value) in &session.bindings {
113
+ let function = script_function(value);
114
+ if let Some(helper) = function.and_then(|function| binary_helper(script, function)) {
115
+ helpers.insert(binding, helper);
116
+ }
117
+ }
118
+ helpers
119
+ }
120
+
121
+ fn binary_helper(script: Script<'_>, function: &Function<'_>) -> Option<BinaryHelper> {
122
+ if function.r#async || function.generator || extract::parameter_count(&function.params) != 2 {
123
+ return None;
124
+ }
125
+ let first = extract::parameter(&function.params, 0)?.symbol_id();
126
+ let second = extract::parameter(&function.params, 1)?.symbol_id();
127
+ let body = function.body.as_deref()?;
128
+ let ([], [Statement::ReturnStatement(returned)]) = (&body.directives[..], &body.statements[..])
129
+ else {
130
+ return None;
131
+ };
132
+ let (operator, left, right) = match returned.argument.as_ref()?.without_parentheses() {
133
+ Expression::BinaryExpression(binary) => (
134
+ Operator::Binary(binary.operator),
135
+ &binary.left,
136
+ &binary.right,
137
+ ),
138
+ Expression::LogicalExpression(logical) => (
139
+ Operator::Logical(logical.operator),
140
+ &logical.left,
141
+ &logical.right,
142
+ ),
143
+ _ => return None,
144
+ };
145
+ let symbol = |expression: &Expression<'_>| match expression.without_parentheses() {
146
+ Expression::Identifier(name) => script.symbol(name),
147
+ _ => None,
148
+ };
149
+ let (left, right) = (symbol(left)?, symbol(right)?);
150
+ if first == second {
151
+ return None;
152
+ }
153
+ let swapped = if left == first && right == second {
154
+ false
155
+ } else if left == second && right == first {
156
+ true
157
+ } else {
158
+ return None;
159
+ };
160
+ Some(BinaryHelper { operator, swapped })
161
+ }
162
+
163
+ /// The function a script function value runs.
164
+ pub(super) fn script_function<'ast>(value: &Value<'ast>) -> Option<&'ast Function<'ast>> {
165
+ if let Value::Function(callable) = value
166
+ && let Callable::Script { function, .. } = &**callable
167
+ {
168
+ return Some(*function);
169
+ }
170
+ None
171
+ }
172
+
173
+ /// Parses a template, which declares one function.
174
+ pub(super) fn template(source: &str) -> ParsedScript {
175
+ ParsedScript::parse("template", source).expect("templates parse")
176
+ }
177
+
178
+ /// The one function a template declares.
179
+ fn template_function<'t>(template: Script<'t>) -> &'t Function<'t> {
180
+ let functions = extract::functions(&template.program.body);
181
+ let [function] = functions.values().copied().collect::<Vec<_>>()[..] else {
182
+ unreachable!("each template declares one function");
183
+ };
184
+ function
185
+ }
186
+
187
+ /// Matches `template` against `function` in `script`, including nested function declarations.
188
+ pub(super) fn matches<'a>(
189
+ template: &ParsedScript,
190
+ script: Script<'a>,
191
+ function: &'a Function<'a>,
192
+ helpers: &BinaryHelpers<'a>,
193
+ ) -> Option<Captures<'a>> {
194
+ if !function.body.as_deref()?.directives.is_empty() {
195
+ return None;
196
+ }
197
+ matches_routine(
198
+ template,
199
+ script,
200
+ function,
201
+ Routine::function(function)?,
202
+ helpers,
203
+ )
204
+ }
205
+
206
+ /// Matches `template` against `routine`, which is `function`'s or is assembled from it.
207
+ pub(super) fn matches_routine<'a>(
208
+ template: &ParsedScript,
209
+ script: Script<'a>,
210
+ function: &'a Function<'a>,
211
+ routine: Routine<'a>,
212
+ helpers: &BinaryHelpers<'a>,
213
+ ) -> Option<Captures<'a>> {
214
+ let template = template.script();
215
+ let template_function = template_function(template);
216
+ let matcher = Matcher {
217
+ template,
218
+ script,
219
+ template_locals: locals(Routine::function(template_function)?),
220
+ actual_locals: locals(routine),
221
+ dead: dead_statements(script, routine),
222
+ mentions: mentions(script, |visitor| visit_routine(visitor, routine)),
223
+ helpers,
224
+ inlined: RefCell::default(),
225
+ allocator: Allocator::default(),
226
+ };
227
+ let mut state = State::default();
228
+ if !matcher.routine(template_function, function, routine, &mut state) {
229
+ return None;
230
+ }
231
+ state.captures.helpers = matcher.inlined.into_inner();
232
+ Some(state.captures)
233
+ }
234
+
235
+ /// Matching state, cloned at choices so a failed alternative leaves no bindings.
236
+ #[derive(Clone, Default)]
237
+ struct State<'a> {
238
+ /// Function locals by template local, and the reverse.
239
+ locals: HashMap<SymbolId, SymbolId>,
240
+ reverse: HashMap<SymbolId, SymbolId>,
241
+ captures: Captures<'a>,
242
+ }
243
+
244
+ /// Runs `matches` on a copy of `state`, and keeps the copy only if it matched.
245
+ fn attempt<'a>(state: &mut State<'a>, matches: impl FnOnce(&mut State<'a>) -> bool) -> bool {
246
+ let mut attempt = state.clone();
247
+ let matched = matches(&mut attempt);
248
+ if matched {
249
+ *state = attempt;
250
+ }
251
+ matched
252
+ }
253
+
254
+ struct Matcher<'t, 'a, 'helpers> {
255
+ template: Script<'t>,
256
+ script: Script<'a>,
257
+ template_locals: HashSet<SymbolId>,
258
+ actual_locals: HashSet<SymbolId>,
259
+ /// Statements of the function to skip, by address.
260
+ dead: HashSet<usize>,
261
+ /// Reads of each binding in the function.
262
+ mentions: HashMap<Binding<'a>, usize>,
263
+ helpers: &'helpers BinaryHelpers<'a>,
264
+ /// See [`Captures::helpers`].
265
+ inlined: RefCell<BTreeSet<Binding<'a>>>,
266
+ /// Holds normal forms of the function's expressions.
267
+ allocator: Allocator,
268
+ }
269
+
270
+ /// Visits a routine's parameters, statements, and what it returns. Its declarations have no
271
+ /// initializers, so they read and write nothing.
272
+ fn visit_routine<'a>(visitor: &mut impl Visit<'a>, routine: Routine<'a>) {
273
+ visitor.visit_formal_parameters(routine.parameters);
274
+ for statement in routine.statements {
275
+ visitor.visit_statement(statement);
276
+ }
277
+ if let Some(returned) = routine.returns {
278
+ visitor.visit_expression(returned);
279
+ }
280
+ }
281
+
282
+ /// Every binding a routine declares, including in nested functions, but not the name of its
283
+ /// function.
284
+ fn locals(routine: Routine<'_>) -> HashSet<SymbolId> {
285
+ #[derive(Default)]
286
+ struct Locals(HashSet<SymbolId>);
287
+
288
+ impl<'a> Visit<'a> for Locals {
289
+ fn visit_binding_identifier(&mut self, name: &BindingIdentifier<'a>) {
290
+ self.0.insert(name.symbol_id());
291
+ }
292
+ }
293
+
294
+ let mut locals = Locals::default();
295
+ for declaration in routine.declarations {
296
+ for declarator in &declaration.declarations {
297
+ locals.visit_binding_pattern(&declarator.id);
298
+ }
299
+ }
300
+ visit_routine(&mut locals, routine);
301
+ locals.0
302
+ }
303
+
304
+ /// What `reference` resolves to in `script`. Also resolves copies of the script's references,
305
+ /// which keep their reference IDs.
306
+ fn resolve<'s>(script: Script<'s>, reference: &IdentifierReference<'_>) -> Binding<'s> {
307
+ let reference = script.scoping.get_reference(reference.reference_id());
308
+ match reference.symbol_id() {
309
+ Some(symbol) => Binding::Symbol(symbol),
310
+ None => match script.nodes.kind(reference.node_id()) {
311
+ AstKind::IdentifierReference(original) => Binding::Global(original.name.as_str()),
312
+ _ => unreachable!("a reference belongs to an identifier"),
313
+ },
314
+ }
315
+ }
316
+
317
+ fn address(statement: &Statement<'_>) -> usize {
318
+ ptr::from_ref(statement).addr()
319
+ }
320
+
321
+ /// A statement that may only build a helper object.
322
+ struct Candidate<'a> {
323
+ address: usize,
324
+ object: Binding<'a>,
325
+ /// The local `x` of `x = d.k`.
326
+ copy: Option<Binding<'a>>,
327
+ }
328
+
329
+ /// Statements that only build helper objects nothing uses: `d = {}` or `d = { k: function ..
330
+ /// }`, `d.k = function ..`, and `x = d.k`, where `d` and `x` are never otherwise mentioned.
331
+ /// They create objects and functions and read plain data properties, so skipping them changes
332
+ /// nothing observable.
333
+ fn dead_statements<'a>(script: Script<'a>, routine: Routine<'a>) -> HashSet<usize> {
334
+ let statements = flattened(script, routine.statements);
335
+ // `d` of `d.k`.
336
+ let object = |member: Option<&MemberExpression<'a>>| match member? {
337
+ MemberExpression::StaticMemberExpression(member) => match &member.object {
338
+ Expression::Identifier(object) => Some(script.binding(object)),
339
+ _ => None,
340
+ },
341
+ _ => None,
342
+ };
343
+ let mut candidates = Vec::new();
344
+ for &statement in &statements {
345
+ let Statement::ExpressionStatement(expression) = statement else {
346
+ continue;
347
+ };
348
+ let Expression::AssignmentExpression(assignment) = &expression.expression else {
349
+ continue;
350
+ };
351
+ if assignment.operator != AssignmentOperator::Assign {
352
+ continue;
353
+ }
354
+ let (object, copy) = match (&assignment.left, &assignment.right) {
355
+ (
356
+ AssignmentTarget::AssignmentTargetIdentifier(object),
357
+ Expression::ObjectExpression(literal),
358
+ ) if literal.properties.iter().all(is_function_property) => {
359
+ (script.binding(object), None)
360
+ }
361
+ (AssignmentTarget::AssignmentTargetIdentifier(copy), right) => {
362
+ let Some(object) = object(right.as_member_expression()) else {
363
+ continue;
364
+ };
365
+ (object, Some(script.binding(copy)))
366
+ }
367
+ (left, Expression::FunctionExpression(_)) => {
368
+ let Some(object) = object(left.as_member_expression()) else {
369
+ continue;
370
+ };
371
+ (object, None)
372
+ }
373
+ _ => continue,
374
+ };
375
+ candidates.push(Candidate {
376
+ address: address(statement),
377
+ object,
378
+ copy,
379
+ });
380
+ }
381
+ // Drop candidates until every helper object and copy is mentioned only in the remaining
382
+ // candidates, so no kept statement reads a removed object.
383
+ let all_mentions = mentions(script, |visitor| visit_routine(visitor, routine));
384
+ let all_writes = writes(script, |visitor| visit_routine(visitor, routine));
385
+ loop {
386
+ let objects: HashSet<Binding<'a>> = candidates
387
+ .iter()
388
+ .filter(|candidate| candidate.copy.is_none())
389
+ .map(|candidate| candidate.object)
390
+ .collect();
391
+ let mut inside_mentions: HashMap<Binding<'a>, usize> = HashMap::default();
392
+ let mut inside_writes: HashMap<Binding<'a>, usize> = HashMap::default();
393
+ for &statement in &statements {
394
+ if candidates
395
+ .iter()
396
+ .any(|candidate| candidate.address == address(statement))
397
+ {
398
+ let read = mentions(script, |visitor| visitor.visit_statement(statement));
399
+ for (binding, count) in read {
400
+ *inside_mentions.entry(binding).or_default() += count;
401
+ }
402
+ let written = writes(script, |visitor| visitor.visit_statement(statement));
403
+ for (binding, count) in written {
404
+ *inside_writes.entry(binding).or_default() += count;
405
+ }
406
+ }
407
+ }
408
+ let only_inside =
409
+ |binding: &Binding<'a>| all_mentions.get(binding) == inside_mentions.get(binding);
410
+ // Helper objects must also hold only the literals these statements assign.
411
+ let only_written_inside =
412
+ |binding: &Binding<'a>| all_writes.get(binding) == inside_writes.get(binding);
413
+ let before = candidates.len();
414
+ candidates.retain(|candidate| {
415
+ objects.contains(&candidate.object)
416
+ && only_inside(&candidate.object)
417
+ && only_written_inside(&candidate.object)
418
+ && candidate.copy.as_ref().is_none_or(only_inside)
419
+ });
420
+ if candidates.len() == before {
421
+ break;
422
+ }
423
+ }
424
+ candidates
425
+ .into_iter()
426
+ .map(|candidate| candidate.address)
427
+ .collect()
428
+ }
429
+
430
+ /// A plain property whose value is a function expression.
431
+ fn is_function_property(property: &ObjectPropertyKind<'_>) -> bool {
432
+ let ObjectPropertyKind::ObjectProperty(property) = property else {
433
+ return false;
434
+ };
435
+ if property.kind != PropertyKind::Init
436
+ || property.method
437
+ || property.shorthand
438
+ || property.computed
439
+ {
440
+ return false;
441
+ }
442
+ let plain = match &property.key {
443
+ PropertyKey::StaticIdentifier(key) => key.name != "__proto__",
444
+ PropertyKey::StringLiteral(key) => key.value != "__proto__",
445
+ _ => false,
446
+ };
447
+ plain && matches!(property.value, Expression::FunctionExpression(_))
448
+ }
449
+
450
+ /// Binding mentions in what `visit` visits.
451
+ fn mentions<'s>(
452
+ script: Script<'s>,
453
+ visit: impl FnOnce(&mut Mentions<'s>),
454
+ ) -> HashMap<Binding<'s>, usize> {
455
+ let mut mentions = Mentions {
456
+ script,
457
+ counts: HashMap::default(),
458
+ };
459
+ visit(&mut mentions);
460
+ mentions.counts
461
+ }
462
+
463
+ /// Reads of bindings, and names of declared functions and classes. Declarations and assignment
464
+ /// targets are not mentions: removing a write to a binding nothing reads changes nothing.
465
+ struct Mentions<'s> {
466
+ script: Script<'s>,
467
+ counts: HashMap<Binding<'s>, usize>,
468
+ }
469
+
470
+ impl<'s> Mentions<'s> {
471
+ fn count(&mut self, binding: Binding<'s>) {
472
+ *self.counts.entry(binding).or_default() += 1;
473
+ }
474
+ }
475
+
476
+ impl<'x> Visit<'x> for Mentions<'_> {
477
+ fn visit_identifier_reference(&mut self, reference: &IdentifierReference<'x>) {
478
+ self.count(resolve(self.script, reference));
479
+ }
480
+
481
+ fn visit_simple_assignment_target(&mut self, target: &SimpleAssignmentTarget<'x>) {
482
+ if !matches!(
483
+ target,
484
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(_)
485
+ ) {
486
+ walk::walk_simple_assignment_target(self, target);
487
+ }
488
+ }
489
+
490
+ fn visit_assignment_target_property_identifier(
491
+ &mut self,
492
+ property: &AssignmentTargetPropertyIdentifier<'x>,
493
+ ) {
494
+ if let Some(init) = &property.init {
495
+ self.visit_expression(init);
496
+ }
497
+ }
498
+
499
+ /// An increment reads its operand.
500
+ fn visit_update_expression(&mut self, update: &UpdateExpression<'x>) {
501
+ match &update.argument {
502
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(name) => {
503
+ self.count(resolve(self.script, name));
504
+ }
505
+ _ => walk::walk_update_expression(self, update),
506
+ }
507
+ }
508
+
509
+ fn visit_function(&mut self, function: &Function<'x>, flags: ScopeFlags) {
510
+ if let Some(name) = &function.id {
511
+ self.count(Binding::Symbol(name.symbol_id()));
512
+ }
513
+ walk::walk_function(self, function, flags);
514
+ }
515
+
516
+ fn visit_class(&mut self, class: &Class<'x>) {
517
+ if let Some(name) = &class.id {
518
+ self.count(Binding::Symbol(name.symbol_id()));
519
+ }
520
+ walk::walk_class(self, class);
521
+ }
522
+ }
523
+
524
+ /// Binding occurrences other than declarations without initializers: assignment targets,
525
+ /// initialized declarations, parameters, and patterns.
526
+ fn writes<'s>(
527
+ script: Script<'s>,
528
+ visit: impl FnOnce(&mut Writes<'s>),
529
+ ) -> HashMap<Binding<'s>, usize> {
530
+ let mut writes = Writes {
531
+ script,
532
+ counts: HashMap::default(),
533
+ };
534
+ visit(&mut writes);
535
+ writes.counts
536
+ }
537
+
538
+ struct Writes<'s> {
539
+ script: Script<'s>,
540
+ counts: HashMap<Binding<'s>, usize>,
541
+ }
542
+
543
+ impl<'s> Writes<'s> {
544
+ fn count(&mut self, binding: Binding<'s>) {
545
+ *self.counts.entry(binding).or_default() += 1;
546
+ }
547
+ }
548
+
549
+ impl<'x> Visit<'x> for Writes<'_> {
550
+ fn visit_binding_identifier(&mut self, name: &BindingIdentifier<'x>) {
551
+ self.count(Binding::Symbol(name.symbol_id()));
552
+ }
553
+
554
+ fn visit_variable_declarator(&mut self, declarator: &VariableDeclarator<'x>) {
555
+ if declarator.init.is_some() {
556
+ walk::walk_variable_declarator(self, declarator);
557
+ }
558
+ }
559
+
560
+ fn visit_simple_assignment_target(&mut self, target: &SimpleAssignmentTarget<'x>) {
561
+ match target {
562
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(name) => {
563
+ self.count(resolve(self.script, name));
564
+ }
565
+ target => walk::walk_simple_assignment_target(self, target),
566
+ }
567
+ }
568
+
569
+ fn visit_assignment_target_property_identifier(
570
+ &mut self,
571
+ property: &AssignmentTargetPropertyIdentifier<'x>,
572
+ ) {
573
+ self.count(resolve(self.script, &property.binding));
574
+ if let Some(init) = &property.init {
575
+ self.visit_expression(init);
576
+ }
577
+ }
578
+
579
+ /// Only assignments write; an increment's operand is a read.
580
+ fn visit_update_expression(&mut self, update: &UpdateExpression<'x>) {
581
+ if !matches!(
582
+ update.argument,
583
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(_)
584
+ ) {
585
+ walk::walk_update_expression(self, update);
586
+ }
587
+ }
588
+
589
+ /// A function's name is not a write.
590
+ fn visit_function(&mut self, function: &Function<'x>, _: ScopeFlags) {
591
+ self.visit_formal_parameters(&function.params);
592
+ if let Some(body) = &function.body {
593
+ self.visit_function_body(body);
594
+ }
595
+ }
596
+
597
+ /// A class's name is not a write.
598
+ fn visit_class(&mut self, class: &Class<'x>) {
599
+ if let Some(heritage) = &class.heritage {
600
+ self.visit_expression(&heritage.expression);
601
+ }
602
+ self.visit_class_body(&class.body);
603
+ }
604
+ }
605
+
606
+ /// A name in a template or function: a reference or a binding.
607
+ #[derive(Clone, Copy)]
608
+ enum Name<'n, 'x> {
609
+ Reference(&'n IdentifierReference<'x>),
610
+ Binding(&'n BindingIdentifier<'x>),
611
+ }
612
+
613
+ impl<'n> Name<'n, '_> {
614
+ fn text(self) -> &'n str {
615
+ match self {
616
+ Self::Reference(reference) => reference.name.as_str(),
617
+ Self::Binding(binding) => binding.name.as_str(),
618
+ }
619
+ }
620
+ }
621
+
622
+ impl<'a> Matcher<'_, 'a, '_> {
623
+ /// Matches the template's function against `actual`, which is `function`'s routine or
624
+ /// assembled from it.
625
+ fn routine(
626
+ &self,
627
+ template: &Function<'_>,
628
+ function: &Function<'_>,
629
+ actual: Routine<'a>,
630
+ state: &mut State<'a>,
631
+ ) -> bool {
632
+ if !self.signature(template, function, state) {
633
+ return false;
634
+ }
635
+ let Some(body) = &template.body else {
636
+ return false;
637
+ };
638
+ let template = running(self.template, &body.statements, None).0;
639
+ let (statements, completes) = running(self.script, actual.statements, Some(&self.dead));
640
+ match actual.returns {
641
+ // The return follows the routine's statements if they can complete.
642
+ Some(returned) if completes => {
643
+ let Some((last, template)) = template.split_last() else {
644
+ return false;
645
+ };
646
+ template.len() == statements.len()
647
+ && self.pairs(template, &statements, state)
648
+ && match last {
649
+ Statement::ReturnStatement(last) => last
650
+ .argument
651
+ .as_ref()
652
+ .is_some_and(|argument| self.expression(argument, returned, state)),
653
+ _ => false,
654
+ }
655
+ }
656
+ _ => template.len() == statements.len() && self.pairs(&template, &statements, state),
657
+ }
658
+ }
659
+
660
+ /// Matches asynchrony, generators, and parameters.
661
+ fn signature(
662
+ &self,
663
+ template: &Function<'_>,
664
+ actual: &Function<'_>,
665
+ state: &mut State<'a>,
666
+ ) -> bool {
667
+ let count = extract::parameter_count(&template.params);
668
+ if template.r#async != actual.r#async
669
+ || template.generator != actual.generator
670
+ || count != extract::parameter_count(&actual.params)
671
+ {
672
+ return false;
673
+ }
674
+ (0..count).all(|index| {
675
+ let template = extract::parameter(&template.params, index);
676
+ let actual = extract::parameter(&actual.params, index);
677
+ template.zip(actual).is_some_and(|(template, actual)| {
678
+ self.name(Name::Binding(template), Name::Binding(actual), state)
679
+ })
680
+ })
681
+ }
682
+
683
+ /// Matches a nested function declaration's function.
684
+ fn function(
685
+ &self,
686
+ template: &Function<'_>,
687
+ actual: &Function<'_>,
688
+ state: &mut State<'a>,
689
+ ) -> bool {
690
+ if !self.signature(template, actual, state) {
691
+ return false;
692
+ }
693
+ match (&template.body, &actual.body) {
694
+ (Some(template), Some(actual)) if actual.directives.is_empty() => {
695
+ self.list(&template.statements, &actual.statements, state)
696
+ }
697
+ _ => false,
698
+ }
699
+ }
700
+
701
+ fn list(
702
+ &self,
703
+ template: &[Statement<'_>],
704
+ actual: &[Statement<'_>],
705
+ state: &mut State<'a>,
706
+ ) -> bool {
707
+ let template = running(self.template, template, None).0;
708
+ let actual = running(self.script, actual, Some(&self.dead)).0;
709
+ template.len() == actual.len() && self.pairs(&template, &actual, state)
710
+ }
711
+
712
+ /// Matches statements pairwise, in order.
713
+ fn pairs(
714
+ &self,
715
+ template: &[&Statement<'_>],
716
+ actual: &[&Statement<'_>],
717
+ state: &mut State<'a>,
718
+ ) -> bool {
719
+ template
720
+ .iter()
721
+ .zip(actual)
722
+ .all(|(template, actual)| self.statement(template, actual, state))
723
+ }
724
+
725
+ /// A statement, treating a lone statement and a block holding only it alike.
726
+ fn body(
727
+ &self,
728
+ template: &Statement<'_>,
729
+ actual: &Statement<'_>,
730
+ state: &mut State<'a>,
731
+ ) -> bool {
732
+ self.list(as_list(template), as_list(actual), state)
733
+ }
734
+
735
+ fn statement(
736
+ &self,
737
+ template: &Statement<'_>,
738
+ actual: &Statement<'_>,
739
+ state: &mut State<'a>,
740
+ ) -> bool {
741
+ // `var x = y = e;`, where nothing reads `x`, only assigns `y`.
742
+ if let Statement::VariableDeclaration(declaration) = actual
743
+ && !declaration.kind.is_using()
744
+ && let [declarator] = &declaration.declarations[..]
745
+ && let BindingPattern::BindingIdentifier(unread) = &declarator.id
746
+ && !self
747
+ .mentions
748
+ .contains_key(&Binding::Symbol(unread.symbol_id()))
749
+ && let Some(Expression::AssignmentExpression(chained)) = &declarator.init
750
+ && chained.operator == AssignmentOperator::Assign
751
+ && let AssignmentTarget::AssignmentTargetIdentifier(target) = &chained.left
752
+ && let Some((name, value)) = assigned(template)
753
+ {
754
+ return self.name(Name::Reference(name), Name::Reference(target), state)
755
+ && self.expression(value, &chained.right, state);
756
+ }
757
+ if let (Some((name, value)), Some((other, init))) =
758
+ (assigned(template), initialized(actual))
759
+ {
760
+ return self.name(Name::Reference(name), Name::Binding(other), state)
761
+ && self.expression(value, init, state);
762
+ }
763
+ if let (Some((name, init)), Some((other, value))) =
764
+ (initialized(template), assigned(actual))
765
+ {
766
+ return self.name(Name::Binding(name), Name::Reference(other), state)
767
+ && self.expression(init, value, state);
768
+ }
769
+ match (template, actual) {
770
+ (Statement::ExpressionStatement(template), Statement::ExpressionStatement(actual)) => {
771
+ self.expression(&template.expression, &actual.expression, state)
772
+ }
773
+ (Statement::ReturnStatement(template), Statement::ReturnStatement(actual)) => {
774
+ self.optional(template.argument.as_ref(), actual.argument.as_ref(), state)
775
+ }
776
+ (Statement::ThrowStatement(template), Statement::ThrowStatement(actual)) => {
777
+ self.expression(&template.argument, &actual.argument, state)
778
+ }
779
+ (Statement::BlockStatement(template), Statement::BlockStatement(actual)) => {
780
+ self.list(&template.body, &actual.body, state)
781
+ }
782
+ (Statement::IfStatement(template), Statement::IfStatement(actual)) => {
783
+ self.expression(&template.test, &actual.test, state)
784
+ && self.body(&template.consequent, &actual.consequent, state)
785
+ && match (&template.alternate, &actual.alternate) {
786
+ (None, None) => true,
787
+ (Some(template), Some(actual)) => self.body(template, actual, state),
788
+ _ => false,
789
+ }
790
+ }
791
+ (Statement::ForStatement(template), Statement::ForStatement(actual)) => {
792
+ self.for_loop(template, actual, state)
793
+ }
794
+ (Statement::VariableDeclaration(template), Statement::VariableDeclaration(actual))
795
+ if !template.kind.is_using() && !actual.kind.is_using() =>
796
+ {
797
+ self.declarations(template, actual, state)
798
+ }
799
+ (Statement::FunctionDeclaration(template), Statement::FunctionDeclaration(actual)) => {
800
+ template
801
+ .id
802
+ .as_ref()
803
+ .zip(actual.id.as_ref())
804
+ .is_some_and(|(name, other)| {
805
+ self.name(Name::Binding(name), Name::Binding(other), state)
806
+ })
807
+ && self.function(template, actual, state)
808
+ }
809
+ _ => false,
810
+ }
811
+ }
812
+
813
+ fn for_loop(
814
+ &self,
815
+ template: &ForStatement<'_>,
816
+ actual: &ForStatement<'_>,
817
+ state: &mut State<'a>,
818
+ ) -> bool {
819
+ let initialized = match (&template.init, &actual.init) {
820
+ (None, None) => true,
821
+ (
822
+ Some(ForStatementInit::VariableDeclaration(template)),
823
+ Some(ForStatementInit::VariableDeclaration(actual)),
824
+ ) => {
825
+ !template.kind.is_using()
826
+ && !actual.kind.is_using()
827
+ && self.declarations(template, actual, state)
828
+ }
829
+ (Some(ForStatementInit::VariableDeclaration(_)), _)
830
+ | (_, Some(ForStatementInit::VariableDeclaration(_))) => false,
831
+ (Some(template), Some(actual)) => {
832
+ self.expression(template.to_expression(), actual.to_expression(), state)
833
+ }
834
+ _ => false,
835
+ };
836
+ initialized
837
+ && self.optional(template.test.as_ref(), actual.test.as_ref(), state)
838
+ && self.optional(template.update.as_ref(), actual.update.as_ref(), state)
839
+ && self.body(&template.body, &actual.body, state)
840
+ }
841
+
842
+ fn declarations(
843
+ &self,
844
+ template: &VariableDeclaration<'_>,
845
+ actual: &VariableDeclaration<'_>,
846
+ state: &mut State<'a>,
847
+ ) -> bool {
848
+ template.kind == actual.kind
849
+ && template.declarations.len() == actual.declarations.len()
850
+ && template
851
+ .declarations
852
+ .iter()
853
+ .zip(&actual.declarations)
854
+ .all(|(template, actual)| {
855
+ let (
856
+ BindingPattern::BindingIdentifier(name),
857
+ BindingPattern::BindingIdentifier(other),
858
+ ) = (&template.id, &actual.id)
859
+ else {
860
+ return false;
861
+ };
862
+ self.name(Name::Binding(name), Name::Binding(other), state)
863
+ && self.optional(template.init.as_ref(), actual.init.as_ref(), state)
864
+ })
865
+ }
866
+
867
+ fn optional(
868
+ &self,
869
+ template: Option<&Expression<'_>>,
870
+ actual: Option<&Expression<'_>>,
871
+ state: &mut State<'a>,
872
+ ) -> bool {
873
+ match (template, actual) {
874
+ (None, None) => true,
875
+ (Some(template), Some(actual)) => self.expression(template, actual, state),
876
+ _ => false,
877
+ }
878
+ }
879
+
880
+ /// Binds a template name to a function name: free names to free bindings, and locals to
881
+ /// locals one to one.
882
+ fn name(&self, template: Name<'_, '_>, actual: Name<'_, '_>, state: &mut State<'a>) -> bool {
883
+ let text = template.text();
884
+ // Constant placeholders only match numeric literals.
885
+ if text.starts_with("$c_") {
886
+ return false;
887
+ }
888
+ let template_symbol = match template {
889
+ Name::Reference(reference) => self.template.symbol(reference),
890
+ Name::Binding(binding) => Some(binding.symbol_id()),
891
+ };
892
+ let actual_binding = match actual {
893
+ Name::Reference(reference) => resolve(self.script, reference),
894
+ Name::Binding(binding) => Binding::Symbol(binding.symbol_id()),
895
+ };
896
+ let template_local = template_symbol.filter(|symbol| self.template_locals.contains(symbol));
897
+ let actual_local = match actual_binding {
898
+ Binding::Symbol(symbol) if self.actual_locals.contains(&symbol) => Some(symbol),
899
+ _ => None,
900
+ };
901
+ let (Some(template_local), Some(actual_local)) = (template_local, actual_local) else {
902
+ if text.starts_with('$') && template_local.is_none() {
903
+ let names = &mut state.captures.names;
904
+ return actual_local.is_none()
905
+ && *names.entry(text.to_owned()).or_insert(actual_binding) == actual_binding;
906
+ }
907
+ // Other free names, such as `Error`, must be the same global.
908
+ return template_symbol.is_none() && actual_binding == Binding::Global(text);
909
+ };
910
+ match (
911
+ state.locals.get(&template_local),
912
+ state.reverse.get(&actual_local),
913
+ ) {
914
+ (Some(bound), _) => *bound == actual_local,
915
+ (None, Some(_)) => false,
916
+ (None, None) => {
917
+ state.locals.insert(template_local, actual_local);
918
+ state.reverse.insert(actual_local, template_local);
919
+ true
920
+ }
921
+ }
922
+ }
923
+
924
+ fn expression(
925
+ &self,
926
+ template: &Expression<'_>,
927
+ actual: &Expression<'_>,
928
+ state: &mut State<'a>,
929
+ ) -> bool {
930
+ if let Expression::Identifier(placeholder) = template.without_parentheses()
931
+ && placeholder.name.starts_with("$e_")
932
+ {
933
+ return self.formula(placeholder.name.as_str(), actual, state);
934
+ }
935
+ if let Some(normalized) = self.normalized(actual) {
936
+ return self.expression(template, normalized, state);
937
+ }
938
+ match (template.without_parentheses(), actual.without_parentheses()) {
939
+ (Expression::Identifier(template), Expression::NumericLiteral(number))
940
+ if template.name.starts_with("$c_") =>
941
+ {
942
+ let constants = &mut state.captures.constants;
943
+ let bound = *constants
944
+ .entry(template.name.as_str().to_owned())
945
+ .or_insert(number.value);
946
+ bound.to_bits() == number.value.to_bits()
947
+ }
948
+ (Expression::Identifier(template), Expression::Identifier(actual)) => {
949
+ self.name(Name::Reference(template), Name::Reference(actual), state)
950
+ }
951
+ (Expression::NumericLiteral(template), Expression::NumericLiteral(actual)) => {
952
+ template.value.to_bits() == actual.value.to_bits()
953
+ }
954
+ (Expression::StringLiteral(template), Expression::StringLiteral(actual)) => {
955
+ template.value == actual.value
956
+ }
957
+ (Expression::BooleanLiteral(template), Expression::BooleanLiteral(actual)) => {
958
+ template.value == actual.value
959
+ }
960
+ (Expression::NullLiteral(_), Expression::NullLiteral(_)) => true,
961
+ (Expression::TemplateLiteral(template), Expression::TemplateLiteral(actual)) => {
962
+ template.expressions.is_empty()
963
+ && actual.expressions.is_empty()
964
+ && template.quasis.len() == actual.quasis.len()
965
+ && template
966
+ .quasis
967
+ .iter()
968
+ .zip(&actual.quasis)
969
+ .all(|(template, actual)| template.value.cooked == actual.value.cooked)
970
+ }
971
+ (Expression::ArrayExpression(template), Expression::ArrayExpression(actual)) => {
972
+ template.elements.len() == actual.elements.len()
973
+ && template
974
+ .elements
975
+ .iter()
976
+ .zip(&actual.elements)
977
+ .all(|pair| match pair {
978
+ (
979
+ ArrayExpressionElement::Elision(_)
980
+ | ArrayExpressionElement::SpreadElement(_),
981
+ _,
982
+ )
983
+ | (
984
+ _,
985
+ ArrayExpressionElement::Elision(_)
986
+ | ArrayExpressionElement::SpreadElement(_),
987
+ ) => false,
988
+ (template, actual) => self.expression(
989
+ template.to_expression(),
990
+ actual.to_expression(),
991
+ state,
992
+ ),
993
+ })
994
+ }
995
+ (Expression::CallExpression(template), Expression::CallExpression(actual)) => {
996
+ self.expression(&template.callee, &actual.callee, state)
997
+ && self.arguments(&template.arguments, &actual.arguments, state)
998
+ }
999
+ (Expression::NewExpression(template), Expression::NewExpression(actual)) => {
1000
+ self.expression(&template.callee, &actual.callee, state)
1001
+ && self.arguments(&template.arguments, &actual.arguments, state)
1002
+ }
1003
+ (Expression::UnaryExpression(template), Expression::UnaryExpression(actual)) => {
1004
+ template.operator == actual.operator
1005
+ && self.expression(&template.argument, &actual.argument, state)
1006
+ }
1007
+ (Expression::UpdateExpression(template), Expression::UpdateExpression(actual)) => {
1008
+ template.operator == actual.operator
1009
+ && template.prefix == actual.prefix
1010
+ && self.simple_target(&template.argument, &actual.argument, state)
1011
+ }
1012
+ (
1013
+ Expression::ConditionalExpression(template),
1014
+ Expression::ConditionalExpression(actual),
1015
+ ) => {
1016
+ self.expression(&template.test, &actual.test, state)
1017
+ && self.expression(&template.consequent, &actual.consequent, state)
1018
+ && self.expression(&template.alternate, &actual.alternate, state)
1019
+ }
1020
+ (
1021
+ Expression::AssignmentExpression(template),
1022
+ Expression::AssignmentExpression(actual),
1023
+ ) => {
1024
+ template.operator == actual.operator
1025
+ && self.target(&template.left, &actual.left, state)
1026
+ && self.expression(&template.right, &actual.right, state)
1027
+ }
1028
+ (Expression::BinaryExpression(template), Expression::BinaryExpression(actual))
1029
+ if template.operator == actual.operator =>
1030
+ {
1031
+ self.binary(template, actual, state)
1032
+ }
1033
+ (Expression::LogicalExpression(template), Expression::LogicalExpression(actual))
1034
+ if template.operator == actual.operator =>
1035
+ {
1036
+ attempt(state, |attempt| {
1037
+ self.expression(&template.left, &actual.left, attempt)
1038
+ && self.expression(&template.right, &actual.right, attempt)
1039
+ })
1040
+ }
1041
+ (template, actual) => template
1042
+ .as_member_expression()
1043
+ .zip(actual.as_member_expression())
1044
+ .is_some_and(|(template, actual)| self.member(template, actual, state)),
1045
+ }
1046
+ }
1047
+
1048
+ fn member(
1049
+ &self,
1050
+ template: &MemberExpression<'_>,
1051
+ actual: &MemberExpression<'_>,
1052
+ state: &mut State<'a>,
1053
+ ) -> bool {
1054
+ if matches!(template.object(), Expression::Super(_))
1055
+ || matches!(actual.object(), Expression::Super(_))
1056
+ {
1057
+ return false;
1058
+ }
1059
+ self.expression(template.object(), actual.object(), state)
1060
+ && match (template, actual) {
1061
+ (
1062
+ MemberExpression::StaticMemberExpression(template),
1063
+ MemberExpression::StaticMemberExpression(actual),
1064
+ ) => template.property.name == actual.property.name,
1065
+ (
1066
+ MemberExpression::ComputedMemberExpression(template),
1067
+ MemberExpression::ComputedMemberExpression(actual),
1068
+ ) => self.expression(&template.expression, &actual.expression, state),
1069
+ _ => false,
1070
+ }
1071
+ }
1072
+
1073
+ /// Matches binary expressions with the same operator. The function's expression is not a
1074
+ /// normalized form (see [`Self::normalized`]).
1075
+ fn binary(
1076
+ &self,
1077
+ template: &BinaryExpression<'_>,
1078
+ actual: &BinaryExpression<'_>,
1079
+ state: &mut State<'a>,
1080
+ ) -> bool {
1081
+ let operator = template.operator;
1082
+ if matches!(
1083
+ operator,
1084
+ BinaryOperator::BitwiseAnd | BinaryOperator::BitwiseOR | BinaryOperator::BitwiseXOR
1085
+ ) {
1086
+ let (mut template_operands, mut actual_operands) = (Vec::new(), Vec::new());
1087
+ self.chain(operator, &template.left, &mut template_operands, false);
1088
+ self.chain(operator, &template.right, &mut template_operands, false);
1089
+ self.chain(operator, &actual.left, &mut actual_operands, true);
1090
+ self.chain(operator, &actual.right, &mut actual_operands, true);
1091
+ return template_operands.len() == actual_operands.len()
1092
+ && self.permutation(&template_operands, &mut actual_operands, state);
1093
+ }
1094
+ let ordered = attempt(state, |attempt| {
1095
+ self.expression(&template.left, &actual.left, attempt)
1096
+ && self.expression(&template.right, &actual.right, attempt)
1097
+ });
1098
+ if ordered {
1099
+ return true;
1100
+ }
1101
+ let commutes = matches!(
1102
+ operator,
1103
+ BinaryOperator::Multiplication
1104
+ | BinaryOperator::StrictEquality
1105
+ | BinaryOperator::StrictInequality
1106
+ | BinaryOperator::Equality
1107
+ | BinaryOperator::Inequality
1108
+ );
1109
+ commutes
1110
+ && attempt(state, |attempt| {
1111
+ self.expression(&template.left, &actual.right, attempt)
1112
+ && self.expression(&template.right, &actual.left, attempt)
1113
+ })
1114
+ }
1115
+
1116
+ /// Matches each template operand to a distinct remaining operand, in some order.
1117
+ fn permutation(
1118
+ &self,
1119
+ template: &[&Expression<'_>],
1120
+ actual: &mut Vec<&Expression<'_>>,
1121
+ state: &mut State<'a>,
1122
+ ) -> bool {
1123
+ let Some((first, rest)) = template.split_first() else {
1124
+ return actual.is_empty();
1125
+ };
1126
+ for index in 0..actual.len() {
1127
+ let mut attempt = state.clone();
1128
+ if !self.expression(first, actual[index], &mut attempt) {
1129
+ continue;
1130
+ }
1131
+ let candidate = actual.remove(index);
1132
+ if self.permutation(rest, actual, &mut attempt) {
1133
+ *state = attempt;
1134
+ return true;
1135
+ }
1136
+ actual.insert(index, candidate);
1137
+ }
1138
+ false
1139
+ }
1140
+
1141
+ /// Captures `actual`, in normal form, as the formula `placeholder` names. Its locals must
1142
+ /// already match template locals, whose names the formula uses.
1143
+ fn formula(&self, placeholder: &str, actual: &Expression<'_>, state: &mut State<'a>) -> bool {
1144
+ if state.captures.formulas.contains_key(placeholder) {
1145
+ return false;
1146
+ }
1147
+ let name = |identifier: &IdentifierReference<'_>| {
1148
+ let Binding::Symbol(symbol) = resolve(self.script, identifier) else {
1149
+ return None;
1150
+ };
1151
+ let template = state.reverse.get(&symbol)?;
1152
+ Some(self.template.scoping.symbol_name(*template).to_owned())
1153
+ };
1154
+ let Some(formula) = Formula::compile(actual, &|expression| self.normal(expression), &name)
1155
+ else {
1156
+ return false;
1157
+ };
1158
+ state
1159
+ .captures
1160
+ .formulas
1161
+ .insert(placeholder.to_owned(), formula);
1162
+ true
1163
+ }
1164
+
1165
+ /// `expression` in normal form (see [`Self::normalized`]).
1166
+ fn normal<'m>(&'m self, mut expression: &'m Expression<'m>) -> &'m Expression<'m> {
1167
+ while let Some(normalized) = self.normalized(expression) {
1168
+ expression = normalized;
1169
+ }
1170
+ expression
1171
+ }
1172
+
1173
+ /// Collects the operands of a chain of `operator`, looking through parentheses and, if
1174
+ /// `normalize` (in the function), normalized forms.
1175
+ fn chain<'m>(
1176
+ &'m self,
1177
+ operator: BinaryOperator,
1178
+ expression: &'m Expression<'m>,
1179
+ operands: &mut Vec<&'m Expression<'m>>,
1180
+ normalize: bool,
1181
+ ) {
1182
+ if normalize && let Some(normalized) = self.normalized(expression) {
1183
+ return self.chain(operator, normalized, operands, normalize);
1184
+ }
1185
+ match expression.without_parentheses() {
1186
+ Expression::BinaryExpression(binary) if binary.operator == operator => {
1187
+ self.chain(operator, &binary.left, operands, normalize);
1188
+ self.chain(operator, &binary.right, operands, normalize);
1189
+ }
1190
+ operand => operands.push(operand),
1191
+ }
1192
+ }
1193
+
1194
+ /// Rewrites a function expression to the plain form it computes, or returns `None`:
1195
+ ///
1196
+ /// - `(t = a, u = b, e)`, where nothing outside `e` reads `t` or `u`, becomes `e` with `a`
1197
+ /// and `b` in place of `t` and `u`. A match only accepts side-effect-free operands, so
1198
+ /// evaluating them where `e` reads them computes the same values.
1199
+ /// - `(x ^ y) + (x & y)` becomes `x | y`, `(x | y) - (x & y)` becomes `x ^ y`, and
1200
+ /// `(x | 0) + (0 | y) - (y | x)` becomes `x & y`, each also under `| 0`. These are
1201
+ /// identities of two's-complement integers, and `|`, `^` and `&` convert both operands to
1202
+ /// them.
1203
+ /// - A call to a binary helper becomes its operator applied to the arguments.
1204
+ fn normalized<'m>(&'m self, expression: &Expression<'_>) -> Option<&'m Expression<'m>> {
1205
+ let expression = expression.without_parentheses();
1206
+ if let Expression::SequenceExpression(sequence) = expression {
1207
+ return self.substituted(sequence);
1208
+ }
1209
+ if let Expression::CallExpression(call) = expression
1210
+ && let Expression::Identifier(callee) = &call.callee
1211
+ && let callee = resolve(self.script, callee)
1212
+ && !matches!(callee, Binding::Symbol(symbol) if self.actual_locals.contains(&symbol))
1213
+ && let Some(helper) = self.helpers.get(&callee)
1214
+ && let [first, second] = &call.arguments[..]
1215
+ && let (Some(first), Some(second)) = (first.as_expression(), second.as_expression())
1216
+ {
1217
+ self.inlined.borrow_mut().insert(callee);
1218
+ let (left, right) = if helper.swapped {
1219
+ (second, first)
1220
+ } else {
1221
+ (first, second)
1222
+ };
1223
+ return Some(self.operation(helper.operator, left, right));
1224
+ }
1225
+ let Expression::BinaryExpression(outer) = expression else {
1226
+ return None;
1227
+ };
1228
+ if outer.operator == BinaryOperator::BitwiseOR
1229
+ && let Some(inner) = truncated(expression)
1230
+ && let Some(normalized) = self.normalized(inner)
1231
+ && matches!(normalized, Expression::BinaryExpression(found)
1232
+ if matches!(found.operator,
1233
+ BinaryOperator::BitwiseOR | BinaryOperator::BitwiseXOR | BinaryOperator::BitwiseAnd))
1234
+ {
1235
+ return Some(normalized);
1236
+ }
1237
+ let binary =
1238
+ |operator, (left, right)| Some(self.operation(Operator::Binary(operator), left, right));
1239
+ match outer.operator {
1240
+ BinaryOperator::Addition => {
1241
+ let (xor, and) = pair(&outer.left, BinaryOperator::BitwiseXOR)
1242
+ .zip(pair(&outer.right, BinaryOperator::BitwiseAnd))
1243
+ .or_else(|| {
1244
+ pair(&outer.right, BinaryOperator::BitwiseXOR)
1245
+ .zip(pair(&outer.left, BinaryOperator::BitwiseAnd))
1246
+ })?;
1247
+ if !self.same_operands(xor, and) {
1248
+ return None;
1249
+ }
1250
+ binary(BinaryOperator::BitwiseOR, xor)
1251
+ }
1252
+ BinaryOperator::Subtraction => {
1253
+ if let (Some(or), Some(and)) = (
1254
+ pair(&outer.left, BinaryOperator::BitwiseOR),
1255
+ pair(&outer.right, BinaryOperator::BitwiseAnd),
1256
+ ) && !is_zero(or.0)
1257
+ && !is_zero(or.1)
1258
+ && self.same_operands(or, and)
1259
+ {
1260
+ return binary(BinaryOperator::BitwiseXOR, or);
1261
+ }
1262
+ let or = pair(&outer.right, BinaryOperator::BitwiseOR)?;
1263
+ let (left, right) = pair(&outer.left, BinaryOperator::Addition)?;
1264
+ let x = truncated(left).or_else(|| int32_literal(left))?;
1265
+ let y = truncated(right).or_else(|| int32_literal(right))?;
1266
+ if !self.same_operands((x, y), or) {
1267
+ return None;
1268
+ }
1269
+ binary(BinaryOperator::BitwiseAnd, (x, y))
1270
+ }
1271
+ _ => None,
1272
+ }
1273
+ }
1274
+
1275
+ /// `(t = a, u = b, e)` with the temporaries substituted (see [`Self::normalized`]).
1276
+ fn substituted<'m>(&'m self, sequence: &SequenceExpression<'_>) -> Option<&'m Expression<'m>> {
1277
+ let (last, temporaries) = sequence.expressions.split_last()?;
1278
+ let mut values: HashMap<SymbolId, &'m Expression<'m>> = HashMap::default();
1279
+ for temporary in temporaries {
1280
+ let Expression::AssignmentExpression(assignment) = temporary else {
1281
+ return None;
1282
+ };
1283
+ let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left else {
1284
+ return None;
1285
+ };
1286
+ let Binding::Symbol(name) = resolve(self.script, name) else {
1287
+ return None;
1288
+ };
1289
+ if assignment.operator != AssignmentOperator::Assign
1290
+ || !self.actual_locals.contains(&name)
1291
+ || values.contains_key(&name)
1292
+ {
1293
+ return None;
1294
+ }
1295
+ let value = self.substitute(&assignment.right, &values);
1296
+ values.insert(name, value);
1297
+ }
1298
+ // Every read of each temporary is in the final expression, which does not write it.
1299
+ let reads = mentions(self.script, |visitor| visitor.visit_expression(last));
1300
+ let written = writes(self.script, |visitor| visitor.visit_expression(last));
1301
+ let all_read_here = values.keys().all(|&name| {
1302
+ let name = Binding::Symbol(name);
1303
+ self.mentions.get(&name) == reads.get(&name) && !written.contains_key(&name)
1304
+ });
1305
+ if !all_read_here {
1306
+ return None;
1307
+ }
1308
+ Some(self.substitute(last, &values))
1309
+ }
1310
+
1311
+ /// A copy of `expression` with each temporary in `values` replaced by its value.
1312
+ fn substitute<'m>(
1313
+ &'m self,
1314
+ expression: &Expression<'_>,
1315
+ values: &HashMap<SymbolId, &'m Expression<'m>>,
1316
+ ) -> &'m Expression<'m> {
1317
+ struct Substitute<'v, 'm, 'a> {
1318
+ script: Script<'a>,
1319
+ allocator: &'m Allocator,
1320
+ values: &'v HashMap<SymbolId, &'m Expression<'m>>,
1321
+ }
1322
+
1323
+ impl<'m> VisitMut<'m> for Substitute<'_, 'm, '_> {
1324
+ fn visit_expression(&mut self, expression: &mut Expression<'m>) {
1325
+ if let Expression::Identifier(name) = expression
1326
+ && let Binding::Symbol(symbol) = resolve(self.script, name)
1327
+ && let Some(value) = self.values.get(&symbol)
1328
+ {
1329
+ *expression = value.clone_in_with_semantic_ids(self.allocator);
1330
+ return;
1331
+ }
1332
+ walk_mut::walk_expression(self, expression);
1333
+ }
1334
+ }
1335
+
1336
+ let mut copy = expression.clone_in_with_semantic_ids(&self.allocator);
1337
+ Substitute {
1338
+ script: self.script,
1339
+ allocator: &self.allocator,
1340
+ values,
1341
+ }
1342
+ .visit_expression(&mut copy);
1343
+ self.allocator.alloc(copy)
1344
+ }
1345
+
1346
+ /// `left <operator> right`, built from copies of the operands.
1347
+ fn operation<'m>(
1348
+ &'m self,
1349
+ operator: Operator,
1350
+ left: &Expression<'_>,
1351
+ right: &Expression<'_>,
1352
+ ) -> &'m Expression<'m> {
1353
+ let builder = AstBuilder::new(&self.allocator);
1354
+ let left = left.clone_in_with_semantic_ids(&self.allocator);
1355
+ let right = right.clone_in_with_semantic_ids(&self.allocator);
1356
+ let expression = match operator {
1357
+ Operator::Binary(operator) => Expression::BinaryExpression(BinaryExpression::boxed(
1358
+ SPAN, left, operator, right, &builder,
1359
+ )),
1360
+ Operator::Logical(operator) => Expression::LogicalExpression(LogicalExpression::boxed(
1361
+ SPAN, left, operator, right, &builder,
1362
+ )),
1363
+ };
1364
+ self.allocator.alloc(expression)
1365
+ }
1366
+
1367
+ /// Whether two operand pairs hold the same operands, in either order.
1368
+ fn same_operands(
1369
+ &self,
1370
+ (a, b): (&Expression<'_>, &Expression<'_>),
1371
+ (c, d): (&Expression<'_>, &Expression<'_>),
1372
+ ) -> bool {
1373
+ (self.same(a, c) && self.same(b, d)) || (self.same(a, d) && self.same(b, c))
1374
+ }
1375
+
1376
+ /// Whether two expressions are the same syntax, outside their parentheses, with the same
1377
+ /// bindings.
1378
+ fn same(&self, left: &Expression<'_>, right: &Expression<'_>) -> bool {
1379
+ let (left, right) = (left.without_parentheses(), right.without_parentheses());
1380
+ left.content_eq(right) && self.bindings(left) == self.bindings(right)
1381
+ }
1382
+
1383
+ /// The bindings `expression` references or declares, in order.
1384
+ fn bindings(&self, expression: &Expression<'_>) -> Vec<Binding<'a>> {
1385
+ struct Bindings<'a> {
1386
+ script: Script<'a>,
1387
+ found: Vec<Binding<'a>>,
1388
+ }
1389
+
1390
+ impl<'x> Visit<'x> for Bindings<'_> {
1391
+ fn visit_identifier_reference(&mut self, reference: &IdentifierReference<'x>) {
1392
+ self.found.push(resolve(self.script, reference));
1393
+ }
1394
+
1395
+ fn visit_binding_identifier(&mut self, name: &BindingIdentifier<'x>) {
1396
+ self.found.push(Binding::Symbol(name.symbol_id()));
1397
+ }
1398
+ }
1399
+
1400
+ let mut bindings = Bindings {
1401
+ script: self.script,
1402
+ found: Vec::new(),
1403
+ };
1404
+ bindings.visit_expression(expression);
1405
+ bindings.found
1406
+ }
1407
+
1408
+ fn arguments(
1409
+ &self,
1410
+ template: &[Argument<'_>],
1411
+ actual: &[Argument<'_>],
1412
+ state: &mut State<'a>,
1413
+ ) -> bool {
1414
+ template.len() == actual.len()
1415
+ && template.iter().zip(actual).all(|(template, actual)| {
1416
+ template
1417
+ .as_expression()
1418
+ .zip(actual.as_expression())
1419
+ .is_some_and(|(template, actual)| self.expression(template, actual, state))
1420
+ })
1421
+ }
1422
+
1423
+ fn target(
1424
+ &self,
1425
+ template: &AssignmentTarget<'_>,
1426
+ actual: &AssignmentTarget<'_>,
1427
+ state: &mut State<'a>,
1428
+ ) -> bool {
1429
+ template
1430
+ .as_simple_assignment_target()
1431
+ .zip(actual.as_simple_assignment_target())
1432
+ .is_some_and(|(template, actual)| self.simple_target(template, actual, state))
1433
+ }
1434
+
1435
+ fn simple_target(
1436
+ &self,
1437
+ template: &SimpleAssignmentTarget<'_>,
1438
+ actual: &SimpleAssignmentTarget<'_>,
1439
+ state: &mut State<'a>,
1440
+ ) -> bool {
1441
+ match (template, actual) {
1442
+ (
1443
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(template),
1444
+ SimpleAssignmentTarget::AssignmentTargetIdentifier(actual),
1445
+ ) => self.name(Name::Reference(template), Name::Reference(actual), state),
1446
+ (template, actual) => template
1447
+ .as_member_expression()
1448
+ .zip(actual.as_member_expression())
1449
+ .is_some_and(|(template, actual)| self.member(template, actual, state)),
1450
+ }
1451
+ }
1452
+ }
1453
+
1454
+ /// The statements that run, without plain declarations and, given `dead`, dead statements, and
1455
+ /// whether the last of them can complete.
1456
+ fn running<'s, 'x>(
1457
+ script: Script<'_>,
1458
+ statements: &'s [Statement<'x>],
1459
+ dead: Option<&HashSet<usize>>,
1460
+ ) -> (Vec<&'s Statement<'x>>, bool) {
1461
+ let mut running = Vec::new();
1462
+ // Nothing after a `return` or `throw` runs, but functions and `var` bindings hoist.
1463
+ let mut reachable = true;
1464
+ for statement in flattened(script, statements) {
1465
+ let declaration = match statement {
1466
+ Statement::VariableDeclaration(declaration) if !declaration.kind.is_using() => {
1467
+ Some(declaration)
1468
+ }
1469
+ _ => None,
1470
+ };
1471
+ let initializes = declaration.is_some_and(|declaration| {
1472
+ declaration
1473
+ .declarations
1474
+ .iter()
1475
+ .any(|declarator| declarator.init.is_some())
1476
+ });
1477
+ let kept =
1478
+ reachable || initializes || matches!(statement, Statement::FunctionDeclaration(_));
1479
+ reachable &= !matches!(
1480
+ statement,
1481
+ Statement::ReturnStatement(_) | Statement::ThrowStatement(_)
1482
+ );
1483
+ let runs = match statement {
1484
+ _ if declaration.is_some() => initializes,
1485
+ Statement::EmptyStatement(_) => false,
1486
+ statement => !dead.is_some_and(|dead| dead.contains(&address(statement))),
1487
+ };
1488
+ if kept && runs {
1489
+ running.push(statement);
1490
+ }
1491
+ }
1492
+ (running, reachable)
1493
+ }
1494
+
1495
+ /// `var x = e;`, which assigns where it stands: the declaration itself only scopes `x`. A `let`
1496
+ /// behaves the same once the template has matched every use after it.
1497
+ fn initialized<'s, 'x>(
1498
+ statement: &'s Statement<'x>,
1499
+ ) -> Option<(&'s BindingIdentifier<'x>, &'s Expression<'x>)> {
1500
+ let Statement::VariableDeclaration(declaration) = statement else {
1501
+ return None;
1502
+ };
1503
+ let [declarator] = &declaration.declarations[..] else {
1504
+ return None;
1505
+ };
1506
+ if matches!(
1507
+ declaration.kind,
1508
+ VariableDeclarationKind::Const
1509
+ | VariableDeclarationKind::Using
1510
+ | VariableDeclarationKind::AwaitUsing
1511
+ ) {
1512
+ return None;
1513
+ }
1514
+ let BindingPattern::BindingIdentifier(name) = &declarator.id else {
1515
+ return None;
1516
+ };
1517
+ Some((name, declarator.init.as_ref()?))
1518
+ }
1519
+
1520
+ /// `x = e;`.
1521
+ fn assigned<'s, 'x>(
1522
+ statement: &'s Statement<'x>,
1523
+ ) -> Option<(&'s IdentifierReference<'x>, &'s Expression<'x>)> {
1524
+ let Statement::ExpressionStatement(statement) = statement else {
1525
+ return None;
1526
+ };
1527
+ let Expression::AssignmentExpression(assignment) = &statement.expression else {
1528
+ return None;
1529
+ };
1530
+ if assignment.operator != AssignmentOperator::Assign {
1531
+ return None;
1532
+ }
1533
+ let AssignmentTarget::AssignmentTargetIdentifier(name) = &assignment.left else {
1534
+ return None;
1535
+ };
1536
+ Some((name, &assignment.right))
1537
+ }
1538
+
1539
+ /// The operands of `expression` if it applies `operator`.
1540
+ fn pair<'e, 'x>(
1541
+ expression: &'e Expression<'x>,
1542
+ operator: BinaryOperator,
1543
+ ) -> Option<(&'e Expression<'x>, &'e Expression<'x>)> {
1544
+ match expression.without_parentheses() {
1545
+ Expression::BinaryExpression(found) if found.operator == operator => {
1546
+ Some((&found.left, &found.right))
1547
+ }
1548
+ _ => None,
1549
+ }
1550
+ }
1551
+
1552
+ fn is_zero(expression: &Expression<'_>) -> bool {
1553
+ matches!(expression.without_parentheses(), Expression::NumericLiteral(number) if number.value == 0.0)
1554
+ }
1555
+
1556
+ /// `x` of `x | 0` or `0 | x`.
1557
+ fn truncated<'e, 'x>(expression: &'e Expression<'x>) -> Option<&'e Expression<'x>> {
1558
+ let (left, right) = pair(expression, BinaryOperator::BitwiseOR)?;
1559
+ if is_zero(right) {
1560
+ Some(left)
1561
+ } else if is_zero(left) {
1562
+ Some(right)
1563
+ } else {
1564
+ None
1565
+ }
1566
+ }
1567
+
1568
+ /// An int32 literal, which is its own `| 0`.
1569
+ fn int32_literal<'e, 'x>(expression: &'e Expression<'x>) -> Option<&'e Expression<'x>> {
1570
+ match expression.without_parentheses() {
1571
+ Expression::NumericLiteral(number)
1572
+ if f64::from(js::int32(number.value)) == number.value =>
1573
+ {
1574
+ Some(expression)
1575
+ }
1576
+ _ => None,
1577
+ }
1578
+ }
1579
+
1580
+ /// Statements with blocks that declare nothing block-scoped replaced by their statements. A
1581
+ /// block may declare functions no other statement mentions: they are then callable only inside
1582
+ /// the block, where it makes no difference that they hoist to the block's start instead.
1583
+ fn flattened<'s, 'x>(
1584
+ script: Script<'_>,
1585
+ statements: &'s [Statement<'x>],
1586
+ ) -> Vec<&'s Statement<'x>> {
1587
+ let mut flat = Vec::with_capacity(statements.len());
1588
+ for (index, statement) in statements.iter().enumerate() {
1589
+ let flattens = |inner: &Statement<'x>| match inner {
1590
+ Statement::VariableDeclaration(declaration) => {
1591
+ declaration.kind == VariableDeclarationKind::Var
1592
+ }
1593
+ Statement::FunctionDeclaration(function) => {
1594
+ let Some(name) = &function.id else {
1595
+ return false;
1596
+ };
1597
+ let name = Binding::Symbol(name.symbol_id());
1598
+ statements
1599
+ .iter()
1600
+ .enumerate()
1601
+ .filter(|(other, _)| *other != index)
1602
+ .all(|(_, other)| {
1603
+ !mentions(script, |visitor| visitor.visit_statement(other))
1604
+ .contains_key(&name)
1605
+ })
1606
+ }
1607
+ inner => !inner.is_declaration(),
1608
+ };
1609
+ match statement {
1610
+ Statement::BlockStatement(block) if block.body.iter().all(flattens) => {
1611
+ flat.extend(flattened(script, &block.body));
1612
+ }
1613
+ statement => flat.push(statement),
1614
+ }
1615
+ }
1616
+ flat
1617
+ }
1618
+
1619
+ /// A block's statements, or a lone statement.
1620
+ fn as_list<'s, 'x>(statement: &'s Statement<'x>) -> &'s [Statement<'x>] {
1621
+ match statement {
1622
+ Statement::BlockStatement(block) => &block.body,
1623
+ statement => slice::from_ref(statement),
1624
+ }
1625
+ }
1626
+
1627
+ #[cfg(test)]
1628
+ mod tests {
1629
+ use super::*;
1630
+
1631
+ /// The names, by placeholder, the constants, and the number of helpers a match captured.
1632
+ type Matched = (BTreeMap<String, String>, BTreeMap<String, f64>, usize);
1633
+
1634
+ /// Matches `template` against the function `actual` declares, with the binary helpers
1635
+ /// `xor` and `sub`. Returns the free bindings captured, by name.
1636
+ fn check(template: &str, actual: &str) -> Option<Matched> {
1637
+ let helper = |name: &'static str, source| {
1638
+ let parsed = super::template(source);
1639
+ let script = parsed.script();
1640
+ let helper = binary_helper(script, template_function(script)).expect("a binary helper");
1641
+ (Binding::Global(name), helper)
1642
+ };
1643
+ let helpers = BinaryHelpers::from_iter([
1644
+ helper("xor", "function xor(p, q) { return p ^ q; }"),
1645
+ helper("sub", "function sub(p, q) { return q - p; }"),
1646
+ ]);
1647
+ let template = super::template(template);
1648
+ let actual = super::template(actual);
1649
+ let script = actual.script();
1650
+ let captures = matches(&template, script, template_function(script), &helpers)?;
1651
+ let names = captures
1652
+ .names
1653
+ .iter()
1654
+ .map(|(placeholder, binding)| {
1655
+ let name = match *binding {
1656
+ Binding::Symbol(symbol) => script.scoping.symbol_name(symbol),
1657
+ Binding::Global(name) => name,
1658
+ };
1659
+ (placeholder.clone(), name.to_owned())
1660
+ })
1661
+ .collect();
1662
+ Some((names, captures.constants, captures.helpers.len()))
1663
+ }
1664
+
1665
+ #[test]
1666
+ fn inlines_binary_helpers_and_skips_unreachable_statements() {
1667
+ let template = "function f(a, b) { return a ^ b - 1; }";
1668
+ let captures = check(
1669
+ template,
1670
+ "function f(a, b) { return xor(sub(1, b), a); return; }",
1671
+ );
1672
+ assert_eq!(captures.expect("matches").2, 2);
1673
+ // Swapped helper arguments, or a local shadowing a helper, fail.
1674
+ for other in [
1675
+ "function f(a, b) { return xor(sub(b, 1), a); }",
1676
+ "function f(a, b) { var xor; return xor(sub(1, b), a); }",
1677
+ ] {
1678
+ assert!(check(template, other).is_none(), "{other}");
1679
+ }
1680
+ }
1681
+
1682
+ #[test]
1683
+ fn matches_renamed_and_reordered_functions() {
1684
+ let template =
1685
+ "function f(a, b) { var c; c = $mix(a) ^ b & 255 ^ $c_1; return c * 2 === 0; }";
1686
+ let (names, constants, _) = check(
1687
+ template,
1688
+ "function g(x, y) { var z, w; z = 7 ^ (255 & y) ^ Ut(x); return 0 === 2 * z; }",
1689
+ )
1690
+ .expect("matches");
1691
+ assert_eq!(names.get("$mix").map(String::as_str), Some("Ut"));
1692
+ assert_eq!(constants.get("$c_1"), Some(&7.0));
1693
+ // Different operators, swapped noncommutative operands, and inconsistent locals fail.
1694
+ for other in [
1695
+ "function g(x, y) { var z; z = Ut(x) ^ y | 255 ^ 7; return z * 2 === 0; }",
1696
+ "function g(x, y) { var z; z = Ut(x) ^ y & 255 ^ 7; return 2 - z === 0; }",
1697
+ "function g(x, y) { var z; z = Ut(y) ^ y & 255 ^ 7; return z * 2 === 0; }",
1698
+ "function g(x, y) { var z; z = x ^ y & 255 ^ 7; return z * 2 === 0; }",
1699
+ ] {
1700
+ assert!(check(template, other).is_none(), "{other}");
1701
+ }
1702
+ }
1703
+
1704
+ #[test]
1705
+ fn normalizes_mixed_boolean_arithmetic() {
1706
+ let template = "function f(a, b) { return (a | b) ^ b ^ 255 ^ a & b; }";
1707
+ let normalized = "function f(a, b) { var t, u; return (t = a, u = b, (t ^ u) + (u & t) | 0) ^ (0 | (b | 255) - (255 & b)) ^ (0 | (a | 0) + (0 | b) - (b | a)); }";
1708
+ assert!(check(template, normalized).is_some());
1709
+ // A temporary read elsewhere, or a wrong identity, does not normalize.
1710
+ for other in [
1711
+ "function f(a, b) { var t, u; return (t = a, u = b, (t ^ u) + (u & t) | 0) ^ t ^ b ^ 255 ^ a & b; }",
1712
+ "function f(a, b) { return (a ^ b) - (a & b) ^ b ^ 255 ^ a & b; }",
1713
+ ] {
1714
+ assert!(check(template, other).is_none(), "{other}");
1715
+ }
1716
+ }
1717
+
1718
+ #[test]
1719
+ fn skips_only_dead_helper_objects() {
1720
+ let template = "function f(a) { return a - 1; }";
1721
+ for dead in [
1722
+ "function f(a) { var h, s; h = {}; h._x = function(p, q) { return p - q; }; s = h._x; return a - 1; }",
1723
+ "function f(a) { var h; h = { _x: function(p, q) { return p - q; } }; return a - 1; }",
1724
+ ] {
1725
+ assert!(check(template, dead).is_some(), "{dead}");
1726
+ }
1727
+ // A used helper, or a getter, keeps its statements.
1728
+ for other in [
1729
+ "function f(a) { var h, s; h = {}; h._x = function(p, q) { return p - q; }; s = h._x; s(a, 1); return a - 1; }",
1730
+ "function f(a) { var h; h = { get _x() { return 1; } }; return a - 1; }",
1731
+ "function f(a) { var h; h = {}; h = g(); h._x = function(p) { return p; }; return a - 1; }",
1732
+ ] {
1733
+ assert!(check(template, other).is_none(), "{other}");
1734
+ }
1735
+ }
1736
+ }