Commit c54d2f97

c54d2f97deaeMerged

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

Description

fix(runtime,codegen): String#[i] returns nil on out-of-bounds

"hello"[20] returns nil in CRuby; spinel's sp_str_sub_range collapsed the bare single-int index into the same call as s[i, len] and returned the spinel-marker empty string on OOB, so a .nil? check on the result surfaced false.

Two pieces:

  1. lib/sp_runtime.h: add sp_str_char_at_or_nil(s, i) that normalizes negative indices against the codepoint length and returns NULL when the resulting index lies outside [0, cl). The two-arg s[i, len] and range forms keep returning "" on OOB via sp_str_sub_range; only the bare single-int index aliases to the nullable variant.

  2. spinel_codegen.rb: the String#[] dispatch single-int fallback now emits sp_str_char_at_or_nil(rc, i) instead of sp_str_sub_range(rc, i, 1). The compile_string_method_expr .nil? arm for string already lowered to (rc == NULL), so the runtime change flows through without analyzer-side typing changes.

Refs #619 puzzle 3.

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

Details

Commit
c54d2f97deae
Parent
b1e92805f9d2

lib/sp_runtime.hmodifiedView file

@@ -1094,6 +1094,11 @@
10941094 static int sp_char_cache_init = 0;
10951095 /* start/len are codepoint indices/counts. */
10961096 static const char*sp_str_sub_range(const char*s,mrb_int start,mrb_int len){mrb_int cl=sp_str_length(s);if(start<0)start+=cl;if(start<0)start=0;if(start>=cl||len<=0){return &("\xff" "")[1];}if(start+len>cl)len=cl-start;size_t boff=sp_utf8_byte_offset(s,start);size_t bend=sp_utf8_byte_offset(s+boff,len)+boff;size_t blen=bend-boff;if(len==1&&blen==1){unsigned char c=(unsigned char)s[boff];if(!sp_char_cache_init){for(int i=0;i<256;i++){sp_char_cache[i][0]=(char)0xff;sp_char_cache[i][1]=(char)i;sp_char_cache[i][2]=0;}sp_char_cache_init=1;}return &sp_char_cache[c][1];}char*r=sp_str_alloc_raw(blen+1);memcpy(r,s+boff,blen);r[blen]=0;return r;}
1097+/* Single-character form of `s[i]`. Returns NULL on out-of-bounds to
1098+ match CRuby's `"hello"[20] -> nil`. The two-arg `s[i, len]` /
1099+ range forms keep returning "" on OOB via sp_str_sub_range; only
1100+ the bare single-int index aliases here. Issue #619 puzzle 3. */
1101+static const char*sp_str_char_at_or_nil(const char*s,mrb_int i){mrb_int cl=sp_str_length(s);if(i<0)i+=cl;if(i<0||i>=cl)return NULL;return sp_str_sub_range(s,i,1);}
10971102 /* Char-indexed variant; the second arg used to be a hoisted byte length, now a
10981103 hoisted codepoint count. We don't need it for correctness, but keeping the
10991104 ABI lets callers pass it without a wrapper. */