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
@@ -1,13 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../reflection"
4
- require_relative "../typing_state"
5
3
  require_relative "../type"
6
- require_relative "../flow_contribution"
7
- require_relative "../flow_contribution/merger"
8
- require_relative "../builtins/hkt_builtins"
9
- require_relative "../builtins/static_return_refinements"
10
- require_relative "anonymous_meta_class"
11
4
  require_relative "dynamic_origin"
12
5
  require_relative "flow_tracer"
13
6
  require_relative "void_tail_summary"
@@ -43,7 +36,17 @@ require_relative "method_dispatcher/universal_object_dispatch"
43
36
  require_relative "method_dispatcher/singleton_mixin_dispatch"
44
37
  require_relative "method_dispatcher/method_folding"
45
38
  require_relative "method_dispatcher/optional_count"
46
- require_relative "../run_scoped_slots"
39
+ require_relative "method_dispatcher/meta_introspection"
40
+ require_relative "method_dispatcher/hkt_builtin_return"
41
+ require_relative "method_dispatcher/static_refinement"
42
+ require_relative "method_dispatcher/synthesized_stub"
43
+ require_relative "method_dispatcher/plugin_contribution"
44
+ require_relative "method_dispatcher/synthetic_method_dispatch"
45
+ require_relative "method_dispatcher/project_patched"
46
+ require_relative "method_dispatcher/dependency_source"
47
+ require_relative "method_dispatcher/discovered_method"
48
+ require_relative "method_dispatcher/user_class_fallback"
49
+ require_relative "method_dispatcher/composite_receiver"
47
50
 
48
51
  module Rigor
49
52
  module Inference
@@ -51,10 +54,10 @@ module Rigor
51
54
  #
52
55
  # Given `(receiver_type, method_name, arg_types, block_type, environment)`, the dispatcher
53
56
  # returns the inferred result type or `nil` when no rule matches. `nil` is a deliberately
54
- # blunt "I don't know" signal: callers (today only `ExpressionTyper`) own the fail-soft
57
+ # blunt "I don't know" signal: callers (`ExpressionTyper`, `StatementEvaluator`, `GuardRebinding`) own the fail-soft
55
58
  # fallback and decide whether to record a `FallbackTracer` event.
56
59
  #
57
- # Tier order is documented inline in `resolve`; the precise-tier group is built from
60
+ # Tier order is documented inline in `resolve_site`; the precise-tier group is built from
58
61
  # `PRECISE_TIERS_HEAD`, `STDLIB_SINGLETON_FOLDERS`, and `PRECISE_TIERS_TAIL`. `ShapeDispatch`
59
62
  # runs above {RbsDispatch} so a precise per-position/per-key answer wins over the projected
60
63
  # `Array#[]`/`Hash#fetch` RBS answer.
@@ -78,11 +81,30 @@ module Rigor
78
81
  def dispatch(receiver_type:, method_name:, arg_types:,
79
82
  block_type: nil, environment: nil,
80
83
  call_node: nil, scope: nil)
81
- result = resolve(
82
- receiver_type: receiver_type, method_name: method_name, arg_types: arg_types,
83
- block_type: block_type, environment: environment,
84
- call_node: call_node, scope: scope
84
+ dispatch_site(
85
+ CallContext.build(
86
+ receiver: receiver_type, method_name: method_name, args: arg_types,
87
+ block_type: block_type, environment: environment,
88
+ call_node: call_node, scope: scope
89
+ )
85
90
  )
91
+ end
92
+
93
+ # `dispatch` for a caller that already holds the call's context, the *site* (ADR-116 WD12): it answers
94
+ # what `dispatch` answers for the seven fields `dispatch` takes, and makes the same two records. `dispatch`
95
+ # is this entry behind one `CallContext.build`, so the two cannot differ.
96
+ #
97
+ # The site is `CallContext.build`'s for those seven fields, and leaves the other two at their defaults:
98
+ # `self_type_override` and `public_only` are what a tier sets on a context it derives for {RbsDispatch},
99
+ # the one tier that reads them. Nothing here checks a site for them, and a site that set one would not be
100
+ # answered as a call with that property: {UserClassFallback} replaces both, and a call dispatched again is
101
+ # built without them, through `resolve` (the optional count, an alias target, a composite receiver's
102
+ # members) or through `dispatch` ({MethodFolding.try_backward}, {ReduceFolding}'s operator).
103
+ #
104
+ # @param context — the site, a `CallContext`.
105
+ # @return inferred result type, or `nil` for "no rule".
106
+ def dispatch_site(context)
107
+ result = resolve_site(context)
86
108
  # ADR-100 WD4 — the transitive-void consult, HERE in the wrapper rather than in any result
87
109
  # tier: which tier answers the intermediate's call depends on where the leaf's RBS came from
88
110
  # (`RbsDispatch` on the ADR-93 synthesized `untyped` skeleton, or the post-dispatch
@@ -90,28 +112,58 @@ module Rigor
90
112
  # are correct types that must not change. Recording is therefore result-independent and
91
113
  # type-blind; a statement-position record stays inert because the collector only reads value
92
114
  # positions.
93
- record_transitive_void_origin(receiver_type, method_name, call_node, scope)
115
+ record_transitive_void_origin(context.receiver, context.method_name, context.call_node, context.scope)
94
116
  # `rigor trace` — record the dispatch outcome (resolved type, or the fail-soft `nil` the
95
117
  # caller widens to `Dynamic[Top]`).
96
118
  if FlowTracer.active?
97
119
  FlowTracer.dispatch(
98
- receiver: receiver_type, method_name: method_name, args: arg_types,
99
- result: result, location: call_node&.location
120
+ receiver: context.receiver, method_name: context.method_name, args: context.args,
121
+ result: result, location: context.call_node&.location
100
122
  )
101
123
  end
102
124
  result
103
125
  end
104
126
 
105
- # `plugin_typed_sink` is internal bookkeeping for the composite-receiver tier below: when it is an
106
- # Array, an answering plugin tier PUSHES the call node instead of recording it on the scope, and
107
- # the tier commits the buffer only if it goes on to answer. See {#try_composite_receiver}.
108
- def resolve(receiver_type:, method_name:, arg_types:, # rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/ParameterLists
127
+ # The tier ladder without `dispatch`'s two records: what a tier that dispatches again calls
128
+ # ({ProjectPatched}'s alias target, {CompositeReceiver}'s members), and what {#resolve_nil_count} calls for
129
+ # each part of an optional count. It builds the context and hands it to {#resolve_site}; it checks nothing
130
+ # itself, so the nil-receiver guard, the optional-count split and the order are written once, there.
131
+ #
132
+ # The two flags are a re-entry's, not the call's, which is why they are parameters here and not fields of
133
+ # the context. `plugin_typed_sink` is internal bookkeeping for the composite-receiver tier below: when it
134
+ # is an Array, an answering plugin tier PUSHES the call node instead of recording it on the scope, and
135
+ # the tier commits the buffer only if it goes on to answer. See {CompositeReceiver}. `skip_project_patched`
136
+ # turns the project-patched tier's two questions off; see {ProjectPatched.project_patched_alias_target}.
137
+ def resolve(receiver_type:, method_name:, arg_types:, # rubocop:disable Metrics/ParameterLists
109
138
  block_type: nil, environment: nil,
110
139
  call_node: nil, scope: nil, plugin_typed_sink: nil, skip_project_patched: false)
140
+ resolve_site(
141
+ CallContext.build(
142
+ receiver: receiver_type, method_name: method_name, args: arg_types,
143
+ block_type: block_type, environment: environment,
144
+ call_node: call_node, scope: scope
145
+ ),
146
+ plugin_typed_sink: plugin_typed_sink, skip_project_patched: skip_project_patched
147
+ )
148
+ end
149
+
150
+ # The one place the ladder is written: the nil-receiver guard, the optional-count split, then the tiers in
151
+ # order. `dispatch_site` and `resolve` both end here, each with a context built once; that context is
152
+ # threaded — unchanged — through every tier (`_DispatchTier#try_dispatch`). Every tier reads the context;
153
+ # the locals bound from it are read below only by the guard, the split and what this method records after
154
+ # an answer.
155
+ def resolve_site(context, plugin_typed_sink: nil, skip_project_patched: false) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
156
+ receiver_type = context.receiver
111
157
  return nil if receiver_type.nil?
112
158
 
159
+ method_name = context.method_name
160
+ block_type = context.block_type
161
+ environment = context.environment
162
+ call_node = context.call_node
163
+ scope = context.scope
164
+
113
165
  # Issue #1393 — a `nil` count on `min` / `max` / `min_by` / `max_by` is the no-count call.
114
- nil_count = OptionalCount.split(receiver_type, method_name, arg_types, block: !block_type.nil?)
166
+ nil_count = OptionalCount.split(receiver_type, method_name, context.args, block: !block_type.nil?)
115
167
  if nil_count
116
168
  return resolve_nil_count(nil_count.first, receiver_type: receiver_type, method_name: method_name,
117
169
  block_type: block_type, environment: environment,
@@ -120,28 +172,19 @@ module Rigor
120
172
  skip_project_patched: skip_project_patched)
121
173
  end
122
174
 
123
- # Build the call context once and thread it — unchanged — through every tier
124
- # (`_DispatchTier#try_dispatch`). The dispatcher's own private fallback tiers still read
125
- # the positional locals below; only the tier modules consume the context object.
126
- context = CallContext.build(
127
- receiver: receiver_type, method_name: method_name, args: arg_types,
128
- block_type: block_type, environment: environment,
129
- call_node: call_node, scope: scope
130
- )
131
-
132
175
  bound_method_result = MethodFolding.try_backward(context)
133
176
  return bound_method_result if bound_method_result
134
177
 
135
178
  precise = dispatch_precise_tiers(context)
136
179
  return precise if precise
137
180
 
138
- # v0.1.1 Track 2 slice 7 — plugin return-type contribution tier. Sits ahead of
181
+ # v0.1.1 Track 2 slice 7 — plugin return-type contribution tier ({PluginContribution}). Sits ahead of
139
182
  # `RbsDispatch` so a plugin that understands a domain-specific dispatch (e.g. an
140
183
  # `ActiveRecord::Base.find` returning `Nominal[<resolved model>]`) wins over the
141
184
  # RBS-projected envelope. Only consults the registry when both `call_node` and `scope`
142
185
  # are supplied — the dispatcher's own internal callers (per-element block fold, etc.)
143
186
  # skip this tier.
144
- plugin_result = try_plugin_contribution(call_node, scope, receiver_type)
187
+ plugin_result = PluginContribution.try_dispatch(context)
145
188
  if plugin_result
146
189
  # Issue #653 — this tier answering is what makes the site's type the plugin's rather than the
147
190
  # RBS's, and `call.undefined-method` reads that record instead of re-deciding from the receiver's
@@ -150,7 +193,7 @@ module Rigor
150
193
  #
151
194
  # Under a composite-receiver projection the record is BUFFERED instead (#1101). It is the one
152
195
  # recording in this method that is set-only — `Scope#plugin_typed_calls` has no removal, and
153
- # `CheckRules#call_site_exempt?` / `#source_arity_envelope` read it as an exemption — so a
196
+ # `UndefinedMethod.call_site_exempt?` / `WrongArity.source_arity_envelope` read it as an exemption — so a
154
197
  # member a plugin answers beside a member that declines would exempt a call this dispatcher
155
198
  # never typed, silencing `call.undefined-method` and `call.wrong-arity` on a firing that stands.
156
199
  # `call_site_exempt?` runs ahead of the receiver-shape branch, so the union rule is covered by
@@ -169,30 +212,26 @@ module Rigor
169
212
  return plugin_result
170
213
  end
171
214
 
172
- # ADR-20 slice 3 — Rigor-bundled HKT-builtin return-type tier. Sits ABOVE
215
+ # ADR-20 slice 3 — Rigor-bundled HKT-builtin return-type tier ({HktBuiltinReturn}). Sits ABOVE
173
216
  # `RbsDispatch.try_dispatch` so the handful of stdlib methods whose upstream RBS
174
217
  # signature is `untyped` but whose runtime shape Rigor models via a Lightweight HKT
175
218
  # (`json::value`, eventually `dry_monads::result`, …) get the reduced type instead of
176
219
  # `Dynamic[Top]`. The table that populates this tier lives in
177
220
  # `Rigor::Builtins::HktBuiltins::METHOD_RETURN_OVERRIDES`; plugin-supplied per-method
178
221
  # overrides are out of scope for slice 3 and continue to flow through the
179
- # `try_plugin_contribution` tier above.
180
- hkt_builtin_result = try_hkt_builtin_return(receiver_type, method_name, arg_types, environment)
181
- return hkt_builtin_result if hkt_builtin_result
182
-
183
- # Rigor-bundled static refinement tier. Sits between HKT and RBS so stdlib methods whose
222
+ # {PluginContribution} tier above.
223
+ #
224
+ # Rigor-bundled static refinement tier ({StaticRefinement}). Sits between HKT and RBS so stdlib methods whose
184
225
  # upstream RBS is broader than the documented behaviour (e.g. `Kernel#__dir__` declared
185
226
  # `() -> String?` when the documented return is `non-empty-string | nil`) get the
186
227
  # tightened type without modifying the vendored `ruby/rbs` submodule. The override table
187
228
  # lives in `Rigor::Builtins::StaticReturnRefinements::OVERRIDES`.
188
- static_refinement = try_static_refinement(receiver_type, method_name, arg_types)
189
- return static_refinement if static_refinement
190
-
229
+ #
191
230
  # `Foo.instance` for a class that includes the stdlib `Singleton` mixin. Ruby grows that method through
192
231
  # an `included` hook and the upstream RBS leaves `Singleton::SingletonClassMethods` empty, so nothing
193
232
  # below can answer it. See {SingletonMixinDispatch} for why the value matters more than the site count.
194
- singleton_mixin = SingletonMixinDispatch.try_dispatch(context)
195
- return singleton_mixin if singleton_mixin
233
+ bundled_override = first_tier_answer(BUNDLED_OVERRIDE_TIERS, context)
234
+ return bundled_override if bundled_override
196
235
 
197
236
  rbs_result = RbsDispatch.try_dispatch(context)
198
237
  if rbs_result
@@ -203,47 +242,41 @@ module Rigor
203
242
  return rbs_result
204
243
  end
205
244
 
206
- # ADR-16 Tier B / Tier C — synthetic-method tier. Sits BELOW RBS dispatch (per WD13:
245
+ # ADR-16 Tier B / Tier C — synthetic-method tier ({SyntheticMethodDispatch}). Sits BELOW RBS dispatch (per WD13:
207
246
  # user-authored RBS overrides substrate synthesis) and ABOVE the dependency-source
208
247
  # inference tier so a plugin's declared emit table beats the generic gem-source fallback
209
248
  # for the same class. Slice 6a-TierB (origin_module dispatch) lands precise return types
210
249
  # for Tier B emissions; Tier C emissions return their manifest `return_type` when the environment
211
250
  # names that class (slice 6b), and `Dynamic[T]` otherwise.
212
- synthetic_result = try_synthetic_method(
213
- receiver_type, method_name, arg_types, block_type, environment
214
- )
251
+ synthetic_result = first_tier_answer(SYNTHETIC_TIERS, context)
215
252
  return synthetic_result if synthetic_result
216
253
 
217
- # ADR-17 slice 2 — project-side patched-method tier. Sits BELOW the substrate / plugin
254
+ # ADR-17 slice 2 — project-side patched-method tier ({ProjectPatched}). Sits BELOW the substrate / plugin
218
255
  # tiers and ABOVE dependency-source inference per ADR-17 § "Inference contract". When
219
256
  # the user's `pre_eval:` list named a file that re-opens a class (e.g.,
220
257
  # `lib/core_ext/string_extensions.rb` declaring `class String; def to_url; end; end`),
221
258
  # the pre-pass populated `ProjectPatchedMethods` with the `(class, method, kind)` triple;
222
259
  # this tier surfaces it as `Dynamic[top]` so the patched call resolves cross-file without
223
260
  # `call.undefined-method`.
224
- patched_result =
225
- unless skip_project_patched
226
- try_project_patched_method(receiver_type, method_name, arg_types, block_type, environment,
227
- call_node: call_node, scope: scope)
228
- end
261
+ patched_result = ProjectPatched.try_dispatch(context) unless skip_project_patched
229
262
  if patched_result
230
263
  scope&.record_dynamic_origin(call_node, DynamicOrigin::EXTERNAL_GEM_WITHOUT_RBS)
231
264
  return patched_result
232
265
  end
233
266
 
234
- # ADR-10 slice 2b-ii — dependency-source inference tier. Sits BELOW RBS dispatch (RBS /
267
+ # ADR-10 slice 2b-ii — dependency-source inference tier ({DependencySource}). Sits BELOW RBS dispatch (RBS /
235
268
  # RBS::Inline / generated stubs / plugin contracts always win) and ABOVE the user-class
236
269
  # fallback so a method defined in an opt-in gem stops emitting `call.undefined-method`
237
270
  # even when no signature contract resolves. Returns `Dynamic[top]` — slice 2b-ii
238
271
  # deliberately stops at the dynamic-origin envelope; per-method return-type precision is
239
272
  # queued for a later slice.
240
- dep_source_result = try_dependency_source(receiver_type, method_name, environment)
273
+ dep_source_result = DependencySource.try_dispatch(context)
241
274
  if dep_source_result
242
275
  scope&.record_dynamic_origin(call_node, DynamicOrigin::EXTERNAL_GEM_WITHOUT_RBS)
243
276
  return dep_source_result
244
277
  end
245
278
 
246
- # v0.1.3 — discovered-method dispatch tier. When the receiver class has no RBS BUT
279
+ # v0.1.3 — discovered-method dispatch tier ({DiscoveredMethod}). When the receiver class has no RBS BUT
247
280
  # scope_indexer recorded `def method_name` for that class (or singleton), the call
248
281
  # dispatches to `Dynamic[top]` rather than falling through to the user-class fallback.
249
282
  # Sits below RBS / dependency-source so authoritative signatures still win. The
@@ -251,7 +284,7 @@ module Rigor
251
284
  # `alias_method`; the `discovered_method?` consult here closes the fail-soft-event hot
252
285
  # spot on implicit-self calls (`sibling_private(...)`) inside `lib/rigor/`'s own
253
286
  # internals (analyser private helpers don't have RBS).
254
- discovered_result = try_discovered_method(receiver_type, method_name, scope)
287
+ discovered_result = DiscoveredMethod.try_dispatch(context)
255
288
  if discovered_result
256
289
  # ADR-82 WD2/WD3 — the call resolved to a discovered user method but its return could not be
257
290
  # inferred (bare `def`, untyped-parameter chain). Record it as an inference gap, not the
@@ -266,45 +299,41 @@ module Rigor
266
299
  # `module Enumerable; def sum_by`). Below the RBS tier, whose decline means no nearer RBS declares the
267
300
  # method, and below the tiers that answer the receiver's own patch or a gem catalogue entry. A nearer
268
301
  # `def` in the project's source (on an RBS-known receiver, which the discovered-method tier leaves to
269
- # user-method inference) stops the walk: see {#project_source_defines?}. That probe reads the scope's def
270
- # index, so a single-file scope (`type-of`, `annotate`, an LSP buffer) cannot see a `def` in another file.
302
+ # user-method inference) stops the walk: see {ProjectPatched.project_source_defines?}. That probe reads the
303
+ # scope's def index, so a single-file scope (`type-of`, `annotate`, an LSP buffer) cannot see a `def` in
304
+ # another file.
271
305
  ancestor_patched =
272
- if !skip_project_patched && scope
273
- try_project_patched_method(receiver_type, method_name, arg_types, block_type, environment,
274
- call_node: call_node, scope: scope, through_ancestors: true)
275
- end
306
+ (ProjectPatched.try_dispatch(context, through_ancestors: true) if !skip_project_patched && scope)
276
307
  if ancestor_patched
277
308
  scope&.record_dynamic_origin(call_node, DynamicOrigin::EXTERNAL_GEM_WITHOUT_RBS)
278
309
  return ancestor_patched
279
310
  end
280
311
 
281
- # ADR-5 robustness — synthesized-stub-type tier. When the receiver is a type Rigor
312
+ # ADR-5 robustness — synthesized-stub-type tier ({SynthesizedStub}). When the receiver is a type Rigor
282
313
  # invented to make an otherwise-unbuildable project signature resolve (a
283
314
  # missing-namespace module, or a stub for a referenced-but-undeclared type like an
284
315
  # unavailable `DRb::DRbServer`), the stub carries no methods, so an unresolved call
285
316
  # against it would otherwise mis-fire `call.undefined-method`. Resolve it to
286
317
  # `Dynamic[Top]` instead — the same no-false-positive contract as the dependency-source
287
318
  # tier. Sits below every real resolution tier so a genuine signature always wins.
288
- stub_result = try_synthesized_stub_type(receiver_type, environment)
289
- return stub_result if stub_result
290
-
319
+ #
291
320
  # The receiver-independent `BasicObject` / `Object` / `Kernel` selectors, for a receiver no tier
292
321
  # above could name. `x.nil?` is `bool` whatever `x` is; without this tier it was `Dynamic[Top]`
293
322
  # like every other call on an untyped receiver. Sits here, below every real resolution tier, so a
294
323
  # nameable receiver always answers from its own signature first — this only ever replaces a
295
324
  # `Dynamic[Top]` the typer was about to produce. See {UniversalObjectDispatch} for the table and
296
325
  # for the selectors deliberately left out of it.
297
- universal_result = UniversalObjectDispatch.try_dispatch(context)
298
- return universal_result if universal_result
326
+ stub_or_universal = first_tier_answer(STUB_AND_UNIVERSAL_TIERS, context)
327
+ return stub_or_universal if stub_or_universal
299
328
 
300
- # Slice 7 phase 10 — user-class ancestor fallback. When the receiver is `Nominal[T]` or
329
+ # Slice 7 phase 10 — user-class ancestor fallback ({UserClassFallback}). When the receiver is `Nominal[T]` or
301
330
  # `Singleton[T]` for a class not in the RBS environment (typically a user-defined class),
302
331
  # retry the dispatch against the implicit ancestor: `Nominal[Object]` for instance
303
332
  # receivers and `Singleton[Object]` for singleton receivers. This resolves Kernel
304
333
  # intrinsics (`require`, `raise`, `puts`, ...) and Module/Class introspection
305
334
  # (`attr_reader`, `private`, ...) on user classes without requiring the user to author
306
335
  # their own RBS.
307
- fallback_result = try_user_class_fallback(receiver_type, environment, call_node, context)
336
+ fallback_result = UserClassFallback.try_dispatch(context)
308
337
  # ADR-82 WD2/WD3 — a user-class receiver whose call resolved to the lenient ancestor fallback
309
338
  # with no inferable return. Same inference-gap provenance as the discovered-method tier, so a
310
339
  # downstream dispatch on this value is labeled honestly rather than `unsupported_syntax`.
@@ -316,8 +345,8 @@ module Rigor
316
345
  # Issue #1101 — composite-receiver projection, the last tier. Every tier above needs a
317
346
  # receiver it can name; a `Union` or a `Difference` is not one, so a composite receiver whose
318
347
  # members WOULD each resolve still lands `Dynamic[top]`. Retry per projected member through
319
- # this same chain. See {#try_composite_receiver} for the projection rule and why it sits here.
320
- try_composite_receiver(context)
348
+ # this same chain. See {CompositeReceiver} for the projection rule and why it sits here.
349
+ first_tier_answer(COMPOSITE_TIERS, context)
321
350
  end
322
351
 
323
352
  # The `nil` part of an optional count dispatches as the no-argument call, the rest as written; a count
@@ -337,18 +366,18 @@ module Rigor
337
366
  # ADR-100 WD4 — records the transitive `-> void` provenance when the called method is a
338
367
  # discovered project `def` whose {VoidTailSummary} chain ends in an author-declared `-> void`
339
368
  # leaf on the same owner. Guards cheapest-first: the internal dispatcher callers nil `scope` /
340
- # `call_node` out; the receiver must project through {#discovered_method_lookup}
369
+ # `call_node` out; the receiver must project through {DiscoveredMethod.discovered_method_lookup}
341
370
  # (`Nominal` / `Singleton` only — unions and `Dynamic` receivers stay out); and the
342
371
  # `discovered_method?` pre-filter (two pure hash reads) keeps the hot path at ~zero cost —
343
372
  # only a call that provably targets a discovered def of the right kind resolves the node and
344
- # consults the summary. The `Prism::CallNode` guard mirrors `collect_plugin_contributions`:
373
+ # consults the summary. The `Prism::CallNode` guard mirrors `PluginContribution.collect_plugin_contributions`:
345
374
  # the `&:symbol` block path dispatches with the `Prism::BlockArgumentNode` itself, which is
346
375
  # never a collector value position, so recording on it would be dead weight.
347
376
  def record_transitive_void_origin(receiver_type, method_name, call_node, scope)
348
377
  return if scope.nil? || call_node.nil?
349
378
  return unless call_node.is_a?(Prism::CallNode)
350
379
 
351
- class_name, kind = discovered_method_lookup(receiver_type)
380
+ class_name, kind = DiscoveredMethod.discovered_method_lookup(receiver_type)
352
381
  return if class_name.nil?
353
382
  return unless scope.discovered_method?(class_name, method_name, kind)
354
383
 
@@ -364,178 +393,15 @@ module Rigor
364
393
  scope.record_void_origin(call_node, origin) if origin
365
394
  end
366
395
 
367
- # v0.1.3 — discovered-method dispatch tier. `scope` carries the `discovered_methods` table
368
- # built once per program by `ScopeIndexer` (a `Hash[String, Hash[Symbol, :instance |
369
- # :singleton]]`). When the receiver names a discovered class AND the requested method is
370
- # recorded for that class's appropriate kind, return `Type::Combinator.untyped` — the
371
- # dispatcher cannot infer a more precise return type from the bare `def` shape, but the
372
- # call site stops being a fail-soft hot spot.
373
- #
374
- # Returns `nil` when scope / receiver class is unavailable, when the method is not in the
375
- # discovered table, OR when `discovered_def_nodes` carries a re-typable body for the method
376
- # (so the downstream `ExpressionTyper#try_user_method_inference` tier can re-type the body
377
- # for a precise return type rather than collapsing to `Dynamic[top]` here).
378
- #
379
- # The tier does NOT gate on `rbs_class_known?`. RBS dispatch already had its turn upstream
380
- # and returned `nil` (otherwise we wouldn't be here). When RBS knows the class but the
381
- # particular method is missing from the sig — common for internal helpers and for
382
- # auto-generated stubs that emit `class X` without enumerating every method — falling
383
- # through to the user-class fallback would mistakenly fire `call.undefined-method`.
384
- # Honoring the discovered table here keeps the sibling-private call resolution working
385
- # under partial RBS coverage.
386
- def try_discovered_method(receiver_type, method_name, scope)
387
- return nil if scope.nil?
388
-
389
- class_name, kind = discovered_method_lookup(receiver_type)
390
- return nil if class_name.nil?
391
- return nil unless scope.discovered_method?(class_name, method_name, kind)
392
- # Decline when a re-typable body is recorded for the method, so the downstream
393
- # `ExpressionTyper` inference tier can fold a precise return instead of collapsing to
394
- # `Dynamic[top]` here — instance bodies via `user_def_for`, singleton bodies (`def
395
- # self.x` / `module_function`) via `singleton_def_for` (module-singleton call
396
- # resolution, ADR-57 follow-up).
397
- return nil if kind == :instance && scope.user_def_for(class_name, method_name)
398
- return nil if kind == :singleton && scope.singleton_def_for(class_name, method_name)
399
-
400
- Type::Combinator.untyped
401
- end
402
-
403
- # Resolves the `(class_name, kind)` pair scope_indexer keys its `discovered_methods` table
404
- # on. `Nominal[X]` looks up instance methods on X; `Singleton[X]` looks up singleton
405
- # methods on X. Other carriers return `[nil, nil]` so the tier declines.
406
- def discovered_method_lookup(receiver_type)
407
- # #525 — the ADR-48 member carriers name their class too: a `Line = Struct.new(...) do ... end`
408
- # value is a StructInstance whose block-def methods are discovered under "Line".
409
- case receiver_type
410
- when Type::Nominal, Type::StructInstance, Type::DataInstance
411
- [receiver_type.class_name, :instance]
412
- when Type::Singleton, Type::StructClass, Type::DataClass
413
- [receiver_type.class_name, :singleton]
414
- else NO_DISCOVERED_LOOKUP
415
- end
416
- end
417
-
418
- # The shared "no discovered-method key" pair; callers destructure it (#775).
419
- NO_DISCOVERED_LOOKUP = [nil, nil].freeze
420
- private_constant :NO_DISCOVERED_LOOKUP
421
-
422
- # ADR-5 robustness — returns `Dynamic[Top]` when the receiver is an instance or singleton
423
- # of a type Rigor synthesized (a missing-namespace module or a referenced-type stub). The
424
- # stub has no methods, so the call would otherwise reach the user-class fallback and
425
- # surface `call.undefined-method`; the honest answer for a type Rigor invented is "unknown
426
- # shape", i.e. `Dynamic[Top]`. Returns nil (declines) for any real type.
427
- def try_synthesized_stub_type(receiver_type, environment)
428
- return nil if environment.nil?
429
-
430
- loader = environment.rbs_loader
431
- return nil if loader.nil? || !loader.respond_to?(:synthesized_type_names)
432
-
433
- names = loader.synthesized_type_names
434
- return nil if names.empty?
435
-
436
- class_name =
437
- case receiver_type
438
- when Type::Nominal, Type::Singleton then receiver_type.class_name.to_s.sub(/\A::/, "")
439
- end
440
- return nil unless class_name && names.include?(class_name)
441
-
442
- Type::Combinator.untyped
443
- end
444
-
445
- # ADR-20 slice 3 — looks up the receiver / method pair in
446
- # {Rigor::Builtins::HktBuiltins::METHOD_RETURN_OVERRIDES} and returns the reduced HKT type.
447
- # Only fires when the receiver is a {Rigor::Type::Singleton} (the `JSON.parse` shape) and
448
- # the registry-backed reduction succeeds; returns `nil` otherwise so the dispatcher falls
449
- # through to RBS.
450
- def try_hkt_builtin_return(receiver_type, method_name, arg_types, environment)
451
- return nil if environment.nil?
452
- return nil unless receiver_type.is_a?(Type::Singleton)
453
-
454
- Rigor::Builtins::HktBuiltins.method_return_override(
455
- class_name: receiver_type.class_name,
456
- method_name: method_name,
457
- kind: :singleton,
458
- arg_types: arg_types,
459
- hkt_registry: environment.hkt_registry
460
- )
461
- end
462
-
463
- # Consults the Rigor-bundled static refinement table for a (owner-class, method-name,
464
- # kind) entry. Kernel methods are mixed into every non-BasicObject class, so an
465
- # implicit-self `__dir__` call (receiver_type = Nominal[ClassName]) is matched by looking
466
- # up Kernel as the owner. Explicit `Kernel.__dir__` (receiver_type = Singleton[Kernel]) and
467
- # instance-side calls (receiver_type = Nominal[Klass]) share the `:both` row.
468
- #
469
- # The receiver-side ancestor check is intentionally cheap: any non-BasicObject Nominal /
470
- # Singleton matches every Kernel-owned override. BasicObject explicitly excludes Kernel and
471
- # is therefore rejected. The narrow risk of a user-defined `def __dir__` shadowing Kernel's
472
- # method would also alter the runtime answer; users with that configuration opt out via a
473
- # `signature_paths` overlay declaring their own return type.
474
- def try_static_refinement(receiver_type, method_name, arg_types)
475
- candidates = Rigor::Builtins::StaticReturnRefinements.owners_for(method_name)
476
- return nil if candidates.empty?
477
-
478
- owner = static_refinement_owner_for(receiver_type, candidates)
479
- return nil unless owner
480
-
481
- kind = receiver_type.is_a?(Type::Singleton) ? :singleton : :instance
482
- Rigor::Builtins::StaticReturnRefinements.lookup(
483
- owner_class_name: owner,
484
- method_name: method_name,
485
- kind: kind,
486
- arg_types: arg_types
487
- )
488
- end
489
-
490
- # Picks the most specific override owner the receiver honours. For Kernel-owned overrides
491
- # the receiver simply needs to be a real-class Nominal / Singleton (i.e. not BasicObject
492
- # and not a Dynamic / Constant / shape carrier — those carriers go through their own
493
- # narrower tiers).
494
- def static_refinement_owner_for(receiver_type, candidates)
495
- receiver_class = static_refinement_class_for(receiver_type)
496
- return nil unless receiver_class
497
-
498
- return "Kernel" if candidates.include?("Kernel") && receiver_class != "BasicObject"
499
-
500
- candidates.find { |owner| owner == receiver_class }
501
- end
502
-
503
- def static_refinement_class_for(receiver_type)
504
- case receiver_type
505
- when Type::Singleton, Type::Nominal
506
- receiver_type.class_name
507
- end
508
- end
509
-
510
- # ADR-2 § "Flow Contribution Bundle" / v0.1.1 Track 2 slice 7; ADR-52 WD3 — consults each
511
- # loaded plugin's gated `dynamic_return` rules, wraps the contributed types as
512
- # `FlowContribution` bundles, merges them through `FlowContribution::Merger`, and returns
513
- # the merged `return_type` slot (or nil when no plugin contributed a return type).
514
- #
515
- # Plugins whose hook raises have their contribution silently dropped for this call so the
516
- # dispatch chain keeps moving — the run-level diagnostic envelope (per ADR-2 § "Plugin
517
- # Trust and I/O Policy") is owned by `Analysis::Runner#plugin_emitted_diagnostics`.
518
- def try_plugin_contribution(call_node, scope, receiver_type)
519
- return nil if call_node.nil? || scope.nil?
520
-
521
- registry = scope.environment&.plugin_registry
522
- return nil if registry.nil? || registry.empty?
523
-
524
- contributions = collect_plugin_contributions(registry, call_node, scope, receiver_type)
525
- return nil if contributions.empty?
526
-
527
- FlowContribution::Merger.merge(contributions).return_type
528
- end
529
-
530
396
  # Issue #963 item 2 — the MEMBERSHIP half of the two plugin tiers, for #618's own-method veto.
531
397
  #
532
- # `ExpressionTyper#try_local_def_dispatch` has to decide whether the call's own `self` answers the
398
+ # `CallLadder::TopLevelDef.try_call` has to decide whether the call's own `self` answers the
533
399
  # name before a same-named top-level `def` may bind, and a plugin-supplied member is an answer Ruby
534
400
  # really dispatches to: a model's column reader, an association, a scope, a macro-synthesised
535
401
  # reader. The veto asked neither tier, so a top-level `def name` bound ahead of the member and
536
402
  # typed the read as the def's `nil` — #618's false positive at a source the veto could not see.
537
403
  #
538
- # The question is asked HERE, of the same two tiers `resolve` consults and in the same order, rather
404
+ # The question is asked HERE, of the same two tiers `resolve_site` consults and in the same order, rather
539
405
  # than reconstructed in the veto: a name this reports as answered is a name the dispatch really would
540
406
  # resolve, and no plugin knowledge moves into the engine's veto. The tiers are the gated
541
407
  # `dynamic_return` walk and the ADR-16 synthetic-method index (Tier C `heredoc_templates` emissions and
@@ -548,228 +414,9 @@ module Rigor
548
414
  # produced a candidate, which needs a project top-level `def` of the same name.
549
415
  def plugin_member_answers?(call_node:, scope:, receiver_type:, method_name:)
550
416
  return false if receiver_type.nil?
551
- return true unless try_plugin_contribution(call_node, scope, receiver_type).nil?
552
-
553
- synthetic_method_member?(receiver_type, method_name, scope&.environment)
554
- end
555
-
556
- # The synthetic-method half of {#plugin_member_answers?} — the same `(class_name, method_name, kind)`
557
- # probe {#try_synthetic_method} makes, without the return-type promotion the veto has no use for.
558
- def synthetic_method_member?(receiver_type, method_name, environment)
559
- index = environment&.synthetic_method_index
560
- return false if index.nil? || index.empty?
561
-
562
- class_name = synthetic_method_class_name(receiver_type)
563
- return false if class_name.nil?
417
+ return true unless PluginContribution.merged_return_type(call_node, scope, receiver_type).nil?
564
418
 
565
- matches = if receiver_type.is_a?(Type::Singleton)
566
- index.lookup_singleton(class_name, method_name)
567
- else
568
- index.lookup_instance(class_name, method_name)
569
- end
570
- !matches.empty?
571
- rescue StandardError
572
- false
573
- end
574
-
575
- # ADR-16 synthetic-method tier. Slice 2b shipped the floor — a match short-circuits at the
576
- # right precedence (above dep-source / discovered / user-class-fallback; below RBS) and
577
- # returns `Dynamic[T]`. Slice 6 (precision promotion):
578
- # - Tier B path (slice 6a, `provenance[:origin_module]` recorded by the slice-3b scanner):
579
- # redispatch on `Nominal[origin_module]` via `RbsDispatch` so the module's authored RBS
580
- # return type wins. Devise's `valid_password?` returns `bool`, not `Dynamic[T]`.
581
- # - Tier C path (slice 6b, plain `return_type:` string from the manifest's emit table):
582
- # look up `environment.nominal_for_name(return_type)` so `attribute :avatar,
583
- # Types::String` emits a synthetic reader returning
584
- # `Nominal[ActiveStorage::Attached::One]` (when the class is in RBS). Unparameterised
585
- # class names only — parameterised forms (`Array[String]`, `Hash[K, V]`) and
586
- # plugin-supplied utility-type names (`Pick<T, K>`) require routing through the full
587
- # ADR-13 `Plugin::TypeNodeResolver` chain, which slice 6 does not yet wire in (the
588
- # resolver chain is consulted only for `%a{rigor:v1:…}` payloads as of ADR-13 slice 3).
589
- def try_synthetic_method(receiver_type, method_name, arg_types, block_type, environment)
590
- index = environment&.synthetic_method_index
591
- return nil if index.nil? || index.empty?
592
-
593
- class_name = synthetic_method_class_name(receiver_type)
594
- return nil if class_name.nil?
595
-
596
- matches = case receiver_type
597
- when Type::Singleton then index.lookup_singleton(class_name, method_name)
598
- else index.lookup_instance(class_name, method_name)
599
- end
600
- return nil if matches.empty?
601
-
602
- promoted = promote_synthetic_match(matches, method_name, arg_types, block_type, environment)
603
- promoted || Type::Combinator.untyped
604
- end
605
-
606
- # First non-nil promotion wins. Tier B (origin_module) and Tier C (return_type nominal
607
- # lookup) are tried in the same registration-order pass per WD11 first-wins — the slice-3b
608
- # scanner sets `origin_module` for Tier B entries and leaves it absent for Tier C, so the
609
- # two paths self-route per match.
610
- def promote_synthetic_match(matches, method_name, arg_types, block_type, environment)
611
- return nil if environment.nil?
612
-
613
- matches.each do |synthetic|
614
- promoted =
615
- promote_via_origin_module(synthetic, method_name, arg_types, block_type, environment) ||
616
- promote_via_return_type(synthetic, environment)
617
- return promoted if promoted
618
- end
619
- nil
620
- end
621
-
622
- # Slice 6a-TierB. For Tier B emissions (origin_module recorded in provenance), redispatch
623
- # the call on the included module's `Nominal[...]` type via `RbsDispatch`. Returns nil when
624
- # the SyntheticMethod is not a Tier B entry or when the origin_module is not in the RBS
625
- # env.
626
- def promote_via_origin_module(synthetic, method_name, arg_types, block_type, environment)
627
- module_name = synthetic.provenance[:origin_module]
628
- return nil unless module_name
629
-
630
- module_type = Type::Combinator.nominal_of(module_name)
631
- RbsDispatch.try_dispatch(
632
- CallContext.build(
633
- receiver: module_type, method_name: method_name, args: arg_types,
634
- environment: environment, block_type: block_type
635
- )
636
- )
637
- end
638
-
639
- # Slice 6b-TierC. For Tier C emissions, look up the manifest-declared `return_type:` string
640
- # via `environment.nominal_for_name`. Skips the placeholder `"untyped"` (Tier B's
641
- # record-but-do-not-resolve marker from the slice-3b scanner) and the `"void"` keyword
642
- # (RBS-style absent return). Falls back to nil when the class is not in the env — caller
643
- # then returns Dynamic[T].
644
- TIER_C_PLACEHOLDER_RETURNS = %w[untyped void].freeze
645
- private_constant :TIER_C_PLACEHOLDER_RETURNS
646
-
647
- def promote_via_return_type(synthetic, environment)
648
- return_type = synthetic.return_type
649
- return nil if return_type.nil? || TIER_C_PLACEHOLDER_RETURNS.include?(return_type)
650
-
651
- environment.nominal_for_name(return_type)
652
- end
653
-
654
- def synthetic_method_class_name(receiver_type)
655
- case receiver_type
656
- when Type::Nominal, Type::Singleton then receiver_type.class_name
657
- end
658
- end
659
-
660
- # ADR-17 slice 2 — project-side patched-method tier. Slice 3a uses the registry's
661
- # heuristic-extracted `return_type` (populated via the same
662
- # `Analysis::DependencySourceInference::ReturnTypeHeuristic` the ADR-10 walker uses): a
663
- # `def to_url; "hello"; end` patched onto `String` now resolves `s.to_url` to
664
- # `Dynamic[Nominal[String]]` instead of the pre-3a `Dynamic[Top]`. Falls back to
665
- # `Dynamic[Top]` when the heuristic declined (non-literal tail expression).
666
- #
667
- # `through_ancestors:` (issue #1708), with a scope, searches the receiver's ancestors as well, through
668
- # {ProjectPatchedMethods#lookup_through_ancestors}, stopping at a nearer project-source `def`. A private or
669
- # protected patch Ruby would not let the call reach ({ProjectPatchedMethods#callable?}) answers nothing, so
670
- # `1.kp` on `module Kernel; private def kp` reads as the undefined call it is.
671
- def try_project_patched_method(receiver_type, method_name, arg_types, block_type, environment, # rubocop:disable Metrics/ParameterLists
672
- call_node: nil, scope: nil, through_ancestors: false)
673
- registry = environment&.project_patched_methods
674
- return nil if registry.nil? || registry.empty?
675
-
676
- class_name = synthetic_method_class_name(receiver_type)
677
- return nil if class_name.nil?
678
-
679
- kind = receiver_type.is_a?(Type::Singleton) ? :singleton : :instance
680
- entry = project_patched_entry(registry, class_name, method_name, kind, environment,
681
- scope: scope, through_ancestors: through_ancestors)
682
- return nil if entry.nil?
683
-
684
- verdict = registry.callable?(entry, explicit: explicit_non_self_receiver?(call_node),
685
- self_type: scope ? scope.self_type : :unknown,
686
- rbs_loader: environment.rbs_loader)
687
- return nil if verdict == false
688
- return Type::Combinator.untyped if verdict.nil?
689
- return Type::Combinator.dynamic(entry.return_type) if entry.return_type
690
-
691
- aliased = project_patched_alias_target(entry, receiver_type, arg_types, block_type, environment)
692
- aliased ? Type::Combinator.dynamic(aliased) : Type::Combinator.untyped
693
- end
694
-
695
- def project_patched_entry(registry, class_name, method_name, kind, environment, scope:, through_ancestors:)
696
- return registry.lookup(class_name: class_name, method_name: method_name, kind: kind) unless through_ancestors
697
-
698
- registry.lookup_through_ancestors(
699
- class_name: class_name, method_name: method_name, kind: kind, rbs_loader: environment.rbs_loader,
700
- source_defines: ->(owner, side) { project_source_defines?(scope, owner, method_name, side) }
701
- )
702
- end
703
-
704
- # Issue #1708 — does the project's own source define `method_name` on `owner` (`side` as the ancestor walk
705
- # reaches it), or on a module the project prepends to or includes into it? Ruby runs that `def` ahead of a
706
- # patch on a farther ancestor: `class Integer; def nn = "s"` beats `class Object; def nn = nil` in a
707
- # `pre_eval:` file. The owner's level of its {Scope::ResolutionChain} (its prepends, itself, its includes
708
- # and their own mixins, or a class object's singleton and its extends) holds those definers; whether one
709
- # of them defines the name does not depend on their order, so the chain is searched without settling it.
710
- def project_source_defines?(scope, owner, method_name, side)
711
- return false unless scope.known_user_class?(owner)
712
-
713
- chain = Scope::ResolutionChain.for(scope, owner, side, :methods)
714
- own_level_end = chain.level_starts[1] || chain.entries.size
715
- found = chain.search(scope, 0, own_level_end) do |entry|
716
- !entry.external? && source_def?(scope, entry.name, method_name, entry.side)
717
- end
718
- !found.nil?
719
- end
720
-
721
- def source_def?(scope, owner, method_name, side)
722
- if side == :singleton
723
- scope.discovered_method?(owner, method_name, :singleton) || !scope.singleton_def_for(owner, method_name).nil?
724
- else
725
- scope.discovered_method?(owner, method_name, :instance) || !scope.user_def_for(owner, method_name).nil?
726
- end
727
- end
728
-
729
- # Issue #1702 — an alias in a `pre_eval:` patch whose old name no earlier patch binding defines
730
- # (`alias old_plus +` on Integer, or `alias_method :orig_succ, :succ` ahead of the patch's own `def succ`)
731
- # names the method the class had before the patch, so it answers what that method answers for the same
732
- # arguments, behind the `Dynamic` every patched method carries. The re-entry skips this tier: a later patch
733
- # `def` of the old name is not the body the alias copied, and the skip is also what ends an alias cycle. It
734
- # carries no call node or scope, so it answers a type and records nothing at the call site.
735
- def project_patched_alias_target(entry, receiver_type, arg_types, block_type, environment)
736
- return nil if entry.alias_of.nil?
737
-
738
- resolve(
739
- receiver_type: receiver_type, method_name: entry.alias_of, arg_types: arg_types,
740
- block_type: block_type, environment: environment, skip_project_patched: true
741
- )
742
- end
743
-
744
- # ADR-10 slice 2b-ii. Consults the per-run `Analysis::DependencySourceInference::Index`
745
- # carried by the environment for `(class_name, method_name)` observations harvested from
746
- # opt-in gems' `roots:`. On a hit, returns `Combinator.untyped` so the call site carries
747
- # the `Dynamic[top]` provenance (per ADR-10's "Inference contract": gem-source-inferred
748
- # shapes never publish as ground-truth `T`). Returns `nil` when the environment carries no
749
- # index, the index has no entry, or the receiver has no nominal class to look up.
750
- def try_dependency_source(receiver_type, method_name, environment)
751
- index = environment&.dependency_source_index
752
- return nil if index.nil? || index.empty?
753
-
754
- class_name = dep_source_class_name(receiver_type)
755
- return nil if class_name.nil?
756
-
757
- # ADR-10 5a — per-receiver plugin veto. When a registered plugin declares
758
- # `manifest(owns_receivers: [<class>])` AND the call's receiver IS that class (or a
759
- # subclass), decline and let plugins handle the call. Plugins that own a receiver are
760
- # the authoritative source for that type; gem-source inference must not contribute
761
- # behind their backs.
762
- return nil if plugin_owns_receiver?(class_name, environment)
763
-
764
- contribution = index.contribution_for(class_name: class_name, method_name: method_name)
765
- return dependency_source_return_type(contribution) if contribution
766
-
767
- # ADR-10 5b — β budget semantics. On a catalog miss, if the receiver class belongs to a
768
- # budget-exceeded gem AND the user opted into `:dependency_silence`, return
769
- # `Dynamic[top]` rather than falling through to the user-class fallback. The user-class
770
- # fallback would otherwise emit `call.undefined-method` for methods Rigor's catalog
771
- # couldn't reach because the walker hit its cap.
772
- budget_silence_result(class_name, index, environment)
419
+ SyntheticMethodDispatch.synthetic_method_member?(receiver_type, method_name, scope&.environment)
773
420
  end
774
421
 
775
422
  # ADR-10 slice 5c — record a `dynamic.dependency-source.boundary-cross` event when RBS
@@ -803,16 +450,6 @@ module Rigor
803
450
  )
804
451
  end
805
452
 
806
- # Maps a {DependencySourceInference::Walker::CatalogEntry} to the Type the dispatcher
807
- # returns at the call site. When the heuristic recovered a static facet, wrap it in
808
- # `Dynamic[T]` per ADR-10's gem-boundary contract; otherwise fall back to the
809
- # pre-heuristic `Dynamic[top]`.
810
- def dependency_source_return_type(contribution)
811
- return Type::Combinator.untyped if contribution.return_type.nil?
812
-
813
- Type::Combinator.dynamic(contribution.return_type)
814
- end
815
-
816
453
  # Composite preflight for {#record_boundary_cross_if_applicable}. Returns the receiver
817
454
  # class name only when every prerequisite for emitting the diagnostic is satisfied
818
455
  # (environment carries an index + reporter, receiver is a nominal carrier, RBS-side result
@@ -824,7 +461,7 @@ module Rigor
824
461
  return nil if environment.boundary_cross_reporter.nil?
825
462
  return nil if rbs_result_untyped?(rbs_result)
826
463
 
827
- dep_source_class_name(receiver_type)
464
+ DependencySource.dep_source_class_name(receiver_type)
828
465
  end
829
466
 
830
467
  def rbs_result_untyped?(rbs_result)
@@ -837,101 +474,60 @@ module Rigor
837
474
  rbs_result.respond_to?(:describe) ? rbs_result.describe : rbs_result.inspect
838
475
  end
839
476
 
840
- def budget_silence_result(class_name, index, _environment)
841
- return nil unless index.budget_overrun_strategy == :dependency_silence
842
-
843
- owning_gem = index.gem_for(class_name)
844
- return nil if owning_gem.nil?
845
- return nil unless index.budget_exceeded.include?(owning_gem)
846
-
847
- Type::Combinator.untyped
848
- end
849
-
850
- # ADR-52 WD1 — the per-dispatch plugins × owns_receivers × `class_ordering` walk moved into
851
- # the compiled contribution table: the union is built once per registry (almost always
852
- # empty → O(1) false) and per-class verdicts memoise per run.
853
- def plugin_owns_receiver?(class_name, environment)
854
- registry = environment&.plugin_registry
855
- return false if registry.nil? || registry.empty?
856
-
857
- registry.contribution_index.owns_receiver?(class_name, environment)
858
- end
859
-
860
- def dep_source_class_name(receiver_type)
861
- case receiver_type
862
- when Type::Nominal, Type::Singleton then receiver_type.class_name
863
- end
864
- end
865
-
866
- # ADR-37 slice 2 / ADR-52 WD3 — gathers each plugin's return-type contribution from the
867
- # gated `dynamic_return` DSL, wrapped as a return-only `FlowContribution` for the shared
868
- # merger. (The legacy ungated `flow_contribution_for` escape valve was deleted once its
869
- # five users migrated.)
870
- EMPTY_CONTRIBUTIONS = [].freeze
871
- private_constant :EMPTY_CONTRIBUTIONS
872
-
873
- # Collects every plugin's flow / dynamic-return contribution for one call site. Two
874
- # prunings keep this off the hot path on plugin-heavy projects (it was the #1 allocation
875
- # site and a top CPU cost):
477
+ # The tiers `resolve_site` asks through an array outside the precise band, each where its comment in
478
+ # `resolve_site` says. A tier is in an array when nothing in `resolve_site` follows its answer; one whose
479
+ # answer `resolve_site` follows with a record on the scope or the reporter stays a call there.
876
480
  #
877
- # 1. Only the plugins that *structurally* implement a per-call path are visited —
878
- # `registry.contribution_index.for_method_dispatch` is the registry-ordered subset
879
- # declaring a `dynamic_return`. Iterating the subset in registry order, and gating each
880
- # path by membership, yields the exact same contributions in the same order as visiting
881
- # every plugin would (a skipped plugin's call returns nil/[] anyway). The
882
- # receiver-class ancestry match still happens per dispatch inside `dynamic_return_type`.
883
- # 2. Contributions accumulate lazily — allocate only when one actually appears, and share a
884
- # frozen empty array otherwise. The caller treats the result as read-only (`.empty?` /
885
- # `Merger.merge`).
886
- # 3. ADR-52 WD1 — method-name gates compiled at registry build. The global gate makes the
887
- # common "no plugin cares about this call" case a single Set probe; the per-plugin gate
888
- # skips a plugin whose `dynamic_return` rules are all `methods:`-gated on other names. A
889
- # pruned consultation could only have returned nil, so contribution order and content
890
- # are unchanged.
891
- def collect_plugin_contributions(registry, call_node, scope, receiver_type)
892
- index = registry.contribution_index
893
- relevant = index.for_method_dispatch
894
- return EMPTY_CONTRIBUTIONS if relevant.empty?
895
-
896
- # `call_node` is not always a CallNode — the `&:symbol` block path dispatches with the
897
- # `Prism::BlockArgumentNode` itself (`ExpressionTyper#symbol_block_return_type`). A bare
898
- # `.name` here raised, and the raise was silently absorbed by `block_return_type_for`'s
899
- # rescue, nil-ing the block type and flipping `select(&:p)`-style calls onto their
900
- # no-block Enumerator overloads (caught by the GitLab corpus gate).
901
- name = call_node.respond_to?(:name) ? call_node.name : nil
902
- return EMPTY_CONTRIBUTIONS unless index.dispatch_candidate?(name)
903
-
904
- collect_gated_contributions(index, relevant, name, call_node, scope, receiver_type)
905
- end
906
-
907
- # The post-gate walk, in registry order — the same order the ungated walk used.
908
- def collect_gated_contributions(index, relevant, name, call_node, scope, receiver_type)
909
- result = nil
910
- relevant.each do |plugin|
911
- next unless index.dynamic_candidate_for?(plugin, name)
481
+ # What Rigor bundles ahead of the RBS answer: the two override tables, then the `instance` the stdlib
482
+ # `Singleton` mixin grows and its upstream RBS leaves undeclared.
483
+ BUNDLED_OVERRIDE_TIERS = Ractor.make_shareable([
484
+ HktBuiltinReturn, StaticRefinement, SingletonMixinDispatch
485
+ ].freeze)
486
+ private_constant :BUNDLED_OVERRIDE_TIERS
487
+
488
+ SYNTHETIC_TIERS = Ractor.make_shareable([SyntheticMethodDispatch].freeze)
489
+ private_constant :SYNTHETIC_TIERS
490
+
491
+ # The two answers for a receiver that has no signature of its own to read: a type Rigor invented, then a
492
+ # `Dynamic`.
493
+ STUB_AND_UNIVERSAL_TIERS = Ractor.make_shareable([SynthesizedStub, UniversalObjectDispatch].freeze)
494
+ private_constant :STUB_AND_UNIVERSAL_TIERS
495
+
496
+ COMPOSITE_TIERS = Ractor.make_shareable([CompositeReceiver].freeze)
497
+ private_constant :COMPOSITE_TIERS
498
+
499
+ # Asks the tiers of one array in order and answers the first answer, or nil when every tier declines.
500
+ #
501
+ # The walk is a `while` loop on purpose. On Ruby 4.0.5 a `return` out of an `each` block allocates one object
502
+ # for every call that answers (a call that declines allocates none), so `tiers.each { |tier| ... return result }`
503
+ # cost an object per dispatch a tier array answered: 171,897 in one `rigor check lib` while the four arrays were
504
+ # walked that way (#3345). Keep the index walk; an `each`, a `find` or an `each_with_index` brings them back.
505
+ def first_tier_answer(tiers, context)
506
+ index = 0
507
+ count = tiers.size
508
+ while index < count
509
+ result = tiers[index].try_dispatch(context)
510
+ return result if result
912
511
 
913
- dynamic = plugin.dynamic_return_type(call_node: call_node, scope: scope, receiver_type: receiver_type)
914
- (result ||= []) << FlowContribution.new(return_type: dynamic) if dynamic
915
- rescue StandardError
916
- next
512
+ index += 1
917
513
  end
918
- result || EMPTY_CONTRIBUTIONS
514
+ nil
919
515
  end
920
516
 
921
517
  # Runs the precision tiers in order and returns the first non-nil answer. Each tier owns its own receiver/argument
922
518
  # shape checks; a tier that does not recognise the receiver returns nil so the next tier
923
- # can try. The RBS tier sits below this chain and is invoked by the outer `dispatch`
924
- # method.
519
+ # can try. The RBS tier sits below this chain and is invoked by `resolve_site`.
925
520
  #
926
521
  # The precise-tier folders, consulted in order via the uniform `_DispatchTier` interface
927
- # (`try_dispatch(CallContext) -> Type?`). Order is significant: ConstantFolding's
928
- # exact-value folds win first, the stdlib singleton folders sit in the middle (each
522
+ # (`try_dispatch(CallContext) -> Type?`). Order is significant: MetaIntrospection answers `class` and
523
+ # `new` first, behind the `Data` and `Struct` value tiers that `dispatch_precise_tiers` asks ahead of
524
+ # this array; ConstantFolding's exact-value folds win next, the stdlib singleton folders sit in the middle (each
929
525
  # gates on a distinct `Singleton` receiver, so their relative order is immaterial), and
930
526
  # BlockFolding runs near the end because its rules only apply to block-taking calls — the cheaper
931
527
  # arity folds above it filter the common cases first. Adding a precise tier is a one-line
932
528
  # append here rather than another link in a hand-written `||` ladder.
933
529
  PRECISE_TIERS_HEAD = Ractor.make_shareable([
934
- ConstantFolding, LiteralStringFolding, ShapeDispatch
530
+ MetaIntrospection, ConstantFolding, LiteralStringFolding, ShapeDispatch
935
531
  ].freeze)
936
532
  private_constant :PRECISE_TIERS_HEAD
937
533
 
@@ -939,9 +535,9 @@ module Rigor
939
535
  # singleton folders are mutually exclusive — each fires only on `Singleton[<its
940
536
  # class>]`, the first check in every `try_dispatch` — so at most one can match a given
941
537
  # receiver and their relative trial order was never observable. Compiling them into a
942
- # class-name table turns nine no-op trials per call into one Hash read, skipped entirely
538
+ # class-name table turns a no-op trial per folder into one Hash read, skipped entirely
943
539
  # when the receiver is not a `Singleton` (the overwhelmingly common case). The table sits
944
- # where the original eight sat in the old flat list: after ShapeDispatch, before KernelDispatch.
540
+ # after ShapeDispatch, before KernelDispatch.
945
541
  STDLIB_SINGLETON_FOLDERS = Ractor.make_shareable({
946
542
  "File" => FileFolding,
947
543
  "Shellwords" => ShellwordsFolding,
@@ -979,13 +575,8 @@ module Rigor
979
575
  struct_result = StructFolding.try_dispatch(context)
980
576
  return struct_result if struct_result
981
577
 
982
- meta_result = try_meta_introspection(context.receiver, context.method_name, context.args, context)
983
- return meta_result if meta_result
984
-
985
- PRECISE_TIERS_HEAD.each do |tier|
986
- result = tier.try_dispatch(context)
987
- return result if result
988
- end
578
+ head_result = first_tier_answer(PRECISE_TIERS_HEAD, context)
579
+ return head_result if head_result
989
580
 
990
581
  folder_result = dispatch_receiver_keyed_folder(context)
991
582
  return folder_result if folder_result
@@ -993,11 +584,7 @@ module Rigor
993
584
  kernel_result = dispatch_kernel_intrinsic(context)
994
585
  return kernel_result if kernel_result
995
586
 
996
- PRECISE_TIERS_TAIL.each do |tier|
997
- result = tier.try_dispatch(context)
998
- return result if result
999
- end
1000
- nil
587
+ first_tier_answer(PRECISE_TIERS_TAIL, context)
1001
588
  end
1002
589
 
1003
590
  # The folders the receiver's class selects, at most one per call: a stdlib singleton folder, or for a
@@ -1027,797 +614,6 @@ module Rigor
1027
614
  KernelDispatch.try_dispatch(context)
1028
615
  end
1029
616
 
1030
- def try_user_class_fallback(receiver_type, environment, call_node, context)
1031
- return nil if environment.nil?
1032
-
1033
- fallback_receiver = user_class_fallback_receiver(receiver_type, environment)
1034
- return nil if fallback_receiver.nil?
1035
- return nil if declared_by_external_ancestor?(receiver_type, environment, context)
1036
- return nil if project_singleton_definer?(receiver_type, context)
1037
-
1038
- # Preserve the ORIGINAL receiver type as the `self` substitution so `Kernel#dup: () ->
1039
- # self` and other `self`-returning methods route through Object's RBS while still
1040
- # returning the caller's type rather than `Object`. Without this, `base = self.dup`
1041
- # inside a `Bundler::URI::Generic` instance method types `base` as `Object` because
1042
- # `Bundler::URI::Generic` is not in RBS and the fallback's `self` resolves to Object.
1043
- #
1044
- # `public_only:` — when the call has an EXPLICIT, non-`self` receiver
1045
- # (`Favourite.select(...)`), suppress the private `Object`/`Kernel`/`Class` methods the
1046
- # fallback would otherwise resolve. Ruby raises `NoMethodError` for a private method
1047
- # called with an explicit receiver, so resolving `Favourite.select` to the private
1048
- # `Kernel#select` (`-> Array[String]`) is a confidently-wrong type. Implicit-self /
1049
- # `self.`-receiver calls (`puts`, `raise`, `require`) keep resolving — those are the
1050
- # fallback's intended targets.
1051
- RbsDispatch.try_dispatch(
1052
- context.with(
1053
- receiver: fallback_receiver,
1054
- self_type_override: receiver_type,
1055
- public_only: explicit_non_self_receiver?(call_node),
1056
- call_node: nil, scope: nil
1057
- )
1058
- )
1059
- end
1060
-
1061
- # Issue #2196 — a project class whose ancestry reaches a core or stdlib class before `Object` (`class FL <
1062
- # Array`) answers a name that class declares from that class, not from `Object` / `Kernel`: Ruby dispatches
1063
- # `select { … }` on an `FL` to `Array#select`, never to the private `Kernel#select` (`-> Array[String]`). The
1064
- # ancestor tiers decline such a name where they cannot type it (`RbsDispatch#returns_the_walked_ancestry?`),
1065
- # and the `Object` fallback then fabricated `Kernel#select`'s answer, so `fields.detect { |f| f.errors }` read
1066
- # `f` as `String`. The fallback declines the name instead, which leaves the call `Dynamic[top]`.
1067
- # {ExternalAncestorResolution.resolve} answers nil for a name only `Object`, `Kernel` or `BasicObject` declares,
1068
- # so `puts` and `raise` keep resolving.
1069
- def declared_by_external_ancestor?(receiver_type, environment, context)
1070
- return false unless receiver_type.is_a?(Type::Nominal)
1071
-
1072
- scope = context.scope
1073
- return false if scope.nil?
1074
-
1075
- class_name = receiver_type.class_name
1076
- method_name = context.method_name
1077
- if MemoAudit.enabled? && MemoAudit.suspended?
1078
- return external_ancestor_declares?(class_name, method_name, scope,
1079
- environment)
1080
- end
1081
-
1082
- memo = external_ancestor_memo(scope, environment)
1083
- key = [class_name, method_name]
1084
- if memo.key?(key)
1085
- return MemoAudit.check("user class fallback external ancestor", memo[key], class_name, method_name) do
1086
- external_ancestor_declares?(class_name, method_name, scope, environment)
1087
- end
1088
- end
1089
-
1090
- memo[key] = MemoAudit.key_audit("user class fallback external ancestor") do
1091
- external_ancestor_declares?(class_name, method_name, scope, environment)
1092
- end
1093
- end
1094
-
1095
- def external_ancestor_declares?(class_name, method_name, scope, environment)
1096
- !ExternalAncestorResolution.resolve(class_name, method_name, :instance,
1097
- scope: scope, environment: environment, record_dependencies: false).nil?
1098
- end
1099
-
1100
- # Issue #2284 — a class object whose singleton chain holds a project definer of the name (its own `def
1101
- # self.name`, one a project superclass wrote, an `extend`ed module's `def name`) answers from that definer,
1102
- # not from `Module#name` / `Class#…` on the `Singleton[Object]` fallback: Ruby's singleton ancestry puts
1103
- # every project entry ahead of `Class`. The fallback declines so the typer's singleton-body inference
1104
- # answers the definer's return, or `Dynamic` where the slot is contested and the def may not be the one
1105
- # that runs.
1106
- #
1107
- # The chain walk files the class edge of every entry it passes, so it runs only for a name some project file
1108
- # defines at all ({BlockCallTiming.project_defines_anywhere?}, which files the `defines:<name>` edge either way,
1109
- # #1459). Without it every class-body `private` / `attr_reader` call on a project class would depend on its
1110
- # whole ancestry. The by-name answer is memoised per discovery index; the edge is filed on every call.
1111
- def project_singleton_definer?(receiver_type, context)
1112
- return false unless receiver_type.is_a?(Type::Singleton)
1113
-
1114
- scope = context.scope
1115
- return false if scope.nil?
1116
- return false unless project_defines_name?(scope, context.method_name)
1117
-
1118
- !scope.singleton_def_through_ancestors(receiver_type.class_name, context.method_name).last.nil?
1119
- end
1120
-
1121
- def project_defines_name?(scope, method_name)
1122
- if MemoAudit.enabled? && MemoAudit.suspended?
1123
- return BlockCallTiming.project_defines_anywhere?(method_name,
1124
- scope)
1125
- end
1126
-
1127
- memo = defines_name_memo(scope)
1128
- if memo.key?(method_name)
1129
- Analysis::DependencyRecorder.read_missing(:defines, method_name) if Analysis::DependencyRecorder.active?
1130
- return MemoAudit.check("user class fallback defines name", memo[method_name], method_name) do
1131
- BlockCallTiming.project_defines_anywhere?(method_name, scope)
1132
- end
1133
- end
1134
-
1135
- memo[method_name] = MemoAudit.key_audit("user class fallback defines name") do
1136
- BlockCallTiming.project_defines_anywhere?(method_name, scope)
1137
- end
1138
- end
1139
-
1140
- # ADR-129 WD1 — a run-scoped Memo: one slot keyed on the identity of the discovery index and the environment,
1141
- # the only inputs the name table's answers read.
1142
- DEFINES_NAME_MEMO = TypingState.memo(
1143
- :user_class_fallback_defines_name,
1144
- run_scoped: true, audit: "user class fallback defines name",
1145
- reason: "one [discovery, environment, names] slot keyed on the identities of the discovery " \
1146
- "index and the environment; each name's answer reads only them"
1147
- )
1148
- private_constant :DEFINES_NAME_MEMO
1149
-
1150
- # One slot per discovery index and environment, as {#external_ancestor_memo} keeps its own: the answer reads
1151
- # only the frozen discovery tables and the environment's `pre_eval:` patches.
1152
- def defines_name_memo(scope)
1153
- discovery = scope.discovery
1154
- environment = scope.environment
1155
- state = TypingState.current
1156
- slot = state[DEFINES_NAME_MEMO]
1157
- unless slot && slot[0].equal?(discovery) && slot[1].equal?(environment)
1158
- slot = [discovery, environment, {}]
1159
- state[DEFINES_NAME_MEMO] = slot
1160
- end
1161
- slot[2]
1162
- end
1163
-
1164
- # ADR-129 WD1 — a run-scoped Memo, keyed as {DEFINES_NAME_MEMO} is.
1165
- EXTERNAL_ANCESTOR_MEMO = TypingState.memo(
1166
- :user_class_fallback_external_ancestor,
1167
- run_scoped: true, audit: "user class fallback external ancestor",
1168
- reason: "one [discovery, environment, answers] slot keyed on the identities of the " \
1169
- "discovery index and the RBS environment, the only inputs the walk reads"
1170
- )
1171
- private_constant :EXTERNAL_ANCESTOR_MEMO
1172
-
1173
- # One slot per discovery index and environment, as `RbsDispatch#ancestor_memo_slot` keeps its own: the answer
1174
- # reads only the frozen discovery tables and the RBS environment, and its walk is withheld from dependency
1175
- # recording, so it may be served again for the same pair.
1176
- def external_ancestor_memo(scope, environment)
1177
- discovery = scope.discovery
1178
- state = TypingState.current
1179
- slot = state[EXTERNAL_ANCESTOR_MEMO]
1180
- unless slot && slot[0].equal?(discovery) && slot[1].equal?(environment)
1181
- slot = [discovery, environment, {}]
1182
- state[EXTERNAL_ANCESTOR_MEMO] = slot
1183
- end
1184
- slot[2]
1185
- end
1186
-
1187
- # True when the call node carries an explicit receiver that is not the literal `self`.
1188
- # Such a call cannot legally dispatch to a private method, so the user-class fallback must
1189
- # skip private signatures rather than return a confidently-wrong type. Returns false for
1190
- # implicit-self calls and `self.`-receiver calls (both may legally reach a private method
1191
- # in modern Ruby), and false when no `call_node` is supplied (internal dispatcher callers).
1192
- def explicit_non_self_receiver?(call_node)
1193
- return false if call_node.nil?
1194
- return false unless call_node.respond_to?(:receiver)
1195
-
1196
- receiver = call_node.receiver
1197
- return false if receiver.nil?
1198
-
1199
- !receiver.is_a?(Prism::SelfNode)
1200
- end
1201
-
1202
- def user_class_fallback_receiver(receiver_type, environment)
1203
- case receiver_type
1204
- when Type::Nominal
1205
- # Modules: even when RBS knows the module, an instance method on a mixin-only module
1206
- # (e.g. `PP::ObjectMixin`) observes Kernel / Object methods through every concrete
1207
- # includer's ancestor chain. Route through the `Nominal[Object]` fallback so
1208
- # `self.inspect` / `self.respond_to?` / `self.class` resolve cleanly when the module
1209
- # itself does not declare them.
1210
- known = Rigor::Reflection.rbs_class_known?(receiver_type.class_name, environment: environment)
1211
- return environment.nominal_for_name("Object") if !known || environment.rbs_module?(receiver_type.class_name)
1212
-
1213
- nil
1214
- when Type::Singleton
1215
- return nil if Rigor::Reflection.rbs_class_known?(receiver_type.class_name, environment: environment)
1216
-
1217
- environment.singleton_for_name("Class")
1218
- end
1219
- end
1220
-
1221
- # Issue #1101 — the composite-receiver projection tier, the LAST thing `resolve` tries.
1222
- #
1223
- # Every tier above needs a receiver it can *name*: `receiver_descriptor`, the discovered-method
1224
- # lookup, the dependency-source and synthesized-stub tiers and the user-class fallback all switch
1225
- # on `Nominal` / `Singleton` / a member carrier. A `Union` or a `Difference` is none of those, so a
1226
- # composite receiver whose members would each resolve perfectly well still fell through the whole
1227
- # chain and landed `Dynamic[top]`.
1228
- #
1229
- # `RbsDispatch` already distributes over a `Union` (and erases a `Difference` to its base, #533),
1230
- # but it does so INSIDE one tier, so a member that needs a LOWER tier — a user class with no RBS,
1231
- # a discovered `def`, an opt-in gem — makes the whole union decline. That was the corpus shape before
1232
- # #2430: rigor-actionpack typed `params[:k]` as the bare `ActionController::Parameters | nil` union, the
1233
- # `Parameters` arm resolved only through the user-class fallback, and so `params[:k].present?` / `#==`
1234
- # / `#blank?` / `#to_s` read opaque on every Rails app. Measured by toggling this file alone: the
1235
- # named-pair census drained 137 sites on redmine and 56 on mastodon, and `rigor check` reported the
1236
- # same diagnostics on both arms across eight survey targets. The plugin now answers a `Dynamic`
1237
- # carrier, which this projection does not reach, so those off-chain calls read `Dynamic[top]` until
1238
- # the carrier is projected here too (#2448).
1239
- #
1240
- # **Why the bottom and not next to `RbsDispatch`.** Sitting here, the tier can only ever replace a
1241
- # `Dynamic[top]` the typer was about to produce — the same ADR-5 argument {UniversalObjectDispatch}
1242
- # makes. Hoisting the projection above `RbsDispatch` would change answers that resolve today, which
1243
- # is a different change with a different measurement.
1244
- #
1245
- # **The projection rule** (`receiver_projection` below; the normative statement lives in
1246
- # [`inference-engine.md`](docs/internal-spec/inference-engine.md) § "Composite receivers"):
1247
- #
1248
- # - `Union[A, B, …]` projects to its members. Each is dispatched through this same chain and the
1249
- # results are unioned; if ANY member declines, the whole tier declines. Never a partial answer —
1250
- # a union whose members disagree about whether the method exists is exactly the case where an
1251
- # answer would be a guess.
1252
- # - `Difference[base, nil]` projects to `base` with its nil-valued members removed. Removing `nil`
1253
- # from a receiver cannot change method resolution at all: `NilClass` is nobody's ancestor, so
1254
- # every remaining inhabitant looks a method up exactly as a plain `base` inhabitant does, and the
1255
- # carrier is value-set-equal to the projection. This is `T.must(x)` (rigor-sorbet's
1256
- # `strip_nil`), which builds `Difference[inferred(x), Constant[nil]]` — over a `T?` local that
1257
- # base IS a union, which is why the two arms compose rather than being separate features.
1258
- # - Any other `Difference` DECLINES. `A − B` for a real `B` is a claim about which inhabitants
1259
- # survive, and the projection has nowhere to put it: dispatching on `A` re-admits exactly the
1260
- # overrides `B` contributed, and over a union base (`(String | Integer) − Integer` is Strings
1261
- # only) it re-admits a member the difference eliminated and unions in its answer — a WIDER type
1262
- # than today's decline, on a shape no corpus target produces. Subtracting a class from a union
1263
- # needs an algebra the `Difference` carrier does not have (it removes a value set, not a member),
1264
- # so the honest answer is to keep declining until something demands it. `RbsDispatch`'s #533
1265
- # erasure is untouched and still answers these for an RBS-known base.
1266
- #
1267
- # `self` binds to the PROJECTED receiver, not to the composite: the projection is the exact set of
1268
- # inhabitants that can reach the method, so a `-> self` method (`dup`, `itself`, `tap`) answers per
1269
- # member and the union reassembles them — `(String | Symbol)#itself` is `String | Symbol`. Nothing is
1270
- # lost on the `Difference` arm because the projection is value-set-equal to the carrier there. This
1271
- # falls out of re-entering `resolve` rather than needing a `self_type_override`.
1272
- def try_composite_receiver(context)
1273
- members = receiver_projection(context.receiver)
1274
- return nil if members.nil? || members.size > COMPOSITE_PROJECTION_MEMBERS
1275
-
1276
- plugin_typed = []
1277
- results = members.map do |member|
1278
- resolve(
1279
- receiver_type: member, method_name: context.method_name, arg_types: context.args,
1280
- block_type: context.block_type, environment: context.environment,
1281
- call_node: context.call_node, scope: context.scope, plugin_typed_sink: plugin_typed
1282
- )
1283
- end
1284
- return nil if results.any?(&:nil?)
1285
-
1286
- plugin_typed.uniq.each { |node| context.scope&.record_plugin_typed_call(node) }
1287
- Type::Combinator.union(*results)
1288
- end
1289
-
1290
- # An upper bound on the fan-out, because this tier re-runs the FULL dispatch chain per member.
1291
- # Real unions are two or three members wide; a receiver wider than this is a join the engine has
1292
- # already lost precision on, and paying N chain walks to union N answers is not worth it.
1293
- COMPOSITE_PROJECTION_MEMBERS = 8
1294
- private_constant :COMPOSITE_PROJECTION_MEMBERS
1295
-
1296
- # The receivers each member of a composite carrier is dispatched as, or nil when the carrier is not
1297
- # projectable. Every member returned MUST itself be non-composite: that is what bounds the re-entry
1298
- # into `resolve` at one level, by construction rather than by a counter — the nested call reaches
1299
- # this tier with a receiver it declines immediately. A normalized `Union` never holds a `Union`, so
1300
- # the shapes the guard turns away are a `Difference` over a `Difference` (`T.must(T.must(x))`) and a
1301
- # `Union` holding one (`c ? T.must(y) : Bar.new`, which normalizes to `(A - nil) | Bar`). Both
1302
- # decline exactly as they did before this tier existed; neither appears in the survey corpus.
1303
- def receiver_projection(receiver)
1304
- members =
1305
- case receiver
1306
- when Type::Union then receiver.members
1307
- when Type::Difference then difference_projection(receiver)
1308
- end
1309
- return nil if members.nil? || members.empty?
1310
- return nil if members.any? { |member| member.is_a?(Type::Union) || member.is_a?(Type::Difference) }
1311
-
1312
- members
1313
- end
1314
-
1315
- # `Difference[base, nil]` projects to `base` minus its nil-valued members; every other difference
1316
- # declines. The nil filter runs over a scalar base as well as a union one, so the rule stays total:
1317
- # `Combinator.difference` does not normalize `NilClass - nil` (or `nil - nil`) to `Bot`, and this
1318
- # tier must not project `[NilClass]` and answer a NilClass method for a carrier with no inhabitant.
1319
- # Nothing observable turns on it today — `RbsDispatch`'s #533 erasure sits above this tier and
1320
- # already answers a nil-only base from the base's own descriptor — which is why the guard is here
1321
- # rather than in `Combinator`, where it would be a normalization change with its own blast radius.
1322
- def difference_projection(difference)
1323
- return nil unless nil_valued_type?(difference.removed)
1324
-
1325
- base = difference.base
1326
- members = base.is_a?(Type::Union) ? base.members : [base]
1327
- retained = members.reject { |member| nil_valued_type?(member) }
1328
- return nil if retained.empty?
1329
-
1330
- retained
1331
- end
1332
-
1333
- # `nil` as either carrier spells it: the value-pinned `Constant[nil]` the engine normally produces,
1334
- # and the `Nominal[NilClass]` a widened or RBS-sourced position carries.
1335
- def nil_valued_type?(type)
1336
- (type.is_a?(Type::Constant) && type.value.nil?) ||
1337
- (type.is_a?(Type::Nominal) && type.class_name == "NilClass")
1338
- end
1339
-
1340
- # Slice 7 phase 8 — meta-introspection shortcuts. The default `Object#class` RBS return
1341
- # type is `Class`, but for a receiver of known nominal identity we can do better:
1342
- # `instance_of(Foo).class` is `Singleton[Foo]` (the class object itself), which downstream
1343
- # dispatch uses to resolve `self.class.some_class_method`. The same logic answers
1344
- # `Foo.class` as `Singleton[Class]` (deliberate; calling `.class` on a class object yields
1345
- # `Class`, the metaclass). We also special-case `is_a?`-adjacent calls and the trivial
1346
- # `instance_of?(self)` later as the rule catalogue grows; for now only `class` is handled.
1347
- def try_meta_introspection(receiver_type, method_name, arg_types = [], context = nil)
1348
- case method_name
1349
- when :class then meta_class(receiver_type, context&.environment)
1350
- when :new then meta_new(receiver_type, arg_types, context)
1351
- end
1352
- end
1353
-
1354
- def meta_class(receiver_type, environment = nil)
1355
- case receiver_type
1356
- when Type::Nominal
1357
- # An instance of module `M` is an instance of some class that includes `M`, never of `M`
1358
- # itself: `self.class` in `M`'s instance method is that includer, which no RBS type names.
1359
- # `Dynamic[Class]` keeps the surface every class shares (`name`, `ancestors`) and answers
1360
- # nothing for the includer's own singleton methods.
1361
- if environment&.rbs_module?(receiver_type.class_name)
1362
- return Type::Combinator.dynamic(Type::Combinator.nominal_of("Class"))
1363
- end
1364
-
1365
- Type::Combinator.singleton_of(receiver_type.class_name)
1366
- when Type::Constant then constant_metaclass(receiver_type.value)
1367
- end
1368
- end
1369
-
1370
- # `Singleton[Foo].new` returns `Nominal[Foo]` (a fresh instance), regardless of whether Foo
1371
- # is in RBS. This short-circuits the Class.new generic-`instance` plumbing for user
1372
- # classes, so a discovered-class `ScanAccumulator.new` types as
1373
- # `Nominal[ScanAccumulator]` rather than `Class`.
1374
- #
1375
- # v0.0.7 — for the curated set of immutable scalar-shaped classes that
1376
- # `Type::Constant::SCALAR_CLASSES` accepts (today: `Pathname`), `.new(Constant<…>)` lifts
1377
- # to a `Constant<…>` carrier so downstream method calls fold through the standard catalog
1378
- # tier.
1379
- def meta_new(receiver_type, arg_types = [], context = nil)
1380
- return nil unless receiver_type.is_a?(Type::Singleton)
1381
-
1382
- constant_lift = constant_constructor_lift(receiver_type.class_name, arg_types)
1383
- return constant_lift if constant_lift
1384
-
1385
- array_lift = array_new_lift(receiver_type.class_name, arg_types, context&.block_type)
1386
- return array_lift if array_lift
1387
-
1388
- range_lift = range_new_lift(receiver_type.class_name, arg_types)
1389
- return range_lift if range_lift
1390
-
1391
- set_lift = set_new_lift(receiver_type.class_name, arg_types, context)
1392
- return set_lift if set_lift
1393
-
1394
- hash_lift = hash_new_lift(receiver_type.class_name, arg_types, context&.call_node)
1395
- return hash_lift if hash_lift
1396
-
1397
- regexp_lift = regexp_new_lift(receiver_type.class_name, arg_types)
1398
- return regexp_lift if regexp_lift
1399
-
1400
- date_lift = date_new_lift(receiver_type.class_name, arg_types)
1401
- return date_lift if date_lift
1402
-
1403
- struct_new_lift = struct_new_lift(receiver_type.class_name, arg_types)
1404
- return struct_new_lift if struct_new_lift
1405
-
1406
- class_new_lift = class_new_lift(receiver_type.class_name, arg_types, context)
1407
- return class_new_lift if class_new_lift
1408
-
1409
- declared_or_nominal(receiver_type.class_name, context)
1410
- end
1411
-
1412
- # Issue #2884 — the `meta_new` tail: a declared `def self.new` ({DeclaredConstructor}), else `Nominal[X]`.
1413
- def declared_or_nominal(class_name, context)
1414
- declared = context && DeclaredConstructor.try_dispatch(class_name, context)
1415
- declared || Type::Combinator.nominal_of(class_name)
1416
- end
1417
-
1418
- # `Struct.new(:a, :b)` synthesises an anonymous Struct *subclass* (a class object), not a
1419
- # Struct *instance* — so the chained idiom `Struct.new(:a, :b).new(1, 2)` must resolve
1420
- # `.new` again on a class-like carrier. The constant-bound form (`S = Struct.new(:a);
1421
- # S.new(1)`) already records `Singleton[S]` via `ScopeIndexer#record_meta_new_constant?`;
1422
- # this lift gives the *chained* (anonymous) position the same class-like carrier so the
1423
- # trailing `.new` dispatches instead of firing a spurious `undefined method 'new' for
1424
- # Struct`.
1425
- #
1426
- # The disambiguation mirrors `ScopeIndexer#struct_new_call?`: a call whose positionals are
1427
- # all `Constant<Symbol>` literals is a member-list class definition → `Singleton[Struct]`.
1428
- # The following `AnonStruct.new(1, 2)` carries non-symbol args, so it falls through this
1429
- # gate to `Nominal[Struct]` (a fresh instance) via the `meta_new` tail. ADR-48 deferred full
1430
- # Struct *value* folding (member-reader precision) on mutability grounds; this is the
1431
- # narrower `.new`-dispatch-only fix and contributes no member layout, so `instance.a` stays
1432
- # at its RBS/Dynamic type.
1433
- def struct_new_lift(class_name, arg_types)
1434
- return nil unless class_name == "Struct"
1435
-
1436
- positional = arg_types.grep_v(Type::HashShape)
1437
- return nil if positional.empty?
1438
- return nil unless positional.all? { |t| t.is_a?(Type::Constant) && t.value.is_a?(Symbol) }
1439
-
1440
- Type::Combinator.singleton_of("Struct")
1441
- end
1442
-
1443
- # `Class.new` and `Class.new(Parent)` create a brand-new anonymous class. Statically that
1444
- # class is representable as the parent's singleton type — its singleton-method surface is
1445
- # the parent's (plus whatever the block defines, which we do not statically track here),
1446
- # so `Singleton[Parent]` lets downstream `klass.some_class_method` resolve. No parent →
1447
- # `singleton(Object)` (or the block's anonymous class, #319 below). Anything else (dynamic parent, more
1448
- # than one positional, …) falls back to `Nominal[Class]` via the surrounding `meta_new` tail.
1449
- # #319 — a `Class.new do ... end` with no parent is NOT `Object`: the block body is a class body, so the
1450
- # class owns whatever that body defines. Answering `Singleton[Object]` handed the call site `Object`'s
1451
- # zero-arity `new` and `Object`'s method surface, so an `initialize(bucket)` written right there produced
1452
- # `wrong number of arguments ... (given 1, expected 0)` on code Ruby runs happily. `ScopeIndexer` registers
1453
- # the body's methods under the call site's anonymous name; return that name so the lookups reach them.
1454
- #
1455
- # Scoped to the parentless form on purpose. `Class.new(Parent) { ... }` keeps `Singleton[Parent]`: the
1456
- # anonymous name would have to carry the full ancestor chain for `Parent`'s own surface to stay reachable,
1457
- # and the parentless case is where the false positive lives.
1458
- def class_new_lift(class_name, arg_types, context = nil)
1459
- return nil unless class_name == "Class"
1460
-
1461
- if arg_types.empty?
1462
- anonymous = anonymous_class_new_name(context)
1463
- return Type::Combinator.singleton_of(anonymous || "Object")
1464
- end
1465
- return nil unless arg_types.size == 1
1466
-
1467
- parent = arg_types.first
1468
- factory_parent = parent.is_a?(Type::StructClass) || parent.is_a?(Type::DataClass)
1469
- return nil if factory_parent && context&.call_node&.block
1470
- return parent if parent.is_a?(Type::Singleton) || factory_parent
1471
-
1472
- nil
1473
- end
1474
-
1475
- # The synthetic name `ScopeIndexer` keyed this call site's block body by, or nil when the context carries no
1476
- # call node (internal dispatcher callers) or the call has no block. The source path is passed through
1477
- # verbatim — including when it is nil, which is exactly what `ScopeIndexer` saw for the same file — so the
1478
- # two passes derive the same name whether or not the caller supplied a path.
1479
- def anonymous_class_new_name(context)
1480
- return nil if context.nil?
1481
-
1482
- AnonymousMetaClass.name_for(context.call_node, context.scope&.source_path)
1483
- end
1484
-
1485
- # ADR-15 Phase 4b.x — `Ractor.make_shareable` on both the outer Hash and each lambda value.
1486
- # A plain `.freeze` leaves the Procs unshareable; reading `CONSTANT_CONSTRUCTORS[class]`
1487
- # from a worker Ractor would raise `Ractor::IsolationError`, which the `rescue
1488
- # StandardError` in `constant_constructor_lift` silently swallows — `meta_new` then falls
1489
- # back to `Nominal[Pathname]` in pool mode while sequential builds the `Constant<Pathname>`
1490
- # lift. The divergence surfaces downstream as a spurious `call.argument-type-mismatch`
1491
- # (sequential's `argument_type_diagnostic` short-circuits on Constant<Pathname> because
1492
- # Pathname is not in its CONSTANT_CLASSES table; pool's Nominal[Pathname] doesn't
1493
- # short-circuit). Surfaced on GitLab FOSS via `lib/gitlab/mail_room.rb:17`.
1494
- CONSTANT_CONSTRUCTORS = Ractor.make_shareable({
1495
- "Pathname" => Ractor.make_shareable(lambda { |arg|
1496
- Pathname.new(arg)
1497
- })
1498
- })
1499
- private_constant :CONSTANT_CONSTRUCTORS
1500
-
1501
- def constant_constructor_lift(class_name, arg_types)
1502
- builder = CONSTANT_CONSTRUCTORS[class_name]
1503
- return nil if builder.nil?
1504
- return nil unless arg_types.size == 1
1505
-
1506
- arg = arg_types.first
1507
- return nil unless arg.is_a?(Type::Constant) && arg.value.is_a?(String)
1508
-
1509
- result = builder.call(arg.value)
1510
- Type::Combinator.constant_of(result)
1511
- rescue StandardError
1512
- nil
1513
- end
1514
-
1515
- # `Array.new(n, value)` and `Array.new(n)` (no value, default `nil`) lift to a per-position
1516
- # `Tuple[…]` when `n` is a small `Constant<Integer>`. Cap at `ARRAY_NEW_TUPLE_LIMIT` (16)
1517
- # so a `Array.new(1_000_000)` does not balloon the carrier; oversize calls fall through to
1518
- # the element-parameter seed below.
1519
- #
1520
- # #317 — `Array.new(n) { |i| ... }` fills every slot from the BLOCK's return type instead
1521
- # of the two-arg `(n, default_value)` overload's `nil` fill. The block and the trailing
1522
- # `default_value` positional are mutually exclusive per `Array#initialize`'s RBS overload
1523
- # set (`(int size, ?E default_value) -> void` vs `(int size) { (Integer index) -> E } ->
1524
- # void`), so a block present at the call site always wins over any (illegal, but tolerated
1525
- # rather than rejected here) second positional.
1526
- ARRAY_NEW_TUPLE_LIMIT = 16
1527
- private_constant :ARRAY_NEW_TUPLE_LIMIT
1528
-
1529
- def array_new_lift(class_name, arg_types, block_type = nil)
1530
- return nil unless class_name == "Array"
1531
- return nil if arg_types.empty? || arg_types.size > 2
1532
-
1533
- size = array_new_size(arg_types.first)
1534
- if size && !size.negative? && size <= ARRAY_NEW_TUPLE_LIMIT
1535
- return Type::Combinator.tuple_of(*Array.new(size, block_type || array_new_fill(arg_types[1])))
1536
- end
1537
-
1538
- array_new_seed(arg_types, block_type)
1539
- end
1540
-
1541
- # The carrier for a constructor whose size is not a small literal — `Array.new(n)`,
1542
- # `Array.new(n, v)`, `Array.new(n) { … }`.
1543
- #
1544
- # This must never be a BARE `Array`. A nominal with no type argument carries no element
1545
- # arm, and the ADR-56 block/loop seams read exactly that as an ELEMENTLESS seed — a fresh
1546
- # accumulator whose every store the seam saw — so they CLOSE the carrier over the block's
1547
- # own stores. `acc = Array.new(n); [1].each { acc.push(1) }` then read `Array[1]` for an
1548
- # array whose other `n` slots hold `nil`, and `acc = Array.new(n, "x")` read `Array[1]` and
1549
- # drew `undefined method 'upcase'` on the correct `acc.first.upcase` (issue #615). Handing
1550
- # the seams a real element arm is what puts the constructor under the #586 rule, which
1551
- # keeps every seed arm through the join.
1552
- #
1553
- # The element itself is the fill value's / block result's type, value-pin widened for the
1554
- # reason `hash_new_lift` widens its default: the slots are rewritten over the array's
1555
- # lifetime, so pinning the parameter to the literal would let a later `a[i] == "x"`
1556
- # constant-fold.
1557
- #
1558
- # **The no-fill form seeds the GRADUAL element, not `nil`.** `Array.new(n)` really does put
1559
- # a `nil` in every slot, but a `Nominal` seed gets DECLARED-carrier semantics downstream:
1560
- # the #586 join keeps a seed arm forever, and `MutationWidening#widen_for_mutator` declines
1561
- # a `Nominal` outright, so no whole-array rewrite — `[]=`, `fill`, `map!`, `replace`,
1562
- # `concat` — can ever retract it. The placeholder would become a permanent nil possibility
1563
- # over the allocate-then-fill idiom that is the whole point of the constructor:
1564
- #
1565
- # dp = Array.new(xs.size); dp[0] = 1
1566
- # (1...n).each { |i| dp[i] = dp[i - 1] + xs[i] } # `undefined method '+' for nil`
1567
- #
1568
- # buf = Array.new(256); 256.times { |i| buf[i] = i.to_s }
1569
- # buf.each { |c| c.upcase } # possible nil receiver
1570
- #
1571
- # Both are correct Ruby, and both went from quiet to an ERROR on the `nil` seed. The true
1572
- # positive the `nil` would buy — `Array.new(n).first.upcase` on an array nothing ever wrote
1573
- # — is not worth the dominant idiom, so the no-fill form stays gradual whatever the size
1574
- # argument reads as. (That also happens to absorb Ruby's array-convertible COPY overload:
1575
- # `Array.new([1, 2])` is `[1, 2]`, not two nils.)
1576
- def array_new_seed(arg_types, block_type)
1577
- fill = block_type || arg_types[1]
1578
- return array_seed_of(Type::Combinator.untyped) if fill.nil?
1579
-
1580
- element = array_new_element(fill)
1581
- # `Array.new(n, nil)` is the same allocate-then-fill idiom as `Array.new(n)`, spelled with the
1582
- # placeholder made explicit — concurrent-ruby writes `@Resolutions = ::Array.new(count, nil)` and
1583
- # fills it by index. A nil-only element would be a PERMANENT nil arm (a Nominal carrier's element is
1584
- # never widened by a later `[]=` / `fill` / `replace`), so every read of a filled slot would draw
1585
- # `undefined method '…' for nil` on correct code. Same trade as the no-fill form above: the seam
1586
- # needs an arm, not a precise one.
1587
- element = Type::Combinator.untyped if nil_only_element?(element)
1588
- array_seed_of(element)
1589
- end
1590
-
1591
- # Whether the widened fill leaves nothing but `nil` behind — see {#array_new_seed}.
1592
- def nil_only_element?(element)
1593
- members = element.is_a?(Type::Union) ? element.members : [element]
1594
- members.all? do |member|
1595
- (member.is_a?(Type::Constant) && member.value.nil?) ||
1596
- (member.is_a?(Type::Nominal) && member.class_name == "NilClass")
1597
- end
1598
- end
1599
-
1600
- def array_seed_of(element)
1601
- Type::Combinator.nominal_of("Array", type_args: [element])
1602
- end
1603
-
1604
- # A fill / block result as an element PARAMETER. Value pinning is dropped, and a literal
1605
- # container widens to its nominal: `Array.new(n) { [] }` builds n INDEPENDENT arrays that
1606
- # the program then appends to, and `Array[Tuple[]]` claims every one of them stays empty —
1607
- # the adjacency-list idiom would read `adj[i].first` as `nil`. Both conversions go through
1608
- # {MutationWidening}'s own helpers, the single owner of "literal container → parameterised
1609
- # nominal" that `MemberShapeProjection` already borrows.
1610
- #
1611
- # The walk is **recursive**, through `Union` members and through a container's own elements /
1612
- # values alike. Every one of those positions is a fresh object per constructed slot that the
1613
- # program goes on to mutate, so stopping at the outermost level only moved the wrong-precise
1614
- # answer one level in: `a = Array.new(n) { [[1]] }; a[0][0] << 5` left `Array[Array[[1]]]`
1615
- # and folded `a[0][0].last == 5` always-falsey on correct code. Judging a `Union` wholesale
1616
- # was the same defect one axis over — `Array.new(n) { flag ? [1] : [2] }` kept both arms as
1617
- # fixed-arity tuples.
1618
- #
1619
- # `depth` is defensive only. A `Type` carrier is an immutable value object assembled
1620
- # bottom-up (`Tuple.new(elements)`, `HashShape.new(pairs)`), so it cannot contain itself and
1621
- # this walk is bounded by the source literal's own nesting; the cap costs nothing on any
1622
- # literal a person writes and stops a malformed carrier from recursing forever.
1623
- ARRAY_NEW_FILL_DEPTH_LIMIT = 8
1624
- private_constant :ARRAY_NEW_FILL_DEPTH_LIMIT
1625
-
1626
- def array_new_element(type, depth = 0)
1627
- return Type::Combinator.untyped if depth > ARRAY_NEW_FILL_DEPTH_LIMIT
1628
-
1629
- case type
1630
- when Type::Tuple then MutationWidening.widen_tuple(recursed_tuple(type, depth))
1631
- when Type::HashShape then MutationWidening.widen_hash_shape(recursed_hash_shape(type, depth))
1632
- when Type::Union then Type::Combinator.union(*type.members.map { |m| array_new_element(m, depth + 1) })
1633
- else Type::Combinator.widen_value_pinned(type)
1634
- end
1635
- end
1636
-
1637
- # The same tuple / hash shape with every element / value already widened, so the
1638
- # {MutationWidening} helper that consumes it sees nominals where the literal had pins. The
1639
- # rebuilt carrier is a throwaway argument — never surfaced — and the helpers read only
1640
- # `elements` / `pairs`, so no policy field rides on it.
1641
- def recursed_tuple(type, depth)
1642
- Type::Combinator.tuple_of(*type.elements.map { |e| array_new_element(e, depth + 1) })
1643
- end
1644
-
1645
- def recursed_hash_shape(type, depth)
1646
- Type::Combinator.hash_shape_of(
1647
- type.pairs.transform_values { |v| array_new_element(v, depth + 1) }
1648
- )
1649
- end
1650
-
1651
- def array_new_size(type)
1652
- return nil unless type.is_a?(Type::Constant) && type.value.is_a?(Integer)
1653
-
1654
- type.value
1655
- end
1656
-
1657
- def array_new_fill(type)
1658
- return Type::Combinator.constant_of(nil) if type.nil?
1659
-
1660
- type
1661
- end
1662
-
1663
- # `Hash.new(default)` — lifts the default value's type into the Hash's value parameter so
1664
- # a subsequent `h[k]` read surfaces the default type rather than `Dynamic[top]`. The
1665
- # common counter idiom `h = Hash.new(0); h[k] += 1` then types the read as `Integer`. The
1666
- # key parameter is left `untyped` (the default carrier imposes no key constraint), so
1667
- # reads of any key resolve through the value parameter. A value-pinned `Constant` default
1668
- # (`0`) is widened to its nominal (`Integer`): the hash's values mutate over its lifetime,
1669
- # so pinning the parameter to the literal would be unsound for the aggregate.
1670
- #
1671
- # Only the single-argument default form folds. The zero-arg (`Hash.new`) and the block
1672
- # form (`Hash.new { |h, k| … }`) keep the bare `Nominal[Hash]` answer — the block's value
1673
- # type is not available at this `:new` dispatch site, and conservatively leaving the read
1674
- # as today's behaviour is precision-additive.
1675
- #
1676
- # Issue #1812 — a brace-less keyword hash is `Hash#initialize`'s `capacity:` keyword, not the
1677
- # default (`Hash.new(capacity: 10).default` is `nil`), so it is dropped before counting the
1678
- # positionals. A braced hash (`Hash.new({ capacity: 10 })`) is a positional and stays the default.
1679
- def hash_new_lift(class_name, arg_types, call_node = nil)
1680
- return nil unless class_name == "Hash"
1681
-
1682
- arg_types = hash_new_positionals(arg_types, call_node)
1683
- return nil unless arg_types&.size == 1
1684
-
1685
- default = arg_types.first
1686
- return nil if default.nil?
1687
-
1688
- value = Type::Combinator.widen_value_pinned(default)
1689
- Type::Combinator.nominal_of("Hash", type_args: [Type::Combinator.untyped, value])
1690
- end
1691
-
1692
- # `Hash.new`'s positional argument types: `arg_types` without a trailing brace-less keyword hash. A literal
1693
- # send (`Hash.send(:new, capacity: 1)`) dispatches with the outer call node, whose arguments are the
1694
- # selector symbol followed by `arg_types`' own, and is read through that offset. When the node's arguments
1695
- # correspond otherwise, a sole hash argument may be the keyword hash, so the answer is nil (decline) and the
1696
- # bare `Hash` stands; any other argument cannot be a keyword hash and is kept.
1697
- def hash_new_positionals(arg_types, call_node)
1698
- return arg_types[0...-1] if ArgumentNodes.keyword_hash_last?(call_node, arg_types)
1699
-
1700
- arguments = call_node.respond_to?(:arguments) ? call_node.arguments&.arguments : nil
1701
- return arg_types if arguments.nil? || arguments.size == arg_types.size
1702
- if arguments.size == arg_types.size + 1 && arguments.first.is_a?(Prism::SymbolNode)
1703
- return arguments.last.is_a?(Prism::KeywordHashNode) ? arg_types[0...-1] : arg_types
1704
- end
1705
-
1706
- arg_types.last.is_a?(Type::HashShape) ? nil : arg_types
1707
- end
1708
-
1709
- # `Range.new(b, e)` / `Range.new(b, e, excl)` — folds to `Constant[Range]` when both
1710
- # endpoints are `Constant[Integer]` or both are `Constant[String]`, and the optional third
1711
- # argument is a `Constant[true/false]`. Nil endpoints (beginless / endless ranges) are not
1712
- # folded because the useful instance methods (`to_a`, `first`, `last`) are not defined for
1713
- # them; the RBS tier answers `Nominal[Range]` for those forms.
1714
- def range_new_lift(class_name, arg_types)
1715
- return nil unless class_name == "Range"
1716
- return nil if arg_types.size < 2 || arg_types.size > 3
1717
-
1718
- b_type = arg_types[0]
1719
- e_type = arg_types[1]
1720
-
1721
- return nil unless b_type.is_a?(Type::Constant) && e_type.is_a?(Type::Constant)
1722
-
1723
- b_val = b_type.value
1724
- e_val = e_type.value
1725
-
1726
- # Only fold homogeneous Integer or String endpoint pairs.
1727
- return nil unless b_val.instance_of?(e_val.class)
1728
- return nil unless b_val.is_a?(Integer) || b_val.is_a?(String)
1729
-
1730
- excl = range_new_excl(arg_types[2])
1731
- return nil if excl.nil?
1732
-
1733
- Type::Combinator.constant_of(Range.new(b_val, e_val, excl))
1734
- rescue StandardError
1735
- nil
1736
- end
1737
-
1738
- # Resolves the optional `exclude_end` argument for `range_new_lift`. Returns `false` (no
1739
- # arg), `true`/`false` (Constant[bool] arg), or `nil` to signal "decline" (wrong type /
1740
- # wrong value class).
1741
- def range_new_excl(excl_type)
1742
- case excl_type
1743
- when nil then false
1744
- when Type::Constant
1745
- excl_type.value if [true, false].include?(excl_type.value)
1746
- end
1747
- end
1748
-
1749
- # `Set.new` / `Set.new(tuple_of_constants)` — folds to `Constant[Set]` when zero arguments
1750
- # are given or the single argument is a `Tuple` whose every element is a `Constant[T]`.
1751
- # Mirrors `SetFolding#fold_new` but lives here so the `:new` path in
1752
- # `try_meta_introspection` can reach it before the RBS tier answers `Nominal[Set]`.
1753
- def set_new_lift(class_name, arg_types, context = nil)
1754
- return nil unless class_name == "Set"
1755
-
1756
- SetFolding.fold_new(arg_types, context&.call_node, context&.block_type)
1757
- end
1758
-
1759
- # `Regexp.new(pattern)` / `Regexp.new(pattern, opts)` — folds to `Constant[Regexp]` when
1760
- # the pattern is a `Constant[String]`. Mirrors `RegexpFolding#fold_new` but lives here so
1761
- # the `:new` path in `try_meta_introspection` can reach it.
1762
- def regexp_new_lift(class_name, arg_types)
1763
- return nil unless class_name == "Regexp"
1764
- return nil if arg_types.empty? || arg_types.size > 2
1765
-
1766
- pattern_arg = arg_types.first
1767
- return nil unless pattern_arg.is_a?(Type::Constant) && pattern_arg.value.is_a?(String)
1768
-
1769
- opts = if arg_types.size == 2
1770
- opt_type = arg_types[1]
1771
- return nil unless opt_type.is_a?(Type::Constant)
1772
-
1773
- opt_type.value
1774
- else
1775
- 0
1776
- end
1777
-
1778
- Type::Combinator.constant_of(Regexp.new(pattern_arg.value, opts))
1779
- rescue StandardError
1780
- nil
1781
- end
1782
-
1783
- # `Date.new(y, m, d)` / `DateTime.new(y, m, d, h, min, s, off)` — folds to `Constant[Date]`
1784
- # / `Constant[DateTime]` when every argument is a `Constant` carrying an Integer (or, for
1785
- # the `DateTime` offset / `start` slots, a Rational or String). `Date.new` carries no
1786
- # timezone, and `DateTime.new`'s offset defaults to UTC, so the literal is
1787
- # machine-independent. `Date.today` / `Date.parse` are not constructors here — they are
1788
- # non-deterministic / string-dependent and stay `Nominal[Date]`.
1789
- DATE_NEW_CLASSES = %w[Date DateTime].freeze
1790
- private_constant :DATE_NEW_CLASSES
1791
-
1792
- def date_new_lift(class_name, arg_types)
1793
- return nil unless DATE_NEW_CLASSES.include?(class_name)
1794
- return nil unless arg_types.size.between?(1, 8)
1795
- return nil unless arg_types.all?(Type::Constant)
1796
-
1797
- values = arg_types.map(&:value)
1798
- return nil unless values.all? { |v| v.is_a?(Integer) || v.is_a?(Rational) || v.is_a?(String) }
1799
-
1800
- klass = class_name == "Date" ? Date : DateTime
1801
- Type::Combinator.constant_of(klass.new(*values))
1802
- rescue StandardError
1803
- nil
1804
- end
1805
-
1806
- CONSTANT_METACLASSES = {
1807
- Integer => "Integer", Float => "Float", String => "String",
1808
- Symbol => "Symbol", Range => "Range",
1809
- TrueClass => "TrueClass", FalseClass => "FalseClass",
1810
- NilClass => "NilClass"
1811
- }.freeze
1812
- private_constant :CONSTANT_METACLASSES
1813
-
1814
- def constant_metaclass(value)
1815
- CONSTANT_METACLASSES.each do |klass, name|
1816
- return Type::Combinator.singleton_of(name) if value.is_a?(klass)
1817
- end
1818
- nil
1819
- end
1820
-
1821
617
  # Returns the positional block parameter types declared by the receiving method's selected
1822
618
  # RBS overload, translated into `Rigor::Type`. Used by the StatementEvaluator's CallNode
1823
619
  # handler to bind block parameter names before evaluating the block body.
@@ -1842,6 +638,24 @@ module Rigor
1842
638
 
1843
639
  RbsDispatch.block_param_types(context)
1844
640
  end
641
+
642
+ # Issue #3265 — {#expected_block_param_types} as a {RbsDispatch::BlockSignature}, which also says whether the
643
+ # block receives a fixed number of values and types its rest and trailing positionals. An iterator-table answer
644
+ # is a fixed list. Nil when neither tier answers.
645
+ def expected_block_signature(receiver_type:, method_name:, arg_types:, environment: nil, scope: nil)
646
+ return nil if receiver_type.nil?
647
+
648
+ context = CallContext.build(
649
+ receiver: receiver_type, method_name: method_name, args: arg_types, environment: environment, scope: scope
650
+ )
651
+ iterator_result = IteratorDispatch.block_param_types(context)
652
+ if iterator_result
653
+ return RbsDispatch::BlockSignature.new(required: iterator_result, optional: [], rest: nil, trailing: [],
654
+ keywords: false)
655
+ end
656
+
657
+ RbsDispatch.block_signature(context)
658
+ end
1845
659
  end
1846
660
  end
1847
661
  end