rigortype 0.4.8 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (349) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/docs/handbook/01-getting-started.md +1 -1
  4. data/docs/handbook/04-tuples-and-shapes.md +6 -1
  5. data/docs/handbook/12-lightweight-hkt.md +1 -1
  6. data/docs/handbook/appendix-typescript.md +28 -17
  7. data/docs/manual/02-cli-reference.md +10 -0
  8. data/docs/manual/03-configuration.md +1 -1
  9. data/docs/manual/04-diagnostics.md +1 -1
  10. data/docs/manual/10-mcp-server.md +122 -10
  11. data/docs/manual/plugins/rigor-activerecord.md +7 -0
  12. data/lib/rigor/analysis/check_rules/always_raises.rb +95 -0
  13. data/lib/rigor/analysis/check_rules/always_truthy_condition_collector.rb +32 -2
  14. data/lib/rigor/analysis/check_rules/argument_type.rb +802 -0
  15. data/lib/rigor/analysis/check_rules/call_facts.rb +2 -2
  16. data/lib/rigor/analysis/check_rules/dead_assignment_collector.rb +30 -1
  17. data/lib/rigor/analysis/check_rules/declaration_sourced_guard.rb +4 -5
  18. data/lib/rigor/analysis/check_rules/duplicate_hash_key_collector.rb +34 -0
  19. data/lib/rigor/analysis/check_rules/ivar_write_collector.rb +131 -4
  20. data/lib/rigor/analysis/check_rules/nil_receiver.rb +195 -0
  21. data/lib/rigor/analysis/check_rules/override_param_narrowed.rb +111 -0
  22. data/lib/rigor/analysis/check_rules/override_return_widened.rb +88 -0
  23. data/lib/rigor/analysis/check_rules/override_support.rb +246 -0
  24. data/lib/rigor/analysis/check_rules/override_visibility.rb +135 -0
  25. data/lib/rigor/analysis/check_rules/published_constant_guard.rb +75 -31
  26. data/lib/rigor/analysis/check_rules/raise_non_exception.rb +198 -0
  27. data/lib/rigor/analysis/check_rules/receiver_predicates.rb +576 -0
  28. data/lib/rigor/analysis/check_rules/return_in_ensure_collector.rb +52 -4
  29. data/lib/rigor/analysis/check_rules/return_type.rb +225 -0
  30. data/lib/rigor/analysis/check_rules/rigor_testing.rb +119 -0
  31. data/lib/rigor/analysis/check_rules/rule_ids.rb +7 -7
  32. data/lib/rigor/analysis/check_rules/rule_walk.rb +4 -3
  33. data/lib/rigor/analysis/check_rules/self_closedness_scanner.rb +2 -0
  34. data/lib/rigor/analysis/check_rules/self_undefined_method.rb +165 -0
  35. data/lib/rigor/analysis/check_rules/shadowed_rescue_collector.rb +34 -0
  36. data/lib/rigor/analysis/check_rules/source_arity.rb +2 -2
  37. data/lib/rigor/analysis/check_rules/special_global_write.rb +256 -0
  38. data/lib/rigor/analysis/check_rules/suppression.rb +275 -0
  39. data/lib/rigor/analysis/check_rules/undefined_method.rb +882 -0
  40. data/lib/rigor/analysis/check_rules/unreachable_branch.rb +97 -0
  41. data/lib/rigor/analysis/check_rules/unreachable_clause_collector.rb +42 -0
  42. data/lib/rigor/analysis/check_rules/unresolved_toplevel.rb +140 -0
  43. data/lib/rigor/analysis/check_rules/visibility_mismatch.rb +252 -0
  44. data/lib/rigor/analysis/check_rules/void_value_use_collector.rb +27 -0
  45. data/lib/rigor/analysis/check_rules/wrong_arity.rb +303 -0
  46. data/lib/rigor/analysis/check_rules.rb +66 -4931
  47. data/lib/rigor/analysis/dependency_recorder.rb +1 -1
  48. data/lib/rigor/analysis/dependency_source_inference/builder.rb +2 -4
  49. data/lib/rigor/analysis/dependency_source_inference/gem_resolver.rb +1 -2
  50. data/lib/rigor/analysis/dependency_source_inference/walker.rb +15 -15
  51. data/lib/rigor/analysis/incremental_session.rb +4 -4
  52. data/lib/rigor/analysis/path_expansion.rb +1 -1
  53. data/lib/rigor/analysis/plugin_fact_fingerprint.rb +5 -5
  54. data/lib/rigor/analysis/reachability/graph.rb +2 -3
  55. data/lib/rigor/analysis/reachability/plugin_roots.rb +2 -2
  56. data/lib/rigor/analysis/reachability/scan.rb +2 -2
  57. data/lib/rigor/analysis/rule_catalog.rb +2 -1
  58. data/lib/rigor/analysis/run_cache_key.rb +9 -8
  59. data/lib/rigor/analysis/runner/buffer_pool_dispatcher.rb +2 -2
  60. data/lib/rigor/analysis/runner/dependency_rows.rb +206 -0
  61. data/lib/rigor/analysis/runner/diagnostic_aggregator.rb +24 -22
  62. data/lib/rigor/analysis/runner/effect_cache_entries.rb +69 -0
  63. data/lib/rigor/analysis/runner/pool_coordinator.rb +6 -8
  64. data/lib/rigor/analysis/runner/project_pre_passes.rb +3 -5
  65. data/lib/rigor/analysis/runner/scope_seed.rb +144 -0
  66. data/lib/rigor/analysis/runner.rb +49 -296
  67. data/lib/rigor/analysis/template_unit_collector.rb +1 -1
  68. data/lib/rigor/analysis/template_units.rb +10 -10
  69. data/lib/rigor/analysis/worker_session.rb +7 -7
  70. data/lib/rigor/bleeding_edge.rb +3 -2
  71. data/lib/rigor/builtins/hkt_builtins.rb +17 -17
  72. data/lib/rigor/builtins/imported_refinements.rb +8 -16
  73. data/lib/rigor/builtins/regex_refinement.rb +3 -3
  74. data/lib/rigor/builtins/static_return_refinements.rb +143 -19
  75. data/lib/rigor/cache/incremental_snapshot.rb +21 -8
  76. data/lib/rigor/cache/rbs_descriptor.rb +18 -1
  77. data/lib/rigor/cli/coverage_renderer.rb +15 -1
  78. data/lib/rigor/cli/coverage_report.rb +19 -1
  79. data/lib/rigor/cli/diagnostic_formats.rb +3 -2
  80. data/lib/rigor/cli/docs_command.rb +5 -5
  81. data/lib/rigor/cli/effects_command.rb +7 -6
  82. data/lib/rigor/cli/fused_protection_report.rb +7 -7
  83. data/lib/rigor/cli/lsp_command.rb +1 -1
  84. data/lib/rigor/cli/mcp_command.rb +5 -2
  85. data/lib/rigor/cli/options.rb +4 -0
  86. data/lib/rigor/cli/plugins_command.rb +1 -1
  87. data/lib/rigor/cli/sig_gen_command.rb +1 -1
  88. data/lib/rigor/cli/skill_command.rb +5 -4
  89. data/lib/rigor/cli/triage_renderer.rb +3 -2
  90. data/lib/rigor/cli/unused_command.rb +4 -4
  91. data/lib/rigor/cli.rb +14 -0
  92. data/lib/rigor/configuration/coercion.rb +418 -0
  93. data/lib/rigor/configuration/defaults.rb +248 -0
  94. data/lib/rigor/configuration/dependencies.rb +1 -1
  95. data/lib/rigor/configuration/loader.rb +354 -0
  96. data/lib/rigor/configuration/severity_profile.rb +4 -4
  97. data/lib/rigor/configuration.rb +51 -860
  98. data/lib/rigor/effects/attribution.rb +1 -1
  99. data/lib/rigor/effects/effect_table.rb +1 -1
  100. data/lib/rigor/effects/identity.rb +3 -3
  101. data/lib/rigor/effects/local_ownership.rb +2 -2
  102. data/lib/rigor/effects/snapshot.rb +1 -1
  103. data/lib/rigor/effects/summary.rb +5 -4
  104. data/lib/rigor/environment/member_consistency.rb +10 -0
  105. data/lib/rigor/environment/rbs_loader.rb +19 -22
  106. data/lib/rigor/environment/reflection.rb +1 -1
  107. data/lib/rigor/environment/unreadable_signature.rb +21 -0
  108. data/lib/rigor/environment.rb +8 -8
  109. data/lib/rigor/flow_contribution/merger.rb +1 -0
  110. data/lib/rigor/hashing/xxh3.rb +1 -1
  111. data/lib/rigor/inference/acceptance.rb +23 -2
  112. data/lib/rigor/inference/alias_mutation_floor/site_collector.rb +5 -0
  113. data/lib/rigor/inference/alias_mutation_floor.rb +0 -5
  114. data/lib/rigor/inference/anonymous_meta_class.rb +2 -2
  115. data/lib/rigor/inference/block_call_timing.rb +6 -0
  116. data/lib/rigor/inference/budget_trace.rb +3 -2
  117. data/lib/rigor/inference/builtins/date_catalog.rb +3 -3
  118. data/lib/rigor/inference/builtins/method_catalog.rb +3 -3
  119. data/lib/rigor/inference/builtins/time_catalog.rb +3 -3
  120. data/lib/rigor/inference/call_ladder/literal_send.rb +98 -0
  121. data/lib/rigor/inference/call_ladder/overriding_def.rb +98 -0
  122. data/lib/rigor/inference/call_ladder/project_singleton.rb +362 -0
  123. data/lib/rigor/inference/call_ladder/refined.rb +212 -0
  124. data/lib/rigor/inference/call_ladder/top_level_def.rb +222 -0
  125. data/lib/rigor/inference/call_ladder/user_method.rb +247 -0
  126. data/lib/rigor/inference/call_ladder.rb +219 -0
  127. data/lib/rigor/inference/callee_write_census.rb +2 -2
  128. data/lib/rigor/inference/captured_locals.rb +2 -2
  129. data/lib/rigor/inference/clause_widening.rb +63 -1
  130. data/lib/rigor/inference/declaration_walk/context.rb +12 -12
  131. data/lib/rigor/inference/declaration_walk/rules.rb +750 -0
  132. data/lib/rigor/inference/declaration_walk/traversal.rb +9 -8
  133. data/lib/rigor/inference/declaration_walk.rb +4 -3
  134. data/lib/rigor/inference/def_node_resolver.rb +2 -2
  135. data/lib/rigor/inference/def_return_typer.rb +14 -6
  136. data/lib/rigor/inference/deferred_mutation.rb +120 -0
  137. data/lib/rigor/inference/define_method_block_self.rb +1 -1
  138. data/lib/rigor/inference/definer_resolution.rb +4 -4
  139. data/lib/rigor/inference/error_info.rb +8 -8
  140. data/lib/rigor/inference/expression_typer/composites.rb +348 -0
  141. data/lib/rigor/inference/expression_typer/per_element_assemblers.rb +233 -0
  142. data/lib/rigor/inference/expression_typer/writes.rb +218 -0
  143. data/lib/rigor/inference/expression_typer.rb +275 -1825
  144. data/lib/rigor/inference/external_ancestor_resolution.rb +2 -2
  145. data/lib/rigor/inference/fallback.rb +1 -0
  146. data/lib/rigor/inference/for_yield_slots.rb +126 -0
  147. data/lib/rigor/inference/genuine_send.rb +92 -0
  148. data/lib/rigor/inference/global_write_census.rb +2 -2
  149. data/lib/rigor/inference/hkt_body.rb +2 -0
  150. data/lib/rigor/inference/in_effect_refinements/walk.rb +2 -2
  151. data/lib/rigor/inference/index_write_widening.rb +4 -4
  152. data/lib/rigor/inference/indexed_narrowing.rb +1 -1
  153. data/lib/rigor/inference/intervening_ivar_reset.rb +46 -9
  154. data/lib/rigor/inference/ivar_writer_census.rb +1 -1
  155. data/lib/rigor/inference/loop_store_sites.rb +239 -0
  156. data/lib/rigor/inference/macro_block_self_type.rb +4 -3
  157. data/lib/rigor/inference/method_dispatcher/block_folding.rb +3 -2
  158. data/lib/rigor/inference/method_dispatcher/call_context.rb +84 -14
  159. data/lib/rigor/inference/method_dispatcher/composite_receiver.rb +144 -0
  160. data/lib/rigor/inference/method_dispatcher/constant_folding.rb +7 -5
  161. data/lib/rigor/inference/method_dispatcher/declared_constructor.rb +1 -1
  162. data/lib/rigor/inference/method_dispatcher/dependency_source.rb +90 -0
  163. data/lib/rigor/inference/method_dispatcher/discovered_method.rb +78 -0
  164. data/lib/rigor/inference/method_dispatcher/file_folding.rb +2 -2
  165. data/lib/rigor/inference/method_dispatcher/hkt_builtin_return.rb +40 -0
  166. data/lib/rigor/inference/method_dispatcher/iterator_dispatch.rb +1 -6
  167. data/lib/rigor/inference/method_dispatcher/literal_string_folding.rb +4 -2
  168. data/lib/rigor/inference/method_dispatcher/match_data_folding.rb +1 -1
  169. data/lib/rigor/inference/method_dispatcher/meta_introspection.rb +506 -0
  170. data/lib/rigor/inference/method_dispatcher/overload_selector.rb +2 -0
  171. data/lib/rigor/inference/method_dispatcher/plugin_contribution.rb +134 -0
  172. data/lib/rigor/inference/method_dispatcher/project_patched.rb +134 -0
  173. data/lib/rigor/inference/method_dispatcher/rbs_dispatch.rb +125 -43
  174. data/lib/rigor/inference/method_dispatcher/reduce_folding.rb +3 -4
  175. data/lib/rigor/inference/method_dispatcher/regexp_folding.rb +1 -1
  176. data/lib/rigor/inference/method_dispatcher/set_folding.rb +1 -1
  177. data/lib/rigor/inference/method_dispatcher/shape_dispatch.rb +19 -6
  178. data/lib/rigor/inference/method_dispatcher/singleton_folding.rb +3 -3
  179. data/lib/rigor/inference/method_dispatcher/singleton_mixin_dispatch.rb +7 -4
  180. data/lib/rigor/inference/method_dispatcher/static_refinement.rb +106 -0
  181. data/lib/rigor/inference/method_dispatcher/synthesized_stub.rb +41 -0
  182. data/lib/rigor/inference/method_dispatcher/synthetic_method_dispatch.rb +133 -0
  183. data/lib/rigor/inference/method_dispatcher/universal_object_dispatch.rb +2 -1
  184. data/lib/rigor/inference/method_dispatcher/user_class_fallback.rb +216 -0
  185. data/lib/rigor/inference/method_dispatcher.rb +175 -1361
  186. data/lib/rigor/inference/method_parameter_binder.rb +18 -18
  187. data/lib/rigor/inference/module_function_state.rb +5 -4
  188. data/lib/rigor/inference/mutation_widening.rb +20 -7
  189. data/lib/rigor/inference/narrowing/case_literals.rb +58 -0
  190. data/lib/rigor/inference/narrowing/class_dispatch.rb +302 -0
  191. data/lib/rigor/inference/narrowing/complements.rb +322 -0
  192. data/lib/rigor/inference/narrowing/presence_predicates.rb +205 -0
  193. data/lib/rigor/inference/narrowing/regex_match.rb +499 -0
  194. data/lib/rigor/inference/narrowing.rb +86 -1269
  195. data/lib/rigor/inference/object_mixins.rb +2 -2
  196. data/lib/rigor/inference/opaque_mutation.rb +214 -0
  197. data/lib/rigor/inference/optimistic_origin.rb +52 -14
  198. data/lib/rigor/inference/parameter_inference_collector.rb +1 -1
  199. data/lib/rigor/inference/pre_eval_constants.rb +11 -9
  200. data/lib/rigor/inference/precision_scanner.rb +27 -2
  201. data/lib/rigor/inference/project_patched_methods.rb +3 -3
  202. data/lib/rigor/inference/range_constant.rb +3 -3
  203. data/lib/rigor/inference/rbs_type_translator.rb +2 -2
  204. data/lib/rigor/inference/refine_self.rb +8 -7
  205. data/lib/rigor/inference/refined_dispatch.rb +2 -2
  206. data/lib/rigor/inference/return_barrier.rb +24 -9
  207. data/lib/rigor/inference/scope_indexer/alias_def_nodes.rb +311 -0
  208. data/lib/rigor/inference/scope_indexer/census_scope.rb +47 -0
  209. data/lib/rigor/inference/scope_indexer/certainty.rb +2 -2
  210. data/lib/rigor/inference/scope_indexer/class_cvar_census.rb +282 -0
  211. data/lib/rigor/inference/scope_indexer/class_cvars_collector.rb +12 -5
  212. data/lib/rigor/inference/scope_indexer/class_declarations.rb +228 -0
  213. data/lib/rigor/inference/scope_indexer/class_ivar_index.rb +2028 -0
  214. data/lib/rigor/inference/scope_indexer/constant_ivar_value.rb +4 -3
  215. data/lib/rigor/inference/scope_indexer/constant_tables.rb +844 -0
  216. data/lib/rigor/inference/scope_indexer/cvar_hierarchy.rb +159 -0
  217. data/lib/rigor/inference/scope_indexer/declaration_artifacts.rb +219 -0
  218. data/lib/rigor/inference/scope_indexer/declaration_signature.rb +212 -0
  219. data/lib/rigor/inference/scope_indexer/def_nestings_collector.rb +2 -2
  220. data/lib/rigor/inference/scope_indexer/factory_call_resolver.rb +53 -0
  221. data/lib/rigor/inference/scope_indexer/literal_receiver_mutations.rb +266 -0
  222. data/lib/rigor/inference/scope_indexer/member_layouts_collector.rb +8 -7
  223. data/lib/rigor/inference/scope_indexer/mixin_accumulator.rb +1 -1
  224. data/lib/rigor/inference/scope_indexer/mixin_effects.rb +470 -0
  225. data/lib/rigor/inference/scope_indexer/mixin_tables.rb +388 -0
  226. data/lib/rigor/inference/scope_indexer/mutated_carrier_widening.rb +163 -0
  227. data/lib/rigor/inference/scope_indexer/mutated_element_census.rb +211 -0
  228. data/lib/rigor/inference/scope_indexer/node_propagation.rb +520 -0
  229. data/lib/rigor/inference/scope_indexer/program_globals.rb +154 -0
  230. data/lib/rigor/inference/scope_indexer/published_constant_cvars.rb +146 -0
  231. data/lib/rigor/inference/scope_indexer/published_constant_ivars.rb +181 -0
  232. data/lib/rigor/inference/scope_indexer/shared_walk_tables.rb +823 -0
  233. data/lib/rigor/inference/scope_indexer/singleton_class_sources.rb +85 -0
  234. data/lib/rigor/inference/scope_indexer/superclasses_collector.rb +5 -5
  235. data/lib/rigor/inference/scope_indexer.rb +2657 -9558
  236. data/lib/rigor/inference/self_call_ivar_writes.rb +22 -3
  237. data/lib/rigor/inference/set_mutation.rb +2 -2
  238. data/lib/rigor/inference/singleton_hook_definers.rb +185 -0
  239. data/lib/rigor/inference/statement_evaluator/def_arguments_and_assertions.rb +365 -0
  240. data/lib/rigor/inference/statement_evaluator/pattern_bindings.rb +581 -0
  241. data/lib/rigor/inference/statement_evaluator.rb +201 -1008
  242. data/lib/rigor/inference/synthetic_method_scanner.rb +0 -3
  243. data/lib/rigor/language_server/completion_provider.rb +8 -8
  244. data/lib/rigor/language_server/diagnostic_publisher.rb +6 -7
  245. data/lib/rigor/language_server/document_symbol_provider.rb +4 -6
  246. data/lib/rigor/language_server/folding_range_provider.rb +3 -3
  247. data/lib/rigor/language_server/hover_provider.rb +2 -2
  248. data/lib/rigor/language_server/loop.rb +2 -2
  249. data/lib/rigor/language_server/server.rb +3 -2
  250. data/lib/rigor/language_server/signature_help_provider.rb +7 -9
  251. data/lib/rigor/lens/document.rb +10 -1
  252. data/lib/rigor/lens/file_reader.rb +2 -1
  253. data/lib/rigor/mcp/loop.rb +48 -6
  254. data/lib/rigor/mcp/server.rb +248 -23
  255. data/lib/rigor/mcp/skill_catalog.rb +157 -0
  256. data/lib/rigor/plugin/base.rb +22 -4
  257. data/lib/rigor/plugin/effect_attribution.rb +1 -1
  258. data/lib/rigor/plugin/inflector.rb +2 -2
  259. data/lib/rigor/plugin/io_boundary.rb +1 -1
  260. data/lib/rigor/plugin/loader.rb +4 -4
  261. data/lib/rigor/plugin/macro/heredoc_template.rb +4 -3
  262. data/lib/rigor/plugin/optimistic_return.rb +20 -0
  263. data/lib/rigor/plugin/registry.rb +2 -2
  264. data/lib/rigor/plugin/template_unit.rb +4 -2
  265. data/lib/rigor/plugin/trust_policy.rb +2 -1
  266. data/lib/rigor/plugin.rb +1 -1
  267. data/lib/rigor/protection/mutator.rb +8 -9
  268. data/lib/rigor/rbs_extended/reporter.rb +2 -2
  269. data/lib/rigor/rbs_extended.rb +2 -2
  270. data/lib/rigor/reflection/constant_ancestors.rb +1 -1
  271. data/lib/rigor/reflection/project_method.rb +2 -2
  272. data/lib/rigor/reflection.rb +4 -4
  273. data/lib/rigor/scope/discovery_index.rb +15 -10
  274. data/lib/rigor/scope/resolution_chain.rb +29 -6
  275. data/lib/rigor/scope.rb +89 -32
  276. data/lib/rigor/sig_gen/generator.rb +5 -4
  277. data/lib/rigor/sig_gen/renderer.rb +3 -3
  278. data/lib/rigor/sig_gen/writer.rb +8 -6
  279. data/lib/rigor/source/parameter_envelope.rb +1 -1
  280. data/lib/rigor/triage/catalogue.rb +4 -4
  281. data/lib/rigor/type/combinator.rb +2 -2
  282. data/lib/rigor/type/data_instance.rb +2 -2
  283. data/lib/rigor/type/struct_instance.rb +3 -3
  284. data/lib/rigor/type_node/generic.rb +2 -1
  285. data/lib/rigor/type_of_memo.rb +2 -1
  286. data/lib/rigor/typing_state.rb +3 -2
  287. data/lib/rigor/version.rb +1 -1
  288. data/plugins/rigor-actioncable/lib/rigor/plugin/actioncable/analyzer.rb +2 -2
  289. data/plugins/rigor-actioncable/lib/rigor/plugin/actioncable/channel_discoverer.rb +1 -1
  290. data/plugins/rigor-actionmailer/lib/rigor/plugin/actionmailer/mailer_discoverer.rb +4 -4
  291. data/plugins/rigor-actionmailer/lib/rigor/plugin/actionmailer.rb +1 -1
  292. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/controller_discoverer.rb +4 -3
  293. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/effects.rb +7 -5
  294. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/erb_compiler.rb +4 -2
  295. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/render_locals.rb +1 -1
  296. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack/view_assigns.rb +3 -2
  297. data/plugins/rigor-actionpack/lib/rigor/plugin/actionpack.rb +7 -7
  298. data/plugins/rigor-activejob/lib/rigor/plugin/activejob/job_discoverer.rb +1 -1
  299. data/plugins/rigor-activejob/lib/rigor/plugin/activejob.rb +2 -2
  300. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/model_discoverer.rb +9 -8
  301. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/model_index.rb +3 -2
  302. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/schema_parser.rb +15 -7
  303. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/schema_table.rb +10 -3
  304. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord/structure_sql_parser.rb +12 -1
  305. data/plugins/rigor-activerecord/lib/rigor/plugin/activerecord.rb +20 -5
  306. data/plugins/rigor-activestorage/lib/rigor/plugin/activestorage/attachment_discoverer.rb +1 -1
  307. data/plugins/rigor-activestorage/lib/rigor/plugin/activestorage.rb +3 -2
  308. data/plugins/rigor-activesupport-core-ext/lib/rigor/plugin/activesupport_core_ext/effects.rb +1 -1
  309. data/plugins/rigor-activesupport-core-ext/lib/rigor/plugin/activesupport_core_ext.rb +8 -7
  310. data/plugins/rigor-dry-schema/lib/rigor/plugin/dry_schema.rb +1 -1
  311. data/plugins/rigor-dry-types/lib/rigor/plugin/dry_types/alias_scanner.rb +1 -1
  312. data/plugins/rigor-dry-types/lib/rigor/plugin/dry_types.rb +6 -7
  313. data/plugins/rigor-factorybot/lib/rigor/plugin/factorybot/factory_discoverer.rb +3 -2
  314. data/plugins/rigor-graphql/lib/rigor/plugin/graphql/type_scanner.rb +4 -3
  315. data/plugins/rigor-hanami/lib/rigor/plugin/hanami.rb +4 -2
  316. data/plugins/rigor-minitest/lib/rigor/plugin/minitest.rb +1 -1
  317. data/plugins/rigor-pundit/lib/rigor/plugin/pundit.rb +1 -1
  318. data/plugins/rigor-rails-i18n/lib/rigor/plugin/rails_i18n/analyzer.rb +5 -3
  319. data/plugins/rigor-rails-i18n/lib/rigor/plugin/rails_i18n.rb +1 -1
  320. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/devise_routes.rb +4 -5
  321. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/doorkeeper_routes.rb +2 -2
  322. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/helper_discoverer.rb +5 -4
  323. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/helper_table.rb +3 -2
  324. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes/routes_parser.rb +30 -31
  325. data/plugins/rigor-rails-routes/lib/rigor/plugin/rails_routes.rb +13 -15
  326. data/plugins/rigor-rbnacl/lib/rigor/plugin/rbnacl.rb +1 -1
  327. data/plugins/rigor-rspec/lib/rigor/plugin/rspec/let_scope_index.rb +4 -3
  328. data/plugins/rigor-rspec/lib/rigor/plugin/rspec/matcher_analyzer.rb +16 -13
  329. data/plugins/rigor-rspec/lib/rigor/plugin/rspec/scope_walker.rb +3 -2
  330. data/plugins/rigor-shoulda-matchers/lib/rigor/plugin/shoulda_matchers/analyzer.rb +6 -6
  331. data/plugins/rigor-sidekiq/lib/rigor/plugin/sidekiq/analyzer.rb +3 -3
  332. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/assertion_recognizer.rb +2 -2
  333. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/catalog.rb +3 -2
  334. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/catalog_walker.rb +6 -5
  335. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/sig_parser.rb +2 -2
  336. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/sigil_detector.rb +4 -5
  337. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet/type_translator.rb +1 -1
  338. data/plugins/rigor-sorbet/lib/rigor/plugin/sorbet.rb +3 -4
  339. data/sig/rigor/analysis/check_rules/suppression.rbs +9 -0
  340. data/sig/rigor/analysis/dependency_recorder.rbs +9 -0
  341. data/sig/rigor/inference.rbs +275 -11
  342. data/sig/rigor/plugin/base.rbs +14 -5
  343. data/sig/rigor/plugin/optimistic_return.rbs +16 -0
  344. data/sig/rigor/scope.rbs +7 -1
  345. data/sig/rigor/source.rbs +4 -0
  346. data/skills/rigor-mcp-setup/SKILL.md +20 -6
  347. data/skills/rigor-plugin-review/SKILL.md +3 -3
  348. data/skills/rigor-type-oracle/references/01-oracle-commands.md +1 -1
  349. metadata +90 -3
@@ -27,6 +27,8 @@ require_relative "../analysis/check_rules/declaration_sourced_guard"
27
27
  require_relative "../analysis/check_rules/inferred_param_guard"
28
28
  require_relative "../analysis/check_rules/published_constant_guard"
29
29
  require_relative "struct_fold_safety"
30
+ require_relative "statement_evaluator/def_arguments_and_assertions"
31
+ require_relative "statement_evaluator/pattern_bindings"
30
32
  require_relative "closure_escape_analyzer"
31
33
  require_relative "self_preserving_block"
32
34
  require_relative "content_join"
@@ -36,6 +38,7 @@ require_relative "macro_block_self_type"
36
38
  require_relative "global_writer_reach"
37
39
  require_relative "guard_rebinding"
38
40
  require_relative "self_call_ivar_writes"
41
+ require_relative "opaque_mutation"
39
42
  require_relative "direct_ivar_writes"
40
43
  require_relative "intervening_ivar_reset"
41
44
  require_relative "match_rebinding"
@@ -48,12 +51,14 @@ require_relative "index_write_widening"
48
51
  require_relative "method_dispatcher"
49
52
  require_relative "method_parameter_binder"
50
53
  require_relative "multi_target_binder"
54
+ require_relative "for_yield_slots"
51
55
  require_relative "mutation_widening"
52
56
  require_relative "out_buffer_mutation"
53
57
  require_relative "narrowing"
54
58
  require_relative "operand_effects"
55
59
  require_relative "operand_walk"
56
60
  require_relative "optimistic_origin"
61
+ require_relative "loop_store_sites"
57
62
  require_relative "loop_value_record"
58
63
  require_relative "project_yielder"
59
64
  require_relative "return_barrier"
@@ -187,8 +192,9 @@ module Rigor
187
192
  private_constant :OPERAND_SEQUENCES
188
193
 
189
194
  # The keywords of a pass whose scopes the per-node scope index must not keep — neither the nodes it
190
- # evaluates nor the later operands an {OperandWalk} inside it takes ({#walk_recorder}).
191
- UNRECORDED = { on_enter: nil, operand_recorder: nil }.freeze
195
+ # evaluates nor the later operands an {OperandWalk} inside it takes ({#walk_recorder}) — nor a loop's store
196
+ # sites (`store_sites:`): the check and display paths run different unrecorded passes and must answer alike.
197
+ UNRECORDED = { on_enter: nil, operand_recorder: nil, store_sites: nil }.freeze
192
198
  private_constant :UNRECORDED
193
199
 
194
200
  # Thread-local sink (an Array) collecting the value types of explicit `return value` nodes reached while
@@ -360,11 +366,14 @@ module Rigor
360
366
  # @param widen_clauses — issue #1231: when true (and a recorder is installed), a rescue or `ensure` clause
361
367
  # records its per-node entry scopes under {#widen_clause_entry}'s widening. The check path sets it; every
362
368
  # other reader of the index (parameter inference, sig-gen, the scanners) keeps the clause's plain entry.
369
+ # @param store_sites — issue #3337: an enclosing loop's table of its body's content-mutation sites
370
+ # ({LoopStoreSites::Pass}), or nil. {#evaluate} writes the scope it reaches such a site with.
363
371
  def initialize(scope:, tracer: nil, on_enter: nil, class_context: [].freeze, # rubocop:disable Metrics/ParameterLists
364
372
  lexical_nesting: EMPTY_NESTING, converged_loop_recording: false, next_scope_sink: nil,
365
373
  operand_scope: nil, in_operand: false, operand_recorder: nil, operand_types: nil,
366
- opaque_class: false, widen_clauses: false)
374
+ opaque_class: false, widen_clauses: false, store_sites: nil)
367
375
  @scope = scope
376
+ @store_sites = store_sites
368
377
  @widen_clauses = widen_clauses
369
378
  @opaque_class = opaque_class
370
379
  @tracer = tracer
@@ -379,8 +388,8 @@ module Rigor
379
388
  @operand_types = operand_types
380
389
  end
381
390
 
382
- # Runs `block` with a fresh return sink installed, then yields the collected explicit-`return` value types to the
383
- # caller. The sink is an array of `Rigor::Type`. Nested invocations stack: the previous sink is restored on exit
391
+ # Runs `block` with a fresh return sink installed and answers `[block result, collected explicit-`return` value
392
+ # types]` (see {ReturnSink#types}). Nested invocations stack: the previous sink is restored on exit
384
393
  # so a `def` evaluated inside another method's body (which itself installed a sink) does not corrupt the outer
385
394
  # one. Used by `ExpressionTyper#infer_user_method_return` to join the explicit returns into the inferred
386
395
  # method-return type.
@@ -430,7 +439,7 @@ module Rigor
430
439
 
431
440
  # Issue #1246 — enters only `call`'s block, from the receiver scope, as the statement form enters it
432
441
  # ({#evaluate_block_if_present}): the per-node scope index's evaluation of a block a value-position call holds
433
- # ({ScopeIndexer#evaluate_unentered_block}). The call's receiver and arguments are left to the index walk.
442
+ # ({ScopeIndexer::NodePropagation#evaluate_unentered_block}). The receiver and arguments stay with the walk.
434
443
  #
435
444
  # Such a block enters with the unknown-`self` mark only ({Scope#with_block_self_unknown}), as the walk entered
436
445
  # it, not with the statement form's opaque-`self` mark ({Scope#entering_opaque_block}): issue #1717 keeps the
@@ -448,6 +457,7 @@ module Rigor
448
457
  return evaluator_at(@scope.forget_last_line).evaluate(node) if forget_last_line_first?(node)
449
458
 
450
459
  @on_enter&.call(node, @scope)
460
+ @store_sites[node] = @scope if @store_sites&.key?(node)
451
461
 
452
462
  handler = HANDLERS[node.class]
453
463
  return forget_aliased_key_guards(node, forget_implicit_call_guards(node, send(handler, node))) if handler
@@ -466,7 +476,7 @@ module Rigor
466
476
  def reset_ivars_past_unknown_code(node, after)
467
477
  return after if @in_operand || !InterveningIvarReset.candidate?(node)
468
478
 
469
- InterveningIvarReset.after_operand(node, after)
479
+ OpaqueMutation.yielded(node, InterveningIvarReset.after_operand(node, after))
470
480
  end
471
481
 
472
482
  # Issue #1429 — a compound write or a `for` loop calls a method its syntax does not spell (`r += r` calls `r.+`,
@@ -1290,7 +1300,7 @@ module Rigor
1290
1300
  # build(key)`, `(@memo ||= {})[[a, b]] ||= compute`, `@targets[name] ||= new(name)` on an ivar the method
1291
1301
  # never writes — where the value the idiom returns is the one it stores, and `Dynamic[top] | rhs` sent
1292
1302
  # every such method to `sig.skipped.untyped-return`. It is the variable form's optimism for an unbound `||=`
1293
- # target (`ExpressionTyper#type_of_compound_variable_write`) keyed on the slot, and no wider: `&&=` is no
1303
+ # target (`ExpressionTyper::Writes.type_of_compound_variable_write`) keyed on the slot, and no wider: `&&=` is no
1294
1304
  # memo (`h[k] &&= v` on an absent slot is `nil`), an operator write has no such reading, and an rvalue
1295
1305
  # with no truthy part stores nothing truthy, so the slot's own value is the answer whenever it is set:
1296
1306
  # `opts[k] ||= raise KeyError` is a guard, never `bot`, and `@flags[n] ||= false` is `true` after an
@@ -1431,8 +1441,8 @@ module Rigor
1431
1441
  end
1432
1442
  end
1433
1443
 
1434
- # The binding half of {#eval_local_write}: the three mutually exclusive provenance paths a local write
1435
- # can take, unchanged from when they were inline.
1444
+ # The binding half of {#eval_local_write}: the provenance paths a local write can take (a declaration-sourced
1445
+ # copy, an inferred-parameter root, or the plain binding with its Dynamic / optimistic origin).
1436
1446
  def bind_local_write(node, rhs_type, post_rhs)
1437
1447
  # ADR-58 WD1 — `r = @right` where `@right`'s optionality is purely declaration-sourced makes `r`
1438
1448
  # declaration-sourced too (the survey's exact rotation/traversal shape `r = @right; r.key`). The mark is
@@ -1559,8 +1569,8 @@ module Rigor
1559
1569
  end
1560
1570
 
1561
1571
  def eval_cvar_write(node)
1562
- rhs_type, post_rhs = sub_eval(node.value, scope)
1563
- [rhs_type, post_rhs.with_cvar(node.name, rhs_type)]
1572
+ rhs, post = sub_eval(node.value, scope) # Issue #3443 — `with_cvar_copy` stamps a published-constant copy.
1573
+ [rhs, post.with_cvar_copy(node.name, rhs, published_constant_copy?(node.value, rhs, post))]
1564
1574
  end
1565
1575
 
1566
1576
  def eval_global_write(node)
@@ -1602,20 +1612,20 @@ module Rigor
1602
1612
  after.without_constant_narrowings_named(target.name.to_s)
1603
1613
  end
1604
1614
 
1605
- # The rvalue call whose block is the class body, for every spelling of the write. Issue #963: the `.freeze`
1606
- # tail and the `||=` / `Const = Const || …` guard are unwrapped by {ScopeIndexer.meta_new_rvalue}, the same
1607
- # recognition the index walks under, so the two passes enter the same node or neither does. The recognition
1608
- # is still the loose one — a CallNode carrying a literal block — because the strict-argument shapes the
1609
- # index declines are entered under an anonymous name rather than dropped.
1615
+ # The rvalue call whose block is the class body, for every spelling of the write. Issue #963: the `.freeze` tail
1616
+ # and the `||=` / `Const = Const || …` guard are unwrapped by {DeclarationWalk::Rules.meta_new_rvalue}, the same
1617
+ # recognition the index walks under, so the two passes enter the same node or neither does. The recognition is
1618
+ # still the loose one — a CallNode carrying a literal block — because the strict-argument shapes the index
1619
+ # declines are entered under an anonymous name rather than dropped.
1610
1620
  def meta_new_block_call(node)
1611
- rvalue = ScopeIndexer.meta_new_rvalue(node)
1621
+ rvalue = DeclarationWalk::Rules.meta_new_rvalue(node)
1612
1622
  rvalue if rvalue.is_a?(Prism::CallNode) && rvalue.block.is_a?(Prism::BlockNode)
1613
1623
  end
1614
1624
 
1615
1625
  # The class context a meta-new rvalue block is entered under, or nil when the rvalue is not that shape. The
1616
1626
  # KEY must be the one `ScopeIndexer` filed the body's defs and member layout under, so the two passes agree —
1617
1627
  # which is why the decision is delegated to the ScopeIndexer's own recognition rather than re-spelled here. A
1618
- # constant write whose rvalue `ScopeIndexer.meta_new_block_body` recognises is keyed by the constant's
1628
+ # constant write whose rvalue `DeclarationWalk::Rules.meta_new_block_body` recognises is keyed by the constant's
1619
1629
  # qualified name, one frame appended to the lexical context exactly as a `class Const` keyword body would be
1620
1630
  # — the path spelling included since [#703](https://github.com/rigortype/rigor/issues/703). A shape the
1621
1631
  # ScopeIndexer's stricter argument check rejects (`Const = Struct.new(*names) do … end`) is registered under
@@ -1633,7 +1643,7 @@ module Rigor
1633
1643
  # ({#eval_class_or_module}), so the stack resets to that frame alone rather than gaining one under the
1634
1644
  # enclosure — `current_class_path` joins the stack, and `ScopeIndexer`'s own prefix resets there too.
1635
1645
  def meta_new_constant_context(node)
1636
- return nil unless ScopeIndexer.meta_new_block_body(node)
1646
+ return nil unless DeclarationWalk::Rules.meta_new_block_body(node)
1637
1647
 
1638
1648
  case node
1639
1649
  when Prism::ConstantWriteNode, Prism::ConstantOrWriteNode
@@ -1856,8 +1866,8 @@ module Rigor
1856
1866
  end
1857
1867
  end
1858
1868
 
1859
- # `h[k] &&= v` / `h[k] += v`. Neither had a handler, so both fell to `evaluate`'s default — typed as a pure
1860
- # expression, scope untouched — and the receiver never widened. They store through `[]=` exactly as
1869
+ # `h[k] &&= v` / `h[k] += v`. Left to `evaluate`'s default they would type as a pure expression with the scope
1870
+ # untouched, and the receiver would never widen. They store through `[]=` exactly as
1861
1871
  # `eval_index_or_write` does, so they take the same widening; the stored value is the compound result —
1862
1872
  # `falsey(h[k]) | v` for `&&=`, the dispatched `h[k] + v` for `+=` — not the rvalue alone.
1863
1873
  #
@@ -2040,21 +2050,6 @@ module Rigor
2040
2050
  typer.implicit_index_read_type(node, receiver, index_types) || Type::Combinator.untyped
2041
2051
  end
2042
2052
 
2043
- # Argument types for a straight-line content mutator (`arr << x`, `h[k] = v`).
2044
- #
2045
- # **The two scopes are different on purpose.** `current_scope` is the post-call scope the widening will
2046
- # actually rewrite, so the receiver gate has to ask IT whether the binding is still a literal-shape
2047
- # carrier — asking the entry scope could green-light a join the widening then declines, or miss one it
2048
- # would make. The arguments, though, are evaluated BEFORE the call in Ruby's order, so their types come
2049
- # from the entry `scope`; that also matches how the block path types its own mutator arguments against
2050
- # the block-ENTRY scope. Between the two points the only edits to the scope are the block / escape /
2051
- # plugin-assertion helpers above, none of which can rebind a mutator call's argument expressions.
2052
- #
2053
- # Both gates are about cost, not correctness — the join declines on its own in either case.
2054
- # `Scope#type_of` builds a fresh `ExpressionTyper` per call and memoizes nothing, so typing arguments a
2055
- # join will not consume is pure overhead, and `<<` on a String buffer is one of the commonest calls
2056
- # there is. The content-adder table skips a non-adding mutator (`pop`, `sort!`); `joinable_receiver?`
2057
- # skips a receiver whose current binding is not a literal-shape carrier.
2058
2053
  # Both mutator-receiver widenings, against one typing of the call's arguments: the bindings the
2059
2054
  # receiver NAMES ({MutationWidening.widen_after_call}) and, when it names none because the
2060
2055
  # receiver is an element read into a local, that element's pin inside its container
@@ -2065,7 +2060,7 @@ module Rigor
2065
2060
  # receiver that may be another local's object floors every local whose object another holder may reach
2066
2061
  # ({AliasMutationFloor}).
2067
2062
  def widen_mutated_receivers(node, current_scope)
2068
- call_node = AliasMutationFloor.literal_send_target(node) || node
2063
+ call_node = AliasMutationFloor.literal_send_target(node) || OpaqueMutation.method_object_target(node) || node
2069
2064
  arg_types = mutator_arg_types(call_node, current_scope)
2070
2065
  widened = MutationWidening.widen_after_call(call_node: call_node, current_scope: current_scope,
2071
2066
  arg_types: arg_types,
@@ -2078,7 +2073,7 @@ module Rigor
2078
2073
  end
2079
2074
  end
2080
2075
  # Issue #2499 — a stdlib call that fills a String argument (`io.read(n, buf)`, `StringIO.new(s)`).
2081
- floor_ivar_mutating_callee(node, OutBufferMutation.floor(call_node, widened))
2076
+ floor_ivar_mutating_callee(node, OpaqueMutation.floor(node, OutBufferMutation.floor(call_node, widened)))
2082
2077
  end
2083
2078
 
2084
2079
  # Issue #2335 — a call on a local that may hold another local's object (`box = Box.new(a)`) to a project method
@@ -2149,6 +2144,12 @@ module Rigor
2149
2144
  end
2150
2145
 
2151
2146
  # `tr!` / `tr_s!` are typed too: whether they can empty a `non-empty-string` turns on their replacement argument.
2147
+ #
2148
+ # The two gates (the content-adder tables, `joinable_receiver?` / `joinable_element_read?`) are about cost, not
2149
+ # correctness: `Scope#type_of` memoizes nothing, so typing arguments a join will not consume is pure overhead, and
2150
+ # the join declines on its own either way. `current_scope` is the post-call scope the widening rewrites, so the
2151
+ # receiver gate asks it whether the binding is still a literal-shape carrier; the arguments are typed from the
2152
+ # call's operand scope, as Ruby evaluates them before the call.
2152
2153
  def mutator_arg_types(call_node, current_scope)
2153
2154
  name = call_node.name
2154
2155
  unless ContentJoin::CONTENT_ADDERS.include?(name) || StringMutation::TRANSLATORS.include?(name) ||
@@ -2232,6 +2233,8 @@ module Rigor
2232
2233
  [scope.type_of(node, tracer: tracer), forget_rebound_specials(widened, node)]
2233
2234
  end
2234
2235
 
2236
+ # @api private — public only so {PatternBindings.bind_rescue_reference} can call it on the evaluator it is given.
2237
+ #
2235
2238
  # The scope effect of calling the writer `writer` on `receiver` outside a `CallNode`: the receiver widening, the
2236
2239
  # drop of every method-chain narrowing rooted at the receiver that `eval_call` makes after any call on it (issue
2237
2240
  # #2693: `x.r ||= v`, `x.r, y = …` and `for x.r in …` call `r=`), and the receiver-wide drop of recorded
@@ -2244,6 +2247,7 @@ module Rigor
2244
2247
  widened = widened.without_method_chain_narrowings_for(*stable)
2245
2248
  IndexedNarrowing.mutator?(writer) ? widened.without_indexed_narrowings_for(*stable) : widened
2246
2249
  end
2250
+ public :widen_attribute_write
2247
2251
 
2248
2252
  # The attribute targets of a multi-write (`h.default, x = 0, 1`), nested ones included, each widening its
2249
2253
  # receiver as the plain writer call would.
@@ -2267,6 +2271,8 @@ module Rigor
2267
2271
  end
2268
2272
  end
2269
2273
 
2274
+ # @api private — public only so {PatternBindings.bind_rescue_reference} can call it on the evaluator it is given.
2275
+ #
2270
2276
  # An index target (`Prism::IndexTargetNode`) stores `stored` through `[]=` on its receiver wherever it
2271
2277
  # appears — a multi-assign slot, a `for` index, a rescue reference — so its receiver widens exactly as the
2272
2278
  # plain store `h[:a] = v` widens it, joining `stored` as content evidence (issue #560), and drops the
@@ -2279,6 +2285,7 @@ module Rigor
2279
2285
  arg_types: index_write_arg_types(target, stored, type_scope: type_scope))
2280
2286
  IndexedNarrowing.invalidate_indexed_write(target, widened)
2281
2287
  end
2288
+ public :widen_index_target
2282
2289
 
2283
2290
  # `if pred; t; (elsif/else)?` runs the predicate first (its post-scope is shared by both branches), then asks
2284
2291
  # `Rigor::Inference::Narrowing` for the truthy and falsey edge scopes derived from the predicate. Slice 6 phase 1
@@ -2418,7 +2425,7 @@ module Rigor
2418
2425
  # (see {Inference::OptimisticOrigin} and docs/internal-spec/inference-engine.md), so eliding an arm on
2419
2426
  # it deletes a branch the program really takes when the lookup misses.
2420
2427
  #
2421
- # The decline lives here and NOT in `Narrowing.falsey_nominal?` / `.narrow_falsey`: `&&=` / `||=` and
2428
+ # The decline lives here and NOT in `Complements.falsey_nominal?` / `Narrowing.narrow_falsey`: `&&=` / `||=` and
2422
2429
  # the and/or surviving-left edge read those too, and widening the falsey fragment there would re-admit
2423
2430
  # `nil` into a bound local and buy `possible nil receiver` false positives — a soundness fix paid for
2424
2431
  # in FPs, which is the wrong trade.
@@ -2438,7 +2445,7 @@ module Rigor
2438
2445
  def eval_case(node)
2439
2446
  subject_type, post_pred = node.predicate ? sub_eval(node.predicate, scope) : [nil, scope]
2440
2447
  branch_results, falsey_scope = eval_case_when_branches(subject_type, node.predicate, node.conditions, post_pred)
2441
- if pattern_case_matches_every_path?(node, branch_results)
2448
+ if pattern_case_matches_every_path?(node, branch_results) || Narrowing.exhausted_when_case?(node, falsey_scope)
2442
2449
  return unmatched_pattern_result(branch_results, node.conditions, post_pred)
2443
2450
  end
2444
2451
 
@@ -2652,8 +2659,8 @@ module Rigor
2652
2659
  # Issue #2211 — a global subject from a `when` test that may rebind it on ({#when_test_rebinds_subject?}): a
2653
2660
  # method may assign a global, and the statement walk keeps a global's binding past a call, so the clause
2654
2661
  # bodies and the later clauses read it as `Dynamic[top]`, as the scope index's walk of a value-position `case`
2655
- # reads it
2656
- # (`ScopeIndexer#forget_called_subject`). `$g = nil; case $g when String then 1 when reset! then 2 else $g + 1
2662
+ # reads it (`ScopeIndexer::NodePropagation#forget_called_subject`).
2663
+ # `$g = nil; case $g when String then 1 when reset! then 2 else $g + 1
2657
2664
  # end`, with `reset!` assigning `$g`, is `6` in Ruby. An instance variable a test's call may write is widened by
2658
2665
  # {#run_when_test} instead; any other subject is left as is.
2659
2666
  def forget_called_global_subject(subject, scope)
@@ -2709,7 +2716,8 @@ module Rigor
2709
2716
  # shape.
2710
2717
  def in_branch_body_and_falsey_scopes(subject_type, subject, branch, falsey_scope)
2711
2718
  truthy_scope, narrowed_falsey = Narrowing.case_clause_scopes(subject, branch, falsey_scope)
2712
- [apply_in_pattern_bindings(subject_type, subject, branch.pattern, truthy_scope), narrowed_falsey]
2719
+ [PatternBindings.apply_in_pattern_bindings(subject_type, subject, branch.pattern, truthy_scope, self),
2720
+ narrowed_falsey]
2713
2721
  end
2714
2722
 
2715
2723
  def eval_case_else(else_clause, falsey_scope)
@@ -2726,9 +2734,9 @@ module Rigor
2726
2734
 
2727
2735
  # Issue #1360 — a `begin` with a rescue chain runs through {#eval_begin} with `$!` and `$@` restored as it
2728
2736
  # leaves ({#restoring_error_info}): Ruby restores them once the `begin` exits, however it exits, so the binding
2729
- # its rescue clauses made ({#bind_rescue_reference}) never reaches the code after it. The retry edge carries
2730
- # locals and instance variables only, so a retried body reads them as the `begin` found them already. A `begin`
2731
- # without a rescue chain binds neither.
2737
+ # its rescue clauses made ({PatternBindings.bind_rescue_reference}) never reaches the code after it. The retry
2738
+ # edge carries locals and instance variables only, so a retried body reads them as the `begin` found them
2739
+ # already. A `begin` without a rescue chain binds neither.
2732
2740
  #
2733
2741
  # A body a `retry` re-enters runs again after the exception it raised, which may have come while a subprocess
2734
2742
  # waited and so left `$?` nil, and the retry edge does not carry `$?`: such a `begin` is evaluated with `$?`
@@ -2782,7 +2790,7 @@ module Rigor
2782
2790
  # after it, or a rescue clause, may have set `$_` enters with it forgotten; a rescue clause runs after any
2783
2791
  # prefix of the body, and so reads it forgotten whenever the body may set it.
2784
2792
  entry = edge ? forget_guard_if_rebinds(LastLine.forget_if_set(scope, node), node) : scope
2785
- rescue_entry = rescue_entry_scope(node, entry)
2793
+ rescue_entry = ClauseWidening.content_entry(rescue_entry_scope(node, entry), node)
2786
2794
  collector = begin_fact_collector(node, rescue_entry, edge)
2787
2795
  primary_type, primary_scope = eval_begin_primary_under(node, entry, edge: edge, collector: collector)
2788
2796
  rescue_chain = collect_rescue_chain_results(node.rescue_clause, rescue_entry,
@@ -2941,7 +2949,8 @@ module Rigor
2941
2949
  sub_eval(statements, widened, **UNRECORDED)
2942
2950
  end
2943
2951
 
2944
- # Runs `block` with no `return`, `next`, `break` or retry-frame sink installed.
2952
+ # Runs `block` with none of {CLAUSE_SINKS} installed: no `return`, `next`, `break` (scope or value) or retry-frame
2953
+ # sink.
2945
2954
  def without_jump_sinks(&)
2946
2955
  TypingState.current.without(CLAUSE_SINKS, &)
2947
2956
  end
@@ -3442,10 +3451,10 @@ module Rigor
3442
3451
  while current
3443
3452
  widened = widen_clause_entry(entry_scope, writes, current.statements)
3444
3453
  record_operand_clause(current.statements, widened)
3445
- rescue_scope = bind_rescue_reference(current, entry_scope)
3454
+ rescue_scope = PatternBindings.bind_rescue_reference(current, entry_scope, self)
3446
3455
  arm = if widened
3447
- eval_widened_clause(current.statements, rescue_scope, bind_rescue_reference(current, widened),
3448
- on_enter: on_enter)
3456
+ eval_widened_clause(current.statements, rescue_scope,
3457
+ PatternBindings.bind_rescue_reference(current, widened, self), on_enter: on_enter)
3449
3458
  else
3450
3459
  eval_branch_or_nil(current.statements, rescue_scope, on_enter: on_enter)
3451
3460
  end
@@ -3492,7 +3501,6 @@ module Rigor
3492
3501
  # ({#loop_body_ivar_writes}).
3493
3502
  def eval_repeating_for(node) = ReflectiveIvarWrite.in_repeating_body { eval_for(node) }
3494
3503
 
3495
- # A loop's evaluation, with its value recorded for `ExpressionTyper#type_of_loop` ({LoopValueRecord}).
3496
3504
  # A conditional's evaluation, recorded when it evaluated a loop ({LoopValueRecord.conditional}): the typer
3497
3505
  # types a conditional that holds a loop again from the scope it was evaluated from, and the loop in its branch
3498
3506
  # is evaluated from a branch scope no record matches.
@@ -3509,6 +3517,7 @@ module Rigor
3509
3517
  result
3510
3518
  end
3511
3519
 
3520
+ # A loop's evaluation, with its value recorded for `ExpressionTyper#type_of_loop` ({LoopValueRecord}).
3512
3521
  def eval_recorded_loop(node) = record_loop_value(node, eval_loop(node))
3513
3522
 
3514
3523
  def eval_recorded_for(node) = record_loop_value(node, eval_repeating_for(node))
@@ -3664,7 +3673,9 @@ module Rigor
3664
3673
  # post-predicate binding; a local FIRST assigned inside the body seeds with `nil` so the 0-iteration path
3665
3674
  # degrades it to `T | nil`, matching the nil-injection treatment.
3666
3675
  break_pass = { entry: nil, arms: [], values: [] } if jumps.breaks || later_pass_returns?(node.statements)
3667
- result = loop_rebind_fixpoint(node, post_pred, names, body_first, jumps, break_pass)
3676
+ sites = loop_store_sites(node.statements)
3677
+ site_pass = LoopStoreSites::Pass.new(sites, @store_sites) unless sites.assigned.empty?
3678
+ result = loop_rebind_fixpoint(node, post_pred, names, body_first, jumps, break_pass, site_pass)
3668
3679
  # Display-path re-record: the fixpoint's body re-evaluations fire `on_enter` with the cap-N INTERMEDIATE
3669
3680
  # assumptions, so the last-visit-wins scope index would annotate loop-body lines with stale pre-convergence
3670
3681
  # constants. One extra pass from the converged bindings (result discarded) re-records the body's entry scopes.
@@ -3674,7 +3685,10 @@ module Rigor
3674
3685
  # << n`) keeps only the seed's element types after the single-pass widen; join the appended/stored types into
3675
3686
  # the continuation collection. Pre-state comes from `post_pred` for a name the loop only content-mutates and
3676
3687
  # from `post_loop` for one it also rebinds, so composition still works — see {#loop_content_writeback}.
3677
- post_loop = loop_content_writeback(node.statements, post_loop, pre_body: post_pred, rebound: names)
3688
+ # Issue #3337 — each store's arguments are typed with the rebound locals as the last pass reached the store.
3689
+ site_scopes = LoopStoreSites.argument_scopes(sites, site_pass, post_loop, result)
3690
+ post_loop = loop_content_writeback(node.statements, post_loop, pre_body: post_pred, rebound: names,
3691
+ stores: sites.stores, site_scopes: site_scopes)
3678
3692
  arms, values = loop_break_arms(node, post_pred, result, body_first, jumps, break_pass)
3679
3693
  [join_break_scopes(post_loop, arms, names), values]
3680
3694
  end
@@ -3779,10 +3793,11 @@ module Rigor
3779
3793
  #
3780
3794
  # The `next` scopes are collected into a sink threaded through `sub_eval` ({#evaluate_invocation} does the same
3781
3795
  # for a block), and the `break` scopes into a thread-local one, each installed only when the body has such a
3782
- # jump. `recorded: false` evaluates without recording into the per-node scope index.
3783
- def loop_iteration(statements, entry, jumps, recorded: true)
3796
+ # jump. `recorded: false` evaluates without recording into the per-node scope index. `store_sites` is the
3797
+ # table the pass leaves its store sites' scopes in: an enclosing loop's by default, none when unrecorded.
3798
+ def loop_iteration(statements, entry, jumps, recorded: true, store_sites: @store_sites)
3784
3799
  next_sink = jumps.nexts && []
3785
- recording = recorded ? {} : UNRECORDED
3800
+ recording = recorded ? { store_sites: store_sites } : UNRECORDED
3786
3801
  evaluate = -> { sub_eval(statements, entry, next_scope_sink: next_sink, **recording).last }
3787
3802
  if jumps.breaks
3788
3803
  break_sink, (fall_through, value_sink) = collect_break_scopes do
@@ -3836,7 +3851,7 @@ module Rigor
3836
3851
  # from the widened binding reaches it ({#loop_break_arms}); without it the method inferred `true` and a
3837
3852
  # caller's test on it folded always-truthy on correct code.
3838
3853
  def later_pass_returns?(statements)
3839
- !typing_state[RETURN_SINK].nil? && ReturnBarrier.exits_method?(statements)
3854
+ !typing_state[RETURN_SINK].nil? && ReturnBarrier.exits_method?(statements, scope)
3840
3855
  end
3841
3856
 
3842
3857
  # Joins each `break` arm's body-written local bindings into the loop continuation, so a `break`-path binding the
@@ -3880,27 +3895,30 @@ module Rigor
3880
3895
  #
3881
3896
  # A name the loop rebinds keeps reading `post_loop`, which is what lets a local both rebound (slice B) and
3882
3897
  # content-mutated compose — the documented behaviour, and there the fixpoint's answer IS the right base.
3883
- def loop_content_writeback(statements, post_loop, pre_body: nil, rebound: nil)
3884
- return post_loop if statements.nil?
3885
-
3886
- mutations = Hash.new { |h, k| h[k] = [] }
3887
- Source::NodeWalker.each(statements) do |descendant|
3888
- name, node = content_mutation_target(descendant) { |_r| true }
3889
- mutations[name] << node unless name.nil?
3890
- end
3891
- return post_loop if mutations.empty?
3898
+ #
3899
+ # `site_scopes` holds, for a store the rebind fixpoint's last pass reached, the scope its arguments are typed
3900
+ # in instead of `post_loop` ({LoopStoreSites.argument_scopes}, issue #3337).
3901
+ def loop_content_writeback(statements, post_loop, pre_body: nil, rebound: nil,
3902
+ stores: loop_store_sites(statements).stores, site_scopes: NO_SHADOWS)
3903
+ return post_loop if stores.empty?
3892
3904
 
3893
3905
  rewrites = local_rewrites(statements) { true }
3894
- mutations.reduce(post_loop) do |acc, (name, calls)|
3906
+ stores.reduce(post_loop) do |acc, (name, calls)|
3895
3907
  seed_scope = content_seed_scope(name, acc, pre_body, rebound)
3896
3908
  seed = lookup_mutated_seed(statements, name, seed_scope.local(name)) { |depth, nesting| depth == nesting }
3897
- joined = join_content_for_param(calls, seed, post_loop)
3909
+ joined = join_content_for_param(calls, seed, post_loop, site_scopes)
3898
3910
  next acc if joined.nil?
3899
3911
 
3900
3912
  acc.with_mutated_local(name, rewritten_capture(joined, seed, rewrites.fetch(name, NO_REWRITES)))
3901
3913
  end
3902
3914
  end
3903
3915
 
3916
+ # The {LoopStoreSites::Sites} of a loop body: every content mutation whose receiver is a local, which
3917
+ # {#loop_content_writeback} joins. A loop body shares the surrounding scope, so there is no depth filter.
3918
+ def loop_store_sites(statements)
3919
+ LoopStoreSites.scan(statements) { |node| content_mutation_target(node) { |_r| true } }
3920
+ end
3921
+
3904
3922
  # The scope a loop content join reads its PRE-STATE from: the pre-body scope for a name the loop only
3905
3923
  # content-mutates, and the accumulating post-loop scope for one the loop also rebinds. {#loop_content_writeback}
3906
3924
  # carries the why.
@@ -3925,11 +3943,11 @@ module Rigor
3925
3943
  # local seeds with its post-predicate binding; a local FIRST assigned inside the body seeds with `nil` so the
3926
3944
  # 0-iteration path (the body may never run) degrades it to `T | nil`, matching the historical nil-injection
3927
3945
  # treatment. `break_pass` rides along so every pass leaves its `break` arms for {#loop_break_arms}.
3928
- def loop_rebind_fixpoint(node, post_pred, names, body_first, jumps, break_pass)
3946
+ def loop_rebind_fixpoint(node, post_pred, names, body_first, jumps, break_pass, site_pass = nil)
3929
3947
  nil_const = Type::Combinator.constant_of(nil)
3930
3948
  seed = names.to_h { |name| [name, CapturedLocals.bound_type(post_pred, name) || nil_const] }
3931
3949
  evaluate_body = lambda do |bindings|
3932
- loop_body_exit_bindings(node, post_pred, bindings, names, body_first, jumps, break_pass)
3950
+ loop_body_exit_bindings(node, post_pred, bindings, names, body_first, jumps, break_pass, site_pass)
3933
3951
  end
3934
3952
  BodyFixpoint.converge(
3935
3953
  names: names,
@@ -4008,9 +4026,14 @@ module Rigor
4008
4026
  # With a `break_pass` record the pass also leaves its entry and its `break` arms there for {#loop_break_arms};
4009
4027
  # `BodyFixpoint` hands every pass the same mutable assumption, and `except` copies it before the fixpoint moves
4010
4028
  # it.
4011
- def loop_body_exit_bindings(node, post_pred, bindings, names, body_first, jumps, break_pass = nil)
4029
+ #
4030
+ # Only a fixpoint pass is given a `site_pass` ({LoopStoreSites::Pass}) to leave its store sites' scopes and its
4031
+ # assumption in. The display path's re-record pass is given none, so both paths type a store from the same pass.
4032
+ def loop_body_exit_bindings(node, post_pred, bindings, names, body_first, jumps, break_pass = nil, # rubocop:disable Metrics/ParameterLists
4033
+ site_pass = nil)
4012
4034
  entry = loop_pass_entry(node, post_pred, bindings, body_first, jumps)
4013
- exit_scope, breaks, values = loop_iteration(node.statements, entry, jumps)
4035
+ site_pass&.start(bindings)
4036
+ exit_scope, breaks, values = loop_iteration(node.statements, entry, jumps, store_sites: site_pass&.scopes)
4014
4037
  if break_pass
4015
4038
  break_pass[:entry] = bindings.except(*body_first)
4016
4039
  break_pass[:arms] = breaks
@@ -4072,11 +4095,11 @@ module Rigor
4072
4095
  # `for index in collection; body; end`. Unlike `each {}` blocks, `for` does NOT create a new variable scope: the
4073
4096
  # index variable AND every local written in the body leak to the surrounding scope. The collection is evaluated
4074
4097
  # once; the body runs zero or more times, so the post-loop scope is the join of the no-iteration scope (just
4075
- # `post_collection`) and the body scope, with half-bound names degraded to `T | nil` via nil-injection. The loop
4098
+ # `post_coll`) and the body scope, with half-bound names degraded to `T | nil` via nil-injection. The loop
4076
4099
  # expression is the collection's `each` value joined with every `break` value ({#for_value}, issue #1216).
4077
4100
  def eval_for(node)
4078
4101
  coll_type, post_coll = sub_eval(node.collection, scope)
4079
- body_entry = for_body_entry(node, for_iteration_element_type(coll_type), post_coll)
4102
+ body_entry = for_body_entry(node, for_iteration_element_type(coll_type, node.index), post_coll)
4080
4103
 
4081
4104
  if node.statements.nil?
4082
4105
  return [for_value(node, coll_type, post_coll, NO_BREAK_ARMS),
@@ -4223,7 +4246,13 @@ module Rigor
4223
4246
  # The scope a `for` body enters with: the index bound to the element. Issue #1359 — a body that may set `$_` runs
4224
4247
  # again after it ran, as a `while` body does ({#eval_loop}).
4225
4248
  def for_body_entry(node, element_type, post_coll)
4226
- body_entry = LastLine.forget_if_set(bind_for_index(node.index, element_type, post_coll), node.statements)
4249
+ bound =
4250
+ if ForYieldSlots.signature?(element_type)
4251
+ ForYieldSlots.bind(node.index, element_type, post_coll) { |*slot| bind_for_index(*slot) }
4252
+ else
4253
+ bind_for_index(node.index, element_type, post_coll)
4254
+ end
4255
+ body_entry = LastLine.forget_if_set(bound, node.statements)
4227
4256
  body_entry = forget_guard_for_body(node, post_coll, body_entry)
4228
4257
  loop_content_entry(node.statements, post_coll, body_entry)
4229
4258
  end
@@ -4241,9 +4270,19 @@ module Rigor
4241
4270
  # consult RBS and the iterator dispatch table (they know, e.g., that `Hash[K, V]#each` yields `[K, V]` even when
4242
4271
  # the receiver is not a literal Hash carrier in our local lattice). When the dispatcher returns nothing (no
4243
4272
  # signature, unknown receiver) the structural answer stands.
4244
- def for_iteration_element_type(coll_type)
4273
+ #
4274
+ # Issue #3205 — the index binds as a block's parameters do: a single target (`for b in`) takes the first yielded
4275
+ # value, a multi-target (`for a, b in`) or splat (`for *s in`) index all of them. So an `each` declared to yield
4276
+ # several values (`{ (A, B) -> void }`) binds a single target to `A`, and an `Enumerator` whose element is a
4277
+ # tuple binds it to `Dynamic[top]` ({#enumerator_floor}). A multi-target or splat index reads the block's
4278
+ # signature ({ForYieldSlots.element_type}, issue #3265).
4279
+ def for_iteration_element_type(coll_type, index)
4280
+ single = !index.is_a?(Prism::MultiTargetNode) && !index.is_a?(Prism::SplatNode)
4245
4281
  structural = collection_element_type(coll_type)
4246
- return structural unless Type::Combinator.untyped?(structural)
4282
+ unless Type::Combinator.untyped?(structural)
4283
+ return single ? enumerator_floor(coll_type, structural) : structural
4284
+ end
4285
+ return ForYieldSlots.element_type(coll_type, structural, scope) unless single
4247
4286
 
4248
4287
  block_params = MethodDispatcher.expected_block_param_types(
4249
4288
  receiver_type: coll_type,
@@ -4254,11 +4293,27 @@ module Rigor
4254
4293
  )
4255
4294
  return structural if block_params.nil? || block_params.empty?
4256
4295
 
4257
- block_params.size == 1 ? block_params.first : Type::Combinator.tuple_of(*block_params)
4296
+ block_params.size == 1 ? enumerator_floor(coll_type, block_params.first) : block_params.first
4258
4297
  rescue StandardError
4259
4298
  Type::Combinator.untyped
4260
4299
  end
4261
4300
 
4301
+ # An `Enumerator[[A, B]]` does not say whether its `each` yields the two values (`each_with_index`,
4302
+ # `each_with_object`, `Hash#select`: a single target binds `A`) or one array (`Hash#each`, `Array#each` over
4303
+ # pairs: it binds `[A, B]`). A single target over such an enumerator, or over an `Enumerator::Lazy`,
4304
+ # `Enumerator::Chain` or other descendant of `Enumerator`, binds neither guess but `Dynamic[top]`.
4305
+ #
4306
+ # An element union with such a tuple member (`ewi.chain(ewi)` reads `Enumerator::Chain[Dynamic[top] | [A, B]]`)
4307
+ # floors as a whole.
4308
+ def enumerator_floor(coll_type, element)
4309
+ members = element.is_a?(Type::Union) ? element.members : [element]
4310
+ return element unless members.any? { |member| member.is_a?(Type::Tuple) && member.elements.size >= 2 }
4311
+ return element unless coll_type.is_a?(Type::Nominal)
4312
+
4313
+ ordering = scope.environment.class_ordering(coll_type.class_name, "Enumerator")
4314
+ %i[equal subclass].include?(ordering) ? Type::Combinator.untyped : element
4315
+ end
4316
+
4262
4317
  # Binds the `for` index variable(s) into `scope`. A single `LocalVariableTargetNode` is bound to `element_type`
4263
4318
  # (the per-iteration value the collection yields). A `MultiTargetNode` (`for a, b in pairs`) delegates to
4264
4319
  # {MultiTargetBinder}, which decomposes a tuple-shaped element into the inner slots.
@@ -4321,9 +4376,9 @@ module Rigor
4321
4376
  end
4322
4377
 
4323
4378
  # Extracts the per-iteration element type from a collection carrier. `Tuple[T1..Tn]` yields the union of its
4324
- # elements; `Nominal[Array, [T]]` and `Nominal[Range, [T]]` yield `T`; `Nominal[Hash, [K, V]]` yields `Tuple[K,
4325
- # V]` (Hash#each yields `[key, value]` pairs); `IntegerRange` yields `Integer`; a `Range` constant reads the
4326
- # literal range's element class. Anything else falls back to `untyped`.
4379
+ # elements; `Nominal[Array, [T]]` (likewise `Range`, `Set`, `Enumerator`) yields `T`; `Nominal[Hash, [K, V]]`
4380
+ # yields `Tuple[K, V]` (Hash#each yields `[key, value]` pairs); `IntegerRange` yields `Integer`; a `Range`
4381
+ # constant reads the literal range's element class. Anything else falls back to `untyped`.
4327
4382
  def collection_element_type(type)
4328
4383
  case type
4329
4384
  when Type::Tuple
@@ -4639,6 +4694,8 @@ module Rigor
4639
4694
  [body_type, scope]
4640
4695
  end
4641
4696
 
4697
+ # @api private — public only so {DefArgumentsAndAssertions} can call it on the evaluator it is given.
4698
+ #
4642
4699
  # `def name(params); body; end`. Builds the method-entry scope by binding the parameter list (RBS-driven where
4643
4700
  # available, or `Dynamic[Top]` for the slice 3 phase 2 fallback) into a fresh scope, then evaluates the body under
4644
4701
  # that scope. The outer scope is left unchanged: a `def` does not introduce a binding in its enclosing scope. Ruby
@@ -4660,6 +4717,7 @@ module Rigor
4660
4717
  end
4661
4718
  [Type::Combinator.constant_of(node.name), scope]
4662
4719
  end
4720
+ public :eval_def
4663
4721
 
4664
4722
  # `recv.foo(args) { |params| body }` and friends. The call type comes from `Scope#type_of` (which routes through
4665
4723
  # `ExpressionTyper#call_type_for` and is itself block-aware since Slice 6 phase C sub-phase 2: it builds the
@@ -4824,7 +4882,7 @@ module Rigor
4824
4882
  # `self.helper` inside reports `undefined method 'helper' for singleton(C)`. Walking each argument-position def
4825
4883
  # under the current evaluator (not a sub_eval — the def's effects do not bind into the surrounding scope)
4826
4884
  # populates the scope index with the correct instance / singleton `self_type` for the def's body.
4827
- evaluate_def_arguments(node)
4885
+ DefArgumentsAndAssertions.evaluate_def_arguments(node, self)
4828
4886
  post_scope = record_closure_escape_if_any(node)
4829
4887
  # ADR-56 slice A — non-escaping block captured-local write-back. A `:non_escaping` block (each / times / upto /
4830
4888
  # map …) that rebinds an outer local must not leave that local's pre-call binding unmodified in the continuation
@@ -4905,7 +4963,7 @@ module Rigor
4905
4963
  post_scope = post_scope.forget_last_line if rebinds_last_line?(node, post_scope)
4906
4964
  if post_scope.guard_narrowed? && GuardRebinding.call_may_rebind?(node, operand_scope)
4907
4965
  # Issue #1596 — a self-call proven to write only some instance variables restores only theirs.
4908
- writes = intervening_call_candidate?(node) ? self_call_ivar_writes(node) : nil
4966
+ writes = intervening_call_candidate?(node) ? self_call_ivar_effects(node)&.written : nil
4909
4967
  post_scope = if writes
4910
4968
  writes.reduce(post_scope) { |acc, name| acc.forget_guard_narrowing_of(:ivar, name) }
4911
4969
  else
@@ -5033,9 +5091,9 @@ module Rigor
5033
5091
  end
5034
5092
 
5035
5093
  def apply_post_return_narrowing(node, post_scope)
5036
- post_scope = apply_rbs_extended_assertions(node, post_scope)
5037
- post_scope = apply_plugin_assertions(node, post_scope)
5038
- apply_rspec_matcher_narrowing(node, post_scope)
5094
+ post_scope = DefArgumentsAndAssertions.apply_rbs_extended_assertions(node, post_scope, tracer)
5095
+ post_scope = DefArgumentsAndAssertions.apply_plugin_assertions(node, post_scope, tracer)
5096
+ DefArgumentsAndAssertions.apply_rspec_matcher_narrowing(node, post_scope)
5039
5097
  end
5040
5098
 
5041
5099
  # True when `node` could rebind the regex match-data globals by itself
@@ -5059,7 +5117,7 @@ module Rigor
5059
5117
  # is one that could plausibly mutate ivars on the enclosing class (implicit-self or explicit `self.foo`).
5060
5118
  # External-receiver calls (`obj.method`) cannot reach the caller's ivars; they pass through unchanged, apart from
5061
5119
  # the literal-block case below.
5062
- # Issue #1596 — where the call is proven to write only some ivars ({#self_call_ivar_writes}), only those widen.
5120
+ # Issue #1596 — where the call is proven to write only some ivars ({#self_call_ivar_effects}), only those widen.
5063
5121
  #
5064
5122
  # Issue #1402 — a proc's call (`blk.call`) is a candidate too, and so is a call on another receiver whose literal
5065
5123
  # block makes one ({InterveningIvarReset.after_block}: `[1].each { reset }`). Both widen as a condition's
@@ -5077,7 +5135,7 @@ module Rigor
5077
5135
  mark = InterveningIvarReset.self_call?(call_node) ? :unproven : true
5078
5136
  direct_writes = -> { DirectIvarWrites.of(call_node, operand_scope) }
5079
5137
  InterveningIvarReset.widen(current_scope, mark: mark, direct_writes: direct_writes) do
5080
- self_call_ivar_writes(call_node)
5138
+ self_call_ivar_effects(call_node)
5081
5139
  end
5082
5140
  else
5083
5141
  InterveningIvarReset.after_block(call_node, current_scope)
@@ -5087,11 +5145,9 @@ module Rigor
5087
5145
 
5088
5146
  # Issue #1596 — the ivars the implicit-self / `self.` call `call_node` may write, or nil when that is not proven
5089
5147
  # ({SelfCallIvarWrites.of}). Memoised per call node: the reset and the guard restore ask it of the same call.
5090
- def self_call_ivar_writes(call_node)
5091
- memo = (@self_call_ivar_writes ||= {}.compare_by_identity)
5092
- return memo[call_node] if memo.key?(call_node)
5093
-
5094
- memo[call_node] = SelfCallIvarWrites.of(call_node, operand_scope)
5148
+ def self_call_ivar_effects(call_node)
5149
+ memo = (@self_call_ivar_effects ||= {}.compare_by_identity)
5150
+ memo.fetch(call_node) { memo[call_node] = SelfCallIvarWrites.effects(call_node, operand_scope) }
5095
5151
  end
5096
5152
 
5097
5153
  def intervening_call_candidate?(call_node)
@@ -5104,341 +5160,6 @@ module Rigor
5104
5160
  end
5105
5161
  end
5106
5162
 
5107
- def evaluate_def_arguments(call_node)
5108
- args = call_node.arguments
5109
- return unless args.respond_to?(:arguments)
5110
-
5111
- args.arguments.each do |arg|
5112
- eval_def(arg) if arg.is_a?(Prism::DefNode)
5113
- end
5114
- end
5115
-
5116
- # v0.0.3 — recognises a small catalogue of RSpec matcher patterns as assert-shaped narrows on the local passed to
5117
- # `expect(...)`. The pattern is matched purely on AST shape; no RBS for RSpec is required (and none is shipped
5118
- # today).
5119
- #
5120
- # Recognised today:
5121
- #
5122
- # expect(x).not_to(be_nil)
5123
- # expect(x).to_not(be_nil)
5124
- # → narrow `x` AWAY from `NilClass`.
5125
- #
5126
- # expect(x).to(be_a(C))
5127
- # expect(x).to(be_kind_of(C))
5128
- # expect(x).to(be_an_instance_of(C))
5129
- # → narrow `x` to `C` (exact for
5130
- # `be_an_instance_of`, subtype-permitting
5131
- # otherwise).
5132
- #
5133
- # Anything else is silently passed through. Symmetric negative class assertions (`not_to be_a(C)`) and narrowing
5134
- # TO `NilClass` are intentionally NOT modelled: they are rarely useful in practice and risk masking bugs if the
5135
- # assertion later fails.
5136
- def apply_rspec_matcher_narrowing(call_node, current_scope)
5137
- narrow = rspec_matcher_narrowing_request(call_node)
5138
- return current_scope if narrow.nil?
5139
-
5140
- local_name = narrow.fetch(:local)
5141
- current_type = current_scope.local(local_name)
5142
- return current_scope if current_type.nil?
5143
-
5144
- narrowed = apply_rspec_narrow(current_type, narrow, current_scope.environment)
5145
- current_scope.with_local(local_name, narrowed)
5146
- end
5147
-
5148
- # Decodes an `expect(x).<chain>` outer call into a narrowing request hash, or `nil` when the shape is not
5149
- # recognised. The hash carries `:local` (the local name being narrowed) plus the narrowing parameters.
5150
- def rspec_matcher_narrowing_request(call_node)
5151
- local_name = rspec_expectation_target(call_node)
5152
- return nil if local_name.nil?
5153
-
5154
- case call_node.name
5155
- when :not_to, :to_not
5156
- rspec_negative_narrow(call_node, local_name)
5157
- when :to
5158
- rspec_positive_narrow(call_node, local_name)
5159
- end
5160
- end
5161
-
5162
- def rspec_negative_narrow(call_node, local_name)
5163
- return nil unless rspec_matcher_argument?(call_node, :be_nil)
5164
-
5165
- { local: local_name, kind: :not_class, class_name: "NilClass", exact: false }
5166
- end
5167
-
5168
- def rspec_positive_narrow(call_node, local_name)
5169
- matcher = rspec_matcher_node(call_node)
5170
- return nil if matcher.nil?
5171
-
5172
- case matcher.name
5173
- when :be_a, :be_kind_of
5174
- rspec_be_a_narrow(matcher, local_name, exact: false)
5175
- when :be_an_instance_of, :be_instance_of
5176
- rspec_be_a_narrow(matcher, local_name, exact: true)
5177
- end
5178
- end
5179
-
5180
- # `be_a` / `be_kind_of` / `be_an_instance_of` accept a single class argument — either a `ConstantReadNode`
5181
- # (`Integer`) or a `ConstantPathNode` (`Rigor::Type::Nominal`).
5182
- def rspec_be_a_narrow(matcher, local_name, exact:)
5183
- args = matcher.arguments&.arguments || []
5184
- return nil unless args.size == 1
5185
-
5186
- class_name = Source::ConstantPath.qualified_name_or_nil(args.first)
5187
- return nil if class_name.nil?
5188
-
5189
- { local: local_name, kind: :class, class_name: class_name, exact: exact }
5190
- end
5191
-
5192
- def apply_rspec_narrow(current_type, narrow, environment)
5193
- case narrow.fetch(:kind)
5194
- when :not_class
5195
- Narrowing.narrow_not_class(current_type, narrow.fetch(:class_name),
5196
- exact: narrow.fetch(:exact), environment: environment)
5197
- when :class
5198
- Narrowing.narrow_class(current_type, narrow.fetch(:class_name),
5199
- exact: narrow.fetch(:exact), environment: environment)
5200
- end
5201
- end
5202
-
5203
- # Returns the local name passed to `expect(...)` when the receiver chain matches `expect(<local>)` exactly, or nil
5204
- # otherwise. Centralised so each per-matcher decoder can short-circuit on a non-matching outer call.
5205
- def rspec_expectation_target(call_node)
5206
- receiver = call_node.receiver
5207
- return nil unless receiver.is_a?(Prism::CallNode) && receiver.name == :expect
5208
- return nil unless receiver.receiver.nil?
5209
-
5210
- args = receiver.arguments&.arguments || []
5211
- return nil unless args.size == 1
5212
-
5213
- target = args.first
5214
- target.is_a?(Prism::LocalVariableReadNode) ? target.name : nil
5215
- end
5216
-
5217
- def rspec_matcher_node(call_node)
5218
- args = call_node.arguments&.arguments || []
5219
- return nil unless args.size == 1
5220
-
5221
- matcher = args.first
5222
- return nil unless matcher.is_a?(Prism::CallNode) && matcher.receiver.nil? && matcher.block.nil?
5223
-
5224
- matcher
5225
- end
5226
-
5227
- # True when `call_node`'s sole argument is an implicit-self matcher call with the given name and no positional
5228
- # arguments — used by the no-arg matchers (`be_nil`).
5229
- def rspec_matcher_argument?(call_node, matcher_name)
5230
- matcher = rspec_matcher_node(call_node)
5231
- return false if matcher.nil?
5232
- return false unless matcher.name == matcher_name
5233
-
5234
- matcher.arguments.nil? || matcher.arguments.arguments.empty?
5235
- end
5236
-
5237
- # Slice 4b-2 (ADR-7 § "Slice 4-A/4-B") — applies the post-return facts the merger produces for an
5238
- # `RBS::Extended`-annotated call. Reads through `RbsExtended.read_flow_contribution` so the bundle carries the
5239
- # canonical `Rigor::FlowContribution::Fact` rows for `:always` assert directives (the slice-4a routing places
5240
- # conditional asserts on `truthy_facts` / `falsey_facts`, which `Narrowing.predicate_scopes` consumes). Plugin
5241
- # `:always` assertions are handled by the sibling `apply_plugin_assertions`, not this path.
5242
- def apply_rbs_extended_assertions(call_node, current_scope)
5243
- method_def = resolve_call_method(call_node, current_scope)
5244
- return current_scope if method_def.nil?
5245
-
5246
- contribution = RbsExtended.read_flow_contribution(method_def, environment: current_scope.environment)
5247
- return current_scope if contribution.nil?
5248
-
5249
- result = Rigor::FlowContribution::Merger.merge([contribution])
5250
- post_return = result.post_return_facts
5251
- return current_scope if post_return.empty?
5252
-
5253
- post_return.reduce(current_scope) do |scope_acc, fact|
5254
- apply_post_return_fact(fact, call_node, scope_acc, method_def)
5255
- end
5256
- end
5257
-
5258
- # ADR-7 § "Slice 4-A" / T.bind priority slice 2 — applies the post-return facts plugin contributions produce. This
5259
- # is the sibling of {apply_rbs_extended_assertions}: the carrier (`Rigor::FlowContribution::Fact`) and the
5260
- # downstream narrowing path (`apply_post_return_fact` → `apply_self_post_return_fact`) are the same; only the
5261
- # *source* of the bundle changes (RBS::Extended vs the registered plugins' `flow_contribution_for`).
5262
- #
5263
- # `:self`-targeted facts narrow `scope.self_type` for the surrounding scope. In a block body, the surrounding
5264
- # scope is the block's own scope, so the narrowing applies to the rest of the block — exactly the contract
5265
- # Sorbet's `T.bind(self, T)` commits to.
5266
- #
5267
- # `:parameter`-targeted facts only land when the called method has an authoritative RBS sig (via
5268
- # `resolve_call_method`); plugins recognising their own synthetic call shapes (e.g. `T.assert_type!`) have no
5269
- # method_def and the parameter facts silently skip — the plugin's own diagnostics_for_file path covers those
5270
- # cases. The full plugin-side parameter-targeting story (PHPStan-style Type-Specifying Extensions on
5271
- # plugin-recognised calls) lives behind a follow-up slice that introduces an `:argument_at` target kind.
5272
- def apply_plugin_assertions(call_node, current_scope)
5273
- registry = current_scope.environment&.plugin_registry
5274
- return current_scope if registry.nil? || registry.empty?
5275
-
5276
- contributions = collect_plugin_contributions(registry, call_node, current_scope)
5277
- return current_scope if contributions.empty?
5278
-
5279
- result = Rigor::FlowContribution::Merger.merge(contributions)
5280
- post_return = result.post_return_facts
5281
- return current_scope if post_return.empty?
5282
-
5283
- method_def = resolve_call_method(call_node, current_scope)
5284
- post_return.reduce(current_scope) do |scope_acc, fact|
5285
- apply_post_return_fact(fact, call_node, scope_acc, method_def)
5286
- end
5287
- end
5288
-
5289
- # ADR-37 slice 2 / ADR-52 WD3 — gathers each plugin's post-return narrowing from the method-gated
5290
- # `narrowing_facts` DSL, wrapped as a facts-only `FlowContribution`, swallowing per-plugin exceptions so a buggy
5291
- # plugin can't abort the assertion path.
5292
- EMPTY_CONTRIBUTIONS = [].freeze
5293
- private_constant :EMPTY_CONTRIBUTIONS
5294
-
5295
- # Fast-exit guard: skip if no plugin declares a `narrowing_facts` rule, or if no registered method-name gate
5296
- # matches the call. See `collect_gated_statement_contributions` for the full consultation.
5297
- def collect_plugin_contributions(registry, call_node, current_scope)
5298
- index = registry.contribution_index
5299
- relevant = index.for_statement
5300
- return EMPTY_CONTRIBUTIONS if relevant.empty?
5301
-
5302
- name = call_node.respond_to?(:name) ? call_node.name : nil
5303
- return EMPTY_CONTRIBUTIONS unless index.statement_candidate?(name)
5304
-
5305
- collect_gated_statement_contributions(index, relevant, name, call_node, current_scope)
5306
- end
5307
-
5308
- # ADR-37 slice 2 / ADR-52 WD1 — post-gate walk in registry order. Visits only plugins in `for_statement` (declare
5309
- # a `narrowing_facts` rule), further gated by the method-name Set probe so the common no-candidate case is a
5310
- # single lookup. Accumulates lazily; caller is read-only.
5311
- def collect_gated_statement_contributions(index, relevant, name, call_node, current_scope)
5312
- result = nil
5313
- relevant.each do |plugin|
5314
- next unless index.narrowing_facts_candidate_for?(plugin, name)
5315
-
5316
- facts = plugin.narrowing_facts_for(call_node: call_node, scope: current_scope)
5317
- (result ||= []) << Rigor::FlowContribution.new(post_return_facts: facts) if facts && !facts.empty?
5318
- rescue StandardError
5319
- next
5320
- end
5321
- result || EMPTY_CONTRIBUTIONS
5322
- end
5323
-
5324
- def resolve_call_method(call_node, current_scope)
5325
- receiver_node = call_node.receiver
5326
- receiver_type =
5327
- if receiver_node
5328
- current_scope.type_of(receiver_node, tracer: tracer)
5329
- else
5330
- current_scope.self_type
5331
- end
5332
- return nil if receiver_type.nil?
5333
-
5334
- class_name = assertion_class_name(receiver_type)
5335
- return nil if class_name.nil?
5336
- return nil unless Rigor::Reflection.rbs_class_known?(class_name, scope: current_scope)
5337
-
5338
- if receiver_type.is_a?(Type::Singleton)
5339
- Rigor::Reflection.singleton_method_definition(class_name, call_node.name, scope: current_scope)
5340
- else
5341
- Rigor::Reflection.instance_method_definition(class_name, call_node.name, scope: current_scope)
5342
- end
5343
- rescue StandardError
5344
- nil
5345
- end
5346
-
5347
- def assertion_class_name(receiver_type)
5348
- case receiver_type
5349
- when Type::Nominal, Type::Singleton then receiver_type.class_name
5350
- end
5351
- end
5352
-
5353
- # Slice 4b-2 — applies a single post-return Fact to the scope. Mirrors `Narrowing#apply_fact_to_scope` (Fact
5354
- # variant of the v0.0.2 `apply_assert_effect`); shares the narrowing logic via `Narrowing.narrow_for_fact` so the
5355
- # predicate / assert / plugin paths all converge on the same hierarchy-aware narrowing rules.
5356
- #
5357
- # v0.1.8 Pillar 2 Slice 1 added the `:local` target_kind branch so plugins recognising bespoke call shapes
5358
- # (`expect(x).to be_a(T)`) can directly narrow a named local in the surrounding scope, bypassing the
5359
- # parameter-name lookup that requires an authoritative RBS sig on the called method (which RSpec matchers lack).
5360
- def apply_post_return_fact(fact, call_node, current_scope, method_def)
5361
- return apply_local_post_return_fact(fact, current_scope) if fact.target_kind == :local
5362
-
5363
- target_node = fact_target_node(fact, call_node, method_def)
5364
- return apply_self_post_return_fact(fact, target_node, current_scope) if fact.target_kind == :self
5365
- return current_scope unless target_node.is_a?(Prism::LocalVariableReadNode)
5366
-
5367
- local_name = target_node.name
5368
- current_type = current_scope.local(local_name)
5369
- return current_scope if current_type.nil?
5370
-
5371
- narrowed = Narrowing.narrow_for_fact(current_type, fact, current_scope.environment)
5372
- current_scope.with_local(local_name, narrowed)
5373
- end
5374
-
5375
- # v0.1.8 Pillar 2 Slice 1 — narrows the named local directly without consulting the call node's argument list. The
5376
- # fact's `target_name` is the local-variable name as written in source. Silently no-ops when the local is unbound
5377
- # in the current scope (the plugin's named local may have already gone out of scope when the contribution fires).
5378
- def apply_local_post_return_fact(fact, current_scope)
5379
- local_name = fact.target_name
5380
- current_type = current_scope.local(local_name)
5381
- return current_scope if current_type.nil?
5382
-
5383
- narrowed = Narrowing.narrow_for_fact(current_type, fact, current_scope.environment)
5384
- current_scope.with_local(local_name, narrowed)
5385
- end
5386
-
5387
- # v0.1.1 Track 1 slice 3 — `assert self is T` post-return narrowing for the four supported receiver shapes
5388
- # (mirrors `Narrowing#apply_self_fact`).
5389
- def apply_self_post_return_fact(fact, receiver_node, current_scope)
5390
- case receiver_node
5391
- when nil, Prism::SelfNode
5392
- current = current_scope.self_type
5393
- return current_scope if current.nil?
5394
-
5395
- narrowed = Narrowing.narrow_for_fact(current, fact, current_scope.environment)
5396
- current_scope.with_self_type(narrowed)
5397
- when Prism::LocalVariableReadNode
5398
- current = current_scope.local(receiver_node.name)
5399
- return current_scope if current.nil?
5400
-
5401
- narrowed = Narrowing.narrow_for_fact(current, fact, current_scope.environment)
5402
- current_scope.with_local(receiver_node.name, narrowed)
5403
- when Prism::InstanceVariableReadNode
5404
- current = current_scope.ivar(receiver_node.name)
5405
- return current_scope if current.nil?
5406
-
5407
- narrowed = Narrowing.narrow_for_fact(current, fact, current_scope.environment)
5408
- current_scope.with_ivar(receiver_node.name, narrowed)
5409
- else
5410
- current_scope
5411
- end
5412
- end
5413
-
5414
- # `:self` routes to the call receiver; otherwise we look up the matching positional argument by parameter name.
5415
- def fact_target_node(fact, call_node, method_def)
5416
- if fact.target_kind == :self
5417
- call_node.receiver
5418
- else
5419
- lookup_post_return_arg(call_node, method_def, fact.target_name)
5420
- end
5421
- end
5422
-
5423
- def lookup_post_return_arg(call_node, method_def, target_name)
5424
- # Plugin-source contributions arrive without an authoritative method_def (the plugin recognised the call shape
5425
- # directly). Parameter-targeting falls back to "no narrow" in that case — the wider plugin-side parameter
5426
- # mapping (`:argument_at`) is a follow-up slice.
5427
- return nil if method_def.nil?
5428
-
5429
- arguments = call_node.arguments&.arguments || []
5430
- # A `(?)` overload (`RBS::Types::UntypedFunction`, #1430) names no parameter and accepts any argument list,
5431
- # so a call may reach it with the target's position holding anything: no overload proves the target.
5432
- return nil unless method_def.method_types.all? { |mt| mt.type.respond_to?(:required_positionals) }
5433
-
5434
- method_def.method_types.each do |mt|
5435
- params = mt.type.required_positionals + mt.type.optional_positionals
5436
- index = params.find_index { |param| param.name == target_name }
5437
- return arguments[index] if index && arguments[index]
5438
- end
5439
- nil
5440
- end
5441
-
5442
5163
  # Issue #1468 — the block of `recv&.m { … }` runs only once `recv` is non-nil, so it is entered from the scope
5443
5164
  # with the receiver narrowed ({Narrowing.safe_navigation_block_scope}), and every entry rule
5444
5165
  # {#enter_call_block} applies reads that scope as any other. The receiver's own type, which the block's
@@ -5512,7 +5233,7 @@ module Rigor
5512
5233
  # The block calls whose body `return` leaves only the block ({ReturnBarrier.block_call?}). Like a `->` body
5513
5234
  # ({#eval_lambda}), each runs with the enclosing method's return sink suspended.
5514
5235
  def return_barrier_block?(node)
5515
- ReturnBarrier.block_call?(node)
5236
+ ReturnBarrier.block_call?(node, scope: scope)
5516
5237
  end
5517
5238
 
5518
5239
  # Runs the block with the method's return sink suspended, for a body whose `return` is not the method's.
@@ -5949,8 +5670,8 @@ module Rigor
5949
5670
  # proof that the callee writes the argument it floors: the owner is {FLOOR_ALL} (an inherited def, a
5950
5671
  # `method_missing`) or {FLOOR_EVERY} (a top-level def that may not be the one called), or the callee hands a
5951
5672
  # parameter on, through any hop, to one of those, by name or to several candidates. A def read as written that
5952
- # writes the argument keeps the
5953
- # precise floor, which is what a later `Integer` parameter or `no_such_method` on the String needs to report.
5673
+ # writes the argument keeps the precise floor, which is what a later `Integer` parameter or `no_such_method` on
5674
+ # the String needs to report.
5954
5675
  # The walk is bounded by {CalleeMutationChain::MAX_NODES}; past it the answer is true.
5955
5676
  def over_approximating_callee?(def_node, owner)
5956
5677
  return true if OVER_APPROXIMATING.include?(owner)
@@ -6675,7 +6396,7 @@ module Rigor
6675
6396
 
6676
6397
  # The `[def, offset]` pairs a self-dispatch `node` resolves to in the enclosing class, `offset` being how many
6677
6398
  # leading arguments of `node` are not the def's. Issue #2521 — the instance def is looked up along the class's
6678
- # ancestors ({Scope#user_def_through_ancestors}), as Ruby dispatches the call: an inherited def is now walked
6399
+ # ancestors ({Scope#user_def_through_ancestors}), as Ruby dispatches the call: an inherited def is walked
6679
6400
  # under the receiver's class, so a self-call inside it to another inherited def must still be found there.
6680
6401
  #
6681
6402
  # Issue #2297 — in a singleton-side body (`def self.x`, a `def` in `class << self`), whose `self` is the class
@@ -6683,9 +6404,8 @@ module Rigor
6683
6404
  # applies when either mutates. Ruby calls only the singleton side, but the hand-offs that reach an instance def
6684
6405
  # from there (`new.call(acc)`, `instance.helper(acc)`) and the singleton defs the index does not record
6685
6406
  # (`module_function :poke`, `define_singleton_method`, `alias_method` in `class << self`) are not followed, and
6686
- # dropping the instance def floored too little on correct code
6687
- # (`approval-queue.d/callee-floor-singleton-side.md`).
6688
- # An instance-side body resolves to instance defs only.
6407
+ # dropping the instance def floored too little on correct code (decided in #2394, ratified in #2501). An
6408
+ # instance-side body resolves to instance defs only.
6689
6409
  #
6690
6410
  # A `send(:name, ...)` / `public_send(:name, ...)` with a symbol literal resolves as the self-call `name(...)`,
6691
6411
  # offset 1, on each side that has no def of the `send` / `public_send` name itself; on a side that has one, it is
@@ -6841,7 +6561,7 @@ module Rigor
6841
6561
  node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)
6842
6562
  end
6843
6563
 
6844
- # The set of `[name, slot]` parameters of `def_node` whose content a block in the body escape-mutates.
6564
+ # The `{ name => slot }` parameters of `def_node` whose content a block in the body escape-mutates.
6845
6565
  # Memoised per def node (the body walk is otherwise repeated at every call site). A parameter is "escape-mutated"
6846
6566
  # when a `param[k] = v` / `param << x` mutation on it appears inside a block whose receiving call is not proven
6847
6567
  # non-escaping.
@@ -6960,11 +6680,11 @@ module Rigor
6960
6680
  node.is_a?(Prism::ConstantPathNode) && node.parent.nil? && FRESH_CONSTRUCTED.include?(node.name)
6961
6681
  end
6962
6682
 
6683
+ # The calls whose result {#callee_write_census} reads as a new object rather than an alias of the receiver.
6963
6684
  FRESH_DUPLICATORS = %i[dup clone].to_set.freeze
6964
6685
  FRESH_CONSTRUCTED = %i[Array Hash String Set].to_set.freeze
6965
6686
  FRESH_COPIERS = %i[map collect select reject merge + -].to_set.freeze
6966
6687
  FRESH_OPERATORS = %i[+ -].to_set.freeze
6967
- # The calls whose result {#callee_write_census} reads as a new object rather than an alias of the receiver.
6968
6688
  # The calls {#callee_write_census} reads as a new container of the receiver's elements, on an Array, a Hash and a
6969
6689
  # String alike: a write to the result misses the receiver, an element of it may be a part. `to_a`, `to_h`
6970
6690
  # (without a block; `to_h { }` is read as one in {CalleeWriteCensus}), `to_s`, `each_slice`, `each_cons` and
@@ -7080,15 +6800,15 @@ module Rigor
7080
6800
  slots
7081
6801
  end
7082
6802
 
7083
- # True when at least one argument of `node` is a bare local-variable read (positional or keyword value) bound in
7084
- # the current scope — a cheap pre-filter so the def resolution / body scan only runs for calls that could actually
7085
- # floor something.
7086
6803
  # A local bound in the current scope, or (issue #2335) one whose object another local may share, which the
7087
6804
  # alias floor reads a callee's write through ({AliasMutationFloor.reaches_other_locals?}).
7088
6805
  def passed_local?(read, node)
7089
6806
  scope.locals.key?(read.name) || AliasMutationFloor.reaches_other_locals?(scope, read, node)
7090
6807
  end
7091
6808
 
6809
+ # True when at least one argument of `node` is a bare local-variable read (positional or keyword value) bound in
6810
+ # the current scope — a cheap pre-filter so the def resolution / body scan only runs for calls that could actually
6811
+ # floor something.
7092
6812
  def call_passes_local_argument?(node)
7093
6813
  args = node.arguments
7094
6814
  return false unless args.respond_to?(:arguments)
@@ -7384,7 +7104,7 @@ module Rigor
7384
7104
  # anonymous-class checks are defensive guards: no such call repeats under that rule today.
7385
7105
  def repeated_block_return_candidate?(call_node, block)
7386
7106
  return false unless block.is_a?(Prism::BlockNode)
7387
- return false unless ReturnBarrier.exits_method?(block.body)
7107
+ return false unless ReturnBarrier.exits_method?(block.body, scope)
7388
7108
  return false if return_barrier_block?(call_node) || refined_class_context(call_node)
7389
7109
  return false if AnonymousMetaClass.name_for(call_node, scope.source_path)
7390
7110
  return true if BlockCallTiming.kernel_loop?(call_node) || !repeating_block_class(call_node).nil?
@@ -7711,9 +7431,9 @@ module Rigor
7711
7431
  end
7712
7432
 
7713
7433
  # The instance variables, class variables and globals the block body writes that {#capturable_non_local?}
7714
- # accepts; no instance variable for a block that runs on another object. Every self-rebinding call classifies
7715
- # `:unknown` today, so neither content seam that calls this meets one; the guard keeps the answer right should
7716
- # the escape analysis learn to call one non-escaping.
7434
+ # accepts; no instance variable for a block that runs on another object. No self-rebinding call classifies
7435
+ # `:non_escaping` today, so neither content seam that calls this meets one; the guard keeps the answer right
7436
+ # should the escape analysis learn to call one non-escaping.
7717
7437
  def rebound_capturable_non_locals(block, call_node)
7718
7438
  return NO_REWRITES if block.body.nil?
7719
7439
 
@@ -7730,7 +7450,7 @@ module Rigor
7730
7450
  # The locals a store reads to build what it stores. An Array index write's index arguments are left out, and so
7731
7451
  # is any name they read: the join classifies the store as an element or a splice from the index's type, and a
7732
7452
  # `Dynamic` index reads as both, so `grid[i] = [x, x]` would join `x` itself as a member of `grid` beside the
7733
- # pair. Such an index keeps its block-entry binding, which is master's reading, and so does a stored value that
7453
+ # pair. Such an index keeps its block-entry binding, and so does a stored value that
7734
7454
  # reads the same name: `ids[n] = n; n += 1` still stores `n`'s first-iteration value.
7735
7455
  def store_value_reads(site, array)
7736
7456
  return local_reads(site) unless array
@@ -7964,7 +7684,7 @@ module Rigor
7964
7684
  # resolves a class variable lexically, and a global is the same one whatever `self` is.
7965
7685
  def captured_content_mutations(block, shadows, call_node)
7966
7686
  mutations = Hash.new { |h, k| h[k] = [] }
7967
- # Every self-rebinding call classifies `:unknown` today, so this seam does not meet one; the guard keeps the
7687
+ # No self-rebinding call classifies `:non_escaping` today, so this seam does not meet one; the guard keeps the
7968
7688
  # ivar arm right should the escape analysis learn to call one non-escaping.
7969
7689
  foreign = foreign_self_block?(call_node)
7970
7690
  Source::NodeWalker.each_with_ancestors(block.body) do |node, ancestors|
@@ -8077,9 +7797,11 @@ module Rigor
8077
7797
 
8078
7798
  # `scope` with each name a site's enclosing inner blocks bind bound to `Dynamic[top]`: the seam's scope cannot
8079
7799
  # see those bindings, and the name would otherwise resolve to the outer local it shadows.
7800
+ # The loop seam's table holds a whole scope for a site instead ({LoopStoreSites}), which answers as it is.
8080
7801
  def site_evidence_scope(scope, site, shadows)
8081
7802
  names = shadows[site]
8082
7803
  return scope if names.nil?
7804
+ return names if names.is_a?(Scope)
8083
7805
 
8084
7806
  names.reduce(scope) { |acc, name| bind_capture_slot(acc, name, Type::Combinator.untyped) }
8085
7807
  end
@@ -8542,20 +8264,21 @@ module Rigor
8542
8264
  # not synthesize a hash carrier — mail's `compose_codepoints` mutated its untyped Array param through
8543
8265
  # integer/range index writes and returned `Hash[Integer | Range, …]` to its caller (issue #553). Dynamic in,
8544
8266
  # Dynamic out: a shapeless pre-state falls through to `join_array_param`, which declines it.
8545
- def join_content_for_param(calls, pre_state, block_entry)
8267
+ # `shadows` is {#site_evidence_scope}'s per-site table; the loop seam passes its store-site scopes there.
8268
+ def join_content_for_param(calls, pre_state, block_entry, shadows = NO_SHADOWS)
8546
8269
  return nil if pre_state.nil?
8547
- return join_string_union(calls, pre_state, block_entry) if string_union?(pre_state)
8270
+ return join_string_union(calls, pre_state, block_entry, shadows) if string_union?(pre_state)
8548
8271
 
8549
8272
  if stringish?(pre_state)
8550
8273
  # String carries no element parameter; mutating `<<`/`concat` makes the constant value unsound (`s = "a"; s <<
8551
8274
  # x` → runtime `"a…"`), so widen to the nominal base. Sound — only widens.
8552
8275
  Type::Combinator.nominal_of("String")
8553
8276
  elsif content_kind(pre_state) == :mixed
8554
- ContentJoin.join_mixed_content(pre_state, *mixed_content_evidence(calls, block_entry))
8277
+ ContentJoin.join_mixed_content(pre_state, *mixed_content_evidence(calls, block_entry, shadows))
8555
8278
  elsif hashish?(pre_state)
8556
- join_hash_param(calls, pre_state, block_entry)
8279
+ join_hash_param(calls, pre_state, block_entry, shadows)
8557
8280
  else
8558
- join_array_param(calls, pre_state, block_entry)
8281
+ join_array_param(calls, pre_state, block_entry, shadows)
8559
8282
  end
8560
8283
  end
8561
8284
 
@@ -8563,8 +8286,8 @@ module Rigor
8563
8286
  # `String`, which has no element evidence to join, and the rest join as a union of their own. Joined whole, the
8564
8287
  # union reached the Array or Hash join, which dropped the String member and read a String mutator's arguments as
8565
8288
  # elements — `x.force_encoding(e)` on an `Array | String` capture typed it `Array[1 | Encoding]`.
8566
- def join_string_union(calls, union, block_entry)
8567
- join_string_members(union) { |others| join_content_for_param(calls, others, block_entry) }
8289
+ def join_string_union(calls, union, block_entry, shadows)
8290
+ join_string_members(union) { |others| join_content_for_param(calls, others, block_entry, shadows) }
8568
8291
  end
8569
8292
 
8570
8293
  # `String` for the String members of `union`, beside what the block answers for the rest (as a union of their
@@ -8586,17 +8309,17 @@ module Rigor
8586
8309
  UnknownStoreWidening.carrier_class(type) == "String"
8587
8310
  end
8588
8311
 
8589
- def join_hash_param(calls, pre_state, block_entry)
8590
- pairs = hash_pair_evidence(calls, block_entry)
8312
+ def join_hash_param(calls, pre_state, block_entry, shadows)
8313
+ pairs = hash_pair_evidence(calls, block_entry, shadows)
8591
8314
  return nil if pairs.empty? && !hashish?(pre_state)
8592
8315
 
8593
8316
  ContentJoin.join_hash_content(pre_state, pairs)
8594
8317
  end
8595
8318
 
8596
- def join_array_param(calls, pre_state, block_entry)
8319
+ def join_array_param(calls, pre_state, block_entry, shadows)
8597
8320
  return nil unless arrayish?(pre_state)
8598
8321
 
8599
- ContentJoin.join_array_content(pre_state, array_element_evidence(calls, block_entry))
8322
+ ContentJoin.join_array_content(pre_state, array_element_evidence(calls, block_entry, shadows))
8600
8323
  end
8601
8324
 
8602
8325
  # No site sits under an inner block that shadows a name — the loop seam's answer, and the default.
@@ -8893,7 +8616,7 @@ module Rigor
8893
8616
  body = block.body
8894
8617
  return build_block_entry_scope(call_node, block) if body.nil? || !CapturedLocals.may_touch_capture?(body, scope)
8895
8618
 
8896
- classification = repeating_block_class(call_node)
8619
+ classification = repeating_block_class(call_node) || BlockCallTiming.loop_class(call_node)
8897
8620
  return build_block_entry_scope(call_node, block) if classification.nil?
8898
8621
 
8899
8622
  bindings = unproven_rebind_bindings(call_node, block, classification)
@@ -8937,7 +8660,7 @@ module Rigor
8937
8660
  # A call the write-back reaches answers none: its fixpoint enters every pass it records at the converged
8938
8661
  # binding.
8939
8662
  def unproven_rebind_bindings(call_node, block, classification)
8940
- return NO_CAPTURE_BINDINGS if call_node.receiver && classification == :non_escaping
8663
+ return NO_CAPTURE_BINDINGS if classification == :loop || (call_node.receiver && classification == :non_escaping)
8941
8664
 
8942
8665
  names = CapturedLocals.writes(block, scope, ivars: true, foreign_self: foreign_self_block?(call_node))
8943
8666
  return NO_CAPTURE_BINDINGS if names.empty?
@@ -9048,7 +8771,7 @@ module Rigor
9048
8771
  lambda_type = scope.type_of(node, tracer: tracer)
9049
8772
  without_return_sink { sub_eval(node.body, build_block_entry_scope(nil, node)) } unless node.body.nil?
9050
8773
 
9051
- [lambda_type, escaping_closure_captures(node, scope)]
8774
+ [lambda_type, MutationWidening.walk_for_outer_mutations(node.body, escaping_closure_captures(node, scope))]
9052
8775
  end
9053
8776
 
9054
8777
  # The continuation effects of an escaping closure body: the outer locals it can rebind drop their narrowing, and
@@ -9366,7 +9089,8 @@ module Rigor
9366
9089
  seeded = scope.class_cvars_for(path)
9367
9090
  return body_scope if seeded.empty?
9368
9091
 
9369
- seeded.reduce(body_scope) { |acc, (name, type)| acc.with_cvar(name, type) }
9092
+ marked = scope.published_constant_cvars_for(path) # Issue #3443 — the cross-method half of the copy mark.
9093
+ seeded.reduce(body_scope) { |acc, (name, type)| acc.with_cvar_copy(name, type, marked.include?(name)) }
9370
9094
  end
9371
9095
 
9372
9096
  # Globals are process-wide. The body scope already inherited the program-global tables through its discovery
@@ -9374,7 +9098,7 @@ module Rigor
9374
9098
  # without consulting the index on every lookup. The frame-local `$_` and `$~` are not in it (issue #1359): a
9375
9099
  # method body starts with a slot of its own. A global Ruby's own signatures declare is seeded with its declared
9376
9100
  # type joined with the file's writes, under the ADR-58 `:global` mark (issue #1362,
9377
- # `ScopeIndexer#join_declared_globals`, `Scope#seed_declaration_sourced_global`).
9101
+ # `ScopeIndexer::ProgramGlobals#join_declared_globals`, `Scope#seed_declaration_sourced_global`).
9378
9102
  def seed_program_globals(body_scope)
9379
9103
  written = scope.program_globals
9380
9104
  return body_scope if written.empty?
@@ -9620,6 +9344,8 @@ module Rigor
9620
9344
  Type::Combinator.tuple_of(*args.map { |arg| sub_eval(arg, scope).first })
9621
9345
  end
9622
9346
 
9347
+ # @api private — public only so {PatternBindings} can call it on the evaluator it is given.
9348
+ #
9623
9349
  # `on_enter: nil` evaluates without recording into the per-node scope index — for a pass whose scopes are not
9624
9350
  # the ones the index should keep. `next_scope_sink:` is replaced only by {#evaluate_invocation} and
9625
9351
  # {#loop_iteration}.
@@ -9627,11 +9353,12 @@ module Rigor
9627
9353
  # unnameable body gets a frame, and its `def`s a nominal `self`, as they did before #1518.
9628
9354
  def sub_eval(node, with_scope, class_context: @class_context, lexical_nesting: @lexical_nesting, # rubocop:disable Metrics/ParameterLists
9629
9355
  on_enter: @on_enter, next_scope_sink: @next_scope_sink, operand_recorder: @operand_recorder,
9630
- opaque_class: @opaque_class && class_context.empty?)
9356
+ opaque_class: @opaque_class && class_context.empty?, store_sites: @store_sites)
9631
9357
  evaluator_at(with_scope, class_context: class_context, lexical_nesting: lexical_nesting, on_enter: on_enter,
9632
9358
  next_scope_sink: next_scope_sink, operand_recorder: operand_recorder,
9633
- opaque_class: opaque_class).evaluate(node)
9359
+ opaque_class: opaque_class, store_sites: store_sites).evaluate(node)
9634
9360
  end
9361
+ public :sub_eval
9635
9362
 
9636
9363
  # An evaluator over `with_scope` that inherits everything else from this one. `operand_scope:` and
9637
9364
  # `operand_types:` are set only by {#invoke_from}, for the evaluator that runs a call from the scope its
@@ -9639,7 +9366,7 @@ module Rigor
9639
9366
  def evaluator_at(with_scope, class_context: @class_context, lexical_nesting: @lexical_nesting, # rubocop:disable Metrics/ParameterLists
9640
9367
  on_enter: @on_enter, next_scope_sink: @next_scope_sink, operand_scope: nil,
9641
9368
  in_operand: @in_operand, operand_recorder: @operand_recorder, operand_types: nil,
9642
- opaque_class: @opaque_class)
9369
+ opaque_class: @opaque_class, store_sites: @store_sites)
9643
9370
  StatementEvaluator.new(
9644
9371
  scope: with_scope,
9645
9372
  tracer: tracer,
@@ -9653,7 +9380,8 @@ module Rigor
9653
9380
  in_operand: in_operand,
9654
9381
  operand_recorder: operand_recorder,
9655
9382
  operand_types: operand_types,
9656
- opaque_class: opaque_class
9383
+ opaque_class: opaque_class,
9384
+ store_sites: store_sites
9657
9385
  )
9658
9386
  end
9659
9387
 
@@ -9664,7 +9392,7 @@ module Rigor
9664
9392
  #
9665
9393
  # The detection is intentionally conservative — it recognises only the most common patterns:
9666
9394
  # - A `Prism::ReturnNode`, `NextNode`, `BreakNode`.
9667
- # - A `Prism::CallNode` whose name is `:raise` or `:throw`.
9395
+ # - A receiver-less `Prism::CallNode` named in {EXIT_CALL_NAMES} (`raise`, `throw`, `exit`, `abort`, `fail`).
9668
9396
  # - A `Prism::StatementsNode`, `Prism::ParenthesesNode`, or
9669
9397
  # `Prism::IfNode`/`UnlessNode` whose final / both
9670
9398
  # branches recursively exit.
@@ -9770,546 +9498,11 @@ module Rigor
9770
9498
  scopes.reduce { |a, b| join_with_nil_injection(a, b) }
9771
9499
  end
9772
9500
 
9773
- # --------------------------------------------------------------- rescue variable binding helpers
9774
- # ---------------------------------------------------------------
9501
+ # The two `HANDLERS` entries whose bodies live in {PatternBindings}. They read this evaluator's scope and
9502
+ # tracer, so those are passed in; {PatternBindings} calls back {#sub_eval} on the evaluator it is given.
9503
+ def eval_match_pattern(node) = PatternBindings.eval_match_pattern(node, scope, tracer, self)
9775
9504
 
9776
- # Returns `scope` extended with the rescue reference variable bound to the exception instance type. Leaves scope
9777
- # unchanged when the node carries no reference (bare `rescue` without `=> var`). An index-target reference
9778
- # (`rescue => h[:e]`) stores the exception through `[]=` instead, so its receiver widens with the exception
9779
- # instance type as the stored value, exactly as `rescue => e; h[:e] = e` widens it.
9780
- #
9781
- # Issue #1360 — with or without a reference, the clause runs with `$!` bound to the exception it rescued, `$@` to
9782
- # its backtrace and `$?` unbound ({ErrorInfo.rescue_entry}); {#eval_begin_node} restores `$!` and `$@` once the
9783
- # `begin` exits.
9784
- def bind_rescue_reference(rescue_node, scope)
9785
- exception_type = rescue_exception_type(rescue_node, scope)
9786
- ref = rescue_node.reference
9787
- reference = ref.name if ref.is_a?(Prism::LocalVariableTargetNode)
9788
- scope = ErrorInfo.rescue_entry(scope, exception_type, rescue_node.statements, reference)
9789
- case ref
9790
- when Prism::LocalVariableTargetNode
9791
- scope.with_local(ref.name, exception_type)
9792
- when Prism::InstanceVariableTargetNode
9793
- # Issue #1446 — `rescue => @io` writes the ivar, which ends a class guard's narrowing of it, and `rescue =>
9794
- # $out` the global, which ends any guard's narrowing of it.
9795
- scope.with_ivar(ref.name, exception_type).without_ivar_guard(ref.name)
9796
- when Prism::GlobalVariableTargetNode
9797
- scope.with_global(ref.name, exception_type)
9798
- when Prism::ClassVariableTargetNode
9799
- scope.with_cvar(ref.name, exception_type)
9800
- when Prism::IndexTargetNode
9801
- widen_index_target(ref, exception_type, scope, type_scope: scope)
9802
- else
9803
- scope
9804
- end
9805
- end
9806
-
9807
- # Derives the exception instance type for a `RescueNode` ({ErrorInfo.rescue_exception_type}): `StandardError` for
9808
- # a bare `rescue`, else the union of the named classes' instances, with `Dynamic[top]` for one that does not
9809
- # resolve to a `Singleton`.
9810
- def rescue_exception_type(rescue_node, scope)
9811
- ErrorInfo.rescue_exception_type(rescue_node) { |exception_node| sub_eval(exception_node, scope).first }
9812
- end
9813
-
9814
- # --------------------------------------------------------------- `case/in` pattern variable binding helpers
9815
- # ---------------------------------------------------------------
9816
-
9817
- # Builds the entry scope for an `in` branch by injecting every variable captured by the pattern as a local
9818
- # binding. `subject_type` is the type of the `case` subject — nil when the `case` carries no predicate, which
9819
- # leaves every binding at the `Dynamic[top]` floor — and `subject_node` the subject expression, which the
9820
- # `deconstruct` / `deconstruct_keys` dispatch reads for its freshness gate.
9821
- def apply_in_pattern_bindings(subject_type, subject_node, pattern, scope)
9822
- bindings = collect_in_pattern_bindings(subject_type, pattern, scope, subject_node: subject_node)
9823
- bound = bindings.reduce(scope) { |s, (name, type)| s.with_local(name, type) }
9824
- marked = subject_node.is_a?(Prism::LocalVariableReadNode) && scope.gradual_narrowing?(subject_node.name)
9825
- mark_gradual_class_capture(subject_type, pattern, bound, marked: marked)
9826
- end
9827
-
9828
- # Issue #2656 — `in C => y` over a `Dynamic` subject binds `y` to `C`'s `Nominal`, as a class guard's edge binds
9829
- # the subject, and marks it as that edge marks a local ({Narrowing.mark_gradual_local}). Only a capture of
9830
- # the whole subject by a class or an alternation of classes is marked.
9831
- def mark_gradual_class_capture(subject_type, pattern, scope, marked: false)
9832
- return scope unless pattern.is_a?(Prism::CapturePatternNode) && class_capture_value?(pattern.value)
9833
-
9834
- name = pattern.target.name
9835
- Narrowing.mark_gradual_local(scope, name, subject_type, scope.local(name), marked: marked)
9836
- end
9837
-
9838
- def class_capture_value?(value)
9839
- case value
9840
- when Prism::ConstantReadNode, Prism::ConstantPathNode then true
9841
- when Prism::AlternationPatternNode then class_capture_value?(value.left) && class_capture_value?(value.right)
9842
- else false
9843
- end
9844
- end
9845
-
9846
- # Returns an array of `[Symbol, Rigor::Type]` pairs for every variable captured by `pattern`, typed against the
9847
- # subject. Unrecognised pattern nodes contribute no bindings (fail-soft).
9848
- #
9849
- # A union subject distributes first (see {#collect_union_pattern_bindings}); every other subject walks the
9850
- # pattern once, and each node kind decides how much of the subject it can name:
9851
- #
9852
- # - a bare target (`in [i, s]`, `in x`) binds the slot the enclosing pattern hands it,
9853
- # - a capture (`Integer => i`, `[a, b] => whole`) binds its own constraint, and recurses into the captured
9854
- # pattern,
9855
- # - an array / find / hash pattern decomposes the subject (see the three collectors below).
9856
- def collect_in_pattern_bindings(subject_type, pattern, scope, subject_node: nil)
9857
- if subject_type.is_a?(Type::Union)
9858
- return collect_union_pattern_bindings(subject_type.members, pattern, scope, subject_node: subject_node)
9859
- end
9860
-
9861
- case pattern
9862
- when Prism::CapturePatternNode
9863
- collect_capture_pattern_bindings(subject_type, pattern, scope)
9864
- when Prism::LocalVariableTargetNode
9865
- [[pattern.name, subject_type || Type::Combinator.untyped]]
9866
- when Prism::ImplicitNode
9867
- collect_in_pattern_bindings(subject_type, pattern.value, scope)
9868
- when Prism::ArrayPatternNode
9869
- collect_array_pattern_bindings(subject_type, pattern, scope, subject_node: subject_node)
9870
- when Prism::FindPatternNode
9871
- collect_find_pattern_bindings(subject_type, pattern, scope, subject_node: subject_node)
9872
- when Prism::HashPatternNode
9873
- collect_hash_pattern_bindings(subject_type, pattern, scope, subject_node: subject_node)
9874
- when Prism::AlternationPatternNode
9875
- collect_alternation_pattern_bindings(subject_type, pattern, scope)
9876
- else
9877
- []
9878
- end
9879
- end
9880
-
9881
- # `pattern => target` binds `target` to what the pattern matched AND every name the pattern itself binds:
9882
- # `in [a, b] => whole` binds `a`, `b` and `whole`. The target's own type is the pattern's constraint when it
9883
- # names a class (`Integer => i`), and the subject otherwise — a capture over any other pattern IS the subject
9884
- # the pattern matched.
9885
- def collect_capture_pattern_bindings(subject_type, pattern, scope)
9886
- target = pattern.target
9887
- inner = collect_in_pattern_bindings(subject_type, pattern.value, scope)
9888
- return inner unless target.is_a?(Prism::LocalVariableTargetNode)
9889
-
9890
- [[target.name, capture_pattern_type(subject_type, pattern.value, scope)]] + inner
9891
- end
9892
-
9893
- # `in [i, s]` / `in [a, *rest, z]` / `in Foo[a, b]`.
9894
- def collect_array_pattern_bindings(subject_type, pattern, scope, subject_node:)
9895
- subject_type = pattern_class_constraint(subject_type, pattern.constant, scope)
9896
- fronts, rest_type, backs = pattern_slot_types(subject_type, pattern, scope, subject_node)
9897
- bindings = pattern.requireds.each_with_index.flat_map do |elem, i|
9898
- collect_in_pattern_bindings(fronts[i], elem, scope)
9899
- end
9900
- bindings += pattern.posts.each_with_index.flat_map do |elem, i|
9901
- collect_in_pattern_bindings(backs[i], elem, scope)
9902
- end
9903
- append_array_splat_binding(bindings, pattern.rest, rest_type)
9904
- bindings
9905
- end
9906
-
9907
- # The per-slot types a positional pattern reads: the subject's own decomposition when it is a carrier
9908
- # {MultiTargetBinder.decompose_slots} accepts (`Tuple`, `Array[T]`), else the `deconstruct` projection of a
9909
- # subject that defines one (`Struct#deconstruct`, a `Data` instance, a class whose `deconstruct` names the
9910
- # parts), else the `Dynamic[top]` floor per slot.
9911
- def pattern_slot_types(subject_type, pattern, scope, subject_node)
9912
- view = positional_pattern_view(subject_type, scope, subject_node)
9913
- return floor_pattern_slots(pattern.requireds.size, pattern.posts.size, !pattern.rest.nil?) if view.nil?
9914
-
9915
- MultiTargetBinder.decompose_slots(
9916
- view, front_count: pattern.requireds.size, back_count: pattern.posts.size,
9917
- rest_present: !pattern.rest.nil?, scope: scope
9918
- )
9919
- end
9920
-
9921
- # The carrier a positional pattern decomposes: the subject itself when {MultiTargetBinder} already accepts it,
9922
- # else what the subject's `deconstruct` answers with (a `Tuple` / `Array[T]` carrier), else nil.
9923
- #
9924
- # `subject_node` rides along as the dispatch's call node so the `Struct` fold's freshness gate can see the
9925
- # receiver: `case Point.new(1, 2); in [x, y]` is a freshly materialised instance and folds, while a stored
9926
- # binding that may have been mutated since does not (ADR-48).
9927
- def positional_pattern_view(subject_type, scope, subject_node)
9928
- return subject_type if subject_type.is_a?(Type::Tuple)
9929
- return subject_type if MultiTargetBinder.array_element_type(subject_type)
9930
-
9931
- deconstruct_projection(subject_type, scope, subject_node)
9932
- end
9933
-
9934
- # What `subject.deconstruct` answers with, when that is a carrier this binder decomposes; nil otherwise —
9935
- # an absent method, or `Struct#deconstruct`'s RBS `Array[untyped]` for a class whose members are not known.
9936
- def deconstruct_projection(subject_type, scope, subject_node)
9937
- result = struct_instance_projection(subject_type, :deconstruct, scope, subject_node) ||
9938
- pattern_decomposition_dispatch(subject_type, :deconstruct, [], scope) ||
9939
- source_decomposition_projection(subject_type, :deconstruct, [], scope)
9940
- return nil if result.nil?
9941
- return result if result.is_a?(Type::Tuple) || MultiTargetBinder.array_element_type(result)
9942
-
9943
- nil
9944
- end
9945
-
9946
- # The inferred return type of a project-defined `deconstruct` / `deconstruct_keys` (issue #1122). The
9947
- # dispatcher answers nil for a class no RBS describes: the body-inference tier that would type
9948
- # `subject.deconstruct` lives on `ExpressionTyper` and needs the call NODE a pattern does not have, so
9949
- # this asks the scope's own entry point for the same answer a resolved call site gets (ADR-84 memo
9950
- # included). nil when the project defines no such method, or when the body's answer is the gradual floor.
9951
- def source_decomposition_projection(subject_type, method_name, arg_types, scope)
9952
- return nil unless subject_type.is_a?(Type::Nominal)
9953
-
9954
- def_node = own_definer_node(scope, subject_type.class_name, method_name)
9955
- return nil if def_node.nil?
9956
-
9957
- result = scope.user_method_return(def_node, subject_type, arg_types)
9958
- return nil if result.nil? || result.is_a?(Type::Dynamic) || result.is_a?(Type::Top)
9959
-
9960
- result
9961
- end
9962
-
9963
- # The `def` node the receiver's OWN class defines `method_name` with, or nil. ADR-119 C2-e (#1615): asked of
9964
- # `DefinerResolution`, so a slot rebuilt from an ADR-85 seed bundle is resolved to a node and the read files
9965
- # its ADR-46 edge. UNKNOWN answers nil: an unsettled or forked chain, or a contested slot once ADR-119 C1d
9966
- # fills the siblings. Conditional or reopened defs are not contested until C1d. A definer further up the
9967
- # chain (a prepended or included module, a superclass) is not the own class's, so the owner check declines it.
9968
- def own_definer_node(scope, class_name, method_name)
9969
- case DefinerResolution.resolve(scope, class_name, method_name, :instance, question: :definer)
9970
- in DefinerResolution::Known(answer: [node, owner])
9971
- owner == class_name ? node : nil
9972
- in DefinerResolution::UNKNOWN # the case/in contract needs one arm per answer
9973
- nil
9974
- in DefinerResolution::ABSENT # rubocop:disable Lint/DuplicateBranch -- see above
9975
- nil
9976
- end
9977
- end
9978
-
9979
- # A `StructInstance`'s own projection — `Tuple` of its member values for `deconstruct`, `HashShape` of
9980
- # its members for `deconstruct_keys` — or nil when the subject is another carrier or the projection would
9981
- # be unsound.
9982
- #
9983
- # The `Struct` fold's freshness gate cannot answer for a pattern through the dispatcher: it asks whether
9984
- # the CALL's receiver was freshly materialised (`Point.new(1, 2).x`), while a pattern's subject node IS
9985
- # that materialisation (`case Point.new(1, 2); in [x, y]`). The gate still applies — a `Struct` is
9986
- # mutable, so a stored binding's member map may be stale (ADR-48) — so this asks it the pattern's own
9987
- # question, with the subject expression as the materialisation. A `Data` instance needs none of this:
9988
- # it is frozen, and the dispatcher already projects it (see `DataFolding`).
9989
- def struct_instance_projection(subject_type, method_name, scope, subject_node)
9990
- return nil unless subject_type.is_a?(Type::StructInstance)
9991
- return nil unless MethodDispatcher::StructMaterialization.materialization_call?(subject_node, scope)
9992
-
9993
- case method_name
9994
- when :deconstruct then Type::Combinator.tuple_of(*subject_type.members.values)
9995
- when :deconstruct_keys then Type::Combinator.hash_shape_of(subject_type.members.dup)
9996
- end
9997
- end
9998
-
9999
- # `deconstruct` / `deconstruct_keys` on a subject carrier. A `Dynamic` / `Top` answer is the gradual floor
10000
- # rather than a method's result, so it reads as "cannot ask" to every caller here.
10001
- #
10002
- # The subject node is deliberately NOT passed as the dispatch's `call_node`: the tiers read a call node's
10003
- # receiver and arguments, and a pattern's subject is any expression at all — `StructFolding`'s freshness
10004
- # gate dereferences `call_node.receiver`, which a local read or a literal does not answer. The one
10005
- # freshness question a pattern needs (`case Point.new(1, 2)`) is asked by
10006
- # {#struct_instance_projection} instead.
10007
- def pattern_decomposition_dispatch(subject_type, method_name, args, scope)
10008
- return nil if subject_type.nil?
10009
-
10010
- result = MethodDispatcher.dispatch(
10011
- receiver_type: subject_type, method_name: method_name, arg_types: args,
10012
- environment: scope.environment, scope: scope
10013
- )
10014
- return nil if result.is_a?(Type::Dynamic) || result.is_a?(Type::Top)
10015
-
10016
- result
10017
- end
10018
-
10019
- # `in [*pre, m, *post]`. Ruby matches a find pattern's required elements at the EARLIEST position the
10020
- # surrounding splats allow (the pre-splat is non-greedy: `[1, 2, 3] in [*pre, x, *post]` binds `pre = []`, `x =
10021
- # 1`), but a required that does not match there slides right, so each required binds the union of every
10022
- # position it could occupy and the surrounding splats bind an `Array` of the subject's element type.
10023
- def collect_find_pattern_bindings(subject_type, pattern, scope, subject_node:)
10024
- subject_type = pattern_class_constraint(subject_type, pattern.constant, scope)
10025
- view = positional_pattern_view(subject_type, scope, subject_node)
10026
- slots = find_pattern_slots(view, pattern.requireds.size)
10027
- bindings = pattern.requireds.each_with_index.flat_map do |elem, i|
10028
- collect_in_pattern_bindings(slots ? slots[i] : Type::Combinator.untyped, elem, scope)
10029
- end
10030
- surround = find_pattern_surround_type(view)
10031
- [pattern.left, pattern.right].each { |splat| append_array_splat_binding(bindings, splat, surround) }
10032
- bindings
10033
- end
10034
-
10035
- # The type each of a find pattern's `count` requireds can see, or nil when the subject cannot supply that many
10036
- # elements (the pattern cannot match).
10037
- def find_pattern_slots(view, count)
10038
- if view.is_a?(Type::Tuple)
10039
- elements = view.elements
10040
- return nil if elements.size < count
10041
-
10042
- return Array.new(count) { |i| Type::Combinator.union(*elements[i..(elements.size - count + i)]) }
10043
- end
10044
-
10045
- element = view && MultiTargetBinder.array_element_type(view)
10046
- element && Array.new(count) { element }
10047
- end
10048
-
10049
- # `*pre` / `*post` capture the elements the requireds did not: `Array[T]` for an `Array[T]` subject, an `Array`
10050
- # of the element union for a `Tuple`, `Array[untyped]` when the subject could not be decomposed.
10051
- def find_pattern_surround_type(view)
10052
- element = case view
10053
- when Type::Tuple then union_of_types(view.elements)
10054
- else view && MultiTargetBinder.array_element_type(view)
10055
- end
10056
- Type::Combinator.nominal_of("Array", type_args: [element || Type::Combinator.untyped])
10057
- end
10058
-
10059
- # `in {name: String => n}` / `in {name:, **rest}`. Each element reads the subject's value at its key through
10060
- # the subject's `deconstruct_keys` projection; `**rest` binds the remaining entries.
10061
- def collect_hash_pattern_bindings(subject_type, pattern, scope, subject_node:)
10062
- subject_type = pattern_class_constraint(subject_type, pattern.constant, scope)
10063
- view = hash_pattern_view(subject_type, scope, subject_node)
10064
- bindings = pattern.elements.flat_map do |assoc|
10065
- next [] unless assoc.is_a?(Prism::AssocNode) && assoc.value
10066
-
10067
- collect_in_pattern_bindings(hash_pattern_value_type(view, assoc.key), assoc.value, scope)
10068
- end
10069
- rest = pattern.rest
10070
- if rest.is_a?(Prism::AssocSplatNode) && rest.value.is_a?(Prism::LocalVariableTargetNode)
10071
- bindings << [rest.value.name, hash_pattern_rest_type(view)]
10072
- end
10073
- bindings
10074
- end
10075
-
10076
- # The `Hash`-shaped view a hash pattern reads: the subject's `deconstruct_keys` answer, which is a `HashShape`
10077
- # for a shape carrier or a `deconstruct_keys` body and `Hash[K, V]` for the RBS answer of a plain `Hash` — or
10078
- # nil when the subject cannot be asked.
10079
- def hash_pattern_view(subject_type, scope, subject_node)
10080
- args = [Type::Combinator.constant_of(nil)]
10081
- struct_instance_projection(subject_type, :deconstruct_keys, scope, subject_node) ||
10082
- pattern_decomposition_dispatch(subject_type, :deconstruct_keys, args, scope) ||
10083
- source_decomposition_projection(subject_type, :deconstruct_keys, args, scope)
10084
- end
10085
-
10086
- # The value type the pattern's key reads out of the view: a `HashShape` answers per key, a `Hash[K, V]`
10087
- # answers `V` for every key, and anything else — a key the AST does not pin (`in {"#{k}": v}`), a shape that
10088
- # does not carry the key — answers the floor.
10089
- def hash_pattern_value_type(view, key_node)
10090
- key = hash_pattern_key(key_node)
10091
- return Type::Combinator.untyped if key.nil?
10092
- return view.pairs[key] || Type::Combinator.untyped if view.is_a?(Type::HashShape)
10093
-
10094
- hash_value_type(view) || Type::Combinator.untyped
10095
- end
10096
-
10097
- # The key a hash pattern element names, or nil when the AST does not pin one (an interpolated or computed key).
10098
- def hash_pattern_key(key_node)
10099
- case key_node
10100
- when Prism::SymbolNode then key_node.unescaped.to_sym
10101
- when Prism::StringNode then key_node.unescaped
10102
- end
10103
- end
10104
-
10105
- # `{ key:, **rest }` binds `rest` to a Hash whose keys are Symbols (the only legal key shape for a hash pattern)
10106
- # and whose values are the view's own value type — the entries the pattern named are a subset of it.
10107
- def hash_pattern_rest_type(view)
10108
- value = view.is_a?(Type::HashShape) ? union_of_types(view.pairs.values) : hash_value_type(view)
10109
- Type::Combinator.nominal_of(
10110
- "Hash",
10111
- type_args: [Type::Combinator.nominal_of("Symbol"), value || Type::Combinator.untyped]
10112
- )
10113
- end
10114
-
10115
- # The `V` of a `Hash[K, V]`, or nil for a raw `Hash`, a non-`Hash` nominal, or a `Dynamic` / `Top` value.
10116
- def hash_value_type(type)
10117
- return nil unless type.is_a?(Type::Nominal) && type.class_name == "Hash" && type.type_args.size == 2
10118
-
10119
- value = type.type_args.last
10120
- return nil if value.is_a?(Type::Dynamic) || value.is_a?(Type::Top)
10121
-
10122
- value
10123
- end
10124
-
10125
- # The union of a list of types, ignoring the gradual floor (`Dynamic[top]` / `Top` carries nothing to union)
10126
- # and answering nil when nothing is left.
10127
- def union_of_types(types)
10128
- known = types.reject { |type| type.is_a?(Type::Dynamic) || type.is_a?(Type::Top) }
10129
- known.empty? ? nil : Type::Combinator.union(*known)
10130
- end
10131
-
10132
- # `[..., *rest, ...]` / `[*pre, x, *post]` capture an Array of the unmatched elements. `rest_type` is the
10133
- # enclosing decomposition's own rest (a `Tuple` of the middle elements for a tuple subject, `Array[T]` for an
10134
- # `Array[T]`); without one — a subject that did not decompose — the rest is `Array[untyped]`.
10135
- def append_array_splat_binding(bindings, splat, rest_type)
10136
- return unless splat.is_a?(Prism::SplatNode)
10137
-
10138
- target = splat.expression
10139
- return unless target.is_a?(Prism::LocalVariableTargetNode)
10140
-
10141
- bindings << [target.name, rest_type || Type::Combinator.nominal_of("Array", type_args: [Type::Combinator.untyped])]
10142
- end
10143
-
10144
- # The `Dynamic[top]` floor per slot, for a subject no rule decomposes.
10145
- def floor_pattern_slots(front_count, back_count, rest_present)
10146
- [
10147
- Array.new(front_count) { Type::Combinator.untyped },
10148
- rest_present ? Type::Combinator.nominal_of("Array", type_args: [Type::Combinator.untyped]) : nil,
10149
- Array.new(back_count) { Type::Combinator.untyped }
10150
- ]
10151
- end
10152
-
10153
- # The class a pattern's own constant asserts (`in Point[x, y]`, `in Foo{...}`), applied to the subject. An
10154
- # opaque subject — `Dynamic` / `Top`, which no `is_a?`-style narrowing can refine — becomes `Nominal[C]`: the
10155
- # pattern's `C === subject` test has just established the class, which is what lets a constrained pattern bind
10156
- # off a subject whose own type named nothing. A subject whose class is already known keeps it.
10157
- def pattern_class_constraint(subject_type, constant_node, scope)
10158
- return subject_type if constant_node.nil?
10159
-
10160
- nominal = singleton_to_nominal(sub_eval(constant_node, scope).first)
10161
- return subject_type unless opaque_pattern_subject?(subject_type)
10162
- return subject_type if nominal.is_a?(Type::Dynamic) || nominal.is_a?(Type::Top)
10163
-
10164
- nominal
10165
- end
10166
-
10167
- def opaque_pattern_subject?(subject_type)
10168
- subject_type.nil? || subject_type.is_a?(Type::Dynamic) || subject_type.is_a?(Type::Top)
10169
- end
10170
-
10171
- # Distributes a union subject over the pattern, the rule {MultiTargetBinder} applies to `a, b = union`: every
10172
- # member walks the same pattern and each name binds the join of its per-member types, while a member that binds
10173
- # `Dynamic[top]` floors the name for the whole union — a precise member must not stand for one nothing is known
10174
- # about. A member that PROVABLY cannot match the pattern contributes nothing at all instead of flooring:
10175
- # `case maybe; in [a, b]` over `Tuple[1, "a"] | nil` binds `1` / `"a"`, because a `nil` subject raises
10176
- # `NoMatchingPatternError` rather than reaching the body.
10177
- def collect_union_pattern_bindings(members, pattern, scope, subject_node: nil)
10178
- reachable = members.reject { |member| pattern_match_impossible?(member, pattern, scope) }
10179
- walks = (reachable.empty? ? [Type::Combinator.untyped] : reachable).map do |member|
10180
- collect_in_pattern_bindings(member, pattern, scope, subject_node: subject_node)
10181
- end
10182
- merge_pattern_bindings(walks)
10183
- end
10184
-
10185
- # Whether `type` provably cannot match `pattern`, so its arm contributes no binding. Only the two
10186
- # decompositions a pattern asks for are checked — `deconstruct` (array / find patterns) and `deconstruct_keys`
10187
- # (hash patterns) — and both only for a class the RBS environment knows, whose method set is closed, the same
10188
- # rule `array_conversion_free?` applies to the multi-assign `to_ary` question (issue #1094). A carrier the
10189
- # check cannot prove negative about (Dynamic, a source class, an unresolved constant) answers false, which
10190
- # keeps the union at the conservative floor.
10191
- def pattern_match_impossible?(type, pattern, scope)
10192
- case pattern
10193
- when Prism::ArrayPatternNode, Prism::FindPatternNode then !decomposable_as_array?(type, scope)
10194
- when Prism::HashPatternNode then !decomposable_as_hash?(type, scope)
10195
- when Prism::CapturePatternNode then pattern_match_impossible?(type, pattern.value, scope)
10196
- else false
10197
- end
10198
- end
10199
-
10200
- def decomposable_as_array?(type, scope)
10201
- return true unless pattern_decomposition_dispatch(type, :deconstruct, [], scope).nil?
10202
-
10203
- class_name = MultiTargetBinder.conversion_class_name(type)
10204
- class_name.nil? || !MethodDispatcher::RbsDispatch.array_conversion_free?(class_name, scope)
10205
- end
10206
-
10207
- def decomposable_as_hash?(type, scope)
10208
- args = [Type::Combinator.constant_of(nil)]
10209
- return true unless pattern_decomposition_dispatch(type, :deconstruct_keys, args, scope).nil?
10210
-
10211
- class_name = MultiTargetBinder.conversion_class_name(type)
10212
- return true if class_name.nil? || scope.environment.nil?
10213
-
10214
- !Reflection.rbs_class_known?(class_name, environment: scope.environment)
10215
- end
10216
-
10217
- # Joins per-member binding lists by name: `Dynamic[top]` from any walk — or a name a walk does not bind —
10218
- # floors the name, otherwise the members union. The first walk's order is the declaration order.
10219
- def merge_pattern_bindings(walks)
10220
- floor = Type::Combinator.untyped
10221
- walks.first.map do |name, _type|
10222
- types = walks.map { |walk| walk.assoc(name)&.last }
10223
- floored = types.any? { |type| type.nil? || Type::Combinator.untyped?(type) }
10224
- [name, floored ? floor : Type::Combinator.union(*types)]
10225
- end
10226
- end
10227
-
10228
- # `expr in pattern` (a `MatchPredicateNode`, evaluating to a boolean) and `expr => pattern` (a
10229
- # `MatchRequiredNode`, evaluating to `nil` and raising `NoMatchingPatternError` on a mismatch) — the one-line
10230
- # pattern matches. Both bind every name the pattern captures into the post-scope, decomposed exactly as an `in`
10231
- # branch of a `case` is, and WITHOUT the nil-injection a surrounding join would add: a name is read on the
10232
- # truthy side only after the pattern matched it, which is the shape `if config in {timeout: Integer => t}`
10233
- # depends on.
10234
- def eval_match_pattern(node)
10235
- subject_type, post_value = sub_eval(node.value, scope)
10236
- bound = apply_in_pattern_bindings(subject_type, node.value, node.pattern, post_value)
10237
- [scope.type_of(node, tracer: tracer), bound]
10238
- end
10239
-
10240
- # --------------------------------------------------------------- named-capture regex binding (`MatchWriteNode`)
10241
- # ---------------------------------------------------------------
10242
-
10243
- # `/(?<year>\d+)/ =~ str` — Prism emits a `MatchWriteNode` that wraps the `=~` call and lists the named-capture
10244
- # targets. Each target is bound to `String | nil` (the capture is absent as nil when the pattern doesn't match or
10245
- # the group didn't participate).
10246
- def eval_match_write(node)
10247
- match_type, post_scope = sub_eval(node.call, scope)
10248
- string_or_nil = Type::Combinator.union(
10249
- Type::Combinator.nominal_of("String"),
10250
- Type::Combinator.constant_of(nil)
10251
- )
10252
- bound_scope = node.targets.reduce(post_scope) do |s, target|
10253
- next s unless target.is_a?(Prism::LocalVariableTargetNode)
10254
-
10255
- s.with_local(target.name, string_or_nil)
10256
- end
10257
- [match_type, bound_scope]
10258
- end
10259
-
10260
- # --------------------------------------------------------------- shared type conversion helper
10261
- # ---------------------------------------------------------------
10262
-
10263
- # Converts a `Singleton[ClassName]` (the class object) to the corresponding `Nominal[ClassName]` (an instance).
10264
- # Falls back to `untyped` for carriers that are not Singleton (e.g. Dynamic[Top] when the class could not be
10265
- # resolved).
10266
- def singleton_to_nominal(type)
10267
- type.is_a?(Type::Singleton) ? Type::Combinator.nominal_of(type.class_name) : Type::Combinator.untyped
10268
- end
10269
-
10270
- # Returns the type to bind for a `CapturePatternNode`'s target. A class reference (`Integer => x`, and every
10271
- # alternate of `Integer | String => x`) answers the constraint's `Nominal[T]` — the pattern's own `T ===
10272
- # subject` test is what licenses the binding even when the subject's type is opaque. A value pattern (`1 => x`)
10273
- # answers the literal's own type. A capture over any other pattern (`[a, b] => whole`, `^(x) => y`) answers the
10274
- # subject, which is what that pattern matched.
10275
- def capture_pattern_type(subject_type, value_node, scope)
10276
- case value_node
10277
- when Prism::ConstantReadNode, Prism::ConstantPathNode
10278
- singleton_to_nominal(sub_eval(value_node, scope).first)
10279
- when Prism::AlternationPatternNode
10280
- Type::Combinator.union(
10281
- capture_pattern_type(subject_type, value_node.left, scope),
10282
- capture_pattern_type(subject_type, value_node.right, scope)
10283
- )
10284
- when Prism::ArrayPatternNode, Prism::FindPatternNode, Prism::HashPatternNode,
10285
- Prism::PinnedVariableNode, Prism::PinnedExpressionNode, Prism::ImplicitNode
10286
- subject_type || Type::Combinator.untyped
10287
- else
10288
- literal_pattern_type(value_node, scope)
10289
- end
10290
- end
10291
-
10292
- # The type a non-class pattern node evaluates to: `Constant[1]` for `1 => x`, the nominal for `/re/ => x`,
10293
- # the range for `1..5 => x`. A class reference is the one carrier that must convert (`Singleton[C]` is the
10294
- # class object; the binding holds an instance), which the caller's constant arm does.
10295
- def literal_pattern_type(value_node, scope)
10296
- type = sub_eval(value_node, scope).first
10297
- type.is_a?(Type::Singleton) ? singleton_to_nominal(type) : type
10298
- end
10299
-
10300
- # `in PatternA | PatternB` — Ruby requires both alternates to bind the same names, but the binder runs against
10301
- # the AST and cannot enforce that. We collect bindings from each side and merge by name, unioning types when both
10302
- # alternates contribute. Names that only one alternate contributes still surface (the parser would have rejected
10303
- # the case at compile time, so by the time we see it the user's intent is the merged set).
10304
- def collect_alternation_pattern_bindings(subject_type, pattern, scope)
10305
- left = collect_in_pattern_bindings(subject_type, pattern.left, scope)
10306
- right = collect_in_pattern_bindings(subject_type, pattern.right, scope)
10307
- merged = {}
10308
- (left + right).each do |name, type|
10309
- merged[name] = merged.key?(name) ? Type::Combinator.union(merged[name], type) : type
10310
- end
10311
- merged.to_a
10312
- end
9505
+ def eval_match_write(node) = PatternBindings.eval_match_write(node, scope, self)
10313
9506
  end
10314
9507
  end
10315
9508
  end