Commit 0989445d

0989445d1b93Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 34 files · +26 added · ~8 modified

Description

Merge remote-tracking branch 'origin/master' into rs-const-defined-bool

Conflicts:

spinel_analyze.rb

Details

Commit
0989445d1b93
Parent
80165494ac62
Merge parent
d981f7961376

lib/sp_runtime.hmodifiedView file

@@ -589,6 +589,18 @@
589589 }
590590
591591 static void sp_oom_die(void);
592+
593+/* ---- Encoding runtime ----
594+ Spinel currently assumes UTF-8 source and string data. Keep Encoding
595+ as a tiny value type so `__ENCODING__` and `String#encoding` can
596+ answer Ruby's Encoding-shaped protocol without carrying full
597+ transcoding state. */
598+typedef struct{const char *name;}sp_Encoding;
599+static inline sp_Encoding sp_encoding_utf8(void){return(sp_Encoding){"UTF-8"};}
600+static inline const char*sp_encoding_name(sp_Encoding e){return e.name?e.name:sp_str_empty;}
601+static inline const char*sp_encoding_inspect(sp_Encoding e){return sp_sprintf("#<Encoding:%s>",sp_encoding_name(e));}
602+static inline mrb_bool sp_encoding_eq(sp_Encoding a,sp_Encoding b){const char*an=sp_encoding_name(a);const char*bn=sp_encoding_name(b);return strcmp(an,bn)==0;}
603+
592604 static char *sp_str_alloc(size_t len) {
593605 size_t total = sizeof(sp_str_hdr) + 1 + len + 1;
594606 sp_str_hdr *h = (sp_str_hdr *)malloc(total);
@@ -1443,6 +1455,24 @@
14431455 static sp_IntStrHash*sp_IntStrHash_dup(sp_IntStrHash*h){sp_IntStrHash*r=sp_IntStrHash_new();r->default_v=h->default_v;for(mrb_int i=0;i<h->len;i++)sp_IntStrHash_set(r,h->order[i],sp_IntStrHash_get(h,h->order[i]));return r;}
14441456 static mrb_bool sp_IntStrHash_eq(sp_IntStrHash*a,sp_IntStrHash*b){if(!a||!b)return a==b;if(a->len!=b->len)return FALSE;for(mrb_int i=0;i<a->len;i++){mrb_int k=a->order[i];if(!sp_IntStrHash_has_key(b,k))return FALSE;if(!sp_str_eq(sp_IntStrHash_get(a,k),sp_IntStrHash_get(b,k)))return FALSE;}return TRUE;}
14451457
1458+/* Int → Int typed hash. Mirrors sp_IntStrHash's open-addressing
1459+ layout (used[] bitmap so 0/-1 keys are distinguishable from
1460+ empty), with int-valued slots. Used by Array#tally on int
1461+ arrays — see #865. */
1462+typedef struct{mrb_int*keys;mrb_int*vals;mrb_int*order;mrb_bool*used;mrb_int len;mrb_int cap;mrb_int mask;mrb_int default_v;}sp_IntIntHash;
1463+static void sp_IntIntHash_fin(void*p){sp_IntIntHash*h=(sp_IntIntHash*)p;free(h->keys);free(h->vals);free(h->order);free(h->used);}
1464+static sp_IntIntHash*sp_IntIntHash_new(void){sp_IntIntHash*h=(sp_IntIntHash*)sp_gc_alloc(sizeof(sp_IntIntHash),sp_IntIntHash_fin,NULL);h->cap=16;h->mask=15;h->keys=(mrb_int*)calloc(h->cap,sizeof(mrb_int));h->vals=(mrb_int*)calloc(h->cap,sizeof(mrb_int));h->order=(mrb_int*)malloc(sizeof(mrb_int)*h->cap);h->used=(mrb_bool*)calloc(h->cap,sizeof(mrb_bool));h->len=0;h->default_v=0;return h;}
1465+static sp_IntIntHash*sp_IntIntHash_new_with_default(mrb_int d){sp_IntIntHash*h=sp_IntIntHash_new();h->default_v=d;return h;}
1466+static void sp_IntIntHash_grow(sp_IntIntHash*h){mrb_int oc=h->cap,ol=h->len;mrb_int*ok=h->keys;mrb_int*ov=h->vals;mrb_bool*ou=h->used;mrb_int*oo=h->order;h->cap*=2;h->mask=h->cap-1;h->keys=(mrb_int*)calloc(h->cap,sizeof(mrb_int));h->vals=(mrb_int*)calloc(h->cap,sizeof(mrb_int));h->order=(mrb_int*)malloc(sizeof(mrb_int)*h->cap);h->used=(mrb_bool*)calloc(h->cap,sizeof(mrb_bool));h->len=ol;for(mrb_int i=0;i<oc;i++){if(!ou[i])continue;mrb_int k=ok[i];mrb_int v=ov[i];mrb_int di=_sp_istr_idx(h->mask,k);while(h->used[di])di=(di+1)&h->mask;h->used[di]=TRUE;h->keys[di]=k;h->vals[di]=v;}for(mrb_int i=0;i<ol;i++)h->order[i]=oo[i];free(ok);free(ov);free(ou);free(oo);}
1467+static void sp_IntIntHash_set(sp_IntIntHash*h,mrb_int k,mrb_int v){if(h->len*2>=h->cap)sp_IntIntHash_grow(h);mrb_int idx=_sp_istr_idx(h->mask,k);while(h->used[idx]){if(h->keys[idx]==k){h->vals[idx]=v;return;}idx=(idx+1)&h->mask;}h->used[idx]=TRUE;h->keys[idx]=k;h->vals[idx]=v;h->order[h->len++]=k;}
1468+static mrb_int sp_IntIntHash_get(sp_IntIntHash*h,mrb_int k){if(!h)return 0;mrb_int idx=_sp_istr_idx(h->mask,k);while(h->used[idx]){if(h->keys[idx]==k)return h->vals[idx];idx=(idx+1)&h->mask;}return h->default_v;}
1469+static mrb_bool sp_IntIntHash_has_key(sp_IntIntHash*h,mrb_int k){mrb_int idx=_sp_istr_idx(h->mask,k);while(h->used[idx]){if(h->keys[idx]==k)return TRUE;idx=(idx+1)&h->mask;}return FALSE;}
1470+static mrb_int sp_IntIntHash_length(sp_IntIntHash*h){return h?h->len:0;}
1471+static sp_IntIntHash*sp_IntIntHash_dup(sp_IntIntHash*h){sp_IntIntHash*r=sp_IntIntHash_new();r->default_v=h->default_v;for(mrb_int i=0;i<h->len;i++)sp_IntIntHash_set(r,h->order[i],sp_IntIntHash_get(h,h->order[i]));return r;}
1472+/* Array#tally on int_array. CRuby returns an Integer-keyed Hash
1473+ mapping each distinct element to its occurrence count. */
1474+static sp_IntIntHash*sp_IntArray_tally_int(sp_IntArray*a){sp_IntIntHash*h=sp_IntIntHash_new();if(!a)return h;for(mrb_int i=0;i<a->len;i++){mrb_int k=a->data[a->start+i];sp_IntIntHash_set(h,k,sp_IntIntHash_get(h,k)+1);}return h;}
1475+
14461476 /* Reuse an existing StrArray for split, avoiding GC alloc.
14471477 Clears a->len and refills. Substring strings are still malloc'd. */
14481478 static void sp_str_split_into(sp_StrArray*a,const char*s,const char*sep){
@@ -1651,6 +1681,7 @@
16511681 on allocation failure. Match the perror+exit pattern used elsewhere
16521682 (see sp_IntArray_replace) instead of returning a partial result. */
16531683 static const char*sp_str_format_strarr(const char*fmt,sp_StrArray*a){size_t cap=strlen(fmt)+64;char*buf=(char*)malloc(cap);if(!buf){perror("malloc");exit(1);}size_t out=0;mrb_int idx=0;const char*p=fmt;while(*p){if(*p=='%'){if(p[1]=='s'){const char*s=(idx<a->len)?a->data[idx]:"";size_t sl=strlen(s);if(out+sl>=cap){size_t nc=(out+sl)*2+1;char*nb=(char*)realloc(buf,nc);if(!nb){free(buf);perror("realloc");exit(1);}buf=nb;cap=nc;}memcpy(buf+out,s,sl);out+=sl;idx++;p+=2;}else if(p[1]=='%'){if(out+1>=cap){size_t nc=cap*2;char*nb=(char*)realloc(buf,nc);if(!nb){free(buf);perror("realloc");exit(1);}buf=nb;cap=nc;}buf[out++]='%';p+=2;}else{if(out+1>=cap){size_t nc=cap*2;char*nb=(char*)realloc(buf,nc);if(!nb){free(buf);perror("realloc");exit(1);}buf=nb;cap=nc;}buf[out++]=*p++;}}else{if(out+1>=cap){size_t nc=cap*2;char*nb=(char*)realloc(buf,nc);if(!nb){free(buf);perror("realloc");exit(1);}buf=nb;cap=nc;}buf[out++]=*p++;}}buf[out]=0;char*r=sp_str_alloc(out);memcpy(r,buf,out);free(buf);return r;}
1684+
16541685 static const char*sp_str_reverse(const char*s){if(!s)return sp_str_empty;size_t bl=strlen(s);char*r=sp_str_alloc_raw(bl+1);size_t end=bl;const char*p=s;while(*p){int cn=sp_utf8_advance(p);end-=cn;memcpy(r+end,p,cn);p+=cn;}r[bl]=0;return r;}
16551686 static const char*sp_str_sub(const char*s,const char*pat,const char*rep){if(!s)return sp_str_empty;if(!pat||!rep)return s;const char*f=strstr(s,pat);if(!f)return s;size_t pl=strlen(pat),rl=strlen(rep),sl=strlen(s);char*r=sp_str_alloc_raw(sl-pl+rl+1);size_t n=f-s;memcpy(r,s,n);memcpy(r+n,rep,rl);memcpy(r+n+rl,f+pl,sl-n-pl+1);return r;}
16561687 static const char*sp_str_capitalize(const char*s){if(!s)return sp_str_empty;size_t l=strlen(s);char*r=sp_str_alloc_raw(l+1);for(size_t i=0;i<=l;i++)r[i]=tolower((unsigned char)s[i]);if(l>0)r[0]=toupper((unsigned char)r[0]);return r;}
@@ -1734,6 +1765,89 @@
17341765 `bytes` / `length` consult the header (not strlen), so callers
17351766 would see the alloc size and trailing NULs. */
17361767 static const char*sp_str_squeeze(const char*s){if(!s)return sp_str_empty;size_t bl=strlen(s);char*r=sp_str_alloc_raw(bl+1);size_t n=0;uint32_t prev=0xFFFFFFFFu;const char*p=s;while(*p){uint32_t cp;int cn=sp_utf8_decode(p,&cp);if(cp!=prev){memcpy(r+n,p,cn);n+=cn;prev=cp;}p+=cn;}r[n]=0;sp_str_set_len(r,n);return r;}
1768+
1769+/* Forward decl from sp_crypto.h (libspinel_rt.a). Used by
1770+ sp_str_crypt below to provide a deterministic crypt-like
1771+ hash without dragging in libc crypt(3). */
1772+const char *sp_crypto_hmac_sha256_b64url(const char *key, const char *msg);
1773+
1774+/* String#crypt — Spinel's crypt is NOT the libc DES crypt. It
1775+ returns `salt[0..1] || hmac_sha256(salt, password)[0..10]` as
1776+ a 13-char string (same length as DES crypt, deterministic,
1777+ stronger primitive). CRuby's spec says String#crypt is impl-
1778+ defined and "should not be used for security"; this matches
1779+ that contract while keeping outputs reproducible across
1780+ spinel builds. Short salts get padded with '.' so the result
1781+ still has the canonical first-2-chars-are-salt shape. */
1782+static const char *sp_str_crypt(const char *s, const char *salt) {
1783+ if (!salt) salt = "";
1784+ char salt2[3];
1785+ salt2[0] = salt[0] ? salt[0] : '.';
1786+ salt2[1] = (salt[0] && salt[1]) ? salt[1] : '.';
1787+ salt2[2] = 0;
1788+ const char *digest = sp_crypto_hmac_sha256_b64url(salt2, s ? s : "");
1789+ char *r = sp_str_alloc(13);
1790+ r[0] = salt2[0];
1791+ r[1] = salt2[1];
1792+ for (int i = 0; i < 11; i++) {
1793+ char c = digest[i];
1794+ /* Map b64url's `-`/`_` to crypt-alphabet `.`/`/` so the
1795+ output stays in `[./0-9A-Za-z]` like the historical
1796+ crypt result. */
1797+ if (c == '-') c = '.';
1798+ else if (c == '_') c = '/';
1799+ r[2 + i] = c;
1800+ }
1801+ r[13] = 0;
1802+ sp_str_set_len(r, 13);
1803+ return r;
1804+}
1805+
1806+/* String#scrub — walk the bytes; for each valid UTF-8 lead +
1807+ continuation sequence, copy through. For invalid bytes (lone
1808+ continuation, truncated multi-byte, overlong, etc.), emit the
1809+ replacement string and skip one byte. NULL replacement uses
1810+ U+FFFD (3 UTF-8 bytes: EF BF BD), matching CRuby. */
1811+static const char *sp_str_scrub(const char *s, const char *repl) {
1812+ if (!s) return sp_str_empty;
1813+ static const char fffd[] = "\xEF\xBF\xBD";
1814+ const char *r = repl ? repl : fffd;
1815+ size_t rlen = strlen(r);
1816+ size_t bl = sp_str_byte_len(s);
1817+ size_t cap = bl + 64;
1818+ char *out = sp_str_alloc_raw(cap);
1819+ size_t olen = 0;
1820+ size_t i = 0;
1821+ while (i < bl) {
1822+ unsigned char c = (unsigned char)s[i];
1823+ int expected = sp_utf8_char_len(c);
1824+ int valid = 1;
1825+ if (expected == 1) {
1826+ if (c >= 0x80) valid = 0;
1827+ } else {
1828+ if (i + (size_t)expected > bl) valid = 0;
1829+ else {
1830+ for (int k = 1; k < expected; k++) {
1831+ if (((unsigned char)s[i + k] & 0xC0) != 0x80) { valid = 0; break; }
1832+ }
1833+ }
1834+ }
1835+ if (valid) {
1836+ if (olen + (size_t)expected + 1 >= cap) { cap = (olen + expected) * 2 + 64; out = (char*)realloc(out, cap); }
1837+ memcpy(out + olen, s + i, (size_t)expected);
1838+ olen += (size_t)expected;
1839+ i += (size_t)expected;
1840+ } else {
1841+ if (olen + rlen + 1 >= cap) { cap = (olen + rlen) * 2 + 64; out = (char*)realloc(out, cap); }
1842+ memcpy(out + olen, r, rlen);
1843+ olen += rlen;
1844+ i += 1;
1845+ }
1846+ }
1847+ out[olen] = 0;
1848+ sp_str_set_len(out, olen);
1849+ return out;
1850+}
17371851 static const char*sp_str_ljust(const char*s,mrb_int w){if(!s)return sp_str_empty;mrb_int cl=sp_str_length(s);if(cl>=w)return s;size_t bl=strlen(s);size_t pad=(size_t)(w-cl);char*r=sp_str_alloc_raw(bl+pad+1);memcpy(r,s,bl);memset(r+bl,' ',pad);r[bl+pad]=0;return r;}
17381852 static const char*sp_str_rjust(const char*s,mrb_int w){if(!s)return sp_str_empty;mrb_int cl=sp_str_length(s);if(cl>=w)return s;size_t bl=strlen(s);size_t pad=(size_t)(w-cl);char*r=sp_str_alloc_raw(bl+pad+1);memset(r,' ',pad);memcpy(r+pad,s,bl);r[bl+pad]=0;return r;}
17391853 static const char*sp_str_center(const char*s,mrb_int w){if(!s)return sp_str_empty;mrb_int cl=sp_str_length(s);if(cl>=w)return s;size_t bl=strlen(s);mrb_int pad=w-cl;mrb_int left=pad/2;mrb_int right=pad-left;char*r=sp_str_alloc_raw(bl+pad+1);memset(r,' ',left);memcpy(r+left,s,bl);memset(r+left+bl,' ',right);r[bl+pad]=0;return r;}
@@ -1826,6 +1940,7 @@
18261940 static const char*sp_StrIntHash_inspect(sp_StrIntHash*h){sp_String*s=sp_String_new("{");if(h){for(mrb_int i=0;i<h->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_str_inspect(h->order[i]));sp_String_append(s,"=>");sp_String_append(s,sp_int_to_s(sp_StrIntHash_get(h,h->order[i])));}}sp_String_append(s,"}");return s->data;}
18271941 static const char*sp_StrStrHash_inspect(sp_StrStrHash*h){sp_String*s=sp_String_new("{");if(h){for(mrb_int i=0;i<h->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_str_inspect(h->order[i]));sp_String_append(s,"=>");sp_String_append(s,sp_str_inspect(sp_StrStrHash_get(h,h->order[i])));}}sp_String_append(s,"}");return s->data;}
18281942 static const char*sp_IntStrHash_inspect(sp_IntStrHash*h){sp_String*s=sp_String_new("{");if(h){for(mrb_int i=0;i<h->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_int_to_s(h->order[i]));sp_String_append(s,"=>");sp_String_append(s,sp_str_inspect(sp_IntStrHash_get(h,h->order[i])));}}sp_String_append(s,"}");return s->data;}
1943+static const char*sp_IntIntHash_inspect(sp_IntIntHash*h){sp_String*s=sp_String_new("{");if(h){for(mrb_int i=0;i<h->len;i++){if(i>0)sp_String_append(s,", ");sp_String_append(s,sp_int_to_s(h->order[i]));sp_String_append(s,"=>");sp_String_append(s,sp_int_to_s(sp_IntIntHash_get(h,h->order[i])));}}sp_String_append(s,"}");return s->data;}
18291944 /* Nested-array inspect: when codegen knows the ptr_array's element
18301945 type is one of the four built-in T_array shapes, recurse into the
18311946 matching primitive inspect . */
@@ -1834,6 +1949,22 @@
18341949 k-element ordered combinations as a PtrArray of IntArrays. */
18351950 static void sp_int_combination_recur(sp_IntArray*src,mrb_int start,mrb_int k,sp_IntArray*acc,sp_PtrArray*out){if(k==0){sp_IntArray*cp=sp_IntArray_new();for(mrb_int i=0;i<acc->len;i++)sp_IntArray_push(cp,acc->data[acc->start+i]);sp_PtrArray_push(out,cp);return;}for(mrb_int i=start;i<=src->len-k;i++){sp_IntArray_push(acc,src->data[src->start+i]);sp_int_combination_recur(src,i+1,k-1,acc,out);acc->len--;}}
18361951 static sp_PtrArray*sp_IntArray_combination(sp_IntArray*a,mrb_int k){sp_PtrArray*out=sp_PtrArray_new();if(!a||k<0||k>a->len)return out;sp_IntArray*acc=sp_IntArray_new();sp_int_combination_recur(a,0,k,acc,out);return out;}
1952+
1953+/* Cartesian product of two int arrays. Returns a PtrArray of
1954+ 2-element IntArrays. */
1955+static sp_PtrArray *sp_IntArray_product(sp_IntArray *a, sp_IntArray *b) {
1956+ sp_PtrArray *out = sp_PtrArray_new();
1957+ if (!a || !b) return out;
1958+ for (mrb_int i = 0; i < a->len; i++) {
1959+ for (mrb_int j = 0; j < b->len; j++) {
1960+ sp_IntArray *pair = sp_IntArray_new();
1961+ sp_IntArray_push(pair, a->data[a->start + i]);
1962+ sp_IntArray_push(pair, b->data[b->start + j]);
1963+ sp_PtrArray_push(out, pair);
1964+ }
1965+ }
1966+ return out;
1967+}
18371968 /* Array#permutation(k) -- ordered k-permutations. */
18381969 static void sp_int_permutation_recur(sp_IntArray*src,mrb_int k,sp_IntArray*used,sp_IntArray*acc,sp_PtrArray*out){if(k==0){sp_IntArray*cp=sp_IntArray_new();for(mrb_int i=0;i<acc->len;i++)sp_IntArray_push(cp,acc->data[acc->start+i]);sp_PtrArray_push(out,cp);return;}for(mrb_int i=0;i<src->len;i++){if(used->data[used->start+i])continue;used->data[used->start+i]=1;sp_IntArray_push(acc,src->data[src->start+i]);sp_int_permutation_recur(src,k-1,used,acc,out);acc->len--;used->data[used->start+i]=0;}}
18391970 static sp_PtrArray*sp_IntArray_permutation(sp_IntArray*a,mrb_int k){sp_PtrArray*out=sp_PtrArray_new();if(!a||k<0||k>a->len)return out;sp_IntArray*used=sp_IntArray_new();for(mrb_int i=0;i<a->len;i++)sp_IntArray_push(used,0);sp_IntArray*acc=sp_IntArray_new();sp_int_permutation_recur(a,k,used,acc,out);return out;}
@@ -2251,6 +2382,9 @@
22512382 the boxed sp_Class's cls_id directly so unboxing is just a
22522383 field read. */
22532384 #define SP_TAG_CLASS 7
2385+/* Encoding values boxed into a poly slot. v.s carries the canonical
2386+ encoding name (`"UTF-8"` in Spinel's current runtime model). */
2387+#define SP_TAG_ENCODING 8
22542388 /* Negative cls_id values let SP_TAG_OBJ also carry built-in pointer
22552389 types (IntArray, FloatArray, ...) — avoids minting a new SP_TAG_*
22562390 per type. Non-negative cls_id stays an index into the user-class
@@ -2286,6 +2420,7 @@
22862420 static sp_RbVal sp_box_sym(sp_sym v) { sp_RbVal r; r.tag = SP_TAG_SYM; r.cls_id = 0; r.v.i = (mrb_int)v; return r; }
22872421 /* box a sp_Class into a poly slot. */
22882422 static sp_RbVal sp_box_class(sp_Class c) { sp_RbVal r; r.tag = SP_TAG_CLASS; r.cls_id = (int)c.cls_id; r.v.i = c.cls_id; return r; }
2423+static sp_RbVal sp_box_encoding(sp_Encoding e) { sp_RbVal r; r.tag = SP_TAG_ENCODING; r.cls_id = 0; r.v.s = sp_encoding_name(e); return r; }
22892424
22902425 /* every non-value-type sp_<C> starts
22912426 with `mrb_int cls_id`. Read it back from a void* when
@@ -2456,6 +2591,7 @@
24562591 case SP_TAG_BOOL: puts(v.v.b ? "true" : "false"); break;
24572592 case SP_TAG_NIL: putchar('\n'); break;
24582593 case SP_TAG_SYM: { const char *_ss = sp_sym_to_s((sp_sym)v.v.i); fputs(_ss, stdout); putchar('\n'); break; }
2594+ case SP_TAG_ENCODING: { const char *_es = v.v.s ? v.v.s : sp_str_empty; fputs(_es, stdout); putchar('\n'); break; }
24592595 case SP_TAG_OBJ: {
24602596 /* MRI's `puts arr` iterates an Array, printing one element per
24612597 line (using to_s on each); a non-Array OBJ falls back to
@@ -2517,6 +2653,7 @@
25172653 case SP_TAG_NIL: return sp_str_empty;
25182654 case SP_TAG_SYM: return sp_sym_to_s((sp_sym)v.v.i);
25192655 case SP_TAG_CLASS: { sp_Class c = {v.v.i}; return sp_class_to_s(c); }
2656+ case SP_TAG_ENCODING: return v.v.s ? v.v.s : sp_str_empty;
25202657 case SP_TAG_OBJ:
25212658 switch (v.cls_id) {
25222659 case SP_BUILTIN_INT_ARRAY: return sp_IntArray_inspect((sp_IntArray *)v.v.p);
@@ -2537,7 +2674,7 @@
25372674 static mrb_int sp_poly_to_i(sp_RbVal v) { if (v.tag == SP_TAG_INT || v.tag == SP_TAG_SYM) return v.v.i; if (v.tag == SP_TAG_STR) return (mrb_int)strtoll(v.v.s ? v.v.s : sp_str_empty, NULL, 10); if (v.tag == SP_TAG_FLT) return (mrb_int)v.v.f; if (v.tag == SP_TAG_BOOL) return v.v.b ? 1 : 0; return 0; }
25382675 static mrb_float sp_poly_to_f(sp_RbVal v) { if (v.tag == SP_TAG_FLT) return v.v.f; if (v.tag == SP_TAG_INT || v.tag == SP_TAG_SYM) return (mrb_float)v.v.i; if (v.tag == SP_TAG_BOOL) return v.v.b ? 1.0 : 0.0; return 0.0; }
25392676 static mrb_bool sp_poly_numeric_p(sp_RbVal v) { return v.tag == SP_TAG_INT || v.tag == SP_TAG_FLT; }
2540-static mrb_bool sp_poly_eq(sp_RbVal a, sp_RbVal b) { if (sp_poly_numeric_p(a) && sp_poly_numeric_p(b)) return sp_poly_to_f(a) == sp_poly_to_f(b); if (a.tag != b.tag) return FALSE; switch (a.tag) { case SP_TAG_INT: return a.v.i == b.v.i; case SP_TAG_STR: return (a.v.s == NULL || b.v.s == NULL) ? (a.v.s == b.v.s) : (strcmp(a.v.s, b.v.s) == 0); case SP_TAG_FLT: return a.v.f == b.v.f; case SP_TAG_BOOL: return a.v.b == b.v.b; case SP_TAG_NIL: return TRUE; case SP_TAG_SYM: return a.v.i == b.v.i; case SP_TAG_OBJ: return a.cls_id == b.cls_id && a.v.p == b.v.p; default: return FALSE; } }
2677+static mrb_bool sp_poly_eq(sp_RbVal a, sp_RbVal b) { if (sp_poly_numeric_p(a) && sp_poly_numeric_p(b)) return sp_poly_to_f(a) == sp_poly_to_f(b); if (a.tag != b.tag) return FALSE; switch (a.tag) { case SP_TAG_INT: return a.v.i == b.v.i; case SP_TAG_STR: return (a.v.s == NULL || b.v.s == NULL) ? (a.v.s == b.v.s) : (strcmp(a.v.s, b.v.s) == 0); case SP_TAG_FLT: return a.v.f == b.v.f; case SP_TAG_BOOL: return a.v.b == b.v.b; case SP_TAG_NIL: return TRUE; case SP_TAG_SYM: return a.v.i == b.v.i; case SP_TAG_ENCODING: return (a.v.s == NULL || b.v.s == NULL) ? (a.v.s == b.v.s) : (strcmp(a.v.s, b.v.s) == 0); case SP_TAG_OBJ: return a.cls_id == b.cls_id && a.v.p == b.v.p; default: return FALSE; } }
25412678 static mrb_int sp_poly_cmp(sp_RbVal a, sp_RbVal b, mrb_bool *comparable) { if (sp_poly_numeric_p(a) && sp_poly_numeric_p(b)) { mrb_float af = sp_poly_to_f(a), bf = sp_poly_to_f(b); *comparable = TRUE; return (af > bf) - (af < bf); } if (a.tag == SP_TAG_STR && b.tag == SP_TAG_STR) { if (a.v.s == NULL || b.v.s == NULL) { *comparable = (a.v.s == b.v.s); return 0; } *comparable = TRUE; return strcmp(a.v.s, b.v.s); } if (a.tag == SP_TAG_SYM && b.tag == SP_TAG_SYM) { *comparable = TRUE; return (a.v.i > b.v.i) - (a.v.i < b.v.i); } *comparable = FALSE; return 0; }
25422679 static mrb_bool sp_poly_lt(sp_RbVal a, sp_RbVal b) { mrb_bool comparable; mrb_int cmp = sp_poly_cmp(a, b, &comparable); return comparable ? (cmp < 0) : FALSE; }
25432680 static mrb_bool sp_poly_le(sp_RbVal a, sp_RbVal b) { mrb_bool comparable; mrb_int cmp = sp_poly_cmp(a, b, &comparable); return comparable ? (cmp <= 0) : FALSE; }
@@ -2630,6 +2767,140 @@
26302767 sp_PolyArray_push(dst, v);
26312768 }
26322769 static sp_PolyArray *sp_PolyArray_flatten(sp_PolyArray *a) { sp_PolyArray *b = sp_PolyArray_new(); if (!a) return b; for (mrb_int i = 0; i < a->len; i++) sp_PolyArray_flatten_into(b, a->data[i]); return b; }
2770+
2771+/* Box-into-poly converters used by the printf-with-array codegen
2772+ (`"%fmt" % typed_array`). The format helper expects sp_RbVal
2773+ slots so it can dispatch per-element. */
2774+static sp_PolyArray *sp_IntArray_to_poly(sp_IntArray *a) {
2775+ sp_PolyArray *r = sp_PolyArray_new();
2776+ if (!a) return r;
2777+ for (mrb_int i = 0; i < a->len; i++) sp_PolyArray_push(r, sp_box_int(a->data[a->start + i]));
2778+ return r;
2779+}
2780+static sp_PolyArray *sp_StrArray_to_poly_fmt(sp_StrArray *a) {
2781+ sp_PolyArray *r = sp_PolyArray_new();
2782+ if (!a) return r;
2783+ for (mrb_int i = 0; i < a->len; i++) sp_PolyArray_push(r, sp_box_str(a->data[i]));
2784+ return r;
2785+}
2786+
2787+/* String#% with a poly_array argument. Walks the format and for
2788+ each spec ("%s", "%d", "%f", "%x", "%o", etc.) pulls the next
2789+ array element. Width / flag chars between `%` and the conv
2790+ letter (`-+0 #`, digits, `.`) are copied verbatim so printf
2791+ does the substitution work. */
2792+static const char *sp_str_format_polyarr(const char *fmt, sp_PolyArray *a) {
2793+ size_t cap = strlen(fmt) + 64;
2794+ char *buf = (char *)malloc(cap);
2795+ if (!buf) { perror("malloc"); exit(1); }
2796+ size_t out = 0; mrb_int idx = 0; const char *p = fmt;
2797+ while (*p) {
2798+ if (*p != '%') {
2799+ if (out + 1 >= cap) { cap = cap * 2; buf = (char *)realloc(buf, cap); }
2800+ buf[out++] = *p++; continue;
2801+ }
2802+ if (p[1] == '%') {
2803+ if (out + 1 >= cap) { cap = cap * 2; buf = (char *)realloc(buf, cap); }
2804+ buf[out++] = '%'; p += 2; continue;
2805+ }
2806+ char spec[64]; size_t sl = 0; spec[sl++] = *p++;
2807+ while (*p && sl < sizeof(spec) - 4) {
2808+ char c = *p;
2809+ if (c == '-' || c == '+' || c == ' ' || c == '#' || c == '0' || c == '.' || (c >= '0' && c <= '9')) { spec[sl++] = c; p++; }
2810+ else break;
2811+ }
2812+ if (!*p) break;
2813+ char conv = *p++; spec[sl++] = conv;
2814+ char fmt_use[80];
2815+ if (conv == 'd' || conv == 'i' || conv == 'x' || conv == 'X' || conv == 'o') {
2816+ memcpy(fmt_use, spec, sl - 1);
2817+ fmt_use[sl - 1] = 'l'; fmt_use[sl] = 'l'; fmt_use[sl + 1] = conv; fmt_use[sl + 2] = 0;
2818+ } else {
2819+ memcpy(fmt_use, spec, sl); fmt_use[sl] = 0;
2820+ }
2821+ char tmp[256]; int wn = 0;
2822+ sp_RbVal v = (idx < a->len) ? a->data[idx] : sp_box_nil();
2823+ idx++;
2824+ if (conv == 'd' || conv == 'i' || conv == 'x' || conv == 'X' || conv == 'o') {
2825+ long long lv = 0;
2826+ if (v.tag == SP_TAG_INT) lv = (long long)v.v.i;
2827+ else if (v.tag == SP_TAG_FLT) lv = (long long)v.v.f;
2828+ else if (v.tag == SP_TAG_STR && v.v.s) lv = strtoll(v.v.s, NULL, 10);
2829+ wn = snprintf(tmp, sizeof(tmp), fmt_use, lv);
2830+ } else if (conv == 'f' || conv == 'e' || conv == 'E' || conv == 'g' || conv == 'G') {
2831+ double dv = 0;
2832+ if (v.tag == SP_TAG_FLT) dv = v.v.f;
2833+ else if (v.tag == SP_TAG_INT) dv = (double)v.v.i;
2834+ wn = snprintf(tmp, sizeof(tmp), fmt_use, dv);
2835+ } else if (conv == 's') {
2836+ const char *sv = "";
2837+ char num_buf[32];
2838+ if (v.tag == SP_TAG_STR) sv = v.v.s ? v.v.s : "";
2839+ else if (v.tag == SP_TAG_INT) { snprintf(num_buf, sizeof(num_buf), "%lld", (long long)v.v.i); sv = num_buf; }
2840+ else if (v.tag == SP_TAG_FLT) { snprintf(num_buf, sizeof(num_buf), "%g", v.v.f); sv = num_buf; }
2841+ wn = snprintf(tmp, sizeof(tmp), fmt_use, sv);
2842+ } else if (conv == 'c') {
2843+ int cv = 0;
2844+ if (v.tag == SP_TAG_INT) cv = (int)v.v.i;
2845+ else if (v.tag == SP_TAG_STR && v.v.s && v.v.s[0]) cv = (unsigned char)v.v.s[0];
2846+ wn = snprintf(tmp, sizeof(tmp), fmt_use, cv);
2847+ } else {
2848+ memcpy(tmp, spec, sl); tmp[sl] = 0; wn = (int)sl; idx--;
2849+ }
2850+ if (wn < 0) continue;
2851+ if (out + (size_t)wn + 1 >= cap) { cap = (out + wn) * 2 + 64; buf = (char *)realloc(buf, cap); }
2852+ memcpy(buf + out, tmp, wn); out += wn;
2853+ }
2854+ buf[out] = 0;
2855+ char *r = sp_str_alloc(out); memcpy(r, buf, out); free(buf); return r;
2856+}
2857+
2858+/* Array#assoc — return the first sub-array (poly_array element)
2859+ whose first element equals `key`. Returns NULL when no match
2860+ so the caller's `.inspect` round-trips to "nil". */
2861+static sp_PolyArray *sp_PolyArray_assoc(sp_PolyArray *a, sp_RbVal key) {
2862+ if (!a) return NULL;
2863+ for (mrb_int i = 0; i < a->len; i++) {
2864+ sp_RbVal el = a->data[i];
2865+ if (el.tag != SP_TAG_OBJ) continue;
2866+ if (el.cls_id != SP_BUILTIN_POLY_ARRAY) continue;
2867+ sp_PolyArray *sub = (sp_PolyArray *)el.v.p;
2868+ if (sub && sub->len >= 1 && sp_poly_eq(sub->data[0], key)) return sub;
2869+ }
2870+ return NULL;
2871+}
2872+
2873+/* Array#rassoc — same as assoc but matches against the second
2874+ element of each sub-array. */
2875+static sp_PolyArray *sp_PolyArray_rassoc(sp_PolyArray *a, sp_RbVal val) {
2876+ if (!a) return NULL;
2877+ for (mrb_int i = 0; i < a->len; i++) {
2878+ sp_RbVal el = a->data[i];
2879+ if (el.tag != SP_TAG_OBJ) continue;
2880+ if (el.cls_id != SP_BUILTIN_POLY_ARRAY) continue;
2881+ sp_PolyArray *sub = (sp_PolyArray *)el.v.p;
2882+ if (sub && sub->len >= 2 && sp_poly_eq(sub->data[1], val)) return sub;
2883+ }
2884+ return NULL;
2885+}
2886+/* Depth-bounded variant. depth==0 returns a shallow copy; each
2887+ recursive step decrements depth, and a negative depth means
2888+ "unlimited" (same as flatten without arg). Used by
2889+ `Array#flatten(n)`. */
2890+static void sp_PolyArray_flatten_into_n(sp_PolyArray *dst, sp_RbVal v, mrb_int depth) {
2891+ if (depth == 0 || v.tag != SP_TAG_OBJ) { sp_PolyArray_push(dst, v); return; }
2892+ if (v.cls_id == SP_BUILTIN_INT_ARRAY) { sp_IntArray *ia = (sp_IntArray *)v.v.p; for (mrb_int i = 0; i < ia->len; i++) sp_PolyArray_push(dst, sp_box_int(ia->data[ia->start + i])); return; }
2893+ if (v.cls_id == SP_BUILTIN_STR_ARRAY) { sp_StrArray *sa = (sp_StrArray *)v.v.p; for (mrb_int i = 0; i < sa->len; i++) sp_PolyArray_push(dst, sp_box_str(sa->data[i])); return; }
2894+ if (v.cls_id == SP_BUILTIN_POLY_ARRAY) { sp_PolyArray *pa = (sp_PolyArray *)v.v.p; for (mrb_int i = 0; i < pa->len; i++) sp_PolyArray_flatten_into_n(dst, pa->data[i], depth - 1); return; }
2895+ sp_PolyArray_push(dst, v);
2896+}
2897+static sp_PolyArray *sp_PolyArray_flatten_n(sp_PolyArray *a, mrb_int depth) {
2898+ sp_PolyArray *b = sp_PolyArray_new();
2899+ if (!a) return b;
2900+ if (depth < 0) depth = INT64_MAX;
2901+ for (mrb_int i = 0; i < a->len; i++) sp_PolyArray_flatten_into_n(b, a->data[i], depth);
2902+ return b;
2903+}
26332904 /* Sum the integer-tagged elements of a poly_array. Used by
26342905 `Array#sum` on a poly_array whose runtime tags are uniform int
26352906 (e.g. the result of `arr.map { _1[:int_key] }`). Non-int tags
@@ -2658,6 +2929,7 @@
26582929 case SP_TAG_BOOL: return v.v.b ? SPL("true") : SPL("false");
26592930 case SP_TAG_NIL: return SPL("nil");
26602931 case SP_TAG_SYM: return sp_str_concat(SPL(":"), sp_sym_to_s((sp_sym)v.v.i));
2932+ case SP_TAG_ENCODING: return sp_sprintf("#<Encoding:%s>", v.v.s ? v.v.s : "");
26612933 case SP_TAG_OBJ:
26622934 /* Built-in container / value-type tags get their typed inspect
26632935 helper. Matches the dispatch shape in sp_poly_to_s above and the
@@ -2682,8 +2954,11 @@
26822954 }
26832955 /* Array#inspect for heterogeneous poly arrays. Each element dispatches
26842956 through sp_poly_inspect, so a mixed `[1, "x", :y]` renders
2685- `[1, "x", :y]` byte-for-byte identical to CRuby. */
2957+ `[1, "x", :y]` byte-for-byte identical to CRuby. NULL renders
2958+ "nil" so callers that store a nil-returning slot (assoc/rassoc
2959+ miss, etc.) round-trip cleanly through `.inspect`. */
26862960 static const char *sp_PolyArray_inspect(sp_PolyArray *a) {
2961+ if (!a) { char *r = sp_str_alloc(3); r[0] = 'n'; r[1] = 'i'; r[2] = 'l'; r[3] = 0; sp_str_set_len(r, 3); return r; }
26872962 sp_String *s = sp_String_new("[");
26882963 for (mrb_int i = 0; i < a->len; i++) {
26892964 if (i > 0) sp_String_append(s, ", ");
@@ -2787,6 +3062,8 @@
27873062 return (mrb_int)v.v.i;
27883063 case SP_TAG_STR:
27893064 return v.v.s ? (mrb_int)sp_str_hash(v.v.s) : 0;
3065+ case SP_TAG_ENCODING:
3066+ return v.v.s ? (mrb_int)sp_str_hash(v.v.s) : 0;
27903067 case SP_TAG_FLT: { uint64_t b; memcpy(&b, &v.v.f, sizeof(b)); return (mrb_int)b; }
27913068 case SP_TAG_OBJ:
27923069 if (sp_obj_hash_hook) return sp_obj_hash_hook(v.cls_id, v.v.p);
@@ -2803,6 +3080,10 @@
28033080 if (a.v.s == b.v.s) return TRUE;
28043081 if (!a.v.s || !b.v.s) return FALSE;
28053082 return strcmp(a.v.s, b.v.s) == 0;
3083+ case SP_TAG_ENCODING:
3084+ if (a.v.s == b.v.s) return TRUE;
3085+ if (!a.v.s || !b.v.s) return FALSE;
3086+ return strcmp(a.v.s, b.v.s) == 0;
28063087 case SP_TAG_FLT:
28073088 return a.v.f == b.v.f;
28083089 case SP_TAG_OBJ: