Commit 1aeb8559

1aeb8559dc2fMerged

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

Description

fix(analyze,codegen): String#rindex(str) returns int? to enable nil-narrow

s.rindex(needle) with a plain string arg used to widen to "poly" via sp_str_rindex_poly (sp_RbVal return). The subsequent nil-check ternary couldn't narrow the slot (the b3f12b3 narrow infra only fires when the slot is nullable, not poly), so slash + 1 flowed through sp_poly_add and the result couldn't pass as the mrb_int arg to sp_str_sub_range_r.

Split the rindex dispatch like String#index:

  • analyze: when the arg is a regex, return "poly"; otherwise return "int?".
  • codegen: regex arg routes through sp_re_rindex_poly (returns sp_RbVal); string arg routes through sp_str_rindex_opt (returns mrb_int with SP_INT_NIL for not-found).

String#rindex_opt already exists in lib/sp_runtime.h; this just flips the default plain-string dispatcher to use it. Pairs with the existing compile_if_expr nil-check narrow (b3f12b3): with slash now int?, the else arm of slash == nil ? T : F sees slash narrowed to int, the .v.i unbox stays a no-op (already mrb_int), and slash + 1 lowers cleanly.

Closes #645.

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
1aeb8559dc2f
Parent
92306b7fe57b

spinel_analyze.rbmodifiedView file

@@ -4332,18 +4332,25 @@
43324332 # `sp_*Array_index_poly` runtime wrappers.
43334333 if recv >= 0
43344334 rt_idx = infer_type(recv)
4335- # String#index uses the int? sentinel path (mname == "index"
4336- # only; rindex still hits the regex-vs-string overload and
4337- # stays on poly for a follow-up). String#rindex stays on poly
4338- # because the regex-receiver branch of compile-side dispatch
4339- # routes through sp_re_rindex_poly which can't fit the int?
4340- # encoding cleanly yet.
4341- if (rt_idx == "string" || rt_idx == "mutable_str") && mname == "index"
4342- return "int?"
4343- end
4335+ # String#index / String#rindex with a plain string arg use the
4336+ # int? sentinel path (SP_INT_NIL for not-found) — the codegen
4337+ # routes through sp_str_index_opt / sp_str_rindex_opt. With a
4338+ # regex arg, the dispatch picks sp_re_*index_poly which returns
4339+ # sp_RbVal, so the static return stays "poly".
43444340 if rt_idx == "string" || rt_idx == "mutable_str"
4345- @needs_rb_value = 1
4346- return "poly"
4341+ arg_t_idx_645 = "string"
4342+ arg_ids_idx_645 = []
4343+ if @nd_arguments[nid] >= 0
4344+ arg_ids_idx_645 = get_args(@nd_arguments[nid])
4345+ end
4346+ if arg_ids_idx_645.length > 0 && @nd_type[arg_ids_idx_645[0]] == "RegularExpressionNode"
4347+ arg_t_idx_645 = "regex"
4348+ end
4349+ if arg_t_idx_645 == "regex"
4350+ @needs_rb_value = 1
4351+ return "poly"
4352+ end
4353+ return "int?"
43474354 end
43484355 # int_array uses the int? sentinel path (returns mrb_int with
43494356 # SP_INT_NIL marking not-found). str_array still goes through