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
@@ -28,6 +28,7 @@ require_relative "def_node_resolver"
28
28
  require_relative "dynamic_origin"
29
29
  require_relative "error_info"
30
30
  require_relative "external_ancestor_resolution"
31
+ require_relative "genuine_send"
31
32
  require_relative "origin_lookup"
32
33
  require_relative "../effects/collector"
33
34
  require_relative "fallback"
@@ -54,6 +55,15 @@ require_relative "struct_fold_safety"
54
55
  require_relative "unknown_store_widening"
55
56
  require_relative "unthreaded_rebinds"
56
57
  require_relative "version_guard"
58
+ require_relative "expression_typer/composites"
59
+ require_relative "expression_typer/per_element_assemblers"
60
+ require_relative "expression_typer/writes"
61
+ require_relative "call_ladder/user_method"
62
+ require_relative "call_ladder/project_singleton"
63
+ require_relative "call_ladder/literal_send"
64
+ require_relative "call_ladder/top_level_def"
65
+ require_relative "call_ladder/overriding_def"
66
+ require_relative "call_ladder/refined"
57
67
 
58
68
  module Rigor
59
69
  module Inference
@@ -249,7 +259,7 @@ module Rigor
249
259
  private_constant :PRISM_DISPATCH
250
260
 
251
261
  # Sentinel distinguishing "the key is not a value-pinned literal" from the legitimate literal hash
252
- # keys `nil` and `false` (see {#static_hash_key}).
262
+ # keys `nil` and `false` (see {Composites.static_hash_key}).
253
263
  NO_STATIC_HASH_KEY = Object.new.freeze
254
264
  private_constant :NO_STATIC_HASH_KEY
255
265
 
@@ -331,10 +341,10 @@ module Rigor
331
341
  # The `receiver[args]` read a compound index write performs before it stores (`c[k] += v` reads `c[k]`),
332
342
  # or nil when no tier answers. No `Prism::CallNode` for that read exists in the tree, so the write node
333
343
  # itself stands in as the call context: it carries the same `receiver` / `arguments` / `block` a
334
- # plain `c[k]` call does, which is what the context-reading tiers consult. With it, the read reaches
335
- # the tiers a plain `c[k]` takes, in the same order — the own-`def` override check, the dispatcher's
336
- # node- and scope-gated tiers, then the project `def` inference a dispatch miss falls to — so a project
337
- # `[]` with no signature answers from its body instead of the whole write degrading to `Dynamic[top]`.
344
+ # plain `c[k]` call does, which is what the context-reading tiers consult. With it, the read asks the
345
+ # `index_read` rungs of {CallLadder::RUNGS} — the own-`def` override check, the dispatcher's node- and
346
+ # scope-gated tiers, then the project `def` inference a dispatch miss falls to — so a project `[]`
347
+ # with no signature answers from its body instead of the whole write degrading to `Dynamic[top]`.
338
348
  #
339
349
  # A plugin `dynamic_return` rule written for `[]` still does not answer this read. Its `methods:` gate
340
350
  # matches `call_node.name`, which an index write does not have, and the shipped rules decline any node
@@ -344,10 +354,12 @@ module Rigor
344
354
  def implicit_index_read_type(node, receiver, arg_types)
345
355
  return splat_index_read_type(node, receiver, arg_types) if splat_arguments?(node)
346
356
 
347
- try_overriding_def_dispatch(node, receiver, arg_types, method_name: :[]) ||
348
- index_read_dispatch(node, receiver, arg_types) ||
349
- try_user_method_inference(receiver, node, arg_types, method_name: :[]) ||
350
- try_project_singleton_inference(receiver, node, arg_types, method_name: :[])
357
+ site = index_read_site(node, receiver, arg_types)
358
+ overriding_def = CallLadder::OverridingDef.try_call(site, self)
359
+ return overriding_def if overriding_def
360
+
361
+ MethodDispatcher.dispatch_site(site) || CallLadder::UserMethod.try_call(site, self) ||
362
+ CallLadder::ProjectSingleton.try_call(site, self)
351
363
  end
352
364
 
353
365
  # Issue #1889 — the type a block-form `inject` / `reduce` accumulator parameter holds across the block's runs,
@@ -493,14 +505,53 @@ module Rigor
493
505
  end
494
506
  end
495
507
 
496
- private
497
-
498
- attr_reader :scope, :tracer
499
-
508
+ # @api private — public only so {Writes} can call it on the typer it is given.
500
509
  def dynamic_top
501
510
  Type::Combinator.untyped
502
511
  end
503
512
 
513
+ # @api private — public only so {Writes} can call it on the typer it is given.
514
+ #
515
+ # Resolves a constant reference through Ruby's lexical constant lookup. Delegates to the shared
516
+ # `Reflection.resolve_constant_type` owner so the same walk (registry singleton, discovered class,
517
+ # in-source value, RBS constant, across the peeled `::` prefix candidates) is reused by
518
+ # `Inference::Narrowing`'s `Constant[Regexp]` match-operand recognition. Returns the matched
519
+ # `Rigor::Type` or nil; the caller decides whether to fall back.
520
+ def resolve_constant_name(name, rooted: false, caller_derived: true)
521
+ Reflection.resolve_constant_type(name, scope: scope, rooted: rooted, caller_derived: caller_derived)
522
+ end
523
+
524
+ # @api private — the scope this typer reads. Public only so a rung module of the call ladder can read it from
525
+ # the typer it is given ({CallLadder::PORT}, with the methods made public at the end of this class).
526
+ attr_reader :scope
527
+
528
+ private
529
+
530
+ attr_reader :tracer
531
+
532
+ # One-line delegators for the node typers `PRISM_DISPATCH` names (and `statements_or_nil`, which the rescue
533
+ # typers call) whose bodies live in the modules under `expression_typer/` (ADR-116 C3); each passes the values it
534
+ # reads from this typer (`scope`, `tracer`) and the typer itself, so the module reads no instance variable.
535
+ def type_of_statements_node(node) = Composites.type_of_statements_node(node, self)
536
+ def type_of_program(node) = Composites.type_of_program(node, self)
537
+ def type_of_hash(node) = Composites.type_of_hash(node, self)
538
+ def type_of_interpolated_string(node) = Composites.type_of_interpolated_string(node, self)
539
+ def type_of_embedded_statements(node) = Composites.type_of_embedded_statements(node, self)
540
+ def type_of_class_or_module(node) = Composites.type_of_class_or_module(node, self)
541
+ def type_of_else(node) = Composites.type_of_else(node, self)
542
+ def type_of_when_or_in(node) = Composites.type_of_when_or_in(node, self)
543
+ def type_of_ensure(node) = Composites.type_of_ensure(node, self)
544
+ def type_of_range(node) = Composites.type_of_range(node, self)
545
+ def statements_or_nil(node) = Composites.statements_or_nil(node, self)
546
+ def type_of_shareable_constant(node) = Composites.type_of_shareable_constant(node, self)
547
+ def type_of_implicit(node) = Composites.type_of_implicit(node, self)
548
+ def array_type_for(node) = Composites.array_type_for(node, self)
549
+ def parentheses_type_for(node) = Composites.parentheses_type_for(node, self)
550
+ def type_of_assignment_write(node) = Writes.type_of_assignment_write(node, self)
551
+ def type_of_compound_variable_write(node) = Writes.type_of_compound_variable_write(node, scope, self)
552
+ def type_of_compound_constant_write(node) = Writes.type_of_compound_constant_write(node, scope, self)
553
+ def type_of_index_compound_write(node) = Writes.type_of_index_compound_write(node, scope, tracer)
554
+
504
555
  def type_of_literal_value(node)
505
556
  Type::Combinator.constant_of(node.value)
506
557
  end
@@ -517,189 +568,6 @@ module Rigor
517
568
  Type::Combinator.constant_of(nil)
518
569
  end
519
570
 
520
- # All `*WriteNode` flavours expose a `.value` rvalue child. Their type is the type of that rvalue.
521
- # Binding the result back into the scope is the responsibility of the statement-level evaluator
522
- # (Slice 3), never of `type_of` itself.
523
- def type_of_assignment_write(node)
524
- type_of(node.value)
525
- end
526
-
527
- # `v += 1` / `@v ||= x` / `$v &&= x` as an EXPRESSION. The value of a compound write is the value it
528
- # stores, which is a function of the variable's CURRENT binding — not of the rvalue alone. Typing it as
529
- # `type_of(node.value)` answered `1` for `total += 1` whatever `total` held.
530
- #
531
- # `StatementEvaluator#compound_eval` already computes the right answer on the straight-line path, so the
532
- # gap only showed where a body is typed WITHOUT that evaluator: the block-return pass types a
533
- # single-statement body by expression alone, and issue #617 residue (3) is the live consequence —
534
- # `total = 0; r = [1, 2].map { total += 1 }` folded to `[1, 1]`, and `r.last == 1` fired a false
535
- # `flow.always-truthy-condition` on a program where it is `2`. Under the per-element fold the captured
536
- # local is already bound to its converged `Integer` (issue #587 (b)); reading that binding here is what
537
- # turns the stale pin into the honest `Integer`.
538
- #
539
- # The algebra is `StatementEvaluator#compound_result_type`'s, deliberately: the two must not disagree
540
- # about what a compound write evaluates to. An unbound target is `Dynamic[top]` — the same fallback the
541
- # evaluator takes — and an operator the receiver does not answer widens to `Dynamic[top]` rather than
542
- # inventing the rvalue.
543
- #
544
- # Constant targets have {#type_of_compound_constant_write}, over the same algebra. Index targets have their
545
- # own handler, {#type_of_index_compound_write}.
546
- def type_of_compound_variable_write(node)
547
- compound_write_value(node, compound_write_current_binding(node), type_of(node.value))
548
- end
549
-
550
- # `H ||= 0` / `Conf::LIMIT += 1` as an EXPRESSION: the value it stores, by
551
- # {#type_of_compound_variable_write}'s algebra. Typed as the rvalue alone, `H = { x: 1 }; v = (H ||= 0);
552
- # v[:x]` reported `Integer#[]` on a program whose `v` is `H`, and `F.transform_values { |e| F ||= 0 }`
553
- # folded every value to `0`.
554
- #
555
- # A constant has no scope binding, so its current binding is what a plain read of the same spelling
556
- # resolves to at the write site — the lexical ladder, the in-source table of plain writes, then RBS —
557
- # less the caller-derived rungs a top-level body keeps for reads Ruby raises on. The memoization idiom
558
- # (`def registry = REGISTRY ||= {}`, legal where a plain `REGISTRY = {}` is a dynamic constant
559
- # assignment) writes a constant nothing else binds, so an unresolved target keeps the rvalue reading
560
- # exactly as an unbound variable does — unless a write other than a memo binds it
561
- # ({#written_constant_binding}). A path whose base renders no static name (`klass::X`, `self::X`) names
562
- # no binding the resolver can look up, and reads as unbound too, on the same condition.
563
- def type_of_compound_constant_write(node)
564
- rhs = type_of(node.value)
565
- compound_write_value(node, compound_write_constant_binding(node), rhs)
566
- end
567
-
568
- def compound_write_value(node, current, rhs)
569
- case node
570
- when Prism::LocalVariableOrWriteNode, Prism::InstanceVariableOrWriteNode,
571
- Prism::ClassVariableOrWriteNode, Prism::GlobalVariableOrWriteNode,
572
- Prism::ConstantOrWriteNode, Prism::ConstantPathOrWriteNode
573
- # An UNBOUND target is the memoization idiom (`def self.default = @default ||= new`): nothing
574
- # has written the variable on any path the analyzer saw, so the stored value is the rvalue.
575
- # Reading it as `Dynamic[top] | rhs` would skip every memoized singleton in `sig-gen`
576
- # (ADR-5 optimism; three `.default` readers went `sig.skipped.untyped-return` without this).
577
- #
578
- # The index rule's exception applies: an rvalue with no truthy part makes the write a guard, not a
579
- # memo. `@settings ||= raise "boot first"` returns only when something the analyzer did not see set
580
- # `@settings`, and `@verbose ||= false` answers `true` once one did, so the value is that unseen
581
- # binding — `Dynamic[top]`, the statement evaluator's reading of an unbound target — never the
582
- # rvalue's `bot` or `false` alone. A local is no exception: the scope a loop body is typed from does
583
- # not carry what the previous iteration stored.
584
- if current.nil?
585
- return rhs unless Narrowing.narrow_truthy(rhs).is_a?(Type::Bot)
586
-
587
- current = dynamic_top
588
- end
589
-
590
- Type::Combinator.union(Narrowing.narrow_truthy(current), rhs)
591
- when Prism::LocalVariableAndWriteNode, Prism::InstanceVariableAndWriteNode,
592
- Prism::ClassVariableAndWriteNode, Prism::GlobalVariableAndWriteNode,
593
- Prism::ConstantAndWriteNode, Prism::ConstantPathAndWriteNode
594
- # `&&=` is no memo: an unset target returns its own `nil` without evaluating the rvalue (a constant or
595
- # class variable raises instead). Beside the rvalue, an UNBOUND target's value is its own falsey value —
596
- # `nil` when unset, or a falsey value a write the analyzer did not see stored — which
597
- # `narrow_falsey(Dynamic[top])` carries as `Dynamic[top]`, the statement evaluator's reading. The index
598
- # rule says the same of `h[k] &&= v`. Read as the rvalue, `if (@x &&= 1)` folded always-truthy on a
599
- # program that takes the else arm.
600
- Type::Combinator.union(Narrowing.narrow_falsey(current || dynamic_top), rhs)
601
- else
602
- compound_operator_result(current || dynamic_top, rhs, node.binary_operator)
603
- end
604
- end
605
-
606
- # `h[k] += v` / `h[k] ||= v` / `h[k] &&= v` as an EXPRESSION. Like a variable compound write, its value is
607
- # what it stores through `[]=` — the dispatched `h[k] + v`, `truthy(h[k]) | v`, `falsey(h[k]) | v` — which
608
- # reads the slot's current type, recorded indexed narrowing included. Typed as the rvalue alone it answered
609
- # `1` for `counts[w] += 1`, so `r = words.map { |w| counts[w] += 1 }` pinned every position to `1` and
610
- # `r.last == 1` drew a false `flow.always-truthy-condition`.
611
- #
612
- # The statement evaluator already owned that algebra for the straight-line write and the `[]=` widening
613
- # join, so this reads its answer rather than keeping a second copy. It asks for the value alone, not a
614
- # whole `evaluate`: the widening and the narrowing record are scope effects a value position discards,
615
- # and the memoizing `@cache[k] ||= build(k)` tail is common enough not to pay for them.
616
- #
617
- # One exception carries over, narrowed, from {#type_of_compound_variable_write}: a memoizing `||=` whose
618
- # slot the analyzer has no evidence about reads as the rvalue. The evaluator's value method owns it,
619
- # because it is decided on the `[]` read the evaluator performs.
620
- def type_of_index_compound_write(node)
621
- StatementEvaluator.new(scope: scope, tracer: tracer).index_compound_write_value(node)
622
- end
623
-
624
- def compound_write_current_binding(node)
625
- case node
626
- when Prism::LocalVariableOperatorWriteNode, Prism::LocalVariableOrWriteNode,
627
- Prism::LocalVariableAndWriteNode then scope.local(node.name)
628
- when Prism::InstanceVariableOperatorWriteNode, Prism::InstanceVariableOrWriteNode,
629
- Prism::InstanceVariableAndWriteNode then scope.ivar(node.name)
630
- when Prism::ClassVariableOperatorWriteNode, Prism::ClassVariableOrWriteNode,
631
- Prism::ClassVariableAndWriteNode then scope.cvar(node.name)
632
- else scope.global(node.name)
633
- end
634
- end
635
-
636
- def compound_write_constant_binding(node)
637
- case node
638
- when Prism::ConstantOperatorWriteNode, Prism::ConstantOrWriteNode, Prism::ConstantAndWriteNode
639
- full_name = node.name.to_s
640
- rooted = false
641
- else
642
- full_name = Source::ConstantPath.qualified_name_or_nil(node.target)
643
- return unnamed_path_binding(node.target) if full_name.nil?
644
-
645
- rooted = Source::ConstantPath.rooted?(node.target)
646
- end
647
- resolve_constant_name(full_name, rooted: rooted, caller_derived: false) ||
648
- written_constant_binding(full_name, rooted)
649
- end
650
-
651
- # A constant the plain read cannot resolve may still be bound: another file writes a value that never
652
- # published (`H = { x: 1 }`), the compound write withdrew one by being the second writer the census
653
- # counts, or this file writes it in a form its own table does not carry (`A, B = …`, `A = B = …`). The
654
- # value is one the analyzer does not have, so the binding is `Dynamic[top]` rather than the memo's
655
- # unbound reading. The one write that does not bind is a memo `||=` no other file shares, so the
656
- # memoization idiom keeps that reading however often its file repeats it; memos of the name in two files
657
- # bind, since either may load first and set what the other reads.
658
- #
659
- # Which name the write reads is the ladder's to decide, not the spelling's: the same resolution runs
660
- # again with only the census's binding names in the in-source table, so `Other::REGISTRY` elsewhere
661
- # leaves a top-level `REGISTRY ||= {}` its memo reading. Two census spellings the ladder cannot reach
662
- # still bind: a write through a base nothing names (`k::X = 1`), which may have written any of them,
663
- # and a path the census keeps as written ([#690](https://github.com/rigortype/rigor/issues/690)), so
664
- # `Foo::BAR = …` inside `module M` binds `M::Foo::BAR ||= 0`.
665
- def written_constant_binding(full_name, rooted)
666
- names = scope.bound_constant_names(full_name)
667
- return nil if names.empty?
668
- return dynamic_top if names.any? { |name| unladdered_census_name?(name, full_name) }
669
-
670
- written = names.to_h { |name| [name, dynamic_top] }
671
- probe = scope.with_discovery(scope.discovery.with(in_source_constants: written))
672
- Reflection.resolve_constant_type(full_name, scope: probe, rooted: rooted, caller_derived: false)
673
- end
674
-
675
- def unladdered_census_name?(name, full_name)
676
- return true if name.start_with?(ScopeIndexer::DYNAMIC_TARGET_PREFIX)
677
-
678
- name.include?("::") && full_name.end_with?("::#{name}")
679
- end
680
-
681
- # `self::X ||= v` / `klass::X ||= v` name no constant the resolver can look up, so any binding write
682
- # that shares the last segment may be the one the base reaches. The answer now depends on other files'
683
- # writes, and this path never reaches `Reflection.resolve_constant_type`, which records the
684
- # `constant:<segment>` edge for every other form — so it records the edge itself, or an incremental
685
- # run keeps serving the reading from before another file's write of the segment appeared.
686
- def unnamed_path_binding(target)
687
- segment = target.name&.to_s
688
- return nil if segment.nil?
689
-
690
- Analysis::DependencyRecorder.read_name(:constant, segment) if Analysis::DependencyRecorder.active?
691
- dynamic_top unless scope.bound_constant_names(segment).empty?
692
- end
693
-
694
- def compound_operator_result(current, rhs, operator)
695
- MethodDispatcher.dispatch(
696
- receiver_type: current,
697
- method_name: operator.to_sym,
698
- arg_types: [rhs],
699
- environment: scope.environment
700
- ) || dynamic_top
701
- end
702
-
703
571
  # Slice 7 phase 1 — instance/class/global variable reads. Each lookup returns the type currently bound
704
572
  # in the surrounding scope's per-kind binding map (populated by `StatementEvaluator` write handlers
705
573
  # within the same method body), falling through to `Dynamic[Top]` when no binding is recorded.
@@ -726,14 +594,6 @@ module Rigor
726
594
  scope.global(node.name) || dynamic_top
727
595
  end
728
596
 
729
- def type_of_statements_node(node)
730
- statements_type_for(node)
731
- end
732
-
733
- def type_of_program(node)
734
- statements_type_for(node.statements)
735
- end
736
-
737
597
  # Recognised position that does not produce a value: parameter lists and individual parameter
738
598
  # declarations, splats inside argument lists, key-value pairs in hashes, and the implicit-rest token
739
599
  # inside destructuring. Returning Dynamic[Top] silently keeps these off the unrecognised list without
@@ -912,192 +772,14 @@ module Rigor
912
772
  # a second source of truth for the same key.
913
773
  end
914
774
 
915
- # Resolves a constant reference through Ruby's lexical constant lookup. Delegates to the shared
916
- # `Reflection.resolve_constant_type` owner so the same walk (registry singleton, discovered class,
917
- # in-source value, RBS constant, across the peeled `::` prefix candidates) is reused by
918
- # `Inference::Narrowing`'s `Constant[Regexp]` match-operand recognition. Returns the matched
919
- # `Rigor::Type` or nil; the caller decides whether to fall back.
920
- def resolve_constant_name(name, rooted: false, caller_derived: true)
921
- Reflection.resolve_constant_type(name, scope: scope, rooted: rooted, caller_derived: caller_derived)
922
- end
923
-
924
- # Slice 5 phase 1 upgrades hash literals to `HashShape{...}` when every entry is a static `AssocNode`
925
- # whose key is a value-pinned scalar literal — Symbol, plain String, Integer, Float, `true`, `false`,
926
- # or `nil` (covering `{ a: 1, "b" => 2 }` and `{ 1 => 2, 1.0 => 4 }` alike) — falling back to the
927
- # generic `Hash[K, V]` form otherwise. Splatted entries (`{ **other }`) and dynamic keys widen to the
928
- # underlying `Hash[K, V]` form by unioning the types each entry exposes — a splat exposes the `[K, V]`
929
- # of the hash it copies plus a `Dynamic[top]` arm (see {#hash_splat_pair}), so every entry contributes a
930
- # pair. A splat never keeps a shape, even over an exact closed one.
931
- def type_of_hash(node)
932
- elements = node.respond_to?(:elements) ? node.elements : []
933
- # v0.0.7 — `{}` resolves to the empty `HashShape{}` carrier rather than `Nominal[Hash]`, mirroring the
934
- # v0.0.6 empty-array literal change. Both forms erase to plain `Hash`, but `HashShape{}` pins the
935
- # literal's known size (zero) so HashShape projections (`empty?`, `first`, `count`, …) fold against it.
936
- return Type::Combinator.hash_shape_of({}) if elements.empty?
937
-
938
- shape = static_hash_shape_for(elements)
939
- return shape if shape
940
-
941
- keys, values = generic_hash_pairs_for(elements)
942
- Type::Combinator.nominal_of(
943
- Hash,
944
- type_args: [Type::Combinator.union(*keys), Type::Combinator.union(*values)]
945
- )
946
- end
947
-
948
- # Builds `HashShape{...}` when every entry is an `AssocNode` whose key is a value-pinned scalar
949
- # literal (Symbol, plain String, Integer, Float, true, false, nil). Returns nil otherwise so the
950
- # caller falls back to the generic shape.
951
- #
952
- # Duplicate keys are LAST-WINS, matching the runtime (`{ a: 1, a: 2 }` keeps `a: 2`; Ruby itself
953
- # only warns under `-w`). Key identity is Ruby `Hash` `eql?` identity because `pairs` is a native
954
- # Hash — `1` and `1.0` stay distinct entries, `1.0` and `1.00` collide. The plain re-assignment
955
- # also reproduces the runtime's ordering: the key keeps its FIRST insertion position while the
956
- # value comes from the LAST occurrence.
957
- def static_hash_shape_for(elements)
958
- pairs = {}
959
- elements.each do |entry|
960
- return nil unless entry.is_a?(Prism::AssocNode)
961
-
962
- key = static_hash_key(entry.key)
963
- return nil if key.equal?(NO_STATIC_HASH_KEY)
964
-
965
- pairs[key] = type_of(entry.value)
966
- end
967
- return nil if pairs.empty?
968
-
969
- Type::Combinator.hash_shape_of(pairs)
970
- end
971
-
972
- # Returns the value-pinned scalar literal carried by a hash key node, or {NO_STATIC_HASH_KEY} when
973
- # the key is dynamic (a computed expression, an interpolated string — SymbolNode#value /
974
- # StringNode#unescaped are nil under interpolation — a constant, a local, …). `nil` / `false` are
975
- # real key values here, hence the sentinel rather than a nil return.
976
- def static_hash_key(node)
977
- case node
978
- when Prism::SymbolNode
979
- raw = node.value
980
- raw.nil? ? NO_STATIC_HASH_KEY : raw.to_sym
981
- when Prism::StringNode
982
- node.unescaped || NO_STATIC_HASH_KEY
983
- when Prism::IntegerNode, Prism::FloatNode then node.value
984
- when Prism::TrueNode then true
985
- when Prism::FalseNode then false
986
- when Prism::NilNode then nil
987
- else NO_STATIC_HASH_KEY
988
- end
989
- end
990
-
991
- def generic_hash_pairs_for(elements)
992
- keys = []
993
- values = []
994
- elements.each do |entry|
995
- if entry.is_a?(Prism::AssocNode)
996
- keys << type_of(entry.key)
997
- values << type_of(entry.value)
998
- else
999
- key, value = hash_splat_pair(entry)
1000
- keys << key
1001
- values << value
1002
- end
1003
- end
1004
- [keys, values]
1005
- end
1006
-
1007
- # The `[K, V]` a `**splat` entry adds to the literal: what the analysis can read of the hash it copies, each
1008
- # side joined with `Dynamic[top]`. Ruby inserts every pair of that hash, so leaving the entry out typed
1009
- # `o = { a: :z }; { **o, b: :y }` as `Hash[:b, :y]` and folded `h[:a] == :z` on correct code.
1010
- #
1011
- # The `Dynamic[top]` arm is there even when the copy is read exactly. The literal builds a new hash that no
1012
- # declaration describes, while `MutationRejoin` regrows a `Hash[K, V]` after `[]=` / `merge!` only when it
1013
- # already carries a gradual arm, because it reads a precise one as a declared claim. Without the arm
1014
- # `h = { **o }; h[:b] = 2; h[:b] == 2` would fold always-falsey and `h[:e] = "s"; h[:e].upcase` would fire
1015
- # `call.undefined-method`, where the `Hash` a splat-only literal used to type as had stayed quiet. The same
1016
- # arm stands in for what the analysis cannot read: an anonymous `**`, an untyped value, a nominal other than
1017
- # `Hash`, an open shape's unlisted entries, and a hash filled through an alias the engine does not track,
1018
- # which still reads `{}`.
1019
- def hash_splat_pair(entry)
1020
- untyped = Type::Combinator.untyped
1021
- copied = entry.value && splatted_hash_pair(type_of(entry.value))
1022
- return [untyped, untyped] if copied.nil?
1023
-
1024
- copied.map { |side| Type::Combinator.union(side, untyped) }
1025
- end
1026
-
1027
- # The `[K, V]` the analysis can read of a splatted value, or nil when it reads nothing: a shape's keys and
1028
- # values, a `Hash[K, V]`'s type arguments (through a difference over one, `non-empty-hash[K, V]`), and the
1029
- # join over a union's members. `nil` reads as nothing because `**nil` splats nothing (Ruby 3.4+; earlier
1030
- # Rubies raise). A `Hash` subclass is not read: its own type arguments, if any, are not `Hash`'s `K` and `V`.
1031
- def splatted_hash_pair(type)
1032
- case type
1033
- when Type::HashShape then splatted_shape_pair(type)
1034
- when Type::Nominal then type.class_name == "Hash" && type.type_args.size == 2 ? type.type_args : nil
1035
- when Type::Difference then splatted_hash_pair(type.base)
1036
- when Type::Union then joined_hash_pair(type.members.filter_map { |member| splatted_hash_pair(member) })
1037
- end
1038
- end
1039
-
1040
- def splatted_shape_pair(shape)
1041
- return nil if shape.pairs.empty?
1042
-
1043
- [Type::Combinator.union(*shape.pairs.keys.map { |k| Type::Combinator.constant_of(k) }),
1044
- Type::Combinator.union(*shape.pairs.values)]
1045
- end
1046
-
1047
- def joined_hash_pair(pairs)
1048
- return nil if pairs.empty?
1049
-
1050
- [Type::Combinator.union(*pairs.map(&:first)), Type::Combinator.union(*pairs.map(&:last))]
1051
- end
1052
-
1053
- # An interpolated string `"#{a}b#{c}"` is `literal-string` when every part contributes literal-bearing
1054
- # material: plain text segments are literal by construction, embedded expressions count when their type
1055
- # is itself literal-string-compatible (a `Constant<String>`, the `literal-string` carrier, an
1056
- # `Intersection` containing it, or a `Union` whose members all qualify). Otherwise the result widens to
1057
- # plain `Nominal[String]` as before.
1058
- def type_of_interpolated_string(node)
1059
- return Type::Combinator.literal_string if interpolation_parts_literal?(node.parts)
1060
-
1061
- Type::Combinator.nominal_of(String)
1062
- end
1063
-
1064
- def interpolation_parts_literal?(parts)
1065
- parts.all? { |part| interpolation_part_literal?(part) }
1066
- end
1067
-
1068
- def interpolation_part_literal?(part)
1069
- case part
1070
- when Prism::StringNode
1071
- true
1072
- when Prism::EmbeddedStatementsNode, Prism::EmbeddedVariableNode
1073
- Type::Combinator.literal_string_compatible?(type_of(part))
1074
- else
1075
- false
1076
- end
1077
- end
1078
-
1079
775
  def type_of_interpolated_symbol(_node)
1080
776
  Type::Combinator.nominal_of(Symbol)
1081
777
  end
1082
778
 
1083
- def type_of_embedded_statements(node)
1084
- statements_type_for(node.statements)
1085
- end
1086
-
1087
779
  def type_of_def(node)
1088
780
  Type::Combinator.constant_of(node.name)
1089
781
  end
1090
782
 
1091
- # `class Foo; body; end`, `module Foo; body; end`, and `class << x; body; end` evaluate to the value of
1092
- # the body's last expression, or `nil` when the body is empty. We do not track class/module scope yet,
1093
- # so the body is typed in the surrounding scope and that result is returned.
1094
- def type_of_class_or_module(node)
1095
- body = node.body
1096
- return Type::Combinator.constant_of(nil) if body.nil?
1097
-
1098
- type_of(body)
1099
- end
1100
-
1101
783
  # `alias x y`, `alias $x $y`, and `undef foo` all evaluate to nil at runtime; the constant carrier
1102
784
  # captures that exactly.
1103
785
  def type_of_nil_value(_node)
@@ -1117,10 +799,6 @@ module Rigor
1117
799
  LoopValueRecord.fetch(node, scope) || LoopValueRecord.miss { scope.evaluate(node, tracer: tracer).first }
1118
800
  end
1119
801
 
1120
- def type_of_else(node)
1121
- statements_or_nil(node.statements)
1122
- end
1123
-
1124
802
  # `a && b` / `a || b` in value position. Issue #1016: this handler used to type both operands in the
1125
803
  # receiver scope, so `x.finite? && x` read `Float | false` while the statement form bound
1126
804
  # `false | finite-float`. Like `type_of_conditional`, it delegates to the statement evaluator, which owns
@@ -1170,7 +848,9 @@ module Rigor
1170
848
  clause_scope = next_scope
1171
849
  end
1172
850
 
1173
- candidates << case_arm_type(node.else_clause, clause_scope) unless reached_yes
851
+ unless reached_yes || Narrowing.exhausted_when_case?(node, clause_scope)
852
+ candidates << case_arm_type(node.else_clause, clause_scope)
853
+ end
1174
854
  Type::Combinator.union(*candidates)
1175
855
  end
1176
856
 
@@ -1249,12 +929,6 @@ module Rigor
1249
929
  { value: type.value }
1250
930
  end
1251
931
 
1252
- # `when` clauses for `case` and `in` clauses for `case ... in` have the same body shape; we reuse one
1253
- # handler for both Prism node classes.
1254
- def type_of_when_or_in(node)
1255
- statements_or_nil(node.statements)
1256
- end
1257
-
1258
932
  # `begin; body; rescue R => e; r1; rescue; r2; else; e; ensure; f; end`. The result is the union of
1259
933
  # every value-producing branch: the body (or the else-clause when present, since it replaces the body's
1260
934
  # value when no exception fires), plus each rescue body in the rescue chain. The ensure clause runs but
@@ -1323,10 +997,6 @@ module Rigor
1323
997
  )
1324
998
  end
1325
999
 
1326
- def type_of_ensure(node)
1327
- statements_or_nil(node.statements)
1328
- end
1329
-
1330
1000
  # `return`, `break`, `next`, `retry`, and `redo` all transfer control instead of producing a value.
1331
1001
  # Their type is Bot, the empty type that absorbs cleanly under union (e.g. `Constant[1] | Bot ==
1332
1002
  # Constant[1]`), so the surrounding control-flow handlers collapse correctly when one branch jumps.
@@ -1356,58 +1026,9 @@ module Rigor
1356
1026
  Type::Combinator.nominal_of(Proc)
1357
1027
  end
1358
1028
 
1359
- def type_of_range(node)
1360
- left_static, left = static_range_endpoint(node.left)
1361
- right_static, right = static_range_endpoint(node.right)
1362
- if left_static && right_static
1363
- range = static_range_value(left, right, node.exclude_end?)
1364
- return Type::Combinator.constant_of(range) if range
1365
- end
1366
-
1367
- nominal_range_for_endpoints(node.left, node.right)
1368
- end
1369
-
1370
- # The `Range` the static endpoints denote, or nil when Ruby would refuse to build it (`1.."a"`,
1371
- # `"a"..1` raise `ArgumentError: bad value for range`). The literal is a runtime error,
1372
- # not a constant, so the fold declines and the caller types it as a plain Range.
1373
- def static_range_value(left, right, exclude_end)
1374
- Range.new(left, right, exclude_end)
1375
- rescue ArgumentError
1376
- nil
1377
- end
1378
-
1379
- # Derives `Nominal[Range, [T]]` from the endpoint expression types when at least one endpoint is
1380
- # statically typeable. The element parameter is the union of the endpoint types (lifted from
1381
- # `Constant<v>` to `Nominal<v.class>` so the carrier matches what `Range#each` would yield). Falls back
1382
- # to bare `Nominal[Range]` when no endpoint contributes a typable shape.
1383
- def nominal_range_for_endpoints(left_node, right_node)
1384
- endpoints = [left_node, right_node].compact.map { |n| range_endpoint_element_type(n) }
1385
- endpoints.reject! { |t| Type::Combinator.untyped?(t) }
1386
- return Type::Combinator.nominal_of("Range") if endpoints.empty?
1387
-
1388
- Type::Combinator.nominal_of("Range", type_args: [Type::Combinator.union(*endpoints)])
1389
- end
1390
-
1391
- def range_endpoint_element_type(node)
1392
- type = type_of(node)
1393
- case type
1394
- when Type::Constant
1395
- value = type.value
1396
- return Type::Combinator.untyped if value.nil?
1397
-
1398
- Type::Combinator.nominal_of(value.class.name)
1399
- when Type::IntegerRange
1400
- Type::Combinator.nominal_of("Integer")
1401
- when Type::FloatRange
1402
- Type::Combinator.nominal_of("Float")
1403
- else
1404
- type
1405
- end
1406
- end
1407
-
1408
1029
  # v0.0.7 — non-interpolated regex literals lift to `Constant<Regexp>` so `Constant<String>#scan(/regex/)`
1409
1030
  # / `#match(/regex/)` etc. can fold through the catalog tier. Interpolated regexes (`/foo#{x}/`) reach
1410
- # the second `Prism::InterpolatedRegularExpressionNode` arm which keeps the conservative
1031
+ # the early return for any node that is not a `Prism::RegularExpressionNode`, which keeps the conservative
1411
1032
  # `Nominal[Regexp]` answer.
1412
1033
  def type_of_regexp(node)
1413
1034
  return Type::Combinator.nominal_of(Regexp) unless node.is_a?(Prism::RegularExpressionNode)
@@ -1418,35 +1039,6 @@ module Rigor
1418
1039
  Type::Combinator.nominal_of(Regexp)
1419
1040
  end
1420
1041
 
1421
- # A range endpoint folds to a static value when it is a literal (`IntegerNode` / `StringNode`) or when
1422
- # its *evaluated* type is a `Constant<v>` carrying a range-able value (Integer / Float / String —
1423
- # matching the literal-path value kinds). The evaluated arm lets `(1..n)` fold to `Constant<Range>`
1424
- # when per-call body inference has pinned `n` to a constant (fact2 chain). A `nil` node is a
1425
- # beginless/endless boundary: keep today's static-nil behaviour (which yields `Constant<Range>` only
1426
- # when the *other* end is also static, preserving today's beginless/endless path).
1427
- def static_range_endpoint(node)
1428
- return [true, nil] if node.nil?
1429
- return [true, node.value] if node.is_a?(Prism::IntegerNode)
1430
- return [true, node.unescaped] if node.is_a?(Prism::StringNode) && node.respond_to?(:unescaped)
1431
-
1432
- type = type_of(node)
1433
- if type.is_a?(Type::Constant)
1434
- value = type.value
1435
- return [true, value] if value.is_a?(Integer) || value.is_a?(Float) || value.is_a?(String)
1436
- end
1437
-
1438
- [false, nil]
1439
- end
1440
-
1441
- # Helper for the many control-flow handlers that read a body `Prism::StatementsNode` or treat its
1442
- # absence as nil. Note that Prism uses nil (rather than an empty `StatementsNode`) for missing bodies
1443
- # in many node kinds.
1444
- def statements_or_nil(statements_node)
1445
- return Type::Combinator.constant_of(nil) if statements_node.nil?
1446
-
1447
- statements_type_for(statements_node)
1448
- end
1449
-
1450
1042
  def type_of_virtual(node)
1451
1043
  case node
1452
1044
  when AST::TypeNode then node.type
@@ -1511,17 +1103,6 @@ module Rigor
1511
1103
  Type::Combinator.positive_int
1512
1104
  end
1513
1105
 
1514
- # `# shareable_constant_value:` magic comment wraps the next constant write. Type is the wrapped
1515
- # write's value.
1516
- def type_of_shareable_constant(node)
1517
- type_of(node.write)
1518
- end
1519
-
1520
- # `{ x: }` shorthand hash. The implicit value is the call to `x` (or a local read of `x`). Delegate.
1521
- def type_of_implicit(node)
1522
- type_of(node.value)
1523
- end
1524
-
1525
1106
  def local_read(node)
1526
1107
  scope.local(node.name) || dynamic_top
1527
1108
  end
@@ -1532,43 +1113,6 @@ module Rigor
1532
1113
  scope.local(:it) || dynamic_top
1533
1114
  end
1534
1115
 
1535
- # Slice 5 phase 1 upgrades array literals to `Tuple[T1..Tn]` when every element is a non-splat value.
1536
- # Splatted entries (`[*xs, 1]`) preserve the Slice 4 phase 2d behavior: we union the contributed
1537
- # element types and emit `Nominal[Array, [union]]`.
1538
- #
1539
- # v0.0.6 — the empty literal `[]` resolves to the empty `Tuple[]` carrier rather than the raw
1540
- # `Nominal[Array]`. Both carriers erase to RBS `Array`, but `Tuple[]` pins the literal's known arity
1541
- # (zero), which lets the per-element block fold concatenate across all-empty positions like `[1,
1542
- # 2].flat_map { |_| [] }`.
1543
- def array_type_for(node)
1544
- elements = node.elements
1545
- return Type::Combinator.tuple_of if elements.empty?
1546
-
1547
- if elements.any?(Prism::SplatNode)
1548
- element_types = elements.map { |e| type_of(e) }
1549
- element_union = Type::Combinator.union(*element_types)
1550
- return Type::Combinator.nominal_of(Array, type_args: [element_union])
1551
- end
1552
-
1553
- Type::Combinator.tuple_of(*elements.map { |e| type_of(e) })
1554
- end
1555
-
1556
- def parentheses_type_for(node)
1557
- body = node.body
1558
- return Type::Combinator.constant_of(nil) if body.nil?
1559
-
1560
- type_of(body)
1561
- end
1562
-
1563
- def statements_type_for(statements_node)
1564
- return Type::Combinator.constant_of(nil) if statements_node.nil?
1565
-
1566
- body = statements_node.body
1567
- return Type::Combinator.constant_of(nil) if body.empty?
1568
-
1569
- type_of(body.last)
1570
- end
1571
-
1572
1116
  # Indexed-collection narrowing — `receiver[key]` after a prior `receiver[key] ||= default` reads the
1573
1117
  # post-`||=` type when the receiver and key are stable enough to address. Sits ahead of
1574
1118
  # `MethodDispatcher.dispatch` so the standard `Hash#[]` / `Array#[]` answer (which would fold to
@@ -1595,114 +1139,10 @@ module Rigor
1595
1139
  end
1596
1140
  end
1597
1141
 
1598
- # v0.0.3 A — implicit-self calls prefer a same-named top-level `def` over RBS dispatch. Without this, a
1599
- # helper like `def select(...)` defined inside an `RSpec.describe ... do ... end` block mis-routes
1600
- # through `Enumerable#select` / `Object#select` and the caller observes `Array[Elem]` instead of the
1601
- # helper's actual return type. The check fires only for `node.receiver.nil?` (true implicit self), so
1602
- # explicit-receiver dispatch is unaffected.
1603
- #
1604
- # Issue #316 — the lookup goes through the confidence-gated `Scope#bindable_top_level_def_for`, not the
1605
- # raw table: inside a block whose `self` is unmodelled, a top-level `def` from ANOTHER file is not
1606
- # evidence about which method the call reaches, so the bind is declined and the call widens.
1607
- #
1608
- # Issue #618 — the binding is a fallback for names the enclosing `self` does NOT answer, not a
1609
- # first-choice tier. A top-level `def` is a private method on `Object`, the last link of every MRO, so
1610
- # whenever the call's own `self` carries the name the class wins at runtime and the top-level body is
1611
- # never reached. Binding regardless of `self_type` inverted that: a top-level `def text` typed the
1612
- # member read inside `class Line < Struct.new(:text); def shout = text.upcase; end` as the def's `nil`
1613
- # and fired `undefined method 'upcase' for nil` on correct code. The candidate is still looked up
1614
- # first — that lookup is a hash probe and owns the ADR-46 cross-file dependency edge — and
1615
- # {#self_type_answers?} then vetoes the bind for a name the enclosing class answers itself.
1616
- #
1617
- # Issue #963 item 2 — {#plugin_member_answers?} is the second veto, for the members no source the
1618
- # engine walks can enumerate: a plugin's `dynamic_return` answer and the ADR-16 synthetic-method
1619
- # index. They are members of `self` exactly as an `attr_reader` is, so a top-level `def` must not
1620
- # bind ahead of them either.
1621
- #
1622
- # Issue #2861 — a bind the #316 gate declines answers `Dynamic[Top]`, never the RBS method of the same name: the
1623
- # block's real `self` reaches either a same-named method of its own or the top-level `def`, which shadows
1624
- # `Kernel#format` and every other `Object` / `Kernel` method on the way. Falling through typed
1625
- # `format(r).bit_length` against `Kernel#format`'s `String` on code that runs the project's `def format`.
1626
- def try_local_def_dispatch(node, receiver, arg_types, block_type = nil)
1627
- return nil unless node.receiver.nil?
1628
-
1629
- local_def = scope.bindable_top_level_def_for(node.name)
1630
- return declined_top_level_def_answer(node) if local_def.nil?
1631
- return nil if self_type_answers?(node.name)
1632
- return nil if plugin_member_answers?(node, receiver)
1633
-
1634
- local_inference = infer_top_level_user_method(local_def, receiver, node, arg_types, block_type)
1635
- return local_inference if local_inference
1636
-
1637
- # The local def matches by name but the inference was disqualified — the parameter shape is too
1638
- # complex for the first-iteration binder (kwargs / optionals / rest), so the body could not be
1639
- # re-typed. `Dynamic[Top]` is the safest answer: RBS dispatch would be wrong (the method is
1640
- # user-defined and shadows whatever ancestor method the dispatch would find), and `Dynamic[Top]`
1641
- # propagates correctly through downstream call chains without surfacing misleading false-positive
1642
- # diagnostics.
1643
- dynamic_top
1644
- end
1645
-
1646
- # Issue #2861 — the answer for an implicit-self call whose top-level `def` the #316 gate declined: nil (dispatch
1647
- # as before) when the project defines no top-level `def` of the name, else `Dynamic[Top]`. The gate declines only
1648
- # where `self_type` is nil, so no member of `self` ({#self_type_answers?}, {#plugin_member_answers?}) can answer.
1649
- def declined_top_level_def_answer(node)
1650
- return nil unless scope.opaque_block_self? && scope.self_type.nil?
1651
- return nil if scope.top_level_def_for(node.name).nil?
1652
-
1653
- dynamic_top
1654
- end
1655
-
1656
- # ADR-110 WD1 / #856 — the receiver's own `def` outranks a declaration that only an ANCESTOR carries.
1657
- #
1658
- # RBS resolves through the fully built method table, so `RbsDispatch` answers a subclass call with a
1659
- # signature written about the base. redmine's `FieldFormat::Base#target_class` honestly declares
1660
- # `-> nil`; `RecordList` overrides it with a real lookup, and every call on a `RecordList` receiver
1661
- # typed as `nil` and fired `undefined method ... for nil` on the subclass's own working code (#744).
1662
- # A signature is authoritative for a receiver only where someone wrote it about that receiver;
1663
- # reaching it through an ancestor is a lookup convenience, not an act of authorship.
1664
- #
1665
- # This is {#try_local_def_dispatch}'s shape one level up — there the enclosing class shadows a
1666
- # top-level `def`, here the receiver's class shadows an ancestor's declaration — and it answers the
1667
- # same way: re-type the override's body, and when that is not possible answer `Dynamic[Top]` rather
1668
- # than let the inherited declaration speak for a method it does not describe.
1669
- #
1670
- # Three conditions, and the third is the blast radius. Clause A of the ADR (an own source `def`, no
1671
- # own declaration) does NOT by itself stay clear of [ADR-43]: `class Foo; def each; end` inheriting
1672
- # `Enumerable#each` satisfies it, and disqualifying bundled declarations that way is the blanket fix
1673
- # ADR-43 rejected — the same reason {#instance_self_answers?}'s RBS arm is own-class only. So the
1674
- # ancestor whose declaration is being disqualified must itself be PROJECT-declared: a project sidecar
1675
- # describes the source under analysis, while a bundled signature describes a class the project does
1676
- # not own, where a project `def` is a monkey-patch and [ADR-17] owns the question.
1677
- # `project_declared_class?` fail-softs to false, so an unattributable environment changes nothing.
1678
- def try_overriding_def_dispatch(node, receiver, arg_types, method_name: node.name)
1679
- return nil unless overriding_own_def?(receiver, method_name)
1680
-
1681
- try_user_method_inference(receiver, node, arg_types, method_name: method_name) || dynamic_top
1682
- end
1683
-
1684
- # The three conditions above: an own source `def` of `method_name` on the receiver's class, which has no
1685
- # declaration of its own but inherits one a project-declared ancestor wrote.
1686
- def overriding_own_def?(receiver, method_name)
1687
- return false unless user_inference_receiver?(receiver)
1688
-
1689
- class_name = receiver.class_name
1690
- return false if class_name.nil?
1691
- # `Scope#user_def_for`, not `discovered_method?`: the cross-file table deliberately withholds a
1692
- # plain instance `def` under the ADR-17 monkey-patch contract, and this gate must see one.
1693
- return false if scope.user_def_for(class_name, method_name).nil?
1694
-
1695
- definition = safe_rbs_method_definition(class_name, method_name, :instance)
1696
- return false if definition.nil?
1697
- return false if rbs_declared_on_class?(definition, class_name)
1698
-
1699
- project_declared_owner?(definition)
1700
- end
1701
-
1702
- # {#implicit_index_read_type}'s dispatcher tier, with the write node as the call context.
1703
- def index_read_dispatch(node, receiver, arg_types)
1704
- MethodDispatcher.dispatch(
1705
- receiver_type: receiver, method_name: :[], arg_types: arg_types,
1142
+ # {#implicit_index_read_type}'s site: the `[]` read, with the write node as the call node and no block.
1143
+ def index_read_site(node, receiver, arg_types)
1144
+ MethodDispatcher::CallContext.build(
1145
+ receiver: receiver, method_name: :[], args: arg_types,
1706
1146
  environment: scope.environment, call_node: node, scope: scope
1707
1147
  )
1708
1148
  end
@@ -1710,147 +1150,22 @@ module Rigor
1710
1150
  # A splat index (`c[*keys] += v`) leaves the read's arity to the splat's expansion, and the one untyped
1711
1151
  # argument standing in for it would bind positionally to a body written for several: `def [](*keys) =
1712
1152
  # keys.size` folded the read of `r[*[0, 1]] += 1` to `1` and drew an always-falsey `n == 3` on a program
1713
- # that takes that branch. So the body tiers decline under a splat, as `try_literal_send` does, and only
1153
+ # that takes that branch. So the body tiers decline under a splat, as `CallLadder::LiteralSend` does, and only
1714
1154
  # the signature-driven dispatch answers. An own `def` overriding an inherited declaration still outranks
1715
- # that declaration; with its body unreadable, it answers `Dynamic[top]`.
1155
+ # that declaration; with its body unreadable, it answers `Dynamic[top]` ({CallLadder::EXCEPTIONS}).
1716
1156
  def splat_index_read_type(node, receiver, arg_types)
1717
- return dynamic_top if overriding_own_def?(receiver, :[])
1157
+ return dynamic_top if CallLadder::OverridingDef.overriding_own_def?(receiver, :[], self)
1718
1158
 
1719
- index_read_dispatch(node, receiver, arg_types)
1720
- end
1721
-
1722
- # Whether the class an inherited declaration was written about is one the project declares itself.
1723
- def project_declared_owner?(definition)
1724
- defined_in = definition.defined_in
1725
- return false if defined_in.nil?
1726
-
1727
- Rigor::Reflection.project_declared_class?(defined_in.to_s, scope: scope)
1728
- rescue StandardError
1729
- false
1730
- end
1731
-
1732
- # Issue #618 — whether the call's enclosing `self` already answers `method_name`. Only a `self` whose
1733
- # class is KNOWN participates: at genuine top level, and inside a block whose `self` is unmodelled,
1734
- # `scope.self_type` is nil, the predicate is false, and the historical top-level binding stands — that
1735
- # is #316's / #319's territory and this veto stays out of it.
1736
- #
1737
- # The ADR-48 member carriers answer from their own map first: a `StructInstance` / `DataInstance`
1738
- # `self` carries the member set the body reads through, and an anonymous `Struct.new(...)` value has no
1739
- # class name to look anything else up under.
1740
- def self_type_answers?(method_name)
1741
- case (self_type = scope.self_type)
1742
- when Type::Singleton then singleton_self_answers?(self_type.class_name, method_name)
1743
- when Type::Nominal then instance_self_answers?(self_type.class_name, method_name)
1744
- when Type::StructInstance, Type::DataInstance
1745
- self_type.members.key?(method_name.to_sym) || instance_self_answers?(self_type.class_name, method_name)
1746
- else false
1747
- end
1748
- end
1749
-
1750
- # Issue #963 item 2 — the plugin arm of the veto: whether a plugin answers `node.name` on the call's
1751
- # own `self`. Asked of `MethodDispatcher.plugin_member_answers?`, which puts the question to the same
1752
- # two tiers dispatch would consult (the gated `dynamic_return` walk and the ADR-16 synthetic-method
1753
- # index), so the veto carries no plugin knowledge of its own.
1754
- #
1755
- # The confidence gate is #618's, unchanged and re-stated here rather than inherited: only a `self`
1756
- # whose class is KNOWN participates. At genuine top level, and inside a block whose `self` is
1757
- # unmodelled, `scope.self_type` is nil, `receiver` is the synthetic `Object` / `Dynamic[Top]` stand-in
1758
- # that {#call_receiver_type_for} substitutes, and asking a plugin about THAT receiver would be asking
1759
- # about a `self` the engine has not modelled — #316's / #319's territory, which this stays out of.
1760
- def plugin_member_answers?(node, receiver)
1761
- return false if scope.self_type.nil?
1762
-
1763
- MethodDispatcher.plugin_member_answers?(
1764
- call_node: node, scope: scope, receiver_type: receiver, method_name: node.name
1765
- )
1766
- end
1767
-
1768
- # The instance side of {#self_type_answers?}: the discovered methods (`def`, `attr_*`,
1769
- # `define_method`, `alias`) of the class or any project ancestor, its `Struct.new` / `Data.define`
1770
- # member accessors, a `def` reached through its project ancestors (superclass chain and included
1771
- # modules), and an RBS method declared on an owner that PRECEDES `::Object` in the MRO.
1772
- #
1773
- # Issue #633 — the discovery arm walks ancestors because inheritance does not distinguish how a
1774
- # method got there: a superclass `attr_accessor :stext` and an included module's `attr_reader` bind
1775
- # ahead of a top-level `def stext` exactly as an inherited `def` does, and only the latter had a walk.
1776
- #
1777
- # The RBS arm's cut-off is `::Object`, not the own class. A top-level `def` IS a private `Object`
1778
- # instance method, the last link of every MRO, so any declared owner that comes before `::Object`
1779
- # wins at runtime — `Exception#message` for a `StandardError` subclass, `Array#first`,
1780
- # `Comparable#clamp`. What the cut-off keeps out is the tier v0.0.3 A exists for and #316 / #319
1781
- # refined: a name owned by `Object` or `Kernel` themselves (`inspect`, `format`) is at or after the
1782
- # top-level `def`'s own rung, so the historical binding still stands there.
1783
- def instance_self_answers?(class_name, method_name)
1784
- return false if class_name.nil?
1785
- return true if scope.discovered_method_through_ancestors?(class_name, method_name, :instance)
1786
- return true if meta_member?(class_name, method_name)
1787
- return true if resolve_user_def_through_ancestors(class_name, method_name)
1788
- return true if rbs_ancestor_answers?(class_name, method_name)
1789
-
1790
- # Issue #2968 — a class on the chain defines methods under names no table holds (`attr_accessor(*FLAGS)`, a
1791
- # splatted `Struct.new(*FIELDS)`), so the name may be one of them, ahead of the top-level `def`.
1792
- return true if Scope::DiscoveryIndex.open_names_on_chain?(scope, class_name, :instance)
1793
-
1794
- # Issue #2994 — a class on the chain mixes in a module no table names (`include(*MODS)`, `include helper`), so
1795
- # the name may be that module's, ahead of the top-level `def`.
1796
- Scope::DiscoveryIndex.unnamed_mixin_on_chain?(scope, class_name)
1797
- end
1798
-
1799
- # The RBS arm of {#instance_self_answers?}. A project class is usually absent from the RBS
1800
- # environment, so the declaration that decides the question is written about an ancestor the project
1801
- # does not declare (`StandardError`, `Array`, `Comparable`) — each is asked on its own terms, and
1802
- # each of them is itself before `::Object` in the reader's MRO by construction.
1803
- #
1804
- # Issue #527 slice 0 — the walk itself lives in {ExternalAncestorResolution}, which reports WHICH
1805
- # declaration answered because the dispatch side needs to dispatch there. This tier only needs to
1806
- # know that one did, so it reads the presence of an answer. Dependency recording stays ON: this
1807
- # arm genuinely read the ancestor's declaration to decide the binding.
1808
- def rbs_ancestor_answers?(class_name, method_name)
1809
- !ExternalAncestorResolution.resolve(class_name, method_name, :instance, scope: scope).nil?
1810
- end
1811
-
1812
- # The singleton side: a class-body `self` is `Singleton[Foo]`, where an implicit-self call reaches
1813
- # `Foo`'s own class methods before `Object`'s private top-level `def`.
1814
- #
1815
- # Issue #633 — both discovery arms follow the superclass chain, because a subclass inherits its
1816
- # parent's class methods; `Scope` narrows the singleton walk to superclasses for the same reason
1817
- # (an `include`d module's `def self.x` is not callable on the includer).
1818
- def singleton_self_answers?(class_name, method_name)
1819
- return false if class_name.nil?
1820
- return true if scope.discovered_method_through_ancestors?(class_name, method_name, :singleton)
1821
- return true unless scope.singleton_def_through_ancestors(class_name, method_name).first.nil?
1822
-
1823
- declared = safe_rbs_method_definition(class_name, method_name, :singleton)
1824
- return true if rbs_declared_on_class?(declared, class_name)
1825
-
1826
- # Issue #2994 — a class object on the chain that a module no table names may extend through a hook (the
1827
- # `:include_hook` open mark of a class with `include(*MODS)`), a class that `extend(*EMODS)`s, or an extended
1828
- # module whose own module set is unknown, may answer any name ahead of the top-level `def`.
1829
- Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods).unnamed_mixin?
1830
- end
1831
-
1832
- # A `Struct.new(:a, :b)` / `Data.define(:a, :b)` member accessor. The layouts are a discovery table of
1833
- # their own, separate from `discovered_methods`, so the accessor names they imply have to be asked for
1834
- # explicitly. Only the reader name is tested: a writer is unreachable as an implicit-self call, since
1835
- # bare `a = v` is a local assignment.
1836
- def meta_member?(class_name, method_name)
1837
- layout = scope.struct_member_layout(class_name)
1838
- members = layout ? layout[:members] : scope.data_member_layout(class_name)
1839
- !members.nil? && members.include?(method_name.to_sym)
1159
+ MethodDispatcher.dispatch_site(index_read_site(node, receiver, arg_types))
1840
1160
  end
1841
1161
 
1842
1162
  # Issue #527 slice 0 — the RBS lookup, its `rescue`, and the `::Object` MRO cut-off moved to
1843
- # {ExternalAncestorResolution}, which the dispatch side reads too. These stay as this class's
1844
- # spelling of them, because three other tiers here (`try_overriding_def_dispatch`,
1845
- # {#singleton_self_answers?}) ask the own-class question without the ancestor walk.
1163
+ # {ExternalAncestorResolution}, which the dispatch side reads too. This stays as this class's
1164
+ # spelling of it, because {#core_finder_member?} asks the own-class question without the ancestor walk.
1846
1165
  def safe_rbs_method_definition(class_name, method_name, kind)
1847
1166
  ExternalAncestorResolution.method_definition(class_name, method_name, kind, scope: scope)
1848
1167
  end
1849
1168
 
1850
- def rbs_declared_on_class?(definition, class_name)
1851
- ExternalAncestorResolution.declared_on_class?(definition, class_name)
1852
- end
1853
-
1854
1169
  # Issue #520 — Ruby defines the value of an attribute / index assignment (`x.attr = v`, `h[k] = v`)
1855
1170
  # as the RHS object itself, whatever the writer method returns. The dispatch pipeline still runs
1856
1171
  # first for everything it observes on the side (effect collection, provenance, recorders, and the
@@ -2212,6 +1527,10 @@ module Rigor
2212
1527
  block_return_type_for(node, receiver, []).is_a?(Type::Bot)
2213
1528
  end
2214
1529
 
1530
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class: the refined rung
1531
+ # ({CallLadder::Refined}) re-enters the ladder here for each member of a union receiver no refinement wins.
1532
+ #
1533
+ # The call ladder: {CallLadder::RUNGS} (`call_ladder.rb`) declares this order, and its spec holds the code to it.
2215
1534
  def call_result_type_for(node, receiver_override: nil)
2216
1535
  narrowed = indexed_narrowing_for(node)
2217
1536
  return narrowed if narrowed
@@ -2225,13 +1544,23 @@ module Rigor
2225
1544
  # asks nothing further of dispatch. Off (the default) this is one integer read.
2226
1545
  Effects::Collector.record_call(node, receiver, scope) if Effects::Collector.active?
2227
1546
 
2228
- refined = try_refined_dispatch(node, receiver, arg_types, block_type)
1547
+ # ADR-116 WD12 — the call's site, built once and asked of every rung that takes one.
1548
+ site = MethodDispatcher::CallContext.build(
1549
+ receiver: receiver,
1550
+ method_name: node.name,
1551
+ args: arg_types,
1552
+ block_type: block_type,
1553
+ environment: scope.environment,
1554
+ call_node: node,
1555
+ scope: scope
1556
+ )
1557
+ refined = CallLadder::Refined.try_call(site, self)
2229
1558
  return refined if refined
2230
1559
 
2231
- literal_send = try_literal_send(node, receiver)
1560
+ literal_send = CallLadder::LiteralSend.try_call(site, self)
2232
1561
  return literal_send if literal_send
2233
1562
 
2234
- local_def_result = try_local_def_dispatch(node, receiver, arg_types, block_type)
1563
+ local_def_result = CallLadder::TopLevelDef.try_call(site, self)
2235
1564
  return local_def_result if local_def_result
2236
1565
 
2237
1566
  # v0.0.6 phase 2 — per-element block fold for Tuple receivers. When `[a, b, c].map { |x| f(x) }` and
@@ -2242,179 +1571,13 @@ module Rigor
2242
1571
  block_fold = try_receiver_block_folds(node, receiver, arg_types)
2243
1572
  return block_fold if block_fold
2244
1573
 
2245
- overriding_def = try_overriding_def_dispatch(node, receiver, arg_types)
1574
+ overriding_def = CallLadder::OverridingDef.try_call(site, self)
2246
1575
  return overriding_def if overriding_def
2247
1576
 
2248
- result = MethodDispatcher.dispatch(
2249
- receiver_type: receiver,
2250
- method_name: node.name,
2251
- arg_types: arg_types,
2252
- block_type: block_type,
2253
- environment: scope.environment,
2254
- call_node: node,
2255
- scope: scope
2256
- )
1577
+ result = MethodDispatcher.dispatch_site(site)
2257
1578
  return result if result
2258
1579
 
2259
- dispatch_miss_result(node, receiver, arg_types, block_type)
2260
- end
2261
-
2262
- # ADR-121 WD2 (issue #1664) — a call through an in-effect Ruby refinement, typed from the winning refine body
2263
- # with the call's receiver as `self`, ahead of every tier below: each answers from the method the refinement
2264
- # replaces (a refined `String#upcase` must not fold, a refined `map` must not fold per element, a top-level
2265
- # `def` must not bind ahead of a refinement of `Object`, a plugin models the class's own method). An unreadable
2266
- # body, or a list that may hold any refinement, answers `Dynamic[top]`, never the replaced method's signature.
2267
- # A union receiver is decided per member; a `Dynamic` receiver and a call no refinement wins fall through. A
2268
- # class object walks its own lookup (issue #1752): under `refine(Object) { def oo = :o }` a refinement that wins
2269
- # `Integer.oo` answers `Dynamic[top]` ({#refined_class_object_result}). A call site no refinement is in effect
2270
- # at answers nil at once and records nothing: its answer cannot change without an edit to its own file.
2271
- #
2272
- # ADR-121 WD7 (A2) — inside the span of an activation that puts an opaque module in effect
2273
- # ({InEffectRefinements.opaque_module?}), any method of any object may be replaced, so every call on an instance
2274
- # or a class object answers `Dynamic[top]`.
2275
- def try_refined_dispatch(node, receiver, arg_types, block_type)
2276
- list = scope.in_effect_refinements(node)
2277
- return nil if list.empty?
2278
-
2279
- InEffectRefinements.record_refinement_names(node.name)
2280
- return dynamic_top if refined_receiver?(receiver) && opaque_refinement_span?(node, list)
2281
- return nil if scope.discovered_refinements.empty?
2282
-
2283
- refined_indirect_result(node, receiver, list) ||
2284
- refined_receiver_result(node, receiver, list, arg_types, block_type)
2285
- end
2286
-
2287
- # ADR-121 WD4 — `send` / `__send__` / `public_send` with a literal name, `respond_to?` and `method` /
2288
- # `public_method` with one, and a `&:name` block argument honour refinements too (CRuby `test_refinement.rb`;
2289
- # probed on Ruby 4.0.5). When the name they reach is refined in effect for the receiver they answer
2290
- # `Dynamic[top]`: typing them through the arm is deferred, and `respond_to?` must never fold to `false`. A
2291
- # `&:name` block's receiver is the yielded element, which is not known here, so any in-effect refinement of the
2292
- # name answers. Only `methods` ignores refinements and keeps its answer.
2293
- def refined_indirect_result(node, receiver, list)
2294
- name = REFINED_NAMING_CALLS.include?(node.name) ? literal_method_name_argument(node) : nil
2295
- return dynamic_top if name && refined_name_for?(receiver, name, list)
2296
-
2297
- block_name = symbol_block_argument(node)
2298
- dynamic_top if block_name && RefinedDispatch.refined_anywhere?(scope, block_name, list)
2299
- end
2300
-
2301
- REFINED_NAMING_CALLS = Set[:send, :__send__, :public_send, :respond_to?, :method, :public_method].freeze
2302
- private_constant :REFINED_NAMING_CALLS
2303
-
2304
- def literal_method_name_argument(node)
2305
- argument = node.arguments&.arguments&.first
2306
- name = argument.unescaped if argument.is_a?(Prism::SymbolNode) || argument.is_a?(Prism::StringNode)
2307
- return nil if name.nil?
2308
-
2309
- name = name.to_sym
2310
- InEffectRefinements.record_refinement_names(name)
2311
- name
2312
- end
2313
-
2314
- def symbol_block_argument(node)
2315
- block = node.block
2316
- return nil unless block.is_a?(Prism::BlockArgumentNode) && block.expression.is_a?(Prism::SymbolNode)
2317
-
2318
- name = block.expression.unescaped.to_sym
2319
- InEffectRefinements.record_refinement_names(name)
2320
- name
2321
- end
2322
-
2323
- def refined_name_for?(receiver, name, list)
2324
- members = receiver.is_a?(Type::Union) ? receiver.members : [receiver]
2325
- members.any? do |member|
2326
- next !RefinedDispatch.winner(scope, member.class_name, name, list, kind: :singleton).nil? if
2327
- member.is_a?(Type::Singleton)
2328
-
2329
- class_name = refined_receiver_class_name(member)
2330
- !class_name.nil? && !RefinedDispatch.winner(scope, class_name, name, list).nil?
2331
- end
2332
- end
2333
-
2334
- # ADR-121 WD7 — does the call's lexical list (a plugin-declared module is the plugin's declaration and never
2335
- # opaque) hold an opaque module? `list` is the full list, which is the lexical one when nothing is declared.
2336
- def opaque_refinement_span?(node, list)
2337
- lexical = scope.declared_refinements.empty? ? list : scope.in_effect_refinements(node, InEffectRefinements::EMPTY)
2338
- InEffectRefinements.opaque_in?(scope, lexical)
2339
- end
2340
-
2341
- # Does `receiver` (or a member of a union) have a lookup the refined arm answers for: an instance of a class,
2342
- # or a class object (issue #1752), not `Dynamic`?
2343
- def refined_receiver?(receiver)
2344
- members = receiver.is_a?(Type::Union) ? receiver.members : [receiver]
2345
- members.any? { |member| member.is_a?(Type::Singleton) || !refined_receiver_class_name(member).nil? }
2346
- end
2347
-
2348
- def refined_receiver_result(node, receiver, list, arg_types, block_type)
2349
- return refined_member_result(node, receiver, list, arg_types, block_type) unless receiver.is_a?(Type::Union)
2350
-
2351
- answers = receiver.members.map { |member| refined_member_result(node, member, list, arg_types, block_type) }
2352
- return nil if answers.none?
2353
-
2354
- members = receiver.members.each_with_index.map do |member, index|
2355
- answers[index] || call_result_type_for(node, receiver_override: member)
2356
- end
2357
- Type::Combinator.union(*members)
2358
- end
2359
-
2360
- def refined_member_result(node, receiver, list, arg_types, block_type)
2361
- return refined_class_object_result(node, receiver, list, arg_types, block_type) if
2362
- receiver.is_a?(Type::Singleton)
2363
-
2364
- class_name = refined_receiver_class_name(receiver)
2365
- return nil if class_name.nil?
2366
-
2367
- winner = RefinedDispatch.winner(scope, class_name, node.name, list)
2368
- return nil if winner.nil?
2369
- return dynamic_top if winner == RefinedDispatch::UNKNOWN
2370
-
2371
- refined_body_return(winner, node, Type::Combinator.nominal_of(class_name), arg_types, block_type) ||
2372
- dynamic_top
2373
- end
2374
-
2375
- # Issue #1752 — a call on a class object, walked through its singleton levels. A refinement that wins answers
2376
- # `Dynamic[top]`, never its refine body's type: a hook on any ancestor (an RBS-declared `include Singleton`, a
2377
- # gem concern, `define_singleton_method(:included)`, a `Module#included` patch) can install the class object's
2378
- # own method where no table sees it, and the body's type then fires downstream on correct code. A walk that finds
2379
- # no winner keeps the class object's own answer (`Integer.sqrt(16)` stays `Integer`).
2380
- def refined_class_object_result(node, receiver, list, _arg_types, _block_type)
2381
- winner = RefinedDispatch.winner(scope, receiver.class_name, node.name, list, kind: :singleton)
2382
- dynamic_top unless winner.nil?
2383
- end
2384
-
2385
- # The winning refine body's inferred return, re-typed with the receiver's class as `self` and the call's
2386
- # argument types bound as an undeclared method's are; nil when the body is not readable here.
2387
- #
2388
- # A body another file wrote is re-typed with that file's in-effect refinements at the `def` (its own module
2389
- # among them), so a sibling override it calls answers from its refine body too.
2390
- def refined_body_return(winner, call_node, self_type, arg_types, block_type)
2391
- def_node, foreign =
2392
- InEffectRefinements.refinement_def_with_query(scope, winner.module_name, winner.refined_class, call_node.name)
2393
- return nil if def_node.nil?
2394
-
2395
- refinements = foreign&.at(def_node.location.start_offset) do |name|
2396
- InEffectRefinements.activated_modules(scope, name)
2397
- end
2398
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
2399
- infer_user_method_return(def_node, self_type, arg_types, yield_type: block_type, refinements: refinements,
2400
- positionals_unknown: positionals_unknown)
2401
- rescue StandardError
2402
- nil
2403
- end
2404
-
2405
- # The class an instance-side receiver is an instance of, or nil for one this instance walk does not answer: a
2406
- # class object (it walks its own lookup, {#refined_class_object_result}), `Dynamic`, `top`, or a shape with no
2407
- # class.
2408
- def refined_receiver_class_name(receiver)
2409
- case receiver
2410
- when Type::Nominal, Type::StructInstance, Type::DataInstance then receiver.class_name
2411
- when Type::Constant then receiver.value.class.name
2412
- when Type::Tuple then "Array"
2413
- when Type::HashShape then "Hash"
2414
- when Type::IntegerRange then "Integer"
2415
- when Type::FloatRange then "Float"
2416
- when Type::Refined, Type::Difference then refined_receiver_class_name(receiver.base)
2417
- end
1580
+ dispatch_miss_result(site, node, receiver)
2418
1581
  end
2419
1582
 
2420
1583
  # Issue #1237 — whether the call's argument list leaves the positional correspondence unknown: it holds a
@@ -2430,6 +1593,8 @@ module Rigor
2430
1593
  (forwards_arguments?(arguments) && ExpressionTyper.current_forwarded_arg_types.nil?)
2431
1594
  end
2432
1595
 
1596
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class.
1597
+ #
2433
1598
  # The argument list and the `positionals_unknown:` flag a body tier re-types a user `def` with. Under
2434
1599
  # {#splat_arguments?} the body is still re-typed, so a body that always raises still answers `bot` and a
2435
1600
  # return that does not read its arguments is kept, but with no positional correspondence
@@ -2562,13 +1727,13 @@ module Rigor
2562
1727
  end
2563
1728
  end
2564
1729
 
2565
- # The post-dispatch tiers for a call `MethodDispatcher` could not answer, in their historical
2566
- # order; extracted from {#call_dispatch_type_for} whole.
2567
- def dispatch_miss_result(node, receiver, arg_types, block_type = nil)
1730
+ # The rungs below the dispatcher, for a call `MethodDispatcher` could not answer: {#call_result_type_for}
1731
+ # continues here, in the order of {CallLadder::RUNGS}.
1732
+ def dispatch_miss_result(site, node, receiver)
2568
1733
  # v0.0.2 #5 — inter-procedural inference for user-defined methods. When dispatch misses but the
2569
1734
  # receiver is a user class with a `def` body, re-type the body with the call's argument types bound
2570
1735
  # and return the body's last-expression type.
2571
- user_inference = try_user_method_inference(receiver, node, arg_types, block_type: block_type)
1736
+ user_inference = CallLadder::UserMethod.try_call(site, self)
2572
1737
  return user_inference if user_inference
2573
1738
 
2574
1739
  # Module-singleton call resolution (ADR-57 follow-up) — when the receiver is `Singleton[Foo]` (a
@@ -2576,7 +1741,7 @@ module Rigor
2576
1741
  # `module_function` body, re-type that body with the call args bound. Sits after the RBS dispatch
2577
1742
  # tier, so foreign / RBS-known singletons (`Math.sqrt`) keep their catalog answer; only
2578
1743
  # project-defined singleton methods reach here.
2579
- singleton_inference = try_project_singleton_inference(receiver, node, arg_types, block_type: block_type)
1744
+ singleton_inference = CallLadder::ProjectSingleton.try_call(site, self)
2580
1745
  return singleton_inference if singleton_inference
2581
1746
 
2582
1747
  # Dynamic-origin propagation: when the receiver is Dynamic[T] and no positive rule resolves the call,
@@ -2641,7 +1806,7 @@ module Rigor
2641
1806
  # Issue #522 — the honest cause for a call the tiers exhausted. When the receiver's class HAS a
2642
1807
  # discovered project def for the method, the miss is a return the engine could not infer (the
2643
1808
  # discovered-method tier deliberately declined in favor of body inference, which then declined too —
2644
- # `MethodDispatcher#try_discovered_method`'s decline arms), which is ADR-82's
1809
+ # `MethodDispatcher::DiscoveredMethod.try_dispatch`'s decline arms), which is ADR-82's
2645
1810
  # `INFERRED_RETURN_UNTYPED`, not "unsupported syntax". Without this, every service-object `#call`
2646
1811
  # whose body defeats inference reports to `coverage --protection` as a syntax gap. The generic cause
2647
1812
  # stays for genuinely unresolved names (framework DSL sends, methods no scanned file defines).
@@ -2765,26 +1930,6 @@ module Rigor
2765
1930
  scope.discovered_method?(class_name, method_name, :singleton)
2766
1931
  end
2767
1932
 
2768
- # v0.0.2 #5 — re-types the body of a user-defined instance method with the call site's argument types
2769
- # bound to the method's parameters. Used as a last-resort tier after `MethodDispatcher.dispatch` has
2770
- # exhausted its catalogue (RBS, shape, constant folding, user-class fallback). Returns nil when:
2771
- #
2772
- # - the receiver is not `Nominal[T]` for some T;
2773
- # - no def_node is recorded for that class/method (the receiver is foreign or has only an RBS sig);
2774
- # - the def has no body, or has a parameter shape we cannot bind from the call's positional args.
2775
- # v0.0.3 A — re-types a top-level (or DSL-block-nested) `def` discovered by `ScopeIndexer` under the
2776
- # `TOP_LEVEL_DEF_KEY` sentinel. Mirrors the `infer_user_method_return` shape but uses the current
2777
- # `scope.self_type` (or implicit `Object`) as the receiver carrier so the body's own self is
2778
- # consistent with the call site's. Returns nil when the parameter shape disqualifies the def, when the
2779
- # body is empty, or when the inference raises.
2780
- def infer_top_level_user_method(def_node, receiver, call_node, arg_types, block_type = nil)
2781
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
2782
- infer_user_method_return(def_node, receiver, arg_types, yield_type: block_type,
2783
- positionals_unknown: positionals_unknown)
2784
- rescue StandardError
2785
- nil
2786
- end
2787
-
2788
1933
  # ADR-24 slice 1 — implicit-self method-call resolution. `discovered_def_nodes` is now carried into
2789
1934
  # method / class body scopes (see `StatementEvaluator#build_fresh_body_scope`), so a call written with
2790
1935
  # no explicit receiver inside a method body resolves against the enclosing class's own definitions and
@@ -2793,516 +1938,77 @@ module Rigor
2793
1938
  # The resolved return type is adopted UNCONDITIONALLY — a resolved user-method call site reads the
2794
1939
  # callee's inferred return, exactly as a toplevel call has since v0.0.3.
2795
1940
  #
2796
- # ADR-24 WD3 originally gated this: inside a class / method body only a `Bot` return was adopted,
2797
- # everything else stayed `Dynamic[top]`, because an early unconditional-adoption experiment regressed
2798
- # `rigor check lib` by 16 diagnostics. ADR-55 / ADR-56 then chipped the gate open for the
2799
- # recursive-fixpoint summary and the value-pinned unroll envelope. ADR-57 closed the arc: it re-ran the
2800
- # gate-open experiment per engine generation and adjudicated every firing as genuine-or-artifact,
2801
- # fixing the artifacts at their root — the tail-only body evaluator dropping explicit `return` (slice
2802
- # 1), multi-value returns not contributing a Tuple (slice 1), escaping block-captured content mutation
2803
- # surviving as a precise seed both inline and across a method boundary (slices 2/3), two over-strict
2804
- # self-authored RBS signatures (slice 1), and an over-optional tuple-slot destructure (slice 3). With
2805
- # the residual all genuine-or-win, the gate opened permanently on 2026-06-12 (ADR-57 WD2): the
2806
- # gate-open `rigor check lib` + plugin self-check delta is zero, and the Mastodon / haml / kramdown
2807
- # corpora show only adjudicated wins (a more precise error message; FP removals).
2808
- #
2809
- # The historical `adoptable_self_call_result?` predicate (its `self_type.nil?` / `Bot` /
2810
- # fixpoint-summary / unroll special cases) is now subsumed by unconditional adoption and removed;
2811
- # `try_local_def_dispatch` / `try_user_method_inference` simply return the inferred return.
2812
- # `clamp_unroll_result` still backstops an untrustworthy unrolled value independently of adoption.
2813
-
2814
- # An extended (value-keyed) guard frame is `[plain_signature, value_key]` where `plain_signature` is
2815
- # itself the `[receiver, method]` pair; a plain frame is that pair directly.
2816
- def extended_frame?(frame)
2817
- frame.is_a?(Array) && frame.size == 2 && frame.first.is_a?(Array)
2818
- end
2819
-
2820
- # The plain `(receiver, method)` signature carried by a guard frame: the frame itself for a plain
2821
- # frame, or its first element for an extended (value-keyed) frame.
2822
- def plain_part(frame)
2823
- extended_frame?(frame) ? frame.first : frame
2824
- end
2825
-
2826
- # True when `type` is a concrete value — a `Type::Constant` or a `Type::Tuple` whose elements are
2827
- # (recursively) all value-pinned. ADR-55 slice 1: a value-pinned self-call result is adopted even
2828
- # inside a class/method body (where WD3 otherwise keeps non-`Bot` returns as `Dynamic[top]`). A concrete
2829
- # value at a call site is strictly more precise and can never enable an undefined-method or argument-type
2830
- # false positive — it is FP-neutral by construction.
2831
- def fully_value_pinned?(type)
2832
- case type
2833
- when Type::Constant then true
2834
- when Type::Tuple then type.elements.all? { |element| fully_value_pinned?(element) }
2835
- when Type::HashShape
2836
- # Issue #3115 — the shape {#pinned_shape_descriptor} keys an unroll on is as pinned as a result.
2837
- type.closed? && type.optional_keys.empty? && type.pairs.each_value.all? { |value| fully_value_pinned?(value) }
2838
- else false
2839
- end
2840
- end
2841
-
2842
- # #525 — instance-side user-method inference accepts the named ADR-48 member carriers alongside
2843
- # plain nominals: a `Line = Struct.new(...) do ... end` value is a StructInstance whose block defs
2844
- # live under "Line", and the carrier itself is the right `self` for the body (member reads inside
2845
- # the def project through it).
2846
- def user_inference_receiver?(receiver)
2847
- case receiver
2848
- when Type::Nominal then true
2849
- when Type::StructInstance, Type::DataInstance then !receiver.class_name.nil?
2850
- else false
2851
- end
2852
- end
2853
-
2854
- # The three receiver-shaped block folds, in their historical order (extracted whole from
2855
- # `call_dispatch_type_for` for method-length budget).
2856
- def try_receiver_block_folds(node, receiver, arg_types)
2857
- rebound = rebound_operand_typer(node)
2858
- return rebound.send(:try_receiver_block_folds, node, receiver, arg_types) if rebound
2859
-
2860
- per_element = try_per_element_block_fold(node, receiver)
2861
- return per_element if per_element
2862
-
2863
- inject_fold = try_block_inject_fold(node, receiver, arg_types)
2864
- return inject_fold if inject_fold
2865
-
2866
- try_hash_shape_block_fold(node, receiver)
2867
- end
2868
-
2869
- # Issue #1365 — Ruby runs a call's receiver chain and arguments before the method yields, so when they may
2870
- # rebind the match globals ({MatchRebinding.operands_may_rebind?}: `[u.index(/(q)/)].map { $1 }`) every
2871
- # pass that types the call's block — the block-return pass, its captured-local fixpoint and the receiver
2872
- # folds — types it under a typer whose scope has forgotten them, as {MatchRebinding.block_entry} does for
2873
- # the call's block and `StatementEvaluator#forget_operand_specials` for the statement. `$_` is forgotten on
2874
- # the same terms when they may set it ({LastLine.operands_may_set?}, issue #1359). nil otherwise.
2875
- def rebound_operand_typer(call_node)
2876
- return nil if call_node.block.nil?
2877
-
2878
- rebound = scope
2879
- if rebound.match_globals_bound? && MatchRebinding.operands_may_rebind?(call_node, scope)
2880
- rebound = rebound.forget_match_globals
2881
- end
2882
- rebound = rebound.forget_last_line if rebound.last_line_bound? && LastLine.operands_may_set?(call_node, scope)
2883
- return nil if rebound.equal?(scope)
2884
-
2885
- ExpressionTyper.new(scope: rebound, tracer: tracer, operand_types: @operand_types, typing_node: @typing_node)
2886
- end
2887
-
2888
- # Issue #533 — `x.send(:selector, args)` with a LITERAL symbol is statically `x.selector(args)`:
2889
- # the private-boundary idiom (protobuf's `send(:get_file_descriptor)` at 84 sites) resolves through
2890
- # the same dispatch + project-inference tiers as the direct call would. `send` legitimately crosses
2891
- # visibility, so no public-only gate applies (`public_send` is treated identically — typing the
2892
- # success path of a call that would raise on a private method is ADR-5 optimism). Declines: a
2893
- # non-literal selector, a splat / forwarded tail (positional correspondence unknown), or a block at
2894
- # the call site (block forwarding is out of this slice).
2895
- LITERAL_SEND_SELECTORS = %i[send __send__ public_send].freeze
2896
- private_constant :LITERAL_SEND_SELECTORS
2897
-
2898
- def try_literal_send(node, receiver)
2899
- return nil unless LITERAL_SEND_SELECTORS.include?(node.name)
2900
- return nil unless node.block.nil?
2901
-
2902
- args = node.arguments&.arguments
2903
- return nil unless args && args.first.is_a?(Prism::SymbolNode)
2904
-
2905
- rest = args[1..]
2906
- return nil if rest.any? { |a| a.is_a?(Prism::SplatNode) || a.is_a?(Prism::ForwardingArgumentsNode) }
2907
-
2908
- inner_name = args.first.unescaped.to_sym
2909
- inner_args = rest.map { |a| type_of(a) }
2910
- MethodDispatcher.dispatch(
2911
- receiver_type: receiver, method_name: inner_name, arg_types: inner_args,
2912
- block_type: nil, environment: scope.environment, call_node: node, scope: scope
2913
- ) ||
2914
- try_user_method_inference(receiver, node, inner_args, method_name: inner_name) ||
2915
- try_project_singleton_inference(receiver, node, inner_args, method_name: inner_name)
2916
- end
2917
-
2918
- def try_user_method_inference(receiver, call_node, arg_types, method_name: call_node.name, block_type: nil)
2919
- return nil unless user_inference_receiver?(receiver)
2920
-
2921
- def_node, owner, raising = resolve_typing_def_with_owner(receiver.class_name, method_name)
2922
- return every_definer_raises_type(raising, receiver, call_node, arg_types, block_type) if def_node.nil?
2923
-
2924
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
2925
- result = infer_user_method_return(def_node, receiver, arg_types,
2926
- self_fold_safe: fold_safe_call_receiver?(call_node),
2927
- yield_type: block_type, positionals_unknown: positionals_unknown)
2928
- return result if result.nil?
2929
-
2930
- degrade_if_overridable(result, owner, method_name, :instance)
2931
- rescue StandardError
2932
- nil
2933
- end
2934
-
2935
- # Issue #525 — whether the RECEIVER EXPRESSION of this call is one whose struct member map is still
2936
- # current. Three arms:
2937
- #
2938
- # - a call that MATERIALISES the struct (`Point.new(…)`, `Point[…]`, `Struct.new(:x).new(…)`, a
2939
- # `.with(…)` copy) — the object was created by this very expression, so nothing has run against it;
2940
- # - a local the fold-safe scan proved is never mutated / aliased / escaped;
2941
- # - `nil` / `self`, inheriting the CURRENT body's own grant, which is what lets a chain of
2942
- # implicit-self readers propagate: `Line.new(…).outer` grants `outer`'s body `:self`, and an
2943
- # `inner` call inside it carries the grant into `inner`'s body.
2944
- #
2945
- # The first arm shares `StructFolding`'s materialisation test with the direct member-read gate. Neither
2946
- # accepts a bare chained call: "chained" is not "fresh" once a method can hand back its own receiver,
2947
- # and a self-returning fluent builder is ordinary Ruby:
2948
- #
2949
- # Line = Struct.new(:text) do
2950
- # def with_text(v) = (self.text = v; self)
2951
- # def shout = text.upcase
2952
- # end
2953
- # Line.new("a").with_text("z").shout # runtime "Z"
2954
- #
2955
- # Accepting the `with_text(…)` receiver as fresh would grant `shout` a member map two statements
2956
- # stale and fold `"A"`. Only the shapes the folding layer itself materialises qualify here.
2957
- #
2958
- # This is only a property of the receiver expression; whether the grant is actually issued also needs
2959
- # a `StructInstance` carrier and a body that survives the self-use scan, both decided in
2960
- # {#build_user_method_body_scope}.
2961
- def fold_safe_call_receiver?(call_node)
2962
- return false if call_node.nil?
2963
-
2964
- case call_node.receiver
2965
- when Prism::CallNode then materialization_call?(call_node.receiver)
2966
- when Prism::LocalVariableReadNode then scope.struct_fold_safe?(call_node.receiver.name)
2967
- when nil, Prism::SelfNode then scope.struct_fold_safe?(:self)
2968
- else false
2969
- end
2970
- end
2971
-
2972
- # Issue #595 — the materialisation test lives ONCE, in
2973
- # [`struct_materialization.rb`](method_dispatcher/struct_materialization.rb), because the direct
2974
- # member-read gate ({MethodDispatcher::StructFolding}`#fresh_receiver?`) needs the identical answer;
2975
- # see {MethodDispatcher::StructMaterialization.materialization_call?}. A `.with` call is never one
2976
- # (`Struct` has no `#with`, #1335), so the test needs no lookup from either consumer.
2977
- def materialization_call?(node)
2978
- MethodDispatcher::StructMaterialization.materialization_call?(node, scope)
2979
- end
2980
-
2981
- # Module-singleton call resolution (ADR-57 follow-up) — resolves `Foo.<name>` on a `Singleton[Foo]`
2982
- # receiver against `Foo`'s user-side singleton defs (`def self.x`, `def Foo.x`, a `class << self`
2983
- # body, or a `module_function` method) and re-types the body with the call's argument types bound.
2984
- # The body scope's `self_type` is the SAME `Singleton[Foo]` carrier, so an implicit-self call inside
2985
- # (`def self.via; helper(x); end`) re-enters this tier and resolves against the same singleton table
2986
- # — the symmetric counterpart of the instance-side ancestor walk.
2987
- #
2988
- # Issue #731 — resolution walks the SUPERCLASS chain, so a class method a base class defines answers
2989
- # on its subclasses (`class Plain < Base` with `def self.build` on `Base`: `Plain.build` was
2990
- # `Dynamic[top]` while `Plain.new.inst` resolved on the same fixture). Superclasses only, which is the
2991
- # whole shape of class-method inheritance — an `include`d module's `def self.x` is not callable on the
2992
- # includer, and `extend M` is already folded into the extender's own singleton entries by
2993
- # `ScopeIndexer`. A miss still degrades to `Dynamic[top]`, never a false resolution.
2994
- #
2995
- # The OWNER — not the receiver class — is what the overridable gate keys on, exactly as the instance
2996
- # side does: adopting `Base`'s literal return is unsound when a subclass redefines the method, and
2997
- # after this change the resolved body is routinely not the receiver's own.
2998
- def try_singleton_method_inference(receiver, call_node, arg_types, method_name: call_node.name,
2999
- block_type: nil)
3000
- return nil unless receiver.is_a?(Type::Singleton)
3001
-
3002
- def_node, owner = resolve_singleton_def_with_owner(receiver.class_name, method_name)
3003
- return nil if def_node.nil?
3004
- # Issue #1936 — a contested slot holds a `def` a later definer may have replaced
3005
- # (`singleton_class.alias_method :x, :y` after `def self.x`), or one that may not have run: its body is not
3006
- # proven to be the method Ruby calls, so the call falls through to `Dynamic`.
3007
- return nil if scope.discovery.contested?(:discovered_singleton_def_nodes, [owner, method_name.to_sym])
3008
-
3009
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
3010
- result = infer_user_method_return(def_node, receiver, arg_types, yield_type: block_type,
3011
- positionals_unknown: positionals_unknown)
3012
- return result if result.nil?
3013
-
3014
- degrade_if_overridable(result, owner, method_name, :singleton)
3015
- rescue StandardError
3016
- nil
3017
- end
3018
-
3019
- # The singleton twin of {#resolve_user_def_with_owner}. Memoised in a bucket nested under the
3020
- # SINGLETON def table's identity as well as the class-graph trio: `class_graph_buckets` keys on
3021
- # `discovered_def_nodes` / `discovered_superclasses` / `discovered_includes`, and this walk reads a
3022
- # fourth table those three do not imply. Keying on what the answer actually depends on is the #682
3023
- # lesson — a memo that outlives its inputs serves one scope's answer to another.
3024
- #
3025
- # It is the TYPING read only, so it also withholds (`[nil, nil]`, the call types `Dynamic`) where an external
3026
- # ancestor may answer ahead of the definer found (#1572: `extend M; extend Enumerable` makes `C.to_a`
3027
- # `Enumerable#to_a`, which the reader passes over). The existence reads keep the reader's own answer.
3028
- def resolve_singleton_def_with_owner(class_name, method_name)
3029
- by_singleton = (class_graph_buckets[:singleton_def] ||= {}.compare_by_identity)
3030
- cache = (by_singleton[scope.discovered_singleton_def_nodes] ||= {})
3031
- table = (cache[class_name.to_s] ||= {})
3032
- key = method_name.to_sym
3033
- if table.key?(key)
3034
- return MemoAudit.check("class graph singleton def", table[key], class_name, key) do
3035
- compute_singleton_def_with_owner(class_name, method_name)
3036
- end
3037
- end
3038
-
3039
- table[key] = MemoAudit.key_audit("class graph singleton def") do
3040
- compute_singleton_def_with_owner(class_name, method_name)
3041
- end
3042
- end
3043
-
3044
- def compute_singleton_def_with_owner(class_name, method_name)
3045
- found = scope.singleton_def_through_ancestors(class_name, method_name)
3046
- owner = found.last
3047
- found = [nil, nil] if owner && SingletonExternalAhead.withhold?(scope, class_name, method_name, owner)
3048
- found = [nil, nil] if found.last && dynamic_singleton_definer_ahead?(class_name, method_name, found.last)
3049
- found = [nil, nil] if found.last && singleton_hook_order_split?(class_name, method_name)
3050
- found = [nil, nil] if found.last && singleton_mixin_split?(class_name, method_name, found)
3051
- found = [nil, nil] if found.last && unseen_definer_split?(class_name, method_name, found)
3052
- found
3053
- end
3054
-
3055
- # A definer no def table holds that Ruby may call instead of `found`: a hook-placed one, or a foreign `def C.x`.
3056
- def unseen_definer_split?(class_name, method_name, found)
3057
- hidden_hook_split?(class_name, method_name, found.last) || foreign_definer_behind_copy?(method_name, found)
3058
- end
3059
-
3060
- # Issue #3155 — a `def C.x` outside C's body (in the extended module, another class or the file) defines C's
3061
- # own `x`, which no def table holds, only its object-singleton mark. A fold copy found on C may then be a
3062
- # body Ruby does not call, so the typing read withholds.
3063
- def foreign_definer_behind_copy?(method_name, found)
3064
- node, owner = found
3065
- return false unless singleton_copy_head(owner, node) != owner
3066
-
3067
- SingletonHookDecline.foreign_singleton_definer?(scope, owner, method_name)
3068
- end
3069
-
3070
- # The hook-placed definers a found singleton `def` may not be the one Ruby calls through.
3071
- def hidden_hook_split?(class_name, method_name, owner)
3072
- hidden_hook_definer?(class_name, method_name, owner) || hook_block_rival?(class_name, method_name, owner)
3073
- end
3074
-
3075
- # Issue #3005 — a class object's own `def self.x` and a `def self.x` a concern's `included` block defines on it
3076
- # replace each other in the order the `def` and the `include` run, which the tables do not hold, so the typing
3077
- # read withholds when the answer is a class object's own `def` and its level's hook-block module defines the
3078
- # name too.
3079
- def hook_block_rival?(class_name, method_name, owner)
3080
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3081
- index = chain.entries.index { |entry| !entry.external? && entry.side == :singleton && entry.name == owner }
3082
- !index.nil? && chain.hook_block_rival?(scope, index, method_name)
3083
- end
3084
-
3085
- # Issue #1592 — a module a hook extends the class with may define the name private (`class_methods do private;
3086
- # def x`), which Ruby refuses on an explicit receiver. The visibility rule does not reach that module, so the
3087
- # typing read withholds rather than answer a call Ruby raises on. A module the class `extend`s itself is left to
3088
- # that rule.
3089
- def hidden_hook_definer?(class_name, method_name, owner)
3090
- visibility = scope.discovered_method_visibility(owner, method_name)
3091
- return false if visibility.nil? || visibility == :public
3092
-
3093
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3094
- return false unless chain.entries.any? { |entry| entry.name == owner && entry.side == :instance }
3095
-
3096
- scope.singleton_extends_of(class_name).none? do |raw|
3097
- written = raw.delete_prefix("::")
3098
- owner == written || owner.end_with?("::#{written}")
3099
- end
3100
- end
3101
-
3102
- # Issue #1592 — whether to withhold `method_name`'s class-side answer: a class object on the chain has
3103
- # hook-extended modules whose order against its own `extend`s is not a fact, and the orders give different
3104
- # definers (the retro world's against the chain's, or, with no retro world, the class objects' alone against
3105
- # the chain's). A `def` the extends fold copied onto a class object is read where Ruby finds it, at the extended
3106
- # module's own entry, since the copy sits ahead of every module in both orders.
3107
- def singleton_hook_order_split?(class_name, method_name)
3108
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3109
- return false unless chain.hook_order_marked?
3110
-
3111
- answer = positioned_singleton_definer(chain, method_name)
3112
- retro = chain.retro_world
3113
- return answer != positioned_singleton_definer(retro, method_name) if retro
3114
-
3115
- answer != positioned_singleton_definer(chain, method_name, copies: true)
3116
- end
3117
-
3118
- # Issues #2998 and #3020 — whether a singleton-side mixin of a class object on the chain may answer ahead of
3119
- # `found`: a named prepend master's order does not place, or a module no table names.
3120
- def singleton_mixin_split?(class_name, method_name, found)
3121
- singleton_prepend_split?(class_name, method_name, found) ||
3122
- unnamed_singleton_mixin_split?(class_name, method_name)
3123
- end
3124
-
3125
- # Issue #2998 — whether to withhold the class-side answer `found` on a chain whose class objects have
3126
- # singleton-side prepends of their own: master's order, which a chain that does not stand answers, places no
3127
- # such prepend, so its definer may not be the one Ruby's order reaches first. A `def` the extends fold copied
3128
- # onto a class object is compared as its module's. A definer from a prepend region whose order is not a fact
3129
- # is withheld whichever order answers.
3130
- def singleton_prepend_split?(class_name, method_name, found)
3131
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3132
- return false unless chain.singleton_prepend_marked?
3133
-
3134
- answer = positioned_singleton_definer(chain, method_name)
3135
- return true if unordered_prepend_definer?(chain, answer)
3136
-
3137
- node, owner = found
3138
- head = scope.singleton_def_for(owner, method_name).equal?(node) ? singleton_copy_head(owner, node) : owner
3139
- head != answer
3140
- end
3141
-
3142
- # Whether `answer` is a module in the prepend region of a class object on the chain whose prepends have no known
3143
- # order: the entries between the start of that class's level and its own entry.
3144
- def unordered_prepend_definer?(chain, answer)
3145
- chain.prepend_order_nodes.any? do |node|
3146
- level = chain.level_classes.index(node)
3147
- next true if level.nil?
3148
-
3149
- start = chain.level_starts[level]
3150
- own = chain.entries.index { |entry| entry.side == :singleton && entry.name == node }
3151
- next true if own.nil?
3152
-
3153
- chain.entries[start...own].any? { |entry| entry.name == answer }
3154
- end
3155
- end
3156
-
3157
- # Issue #3020 — whether to withhold the class-side answer on a chain whose class objects mix a module no table
3158
- # names into their singleton side, which may define the name. A prepend (`class << self; prepend(*MODS)`) sits
3159
- # ahead of the class object's own `def self.`, so a definer at or behind that class object's level is withheld;
3160
- # an `extend(*MODS)` or a `class << self` `include(*MODS)` sits right behind it, so a definer behind the class
3161
- # object's own entry is withheld and its own `def self.` still answers.
3162
- def unnamed_singleton_mixin_split?(class_name, method_name)
3163
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3164
- prepends = chain.unnamed_prepend_nodes
3165
- extends = chain.unnamed_extend_nodes
3166
- return false if prepends.empty? && extends.empty?
3167
-
3168
- answer = positioned_singleton_definer(chain, method_name)
3169
- prepends.any? { |node| !answered_ahead?(chain, answer, level_start_of(chain, node)) } ||
3170
- extends.any? { |node| !answered_ahead?(chain, answer, own_singleton_index(chain, node)&.succ) }
3171
- end
1941
+ # ADR-24 WD3 originally gated this (inside a class / method body only a `Bot` return was adopted,
1942
+ # everything else stayed `Dynamic[top]`). ADR-55 / ADR-56 chipped the gate open, and ADR-57 adjudicated
1943
+ # every remaining firing as genuine-or-artifact, fixing the artifacts at their root; the gate opened
1944
+ # permanently on 2026-06-12 (ADR-57 WD2) with a zero `rigor check lib` + plugin self-check delta.
1945
+ #
1946
+ # The `adoptable_self_call_result?` predicate is subsumed by unconditional adoption and removed;
1947
+ # `CallLadder::TopLevelDef.try_call` / `CallLadder::UserMethod.infer` simply return the inferred return.
1948
+ # `clamp_unroll_result` still backstops an untrustworthy unrolled value independently of adoption.
3172
1949
 
3173
- # Whether `answer` owns an entry before `stop` (nil when the position is unknown: never). A nil `answer` (no class
3174
- # object's own def) owns none.
3175
- def answered_ahead?(chain, answer, stop)
3176
- !stop.nil? && chain.entries[0...stop].any? { |entry| entry.name == answer }
1950
+ # An extended (value-keyed) guard frame is `[plain_signature, value_key]` where `plain_signature` is
1951
+ # itself the `[receiver, method]` pair; a plain frame is that pair directly.
1952
+ def extended_frame?(frame)
1953
+ frame.is_a?(Array) && frame.size == 2 && frame.first.is_a?(Array)
3177
1954
  end
3178
1955
 
3179
- def level_start_of(chain, node)
3180
- level = chain.level_classes.index(node)
3181
- level && chain.level_starts[level]
1956
+ # The plain `(receiver, method)` signature carried by a guard frame: the frame itself for a plain
1957
+ # frame, or its first element for an extended (value-keyed) frame.
1958
+ def plain_part(frame)
1959
+ extended_frame?(frame) ? frame.first : frame
3182
1960
  end
3183
1961
 
3184
- def own_singleton_index(chain, node)
3185
- chain.entries.index { |entry| entry.side == :singleton && entry.name == node }
1962
+ # True when `type` is a concrete value — a `Type::Constant` or a `Type::Tuple` whose elements are
1963
+ # (recursively) all value-pinned. ADR-55 slice 1: a value-pinned self-call result is adopted even
1964
+ # inside a class/method body (where WD3 otherwise keeps non-`Bot` returns as `Dynamic[top]`). A concrete
1965
+ # value at a call site is strictly more precise and can never enable an undefined-method or argument-type
1966
+ # false positive — it is FP-neutral by construction.
1967
+ def fully_value_pinned?(type)
1968
+ case type
1969
+ when Type::Constant then true
1970
+ when Type::Tuple then type.elements.all? { |element| fully_value_pinned?(element) }
1971
+ when Type::HashShape
1972
+ # Issue #3115 — the shape {#pinned_shape_descriptor} keys an unroll on is as pinned as a result.
1973
+ type.closed? && type.optional_keys.empty? && type.pairs.each_value.all? { |value| fully_value_pinned?(value) }
1974
+ else false
1975
+ end
3186
1976
  end
3187
1977
 
3188
- # The owner of the first `def` of the name along the chain: a fold copy is skipped, or with `copies:` read as
3189
- # its module's, on the class objects alone (the answer master gives).
3190
- def positioned_singleton_definer(chain, method_name, copies: false)
3191
- chain.search(scope, side: copies ? :singleton : nil) do |entry|
3192
- next if entry.external?
1978
+ # The three receiver-shaped block folds, in their historical order (extracted whole from
1979
+ # `call_result_type_for` for method-length budget).
1980
+ def try_receiver_block_folds(node, receiver, arg_types)
1981
+ rebound = rebound_operand_typer(node)
1982
+ return rebound.send(:try_receiver_block_folds, node, receiver, arg_types) if rebound
3193
1983
 
3194
- name = entry.name
3195
- if entry.side == :singleton
3196
- node = scope.singleton_def_for(name, method_name)
3197
- next nil if node.nil?
1984
+ per_element = try_per_element_block_fold(node, receiver)
1985
+ return per_element if per_element
3198
1986
 
3199
- head = singleton_copy_head(name, node)
3200
- copies ? head : (name if head == name)
3201
- elsif scope.user_def_for(name, method_name)
3202
- name
3203
- end
3204
- end
3205
- end
1987
+ inject_fold = try_block_inject_fold(node, receiver, arg_types)
1988
+ return inject_fold if inject_fold
3206
1989
 
3207
- # The module a receiverless singleton `def` was written in when the extends fold copied it onto `owner`, else
3208
- # `owner`.
3209
- def singleton_copy_head(owner, node)
3210
- head = node.receiver.nil? ? scope.discovery.recorded_def_nesting(node)&.first : nil
3211
- head.nil? ? owner : head
3212
- end
3213
-
3214
- SINGLETON_WILDCARD_SLOT = %i[singleton *].freeze
3215
- private_constant :SINGLETON_WILDCARD_SLOT
3216
-
3217
- # Issue #2284 — a project entry nearer than the `def`'s owner on the singleton chain may define the name
3218
- # without a `def`, which the def tables do not hold: `class S < B; define_singleton_method(:x) { "s" }; end`
3219
- # calls S's block, not `B.x`. The farther `def` is then withheld and the call types `Dynamic`. A class's own
3220
- # singleton side is read from the visibility-contest census: `define_singleton_method(:x)`,
3221
- # `singleton_class.define_method(:x)` / `attr_*` and a computed name contest the entry's slot whether or not a
3222
- # `def` is recorded (#1984, #2013). An `extend`ed module's side is read from `discovered_methods`, which holds
3223
- # its `attr_*` and `define_method` rows, and the module's `def self.extended` hook may define any name on the
3224
- # extender, so it withholds too.
3225
- #
3226
- # An `inherited` hook anywhere on the chain past the receiver's own entry runs when the receiver's class is
3227
- # created and may define any singleton method on it (`def self.inherited(s) = s.define_singleton_method(:x)`),
3228
- # so a `def` the receiver only inherits is withheld then as well: a class's `def self.inherited`, or an
3229
- # `inherited` an extended module defines.
3230
- def dynamic_singleton_definer_ahead?(class_name, method_name, owner)
3231
- name = method_name.to_sym
3232
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :singleton, :methods)
3233
- return true if class_name.to_s != owner.to_s && inherited_hook_on_chain?(chain, class_name.to_s)
3234
-
3235
- chain.entries.each do |entry|
3236
- next if entry.external?
3237
- return false if entry.name == owner.to_s
3238
- return true if entry_defines_without_def?(entry, name)
3239
- # Issue #1592 — a hook of a module the class includes may have extended it with a module no table names.
3240
- return true if entry.side == :singleton && chain.hook_open_nodes.include?(entry.name)
3241
- end
3242
- false
1990
+ try_hash_shape_block_fold(node, receiver)
3243
1991
  end
3244
1992
 
3245
- def inherited_hook_on_chain?(chain, receiver_name)
3246
- chain.entries.any? do |entry|
3247
- next false if entry.external? || entry.name == receiver_name
3248
-
3249
- if entry.side == :singleton
3250
- !scope.singleton_def_for(entry.name, :inherited).nil?
3251
- else
3252
- scope.discovered_method?(entry.name, :inherited, :instance)
3253
- end
3254
- end
3255
- end
1993
+ # Issue #1365 — Ruby runs a call's receiver chain and arguments before the method yields, so when they may
1994
+ # rebind the match globals ({MatchRebinding.operands_may_rebind?}: `[u.index(/(q)/)].map { $1 }`) every
1995
+ # pass that types the call's block — the block-return pass, its captured-local fixpoint and the receiver
1996
+ # folds — types it under a typer whose scope has forgotten them, as {MatchRebinding.block_entry} does for
1997
+ # the call's block and `StatementEvaluator#forget_operand_specials` for the statement. `$_` is forgotten on
1998
+ # the same terms when they may set it ({LastLine.operands_may_set?}, issue #1359). nil otherwise.
1999
+ def rebound_operand_typer(call_node)
2000
+ return nil if call_node.block.nil?
3256
2001
 
3257
- def entry_defines_without_def?(entry, name)
3258
- unless entry.side == :singleton
3259
- return scope.discovered_method?(entry.name, name, :instance) ||
3260
- !scope.singleton_def_for(entry.name, :extended).nil?
2002
+ rebound = scope
2003
+ if rebound.match_globals_bound? && MatchRebinding.operands_may_rebind?(call_node, scope)
2004
+ rebound = rebound.forget_match_globals
3261
2005
  end
2006
+ rebound = rebound.forget_last_line if rebound.last_line_bound? && LastLine.operands_may_set?(call_node, scope)
2007
+ return nil if rebound.equal?(scope)
3262
2008
 
3263
- discovery = scope.discovery
3264
- # No edge of its own: `singleton_def_through_ancestors`' chain search filed every entry ahead of the owner.
3265
- discovery.contested?(:discovered_method_visibilities, [entry.name, [:singleton, name]]) ||
3266
- discovery.contested?(:discovered_method_visibilities, [entry.name, SINGLETON_WILDCARD_SLOT])
3267
- end
3268
-
3269
- # The project-side singleton-method band: a `Foo.bar` call resolved against a `class << …` / `def self.…`
3270
- # body the project itself wrote. Which of the two tiers applies is decided by the receiver carrier —
3271
- # `Singleton[Foo]` when the constant names a class or module, `Nominal[…]` when it holds an ordinary
3272
- # object (#320) — so the two are mutually exclusive and consulting both is one resolution attempt.
3273
- def try_project_singleton_inference(receiver, call_node, arg_types, method_name: call_node.name,
3274
- block_type: nil)
3275
- kwargs = { method_name: method_name, block_type: block_type }
3276
- try_singleton_method_inference(receiver, call_node, arg_types, **kwargs) ||
3277
- try_singleton_object_constant_inference(receiver, call_node, arg_types, **kwargs)
3278
- end
3279
-
3280
- # #320 — resolves a call whose receiver is a constant holding an ordinary object with a `class << Const`
3281
- # singleton body, re-typing that body with the call's argument types bound. `self` inside the body IS
3282
- # that object, so the receiver carrier is passed through unchanged. Own-constant only, and only for a
3283
- # name the project actually recorded — a miss degrades to today's `Dynamic[top]`, never a false
3284
- # resolution. `Singleton` receivers never reach here: {#try_singleton_method_inference} owns them.
3285
- def try_singleton_object_constant_inference(receiver, call_node, arg_types, method_name: call_node.name,
3286
- block_type: nil)
3287
- return nil unless receiver.is_a?(Type::Nominal)
3288
-
3289
- def_node = SingletonObjectConstant.def_node_for(call_node, receiver, method_name, scope)
3290
- return nil if def_node.nil?
3291
-
3292
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
3293
- infer_user_method_return(def_node, receiver, arg_types, yield_type: block_type,
3294
- positionals_unknown: positionals_unknown)
3295
- rescue StandardError
3296
- nil
2009
+ ExpressionTyper.new(scope: rebound, tracer: tracer, operand_types: @operand_types, typing_node: @typing_node)
3297
2010
  end
3298
2011
 
3299
- # ADR-24 slice 2 — resolves `method_name` against the project definers on `class_name`'s
3300
- # {Scope::ResolutionChain}, in Ruby's order: prepended modules, the class, its included modules, then the
3301
- # superclass's chain likewise. RBS-known ancestors are NOT answered here — the `MethodDispatcher` RBS
3302
- # tier runs before `try_user_method_inference` and already covers them; they sit on the chain as
3303
- # external entries this lookup passes over. Cross-file: the chain is built from the tables the runner
3304
- # seeds from the project-wide pre-pass, cycle-guarded and capped at `Scope::ANCESTOR_WALK_LIMIT`.
3305
-
3306
2012
  CLASS_GRAPH_CACHE = TypingState.memo(
3307
2013
  :class_graph_cache,
3308
2014
  run_scoped: true,
@@ -3312,6 +2018,8 @@ module Rigor
3312
2018
  )
3313
2019
  private_constant :CLASS_GRAPH_CACHE
3314
2020
 
2021
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class.
2022
+ #
3315
2023
  # Memo for the static class-graph resolvers below. They are pure functions of the scope's *frozen*
3316
2024
  # discovery tables — `user_def_for` / `superclass_of` / `includes_of` and the ancestor-name resolver
3317
2025
  # read nothing else, and never touch the current scope's locals or narrowings — so a result computed
@@ -3354,7 +2062,7 @@ module Rigor
3354
2062
  unless slot && slot[0].equal?(discovery)
3355
2063
  # `self_pure` is issue #525's grant scan (identity-keyed by def node); it belongs here because it
3356
2064
  # is a pure function of the same frozen index — the sibling resolver it walks reads nothing else.
3357
- # `singleton_def` is added lazily by {#singleton_def_through_ancestors}'s caller.
2065
+ # `singleton_def` is added lazily by {CallLadder::ProjectSingleton.resolve_singleton_def_with_owner}.
3358
2066
  slot = [discovery, fresh_class_graph_buckets]
3359
2067
  state[CLASS_GRAPH_CACHE] = slot
3360
2068
  end
@@ -3365,119 +2073,14 @@ module Rigor
3365
2073
  { user_def: {}, typing_def: {}, self_pure: {}.compare_by_identity, yields: {}.compare_by_identity }
3366
2074
  end
3367
2075
 
3368
- # ADR-119 C2-b1 — the TYPING read of {#resolve_user_def_with_owner}: the same `[def_node, owner]` pair, but
3369
- # answered through {DefinerResolution} so a chain that does not stand for the name (a conditional definer,
3370
- # a conditional include, a fork, an external ancestor that may answer first) is `[nil, nil]` and the call
3371
- # types `Dynamic` instead of from a definer Ruby may not reach. ABSENT is the same `[nil, nil]`: at a typing
3372
- # site "no definer" and "cannot say" both fall through to `dispatch_miss_result`. Existence reads
3373
- # ({#resolve_user_def_through_ancestors}, the self-purity scan) stay on the union memo above: an existence
3374
- # read turning false there could ADD a `call.undefined-method` firing.
2076
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class.
3375
2077
  #
3376
- # UNKNOWN carries a third element, the `bot` exception's definers ({#every_project_definer}): the def nodes
3377
- # of every project entry on the chain that defines the name, or nil where the exception cannot apply.
3378
- def resolve_typing_def_with_owner(class_name, method_name)
3379
- cache = class_graph_buckets[:typing_def]
3380
- table = (cache[class_name.to_s] ||= {})
3381
- key = method_name.to_sym
3382
- if table.key?(key)
3383
- return MemoAudit.check("class graph typing def", table[key], class_name, key) do
3384
- compute_typing_def_with_owner(class_name, method_name)
3385
- end
3386
- end
3387
-
3388
- table[key] = MemoAudit.key_audit("class graph typing def") do
3389
- compute_typing_def_with_owner(class_name, method_name)
3390
- end
3391
- end
3392
-
3393
- def compute_typing_def_with_owner(class_name, method_name)
3394
- case DefinerResolution.resolve(scope, class_name, method_name, :instance, question: :definer)
3395
- in DefinerResolution::Known(answer: [node, owner])
3396
- [node, owner]
3397
- in DefinerResolution::UNKNOWN
3398
- [nil, nil, every_project_definer(class_name, method_name)]
3399
- in DefinerResolution::ABSENT
3400
- [nil, nil]
3401
- end
3402
- end
3403
-
3404
- # ADR-119 C2-b1 errata (the `bot` exception) — an UNKNOWN chain does not say WHICH definer Ruby calls, but
3405
- # when every project definer of the name on the chain types `bot` (each raises or exits), the call cannot
3406
- # return whichever of them runs, so it types `bot` and a guard such as `fail_with 'no' unless count` still
3407
- # narrows. `defs` is {#every_project_definer}'s list; each is inferred with this call's receiver and
3408
- # arguments, stopping at the first that returns (the answer is then `Dynamic` whatever the rest say).
3409
- # Accepted cost: an RBS-unknown external ahead of them that really defines the name and returns is a
3410
- # narrowing false negative; `bot` reports nothing about a value, and that exposure is master's.
3411
- def every_definer_raises_type(defs, receiver, call_node, arg_types, block_type)
3412
- return nil if defs.nil?
3413
-
3414
- self_fold_safe = fold_safe_call_receiver?(call_node)
3415
- arg_types, positionals_unknown = positional_correspondence(call_node, arg_types)
3416
- defs.each do |def_node|
3417
- result = infer_user_method_return(def_node, receiver, arg_types,
3418
- self_fold_safe: self_fold_safe, yield_type: block_type,
3419
- positionals_unknown: positionals_unknown)
3420
- return nil unless result.is_a?(Type::Bot)
3421
- end
3422
- Type::Combinator.bot
3423
- end
3424
-
3425
- # The def node of every project entry on `class_name`'s instance chain that defines `method_name`, in any
3426
- # position (the order is what UNKNOWN does not know), or nil where the `bot` exception cannot apply: a cut
3427
- # chain, no project definer, an entry whose only record of the name has no body (an `attr_*` or a
3428
- # `define_method` with no `def`), a definer resting on a `possible` or contested fact (another body may be the
3429
- # one Ruby holds), or an external RBS knows that declares the name. An external RBS does not know is passed
3430
- # over. Only what the tables hold is read: a `define_method` beside an entry's own `def` of the name, and a
3431
- # receiver-form `X.include(M)` outside `X`'s body, are not seen (as on the Known path).
3432
- #
3433
- # ADR-46: the answer depends on every entry, so each files its class edge and its negative class edge (a new
3434
- # file reopening it may add a definer or a mixin), and each project entry's {Scope#user_def_for} files the
3435
- # method edge, positive for a definer and `read_missing(:method, "Owner#name")` for one that lacks the
3436
- # `def`. `DefinerResolution`'s decline filed none of this past the external that stopped it.
3437
- def every_project_definer(class_name, method_name)
3438
- chain = Scope::ResolutionChain.for(scope, class_name.to_s, :instance, :methods)
3439
- chain.record(scope)
3440
- return nil if chain.truncated?
3441
-
3442
- defs = []
3443
- declined = false
3444
- chain.entries.uniq.each do |entry|
3445
- if entry.external?
3446
- note_missing_class(entry.raw.to_s.split("::").last)
3447
- declined = true if external_declares?(entry.candidates, method_name)
3448
- next
3449
- end
3450
- note_missing_class(entry.last_segment)
3451
- node = scope.user_def_for(entry.name, method_name)
3452
- defs << node if node
3453
- declined = true if definer_without_single_body?(entry.name, method_name, node)
3454
- end
3455
- declined || defs.empty? ? nil : defs.freeze
3456
- end
3457
-
3458
- def note_missing_class(segment)
3459
- Analysis::DependencyRecorder.read_missing(:class, segment) if Analysis::DependencyRecorder.active?
3460
- end
3461
-
3462
- def definer_without_single_body?(owner, method_name, node)
3463
- discovery = scope.discovery
3464
- key = [owner, method_name.to_sym]
3465
- (node.nil? && scope.discovered_method?(owner, method_name, :instance)) ||
3466
- discovery.possible_method?(owner, method_name, :instance) ||
3467
- discovery.contested?(:discovered_def_nodes, key)
3468
- end
3469
-
3470
- # True where RBS knows one of the names the external's spelling can denote and declares the instance method
3471
- # in it; a lookup that fails counts as declaring (the exception then does not apply).
3472
- def external_declares?(candidates, method_name)
3473
- known = candidates.find { |candidate| Rigor::Reflection.rbs_class_known?(candidate, scope: scope) }
3474
- return false if known.nil?
3475
-
3476
- !Rigor::Reflection.instance_method_definition(known, method_name, scope: scope).nil?
3477
- rescue StandardError
3478
- true
3479
- end
3480
-
2078
+ # ADR-24 slice 2 — resolves `method_name` against the project definers on `class_name`'s
2079
+ # {Scope::ResolutionChain}, in Ruby's order: prepended modules, the class, its included modules, then the
2080
+ # superclass's chain likewise. RBS-known ancestors are NOT answered here — the `MethodDispatcher` RBS
2081
+ # tier runs before {CallLadder::UserMethod} and already covers them; they sit on the chain as
2082
+ # external entries this lookup passes over. Cross-file: the chain is built from the tables the runner
2083
+ # seeds from the project-wide pre-pass, cycle-guarded and capped at `Scope::ANCESTOR_WALK_LIMIT`.
3481
2084
  def resolve_user_def_through_ancestors(class_name, method_name)
3482
2085
  resolve_user_def_with_owner(class_name, method_name).first
3483
2086
  end
@@ -3512,6 +2115,8 @@ module Rigor
3512
2115
  scope.user_def_through_ancestors(class_name, method_name)
3513
2116
  end
3514
2117
 
2118
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class.
2119
+ #
3515
2120
  # ADR-57 N5 — overridable-method adoption gate. A self-call resolved to a project `def` whose owner has
3516
2121
  # a discovered subclass / includer that REDEFINES the same method (same instance-vs-singleton kind) is
3517
2122
  # a template-method site: the base body's literal return is the *default*, not the value every
@@ -3777,6 +2382,32 @@ module Rigor
3777
2382
  )
3778
2383
  private_constant :SUMMARY_CONSULT_DEPTHS
3779
2384
 
2385
+ # ADR-129 WD3 — the return memo's entry protocol. The slot holds `[generation, bucket]` ({#return_memo_bucket}),
2386
+ # and a journal record keys an entry on `[def_node, memo_key]`. A replay writes into the bucket the slot holds: a
2387
+ # `type_of` memo entry lives no longer than its file's analysis, inside one run generation, so a slot with no
2388
+ # bucket means the entry outlived its run, which is a defect to surface rather than a bucket to invent.
2389
+ module ReturnMemoEntries
2390
+ module_function
2391
+
2392
+ def entry(slot_value, key)
2393
+ per_def = slot_value&.[](1)&.[](key[0])
2394
+ per_def.nil? ? TypingState::ABSENT : per_def.fetch(key[1], TypingState::ABSENT)
2395
+ end
2396
+
2397
+ def put(slot_value, key, value)
2398
+ (slot_value[1][key[0]] ||= {})[key[1]] = value
2399
+ end
2400
+
2401
+ def delete(slot_value, key)
2402
+ per_def = slot_value && slot_value[1][key[0]]
2403
+ per_def&.delete(key[1])
2404
+ end
2405
+
2406
+ def container(state, slot)
2407
+ state[slot] || raise(ArgumentError, "no return memo bucket to replay into: its entry outlived its run")
2408
+ end
2409
+ end
2410
+
3780
2411
  # ADR-57 follow-up — run-scoped memo for resolved user-method return types. The ADR-57 gate-open made
3781
2412
  # every resolved in-body self-call adopt the callee's inferred return, which re-types the callee body
3782
2413
  # once per call site. With a project-wide discovery index, file N re-types callees defined in files
@@ -3828,32 +2459,6 @@ module Rigor
3828
2459
  # ADR-129 WD1 — a Table, not a Memo: its WD3 serves a standalone result where a fresh compute inside a cycle
3829
2460
  # would be tainted, and its WD6 serves a stored `untyped`, so it is not extensional. Its reads and stores are
3830
2461
  # journaled ({#log_return_memo}).
3831
- # ADR-129 WD3 — the return memo's entry protocol. The slot holds `[generation, bucket]` ({#return_memo_bucket}),
3832
- # and a journal record keys an entry on `[def_node, memo_key]`. A replay writes into the bucket the slot holds: a
3833
- # `type_of` memo entry lives no longer than its file's analysis, inside one run generation, so a slot with no
3834
- # bucket means the entry outlived its run, which is a defect to surface rather than a bucket to invent.
3835
- module ReturnMemoEntries
3836
- module_function
3837
-
3838
- def entry(slot_value, key)
3839
- per_def = slot_value&.[](1)&.[](key[0])
3840
- per_def.nil? ? TypingState::ABSENT : per_def.fetch(key[1], TypingState::ABSENT)
3841
- end
3842
-
3843
- def put(slot_value, key, value)
3844
- (slot_value[1][key[0]] ||= {})[key[1]] = value
3845
- end
3846
-
3847
- def delete(slot_value, key)
3848
- per_def = slot_value && slot_value[1][key[0]]
3849
- per_def&.delete(key[1])
3850
- end
3851
-
3852
- def container(state, slot)
3853
- state[slot] || raise(ArgumentError, "no return memo bucket to replay into: its entry outlived its run")
3854
- end
3855
- end
3856
-
3857
2462
  RETURN_MEMO = TypingState.table(
3858
2463
  :user_method_return_memo,
3859
2464
  run_scoped: true, computed: "return memo", entries: ReturnMemoEntries,
@@ -3987,6 +2592,8 @@ module Rigor
3987
2592
  RECURSION_VALUE_SIZE_CAP = 64
3988
2593
  private_constant :RECURSION_VALUE_SIZE_CAP
3989
2594
 
2595
+ # @api private — a member of {CallLadder::PORT}, made public at the end of this class.
2596
+ #
3990
2597
  # `self_fold_safe` (issue #525) is the caller's statement that its RECEIVER EXPRESSION was foldable;
3991
2598
  # {#build_user_method_body_scope} turns it into the body scope's `:self` sentinel when the carrier and
3992
2599
  # the body both qualify. It does NOT need its own memo-key slot here — the bit is observable on the
@@ -4037,8 +2644,9 @@ module Rigor
4037
2644
  # `accepts_one` → `accepts_dynamic` → `accepts`) recurse unboundedly whenever the carried argument
4038
2645
  # types differ at each level — observed as a `SystemStackError` once implicit-self calls began
4039
2646
  # resolving during the main walk. `describe(:short)` keeps non-Nominal receivers (the implicit
4040
- # `Object` carrier for top-level / DSL-block defs) printable.
4041
- plain_signature = [receiver.describe(:short), def_node.name]
2647
+ # `Object` carrier for top-level / DSL-block defs) printable. A `Struct` / `Data` instance is keyed
2648
+ # without its field values ({#recursion_receiver_descriptor}).
2649
+ plain_signature = [recursion_receiver_descriptor(receiver), def_node.name]
4042
2650
  stack = typing_state.stack(INFERENCE_GUARD)
4043
2651
 
4044
2652
  # WD0 (RIGOR_BUDGET_TRACE) — one entry into user-method return inference. No-op when disabled.
@@ -4316,7 +2924,7 @@ module Rigor
4316
2924
  # outermost entry; exhaustion or value blow-up falls back to the plain `(receiver, method)` guard —
4317
2925
  # today's behaviour. Non-constant args never reach this path.
4318
2926
  signature = plain_signature
4319
- value_key = constant_argument_value_key(arg_types)
2927
+ value_key = recursion_value_key(receiver, arg_types)
4320
2928
  extended = value_key && unroll_fuel_remaining(stack).positive?
4321
2929
  signature = [plain_signature, value_key] if extended
4322
2930
 
@@ -4332,7 +2940,8 @@ module Rigor
4332
2940
  # Issue #3162 — the summary is read only where its frame covers the re-entry's own parameter
4333
2941
  # bindings and block. A value-keyed re-entry is tested like any other: the unroll frame it
4334
2942
  # re-enters holds its constants, but the summary it reads is the outermost frame's.
4335
- floor = uncovered_reentry_floor(summaries[plain_signature], def_node, body_scope, positionals_unknown)
2943
+ floor = uncovered_reentry_floor(summaries[plain_signature], def_node, body_scope, receiver,
2944
+ positionals_unknown)
4336
2945
  return floor || consult_summary(summaries, plain_signature)
4337
2946
  end
4338
2947
 
@@ -4631,9 +3240,9 @@ module Rigor
4631
3240
  # switched the summary to its floor ({#floored_uncovered_reentries?}) it still reads the summary,
4632
3241
  # so a body whose iterate is `bot` reaches the widened retry as before. On the floor it answers
4633
3242
  # `untyped`, the pre-slice-2 observable for an in-cycle call.
4634
- def uncovered_reentry_floor(entry, def_node, body_scope, positionals_unknown)
3243
+ def uncovered_reentry_floor(entry, def_node, body_scope, receiver, positionals_unknown)
4635
3244
  return nil if entry.nil?
4636
- return nil if summary_covers_reentry?(entry, def_node, body_scope.locals, positionals_unknown)
3245
+ return nil if summary_covers_reentry?(entry, def_node, body_scope.locals, receiver, positionals_unknown)
4637
3246
 
4638
3247
  entry[:uncovered] = true
4639
3248
  return nil unless entry[:floor]
@@ -4653,8 +3262,11 @@ module Rigor
4653
3262
  # `*rest`) is covered, and any other is not.
4654
3263
  #
4655
3264
  # The block is part of the frame too: `yield` answers the frame's block ({#reentry_block_covered?}).
4656
- def summary_covers_reentry?(entry, def_node, locals, positionals_unknown)
3265
+ # So is `self` (issue #3184): a `Struct` / `Data` re-entry whose field values differ from the frame's
3266
+ # shares its plain signature ({#recursion_receiver_descriptor}) but not its return.
3267
+ def summary_covers_reentry?(entry, def_node, locals, receiver, positionals_unknown)
4657
3268
  return false unless reentry_block_covered?(entry, def_node)
3269
+ return false unless binding_covers?(entry[:receiver], receiver)
4658
3270
 
4659
3271
  kept = (entry[:kept] ||= kept_positional_parameters(def_node, entry[:receiver])) if positionals_unknown
4660
3272
  frame = entry[:locals]
@@ -4816,7 +3428,7 @@ module Rigor
4816
3428
 
4817
3429
  def recursion_def_for(receiver, method_name)
4818
3430
  return scope.singleton_def_for(receiver.class_name, method_name) if receiver.is_a?(Type::Singleton)
4819
- return :unknown unless user_inference_receiver?(receiver)
3431
+ return :unknown unless CallLadder::UserMethod.user_inference_receiver?(receiver)
4820
3432
 
4821
3433
  resolve_user_def_through_ancestors(receiver.class_name, method_name)
4822
3434
  end
@@ -4976,6 +3588,42 @@ module Rigor
4976
3588
  keys.map(&:first)
4977
3589
  end
4978
3590
 
3591
+ # Issue #3184 — the receiver half of the guard signature. A `Struct` / `Data` instance describes its field
3592
+ # values (`Pt(x: 1)`), so recursing on a new instance (`Pt.new(x + 1).m`) would never meet the guard. It is
3593
+ # keyed by class and member names; pinned field values unroll under the fuel ({#recursion_value_key}).
3594
+ def recursion_receiver_descriptor(receiver)
3595
+ case receiver
3596
+ when Type::StructInstance, Type::DataInstance
3597
+ kind = receiver.is_a?(Type::StructInstance) ? "Struct" : "Data"
3598
+ "#{receiver.class_name || kind}(#{kind}: #{receiver.member_names.join(', ')})"
3599
+ else receiver.describe(:short)
3600
+ end
3601
+ end
3602
+
3603
+ # The ADR-55 slice 1 value key: the pinned argument values, after a `Struct` / `Data` receiver's pinned
3604
+ # field values (#3184). Nil when an argument or field is not value-pinned, or the values are too large.
3605
+ def recursion_value_key(receiver, arg_types)
3606
+ fields = pinned_receiver_fields(receiver)
3607
+ return constant_argument_value_key(arg_types) if fields.nil?
3608
+
3609
+ size = fields.sum { |_, field_size| field_size }
3610
+ return nil if size > RECURSION_VALUE_SIZE_CAP
3611
+
3612
+ args = arg_types.empty? ? [] : constant_argument_value_key(arg_types)
3613
+ args && [["r", fields.map(&:first)], *args]
3614
+ end
3615
+
3616
+ def pinned_receiver_fields(receiver)
3617
+ return nil unless receiver.is_a?(Type::StructInstance) || receiver.is_a?(Type::DataInstance)
3618
+
3619
+ receiver.members.map do |_, type|
3620
+ descriptor = pinned_value_descriptor(type)
3621
+ return nil if descriptor.nil?
3622
+
3623
+ descriptor
3624
+ end
3625
+ end
3626
+
4979
3627
  # Returns `[descriptor, structural_size]` for a value-pinned type, or nil for anything else. Strings
4980
3628
  # count by a cheap length proxy (length > 256 ≈ 64+ nodes) so a long built string disqualifies the
4981
3629
  # frame without a deep walk; tuples recurse.
@@ -5802,8 +4450,8 @@ module Rigor
5802
4450
  # The identity-keyed set of `next` nodes whose value is THIS block's value — reachable from the body
5803
4451
  # without crossing a {JUMP_BOUNDARY_NODES} construct that retargets them — or nil for "do not join".
5804
4452
  #
5805
- # nil means "do not join": a body with no block-level `next` keeps today's path exactly, and pays only
5806
- # the allocation-free scan that answers so. A co-resident block-level `break` used to decline here as
4453
+ # A body with no block-level `next` keeps today's path exactly, and pays only the allocation-free scan
4454
+ # that answers so. A co-resident block-level `break` used to decline here as
5807
4455
  # well, because its value was dropped and joining the `next` arms would have dressed a still-incomplete
5808
4456
  # answer as a complete one; since issue #853 the `break` arms are unioned into the yielding call
5809
4457
  # ({#call_break_arm_types}), so the two exits are modelled at their own levels and neither blocks the
@@ -6032,7 +4680,7 @@ module Rigor
6032
4680
  # `StatementEvaluator` widens the three compound writes in straight-line code, and its captured-local
6033
4681
  # write-back widens all four when a nested block stores through one. A straight-line index TARGET widens
6034
4682
  # too, at the multi-assign, `for` index or `rescue =>` reference that owns it (`eval_multi_write`,
6035
- # `bind_for_index`, `bind_rescue_reference`).
4683
+ # `bind_for_index`, `PatternBindings.bind_rescue_reference`).
6036
4684
  INDEX_WRITE_NODES = Set.new(IndexWriteWidening::CONTENT_WRITE_NODE_CLASSES).freeze
6037
4685
  private_constant :INDEX_WRITE_NODES
6038
4686
 
@@ -6059,12 +4707,12 @@ module Rigor
6059
4707
  CLOSURE_NODES = Set[Prism::BlockNode, Prism::LambdaNode].freeze
6060
4708
  private_constant :CLOSURE_NODES
6061
4709
 
6062
- # v0.0.6 phase 2 — per-element block fold for Tuple receivers under `:map` / `:collect`. Walks every
6063
- # Tuple position, binds the block parameter to that element's type, and re-types the block body. The
6064
- # per-position results are assembled into `Tuple[U_1..U_n]`, strictly tighter than the RBS-projected
6065
- # `Array[union]`.
4710
+ # Per-element block fold for Tuple (and short finite `Constant<Range>`) receivers under the methods in
4711
+ # `PER_ELEMENT_TUPLE_METHODS`. Walks every position, binds the block parameter to that element's type,
4712
+ # and re-types the block body. The per-position results are assembled into a `Tuple` (`map`:
4713
+ # `Tuple[U_1..U_n]`), strictly tighter than the RBS-projected `Array[union]`.
6066
4714
  #
6067
- # Declines (returns nil) when the receiver is not a `Tuple` with at least one element, when the call
4715
+ # Declines (returns nil) when the receiver pins no finite non-empty element list, when the call
6068
4716
  # has no `Prism::BlockNode`, when the method is outside the supported set, when the call carries an
6069
4717
  # argument, when block typing raises mid-loop, or when the block has no body. The decline path leaves the
6070
4718
  # dispatch chain untouched.
@@ -6110,7 +4758,7 @@ module Rigor
6110
4758
  per_position = evaluate_per_element_positions(call_node.block, element_types, name)
6111
4759
  return nil if per_position.nil?
6112
4760
 
6113
- assemble_per_element_result(name, per_position, element_types) ||
4761
+ PerElementAssemblers.assemble_per_element_result(name, per_position, element_types) ||
6114
4762
  undecided_fold_floor(name, element_types, receiver_type)
6115
4763
  end
6116
4764
 
@@ -6179,14 +4827,6 @@ module Rigor
6179
4827
  Type::Combinator.nominal_of("Array", type_args: [element])
6180
4828
  end
6181
4829
 
6182
- # Evaluates the call's block once per receiver element. Two block shapes are supported:
6183
- #
6184
- # - `Prism::BlockNode` — a full `do … end` / `{ … }` block; the body is re-typed per position with the
6185
- # element bound to the block parameter.
6186
- # - `Prism::BlockArgumentNode` wrapping a `SymbolNode` — the `&:predicate` shorthand; the symbol is
6187
- # dispatched as a zero-arg method on each element type.
6188
- #
6189
- # Any other shape (`&proc_local`, `&method(:foo)`, no block) returns `nil` so the fold declines.
6190
4830
  # Arity cap on the scope-threading fold under this per-element walk. The `Constant<Range>` receivers are
6191
4831
  # already capped at {PER_ELEMENT_RANGE_LIMIT} positions, but a Tuple's elements come through
6192
4832
  # {#per_element_elements_of} uncapped — a 40-element array literal is 40 positions, and each one that
@@ -6199,6 +4839,14 @@ module Rigor
6199
4839
  PER_ELEMENT_THREADING_LIMIT = PER_ELEMENT_RANGE_LIMIT
6200
4840
  private_constant :PER_ELEMENT_THREADING_LIMIT
6201
4841
 
4842
+ # Evaluates the call's block once per receiver element. Two block shapes are supported:
4843
+ #
4844
+ # - `Prism::BlockNode` — a full `do … end` / `{ … }` block; the body is re-typed per position with the
4845
+ # element bound to the block parameter.
4846
+ # - `Prism::BlockArgumentNode` wrapping a `SymbolNode` — the `&:predicate` shorthand; the symbol is
4847
+ # dispatched as a zero-arg method on each element type.
4848
+ #
4849
+ # Any other shape (`&proc_local`, `&method(:foo)`, no block) returns `nil` so the fold declines.
6202
4850
  def per_element_block_results(block, element_types)
6203
4851
  case block
6204
4852
  when Prism::BlockNode
@@ -6823,216 +5471,10 @@ module Rigor
6823
5471
  result
6824
5472
  end
6825
5473
 
6826
- PER_ELEMENT_ASSEMBLERS = {
6827
- map: :assemble_map_result,
6828
- collect: :assemble_map_result,
6829
- filter_map: :assemble_filter_map_result,
6830
- flat_map: :assemble_flat_map_result,
6831
- collect_concat: :assemble_flat_map_result,
6832
- select: :assemble_select_result,
6833
- filter: :assemble_select_result,
6834
- find_all: :assemble_select_result,
6835
- reject: :assemble_reject_result,
6836
- take_while: :assemble_take_while_result,
6837
- drop_while: :assemble_drop_while_result,
6838
- partition: :assemble_partition_result,
6839
- count: :assemble_count_result,
6840
- find: :assemble_find_result,
6841
- detect: :assemble_find_result,
6842
- rfind: :assemble_rfind_result,
6843
- find_index: :assemble_find_index_result,
6844
- index: :assemble_find_index_result,
6845
- rindex: :assemble_rindex_result
6846
- }.freeze
6847
- private_constant :PER_ELEMENT_ASSEMBLERS
6848
-
6849
- def assemble_per_element_result(method_name, per_position, element_types)
6850
- handler = PER_ELEMENT_ASSEMBLERS[method_name]
6851
- send(handler, per_position, element_types) if handler
6852
- end
6853
-
6854
- def assemble_map_result(per_position, _element_types)
6855
- Type::Combinator.tuple_of(*per_position)
6856
- end
6857
-
6858
- def assemble_select_result(per_position, element_types)
6859
- assemble_filter_result(per_position, element_types, keep_on_truthy: true)
6860
- end
6861
-
6862
- def assemble_reject_result(per_position, element_types)
6863
- assemble_filter_result(per_position, element_types, keep_on_truthy: false)
6864
- end
6865
-
6866
- # `select` / `filter` / `reject`: keeps each receiver element whose per-position predicate result
6867
- # folds to a decisive `Constant` — Ruby-truthy for `select` / `filter`, Ruby-falsey for `reject`. The
6868
- # surviving elements assemble into a `Tuple`, strictly tighter than the RBS-projected `Array[Elem]`.
6869
- #
6870
- # Folds tightly only when EVERY position is a `Constant`: a single non-`Constant` position leaves the
6871
- # result cardinality unknown (the element might or might not survive), so the dispatcher declines and
6872
- # the RBS tier widens to `Array[Elem]`. `[].select` style empty results are sound — an empty `Tuple`
6873
- # is the empty-array carrier.
6874
- def assemble_filter_result(per_position, element_types, keep_on_truthy:)
6875
- return nil unless per_position.all?(Type::Constant)
6876
-
6877
- kept = element_types.each_index.filter_map do |index|
6878
- element_types[index] if truthy_constant?(per_position[index]) == keep_on_truthy
6879
- end
6880
- Type::Combinator.tuple_of(*kept)
6881
- end
6882
-
6883
- # `take_while` / `drop_while`: stops at the first falsey `Constant` position when every preceding
6884
- # position is a truthy `Constant` (or takes/drops all elements when every position is a truthy
6885
- # `Constant`). Declines when an undecided position precedes the stopping point.
6886
- def assemble_take_while_result(per_position, element_types)
6887
- cutoff = leading_truthy_cutoff(per_position)
6888
- return nil if cutoff.nil?
6889
-
6890
- Type::Combinator.tuple_of(*element_types[0...cutoff])
6891
- end
6892
-
6893
- def assemble_drop_while_result(per_position, element_types)
6894
- cutoff = leading_truthy_cutoff(per_position)
6895
- return nil if cutoff.nil?
6896
-
6897
- Type::Combinator.tuple_of(*element_types[cutoff..])
6898
- end
6899
-
6900
- def leading_truthy_cutoff(per_position)
6901
- first_falsey_index = per_position.index { |type| falsey_constant?(type) }
6902
- return (per_position.all?(Type::Constant) ? per_position.size : nil) if first_falsey_index.nil?
6903
- return nil unless per_position[0...first_falsey_index].all?(Type::Constant)
6904
-
6905
- first_falsey_index
6906
- end
6907
-
6908
- # `partition`: returns `Tuple[truthy_tuple, falsey_tuple]` when every position folds to a `Constant`.
6909
- def assemble_partition_result(per_position, element_types)
6910
- return nil unless per_position.all?(Type::Constant)
6911
-
6912
- truthy = assemble_filter_result(per_position, element_types, keep_on_truthy: true)
6913
- falsey = assemble_filter_result(per_position, element_types, keep_on_truthy: false)
6914
- Type::Combinator.tuple_of(truthy, falsey)
6915
- end
6916
-
6917
- # `count`: returns `Constant[Integer]` of the truthy positions when every position folds to a `Constant`.
6918
- def assemble_count_result(per_position, _element_types)
6919
- return nil unless per_position.all?(Type::Constant)
6920
-
6921
- Type::Combinator.constant_of(per_position.count { |type| truthy_constant?(type) })
6922
- end
6923
-
6924
- # `filter_map` folds tightly only when every per-position result is a `Constant`: positions whose
6925
- # value is `nil` or `false` drop, the rest survive in declaration order. When any position is
6926
- # non-Constant the dispatcher declines (returns nil) so the RBS tier widens to `Array[U]`.
6927
- def assemble_filter_map_result(per_position, _element_types = nil)
6928
- return nil unless per_position.all?(Type::Constant)
6929
-
6930
- kept = per_position.reject { |type| type.value.nil? || type.value == false }
6931
- Type::Combinator.tuple_of(*kept)
6932
- end
6933
-
6934
- # `flat_map` flattens a single level: if the per-position result is a `Tuple`, its elements are
6935
- # concatenated; if it's a non-Array scalar carrier (`Constant<…>` over a non-Array literal) it
6936
- # contributes one element. We fold tightly only when every per-position result is one of those two
6937
- # recognisable shapes — `Nominal[Array[T]]`, `Union[…]`, and other opaque carriers decline so the RBS
6938
- # tier widens to `Array[U]`.
6939
- #
6940
- # `Type::Constant` only ever holds non-Array scalars (the carrier rejects Array literals), so a single
6941
- # `Constant` safely contributes itself as a single Tuple element.
6942
- def assemble_flat_map_result(per_position, _element_types = nil)
6943
- flattened = per_position.flat_map { |type| flat_map_contribution(type) }
6944
- return nil if flattened.nil? || flattened.any?(&:nil?)
6945
-
6946
- Type::Combinator.tuple_of(*flattened)
6947
- end
6948
-
6949
- def flat_map_contribution(type)
6950
- case type
6951
- when Type::Tuple then type.elements
6952
- when Type::Constant then [type]
6953
- else [nil]
6954
- end
6955
- end
6956
-
6957
- # `find` / `detect`: returns the first receiver element whose block result is Ruby-truthy, or `nil`
6958
- # when no position folds to truthy.
6959
- #
6960
- # When the first decisive truthy position is found, the answer is the corresponding receiver element,
6961
- # joined with the element of every earlier position whose result is not a `Type::Constant`: such a
6962
- # position may match first, but the search ends at the truthy one whatever it answers, so the call
6963
- # never returns `nil`. When every position folds to falsey, the answer is `Constant[nil]`. With no
6964
- # decisive truthy position and some undecided one, it declines ({#undecided_fold_floor}).
6965
- def assemble_find_result(per_position, element_types)
6966
- candidates = first_match_candidates(per_position)
6967
- return candidates if candidates.nil? || candidates.equal?(NO_MATCH)
6968
-
6969
- Type::Combinator.union(*candidates.map { |index| element_types[index] })
6970
- end
6971
-
6972
- # `rfind`: reverse of `find` — returns the last receiver element whose block result is Ruby-truthy,
6973
- # joined with any undecided positions to its right.
6974
- def assemble_rfind_result(per_position, element_types)
6975
- candidates = last_match_candidates(per_position)
6976
- return candidates if candidates.nil? || candidates.equal?(NO_MATCH)
6977
-
6978
- Type::Combinator.union(*candidates.map { |index| element_types[index] })
6979
- end
6980
-
6981
- # `find_index` / `index`: returns the index of the first truthy position, or `Constant[nil]` when
6982
- # nothing matches, on {#assemble_find_result}'s terms.
6983
- def assemble_find_index_result(per_position, _element_types = nil)
6984
- candidates = first_match_candidates(per_position)
6985
- return candidates if candidates.nil? || candidates.equal?(NO_MATCH)
6986
-
6987
- Type::Combinator.union(*candidates.map { |index| Type::Combinator.constant_of(index) })
6988
- end
6989
-
6990
- # `rindex`: returns the index of the last truthy position, or `Constant[nil]` when nothing matches.
6991
- def assemble_rindex_result(per_position, _element_types = nil)
6992
- candidates = last_match_candidates(per_position)
6993
- return candidates if candidates.nil? || candidates.equal?(NO_MATCH)
6994
-
6995
- Type::Combinator.union(*candidates.map { |index| Type::Combinator.constant_of(index) })
6996
- end
6997
-
5474
+ # Read by {PerElementAssemblers} (lexically: the constant is private to this class).
6998
5475
  NO_MATCH = Type::Combinator.constant_of(nil)
6999
5476
  private_constant :NO_MATCH
7000
5477
 
7001
- # The positions `find` may stop at — the first decisive truthy one and every undecided one before it —
7002
- # `NO_MATCH` when every position folds falsey, or nil when an undecided position has no truthy one after it.
7003
- def first_match_candidates(per_position)
7004
- first_truthy_index = per_position.index { |type| truthy_constant?(type) }
7005
- if first_truthy_index.nil?
7006
- return per_position.all?(Type::Constant) ? NO_MATCH : nil
7007
- end
7008
-
7009
- undecided = (0...first_truthy_index).reject { |index| per_position[index].is_a?(Type::Constant) }
7010
- undecided + [first_truthy_index]
7011
- end
7012
-
7013
- # The positions `rfind` / `rindex` may stop at — the last decisive truthy one and every undecided one
7014
- # after it — `NO_MATCH` when every position folds falsey, or nil when an undecided position has no
7015
- # truthy one before it.
7016
- def last_match_candidates(per_position)
7017
- last_truthy_index = per_position.rindex { |type| truthy_constant?(type) }
7018
- if last_truthy_index.nil?
7019
- return per_position.all?(Type::Constant) ? NO_MATCH : nil
7020
- end
7021
-
7022
- undecided = ((last_truthy_index + 1)...per_position.size).reject do |index|
7023
- per_position[index].is_a?(Type::Constant)
7024
- end
7025
- [last_truthy_index] + undecided
7026
- end
7027
-
7028
- def truthy_constant?(type)
7029
- type.is_a?(Type::Constant) && !type.value.nil? && type.value != false
7030
- end
7031
-
7032
- def falsey_constant?(type)
7033
- type.is_a?(Type::Constant) && (type.value.nil? || type.value == false)
7034
- end
7035
-
7036
5478
  # Per-pair block fold for `HashShape#transform_keys` and `HashShape#transform_values` (and their bang
7037
5479
  # variants).
7038
5480
  #
@@ -7245,6 +5687,14 @@ module Rigor
7245
5687
  rescue StandardError
7246
5688
  nil
7247
5689
  end
5690
+
5691
+ # @api private — the typer's side of the call ladder's port (ADR-116 WD12). A rung module under `call_ladder/`
5692
+ # is given the walking typer and calls these six on it, and reads `scope`; `CallLadder::PORT` is that list and
5693
+ # `spec/rigor/inference/call_ladder/port_spec.rb` holds both sides to it. Each runs this typer's own code inside
5694
+ # the `type_of` walk that asked the rung, so nothing outside `call_ladder/` may call one on a typer it holds
5695
+ # (`spec/rigor/inference/call_ladder/reentry_spec.rb`).
5696
+ public :class_graph_buckets, :positional_correspondence, :infer_user_method_return, :degrade_if_overridable,
5697
+ :resolve_user_def_through_ancestors, :call_result_type_for
7248
5698
  end
7249
5699
  end
7250
5700
  end