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
@@ -0,0 +1,499 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+ require_relative "../../reflection"
5
+ require_relative "../../source/constant_path"
6
+ require_relative "../../type"
7
+ require_relative "../../builtins/regex_refinement"
8
+ require_relative "../project_method_ownership"
9
+
10
+ module Rigor
11
+ module Inference
12
+ module Narrowing
13
+ # ADR-116 C1 — the regex match predicates and the capture-group analysis: `=~`, `!~`, `match`, `match?`
14
+ # and the whole-receiver refinement a match proves ({.analyse_regex_match_predicate},
15
+ # {.analyse_regex_not_match_predicate}, {.analyse_whole_regex_match_predicate}), the scopes a successful match
16
+ # binds ({.regex_match_predicate_scopes}), the receiver's kind ({.match_member_kinds}) and the groups a pattern
17
+ # captures unconditionally ({.unconditional_capture_groups}).
18
+ #
19
+ # Calls back into `Narrowing` for `narrow_nil` and `narrow_not_class` only, which `match_member_kind` asks to
20
+ # classify a receiver member as `nil`, a `String` or a `Symbol`; nothing else in `Narrowing` is reached from
21
+ # here. `Narrowing`'s `case`/`when` entries and `string_match_receiver?` call {.regex_match_predicate_scopes},
22
+ # {.unconditional_capture_groups} and {.match_member_kinds}.
23
+ # rubocop:disable-next Metrics/ModuleLength
24
+ module RegexMatch
25
+ module_function
26
+
27
+ # A recognised `=~` regex pattern operand: the pattern `source` string and whether it was
28
+ # compiled in extended (`//x`) mode. Extraction from a literal `RegularExpressionNode` and from
29
+ # a value-pinned `Constant[Regexp]` share this carrier so the participation walk and the
30
+ # extended-mode bail read one shape.
31
+ RegexMatchPattern = Data.define(:source, :extended)
32
+ private_constant :RegexMatchPattern
33
+
34
+ # Survey item (b): `/regex/ =~ str` and `str =~ /regex/` bind the regex match-data
35
+ # globals on each edge ({#regex_match_edges}), gated on the subject (#1494): an edge is
36
+ # narrowed only when the receiver proves what the frame holds on it
37
+ # ({#match_receiver_edges}), and an edge it cannot vouch for keeps the match globals
38
+ # forgotten. A `String?` subject keeps the match edge only, since `NilClass#=~` answers
39
+ # nil with the previous match still bound; an untyped one is read the same way.
40
+ #
41
+ # Returns nil (no narrowing) when the receiver / argument pair does not resolve to exactly one
42
+ # regex pattern we can count (see {#regex_match_pattern}).
43
+ def analyse_regex_match_predicate(node, scope)
44
+ gated_regex_match_edges(node, scope)
45
+ end
46
+
47
+ # Issue #1379 — `subject !~ pattern` is `Kernel#!~`, which returns `!(subject =~ pattern)`. It runs the same
48
+ # match in the caller's frame, so its edges are {#analyse_regex_match_predicate}'s swapped: the falsey edge is
49
+ # the match edge (`$~` a `MatchData`, an unconditional `$N` a `String`, and the whole-receiver refinement), the
50
+ # truthy edge the no-match edge (`$~` and `$N` nil). The same patterns are recognised and the same ones
51
+ # declined (a non-regex operand, an ambiguous constant, `//x`), and the receiver gates the edges alike.
52
+ def analyse_regex_not_match_predicate(node, scope)
53
+ gated_regex_match_edges(node, scope)&.reverse
54
+ end
55
+
56
+ # `[match_edge, no_match_edge]` of a `=~` / `!~` predicate, each kept only where
57
+ # {#match_receiver_edges} lets it be; an edge it cannot vouch for is the entry scope with the
58
+ # match globals forgotten, since the call may still have rebound them. The whole-receiver
59
+ # refinement is kept only when the local it would narrow is known to be a String on the
60
+ # match edge ({#refinable_operand?}).
61
+ def gated_regex_match_edges(node, scope)
62
+ edges = regex_match_edges(node, scope, refine: refinable_operand?(node, scope))
63
+ return nil if edges.nil?
64
+
65
+ match, no_match = edges
66
+ forgotten = scope.forget_match_globals
67
+ case match_receiver_edges(node, scope)
68
+ when :both then [match, no_match]
69
+ when :match then [match, forgotten]
70
+ else [forgotten, forgotten]
71
+ end
72
+ end
73
+
74
+ # The ungated edges of a match:
75
+ #
76
+ # - Match edge (`=~` returned an Integer position — the match succeeded): `$~` to
77
+ # `Nominal[MatchData]`; `$&` and `$1..$N` (where N is the number of capture groups in
78
+ # the regex source) to `Nominal[String]`. This is the same optimistic-narrowing shape
79
+ # the existing `analyse_match_write` uses for named captures inside `if /(?<x>...)/
80
+ # =~ str` — optional groups in the regex source (`(\d+)?`) would bind `$N` to `nil`
81
+ # at runtime, but the floor here matches the common idiom (required captures) and
82
+ # lets `unless /(\d+)/ =~ s; raise; end; $1.to_i` resolve cleanly.
83
+ # - No-match edge (`=~` returned nil): `$~` and every numbered / back-reference
84
+ # global bound to `Constant<nil>`.
85
+ #
86
+ # `refine: false` leaves out the whole-receiver refinement, which names a String.
87
+ def regex_match_edges(node, scope, refine:)
88
+ return nil if node.arguments.nil?
89
+ return nil unless node.arguments.arguments.size == 1
90
+
91
+ arg = node.arguments.arguments.first
92
+ pattern = regex_match_pattern(node.receiver, arg, scope)
93
+ return nil if pattern.nil?
94
+ # Extended mode (`//x`) lets the pattern carry free whitespace and `#` comments, and a
95
+ # comment may contain a literal `(` — which the light char-scan walker would miscount as a
96
+ # capturing group, shifting `$N` indices and narrowing the wrong global. That is a
97
+ # false-negative-class misnarrowing, so bail rather than risk it. The literal path shares
98
+ # this bail: `RegularExpressionNode` carries the same latent miscount.
99
+ return nil if pattern.extended
100
+
101
+ unconditional = unconditional_capture_groups(pattern.source)
102
+ truthy, falsey = regex_match_predicate_scopes(scope, unconditional)
103
+ # #164 — layer whole-receiver refinement onto the truthy edge without disturbing the
104
+ # match-global logic above. A successful `str =~ /\A\d+\z/` proves the WHOLE string
105
+ # matched, so the string operand narrows to the imported refinement the anchored pattern
106
+ # names. The falsey edge is untouched: a failed match proves nothing about the shape.
107
+ truthy = apply_whole_receiver_refinement(truthy, node.receiver, arg, pattern.source, scope) if refine
108
+ [truthy, falsey]
109
+ end
110
+
111
+ # Which edges of `recv =~ pattern` / `recv !~ pattern` the receiver lets {#gated_regex_match_edges} narrow:
112
+ # `:both`, `:match` (the match edge only) or nil. `Kernel#!~` dispatches `=~` on the receiver:
113
+ #
114
+ # - A Regexp receiver (the pattern on the left) runs `Regexp#=~`, which sets `$~` on both outcomes, a `nil`
115
+ # argument included: `:both`.
116
+ # - `String#=~` and `Symbol#=~` do the same: `:both` when every member of the receiver's type is a String
117
+ # (a project subclass of String included) or a Symbol.
118
+ # - `NilClass#=~` answers nil and leaves `$~` alone, so a nil receiver reaches the no-match edge with the
119
+ # previous match still bound; it never reaches the match edge. A `Dynamic` receiver may be nil at run time
120
+ # whatever its static facet says. So does a safe-navigation call, which answers nil without matching on a
121
+ # nil receiver.
122
+ #
123
+ # The two operators part over a receiver that is none of those ({#match_operator_edges},
124
+ # {#not_match_operator_edges}).
125
+ def match_receiver_edges(node, scope)
126
+ return nil if node.receiver.nil?
127
+
128
+ edges =
129
+ if regex_operand_pattern(node.receiver, scope).is_a?(RegexMatchPattern)
130
+ :both
131
+ else
132
+ kinds = match_member_kinds(scope.type_of(node.receiver), scope)
133
+ node.name == :=~ ? match_operator_edges(kinds) : not_match_operator_edges(kinds)
134
+ end
135
+ return edges unless node.safe_navigation?
136
+
137
+ :match if edges && node.name == :=~
138
+ end
139
+
140
+ STRING_MATCH_KINDS = %i[string string_subclass symbol].freeze
141
+ private_constant :STRING_MATCH_KINDS
142
+
143
+ # `recv =~ pattern`'s match edge is the truthy one. Only a member known to define its own `=~` in the
144
+ # project keeps it out (#1494): that method binds `$~` in its own frame, not the caller's. Any other member
145
+ # either matches in the caller's frame, answers nil (`NilClass`), or has no `=~` at all (`Integer` since
146
+ # Ruby 3.2 drops `Object#=~`) and so never reaches the edge; a receiver the analyzer cannot classify keeps the
147
+ # edge, as every `=~` did before #1494.
148
+ def match_operator_edges(kinds)
149
+ return nil if kinds.include?(:custom)
150
+ return :both if kinds.all? { |kind| STRING_MATCH_KINDS.include?(kind) }
151
+
152
+ :match
153
+ end
154
+
155
+ # `recv !~ pattern`'s match edge is the falsey one, which a receiver whose `=~` is not the caller's match
156
+ # also reaches, so it is kept only when every member is a String, a Symbol, nil, or a `Dynamic` that is
157
+ # untyped or whose facet holds only those (#1379).
158
+ def not_match_operator_edges(kinds)
159
+ return :both if kinds.all? { |kind| STRING_MATCH_KINDS.include?(kind) }
160
+
161
+ :match if kinds.all? { |kind| (STRING_MATCH_KINDS + %i[nil dynamic]).include?(kind) }
162
+ end
163
+
164
+ # Whether the local operand {#apply_whole_receiver_refinement} would narrow holds only Strings and nil, which
165
+ # the match edge excludes. The refinement names a String, so a member that may be a Symbol — a Symbol, or an
166
+ # untyped `Dynamic` that may be one at run time — keeps it out: `return unless raw =~ /\A\d+\z/` on an untyped
167
+ # `raw` must not make `raw.to_proc` an undefined method (#1379, #1494).
168
+ def refinable_operand?(node, scope)
169
+ operand = [node.receiver, *node.arguments&.arguments].find { |o| o.is_a?(Prism::LocalVariableReadNode) }
170
+ type = operand && scope.local(operand.name)
171
+ return true if type.nil?
172
+
173
+ match_member_kinds(type, scope).all? { |kind| %i[string nil].include?(kind) }
174
+ end
175
+
176
+ def match_member_kinds(type, scope)
177
+ (type.is_a?(Type::Union) ? type.members : [type]).map { |member| match_member_kind(member, scope) }
178
+ end
179
+
180
+ # `:custom` for a member whose class the project gives a `=~` of its own (in its ancestry, a reopened
181
+ # `String` included); `:string` or `:symbol` for a member {.narrow_not_class} proves a String or a Symbol (a
182
+ # value or refinement of either, or a class the environment orders below it); `:string_subclass` for a
183
+ # project class whose superclass chain reaches `String`, which the environment cannot order; `:nil`;
184
+ # `:dynamic` for a `Dynamic` whose facet is untyped or holds only Strings, Symbols and nil; or nil for anything
185
+ # else.
186
+ def match_member_kind(member, scope)
187
+ return match_dynamic_kind(member, scope) if member.is_a?(Type::Dynamic)
188
+ return :nil if Narrowing.narrow_nil(member) == member && !member.is_a?(Type::Bot)
189
+ return :custom if custom_match_operator?(member, scope)
190
+
191
+ environment = scope.environment
192
+ { "String" => :string, "Symbol" => :symbol }.each do |class_name, kind|
193
+ if Narrowing.narrow_not_class(member, class_name, environment: environment, scope: scope).is_a?(Type::Bot)
194
+ return kind
195
+ end
196
+ end
197
+ :string_subclass if project_string_subclass?(member, scope)
198
+ end
199
+
200
+ def match_dynamic_kind(member, scope)
201
+ facet = member.static_facet
202
+ return :dynamic if Type::Combinator.untyped?(member)
203
+
204
+ facet_kinds = match_member_kinds(facet, scope)
205
+ :dynamic if facet_kinds.all? { |kind| (STRING_MATCH_KINDS + [:nil]).include?(kind) }
206
+ end
207
+
208
+ def custom_match_operator?(member, scope)
209
+ targets = ProjectMethodOwnership.targets(member)
210
+ return false if targets.nil?
211
+
212
+ targets.any? { |class_name, kind| ProjectMethodOwnership.defines?(class_name, :=~, kind, scope) }
213
+ end
214
+
215
+ def project_string_subclass?(member, scope)
216
+ return false unless member.is_a?(Type::Nominal) && scope.known_user_class?(member.class_name)
217
+
218
+ scope.external_ancestor_name_candidates(member.class_name, mixins: false)
219
+ .flatten.any? { |name| name.to_s.delete_prefix("::") == "String" }
220
+ end
221
+
222
+ # `str.match?(/\A\d+\z/)` — `String#match?` is a pure boolean predicate whose truthy edge
223
+ # proves a property of the ENTIRE receiver. When the argument is a fully `\A…\z`-anchored
224
+ # single-char-class pattern recognised by {RegexRefinement.for_whole_pattern}, narrow the
225
+ # receiver local to the matching imported refinement on the truthy edge; the falsey edge
226
+ # passes through unchanged (failing one pattern proves nothing about the string's shape).
227
+ # A non-literal / unanchored / `\Z` / line-anchored / `//x` pattern falls through to no
228
+ # narrowing.
229
+ #
230
+ # The refinement names a String, so it shares `=~`'s gate (#1955): a receiver that may be a Symbol, or an
231
+ # untyped one, is left as it is ({#refinable_operand?}).
232
+ def analyse_whole_regex_match_predicate(node, scope)
233
+ return nil unless node.receiver.is_a?(Prism::LocalVariableReadNode)
234
+ return nil if node.arguments.nil? || node.arguments.arguments.size != 1
235
+ return nil unless refinable_operand?(node, scope)
236
+
237
+ pattern = regex_operand_pattern(node.arguments.arguments.first, scope)
238
+ return nil unless pattern.is_a?(RegexMatchPattern)
239
+ return nil if pattern.extended
240
+
241
+ refinement = ::Rigor::Builtins::RegexRefinement.for_whole_pattern(pattern.source)
242
+ return nil if refinement.nil?
243
+
244
+ local_name = node.receiver.name
245
+ return nil if scope.local(local_name).nil?
246
+
247
+ [scope.with_local(local_name, refinement), scope]
248
+ end
249
+
250
+ # Narrows the string operand of a `=~` predicate to a whole-receiver refinement when the
251
+ # regex source is a recognised `\A…\z`-anchored pattern. Returns the (possibly unchanged)
252
+ # truthy scope; the falsey edge is never touched by this layer.
253
+ def apply_whole_receiver_refinement(truthy, receiver, arg, source, scope)
254
+ refinement = ::Rigor::Builtins::RegexRefinement.for_whole_pattern(source)
255
+ return truthy if refinement.nil?
256
+
257
+ # `regex_match_pattern` already resolved the regex operand from a literal or a
258
+ # `Constant[Regexp]` constant read — never a bare local — so the string subject is
259
+ # unambiguously the local-read operand, if either operand is one.
260
+ subject = [receiver, arg].find { |operand| operand.is_a?(Prism::LocalVariableReadNode) }
261
+ return truthy if subject.nil? || scope.local(subject.name).nil?
262
+
263
+ truthy.with_local(subject.name, refinement)
264
+ end
265
+
266
+ # Recognises the regex pattern operand of a `=~` predicate. An operand resolves to a regex when
267
+ # it is either a syntactic `RegularExpressionNode` literal OR a constant read whose type is a
268
+ # value-pinned `Constant[Regexp]` (`RE = /.../` and `RE = Regexp.new(...)` both fold to the
269
+ # carrier in the whole-program constant pre-pass). Returns a single {RegexMatchPattern}, or nil
270
+ # (no narrowing) when NEITHER operand resolves to a regex, when BOTH do (`/a/ =~ /b/` — no
271
+ # string subject to bind), or when a constant operand is ambiguous — typed as a `Union` from a
272
+ # twice-assigned constant, where no single source can be pinned.
273
+ def regex_match_pattern(left, right, scope)
274
+ left_pattern = regex_operand_pattern(left, scope)
275
+ right_pattern = regex_operand_pattern(right, scope)
276
+ return nil if left_pattern == :ambiguous || right_pattern == :ambiguous
277
+
278
+ patterns = [left_pattern, right_pattern].grep(RegexMatchPattern)
279
+ patterns.size == 1 ? patterns.first : nil
280
+ end
281
+
282
+ # Classifies one `=~` operand: a {RegexMatchPattern} when it resolves to a regex (literal or
283
+ # `Constant[Regexp]`), `:ambiguous` when a constant operand types as a `Union` (a twice-assigned
284
+ # constant), or nil when the operand is not a regex at all.
285
+ def regex_operand_pattern(node, scope)
286
+ case node
287
+ when Prism::RegularExpressionNode
288
+ RegexMatchPattern.new(source: node.unescaped, extended: node.extended?)
289
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
290
+ regex_operand_from_constant(node, scope)
291
+ end
292
+ end
293
+
294
+ # Resolves a constant-reference operand to a regex pattern via the shared lexical-constant
295
+ # resolution (`Reflection.resolve_constant_type`). `Regexp#options` gives the real
296
+ # extended-mode flag; `Regexp#source` the pattern. Returns `:ambiguous` for a `Union`-typed
297
+ # constant so the caller bails, and nil when the constant does not resolve to a `Constant[Regexp]`.
298
+ def regex_operand_from_constant(node, scope)
299
+ name = Source::ConstantPath.qualified_name_or_nil(node)
300
+ return nil if name.nil?
301
+
302
+ type = Reflection.resolve_constant_type(name, scope: scope,
303
+ rooted: Source::ConstantPath.rooted?(node))
304
+ return :ambiguous if type.is_a?(Type::Union)
305
+ return nil unless type.is_a?(Type::Constant)
306
+
307
+ value = type.value
308
+ return nil unless value.is_a?(Regexp)
309
+
310
+ RegexMatchPattern.new(source: value.source, extended: value.options.anybits?(Regexp::EXTENDED))
311
+ end
312
+
313
+ # Curated set of match globals bound non-nil on every successful `=~` regardless of grouping:
314
+ # `$~` (the MatchData), `$&` (whole match), `` $` `` (pre-match), `$'` (post-match). Numbered
315
+ # references (`$1..$N`) and `$+` (the last matched group) are handled separately because they
316
+ # depend on the regex source — `$+` is gated on the same participation set as `$N` (#177).
317
+ REGEX_MATCH_GLOBALS = %i[$~ $& $` $'].freeze
318
+ private_constant :REGEX_MATCH_GLOBALS
319
+
320
+ # `unconditional` is the Set of 1-based numbered-capture indices whose group is
321
+ # guaranteed to participate in any successful match (no optional quantifier on the
322
+ # group or an ancestor, no alternation in the pattern). Those `$N` are bound to
323
+ # `String`; every other numbered group present in the pattern stays `String | nil` on
324
+ # both edges (a truthy match leaves an optional group nil at runtime), so we do not
325
+ # narrow it on the truthy edge.
326
+ #
327
+ # Both edges start from `scope` with the match globals forgotten (#1385): the match rebinds every one of them,
328
+ # so a `$N` an earlier match narrowed says nothing here. Without that, a `when /(x)/` arm, or the right operand
329
+ # of `s =~ /(a)(b)(c)/ && t =~ /(x)/`, kept `$2` and `$3` narrowed to `String` where Ruby reads nil.
330
+ def regex_match_predicate_scopes(scope, unconditional)
331
+ string_t = Type::Combinator.nominal_of("String")
332
+ match_data_t = Type::Combinator.nominal_of("MatchData")
333
+ nil_t = Type::Combinator.constant_of(nil)
334
+
335
+ truthy = scope.forget_match_globals
336
+ falsey = truthy
337
+ truthy = truthy.with_global(:$~, match_data_t)
338
+ falsey = falsey.with_global(:$~, nil_t)
339
+ REGEX_MATCH_GLOBALS.each do |name|
340
+ next if name == :$~
341
+
342
+ truthy = truthy.with_global(name, string_t)
343
+ falsey = falsey.with_global(name, nil_t)
344
+ end
345
+ unconditional.each do |index|
346
+ name = :"$#{index}"
347
+ truthy = truthy.with_global(name, string_t)
348
+ falsey = falsey.with_global(name, nil_t)
349
+ end
350
+ # `$+` is the LAST matched group, so it is nil on a successful match whose groups are all
351
+ # optional (`"b" =~ /(a)?b/` matches yet leaves `$+` nil) or absent (no capture group). It
352
+ # narrows to `String` only when some group is guaranteed to participate — the same
353
+ # participation gate `$N` uses (#177). With no unconditional group it is left unbound on both
354
+ # edges (fall through to the RBS `String?` default), exactly as an optional `$N` is.
355
+ unless unconditional.empty?
356
+ truthy = truthy.with_global(:$+, string_t)
357
+ falsey = falsey.with_global(:$+, nil_t)
358
+ end
359
+ [truthy, falsey]
360
+ end
361
+
362
+ # Returns the Set of 1-based numbered-capture indices that are UNCONDITIONAL in
363
+ # `source`: present on every successful match because no optional quantifier (`?`,
364
+ # `*`, `{0,…}`, `{,…}`) applies to the group or any ancestor group, and the pattern contains no
365
+ # alternation (`|`). Optional and alternation-reachable groups are excluded — at
366
+ # runtime `$N` is `nil` for them even when the overall match succeeds, so narrowing
367
+ # them to non-nil `String` would be unsound. The walker is intentionally light (char
368
+ # scan, not a regex-AST parse): backslash escapes are skipped; `(?:…)`, lookahead
369
+ # `(?=…)`/`(?!…)`, and lookbehind `(?<=…)`/`(?<!…)` do not capture; named groups
370
+ # `(?<name>…)` / `(?'name'…)` do. Once the pattern has a named group, Ruby numbers only
371
+ # the named groups and a plain `(…)` does not capture (#1471): `/(?<x>a)(b)/` has one
372
+ # group, so `$2` is nil. Conservatism is one-directional — when in doubt a group is
373
+ # treated as conditional (dropped from the Set), never the reverse.
374
+ def unconditional_capture_groups(source)
375
+ # `unconditional` collects every capturing index; a group is later removed (with its
376
+ # whole subtree) when it is optionally quantified, nested under an optional ancestor,
377
+ # or sits in an alternation branch. `stack` holds one frame per open group (plus a
378
+ # virtual root frame for the top level) as `[group_index_or_nil, descendant_indices,
379
+ # alternated?]`. A `|` marks the CURRENT group's frame alternated — its branches are
380
+ # mutually exclusive, so its descendant captures may be absent on a successful match;
381
+ # the group itself still participates. Closing a frame rolls its subtree up to the
382
+ # parent so an optional / alternated ancestor disqualifies it.
383
+ state = { unconditional: Set.new, stack: [[nil, [], false]], group_index: 0, named: named_groups?(source) }
384
+ each_structural_char(source) { |pos, chr| scan_group_char(source, pos, chr, state) }
385
+ # Drain the virtual root: a top-level `|` disqualifies all.
386
+ finalize_frame(state, state[:stack].pop, optional: false)
387
+ state[:unconditional]
388
+ end
389
+
390
+ # Yields each position of `source` outside a backslash escape and a character class, with its char.
391
+ def each_structural_char(source)
392
+ pos = 0
393
+ length = source.length
394
+ while pos < length
395
+ chr = source[pos]
396
+ if chr == "\\"
397
+ pos += 2
398
+ next
399
+ end
400
+ if chr == "["
401
+ pos = skip_char_class(source, pos) + 1
402
+ next
403
+ end
404
+ yield pos, chr
405
+ pos += 1
406
+ end
407
+ end
408
+
409
+ def named_groups?(source)
410
+ each_structural_char(source) { |pos, chr| break true if chr == "(" && named_group?(source, pos) } == true
411
+ end
412
+
413
+ # Updates the walk `state` at a group-relevant char during
414
+ # {#unconditional_capture_groups}: `(` pushes a frame, `)` pops and resolves it, `|`
415
+ # flags the current frame as alternated.
416
+ def scan_group_char(source, pos, chr, state)
417
+ case chr
418
+ when "("
419
+ idx = nil
420
+ if capturing_group?(source, pos, named: state[:named])
421
+ idx = (state[:group_index] += 1)
422
+ state[:unconditional] << idx
423
+ end
424
+ state[:stack].push([idx, [], false])
425
+ when ")"
426
+ finalize_frame(state, state[:stack].pop, optional: next_quantifier_optional?(source, pos + 1))
427
+ when "|"
428
+ state[:stack].last[2] = true
429
+ end
430
+ end
431
+
432
+ # Resolves a closed (or virtual-root) group frame: its subtree is its own index plus
433
+ # every descendant index. The subtree is disqualified when the group is optionally
434
+ # quantified or its branches are alternated (only the descendants in that case — but a
435
+ # self subtree always keeps its own index unless optional).
436
+ def finalize_frame(state, frame, optional:)
437
+ idx, descendants, alternated = frame
438
+ subtree = descendants.dup
439
+ subtree << idx if idx
440
+ state[:unconditional].subtract(subtree) if optional
441
+ # Alternation disqualifies the branch contents (descendants),
442
+ # never the enclosing group itself.
443
+ state[:unconditional].subtract(descendants) if alternated
444
+ state[:stack].last && state[:stack].last[1].concat(subtree)
445
+ end
446
+
447
+ # True when the group whose closing paren is at `source[pos]` is followed by a
448
+ # quantifier that permits zero repetitions (`?`, `*`, `{0…}`, `{,…}`). `+` and `{1,…}`
449
+ # do NOT make a group optional. A lazy/possessive suffix (`*?`, `*+`) is still
450
+ # zero-permitting on the base quantifier. `{,…}` counts only with a digit after the
451
+ # comma — `{,}`, `{,x}` and `{, }` are literal braces, not quantifiers.
452
+ def next_quantifier_optional?(source, pos)
453
+ case source[pos]
454
+ when "?", "*" then true
455
+ when "{" then source[pos + 1] == "0" ||
456
+ (source[pos + 1] == "," && source[pos + 2].to_s.match?(/\d/))
457
+ else false
458
+ end
459
+ end
460
+
461
+ # A plain `(…)` captures unless the pattern has a named group (`named:`); of the `(?…)` forms only a named
462
+ # group does.
463
+ def capturing_group?(source, pos, named:)
464
+ return !named unless source[pos + 1] == "?"
465
+
466
+ named_group?(source, pos)
467
+ end
468
+
469
+ # `(?<name>…)` and `(?'name'…)` are named groups; `(?<=…)`/`(?<!…)` (lookbehind) and
470
+ # `(?:…)`/`(?=…)`/`(?!…)` are not.
471
+ def named_group?(source, pos)
472
+ return false unless source[pos + 1] == "?"
473
+ return true if source[pos + 2] == "'"
474
+
475
+ source[pos + 2] == "<" && source[pos + 3] != "=" && source[pos + 3] != "!"
476
+ end
477
+
478
+ def skip_char_class(source, start)
479
+ pos = start + 1
480
+ pos += 1 if source[pos] == "^"
481
+ pos += 1 if source[pos] == "]" # literal ] as first member
482
+ while pos < source.length
483
+ return pos if source[pos] == "]"
484
+
485
+ pos += source[pos] == "\\" ? 2 : 1
486
+ end
487
+ pos
488
+ end
489
+
490
+ private_class_method :gated_regex_match_edges, :regex_match_edges, :match_receiver_edges, :match_operator_edges,
491
+ :not_match_operator_edges, :refinable_operand?, :match_member_kind, :match_dynamic_kind,
492
+ :custom_match_operator?, :project_string_subclass?, :apply_whole_receiver_refinement,
493
+ :regex_match_pattern, :regex_operand_pattern, :regex_operand_from_constant,
494
+ :each_structural_char, :named_groups?, :scan_group_char, :finalize_frame,
495
+ :next_quantifier_optional?, :capturing_group?, :named_group?, :skip_char_class
496
+ end
497
+ end
498
+ end
499
+ end