Commit 2fad5785

2fad57854031Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

feat(analyze,codegen): nil-guard narrow extends to int_array.index int?

infer_nil_guard_narrow_type already recognized s.index / rindex / find_index on a string receiver and narrowed the post-guard local to plain int. Extends the same logic to arr.index on an int_array now that the call returns int? instead of poly. Result:

i = arr.index(target) return 0 if i.nil? i + 1

emits mrb_int lv_i = sp_IntArray_index_opt(...), a sentinel check via sp_int_is_nil, and direct lv_i + 1LL arithmetic — no box / unbox round-trip through sp_RbVal at any point, which is the whole reason the int? encoding exists.

test/array_index_int_opt_narrow.rb covers the narrow path plus the plain .inspect / .nil? cases on the int? value (which the prior commit's int? dispatch already handled).

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
2fad57854031
Parent
6f920fb2551c

compiler_helpers.rbmodifiedView file

@@ -91,6 +91,12 @@
9191 if rt_eg == "string" || rt_eg == "mutable_str"
9292 return "int"
9393 end
94+ # Array#index family on int_array now returns int? (sentinel-
95+ # encoded). After `return if h.nil?` the live arm sees the value
96+ # as a plain int, same as the String#index narrow above.
97+ if rt_eg == "int_array"
98+ return "int"
99+ end
94100 ""
95101 end
96102