Commit 86aadadc
86aadadc63a8Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
Fix frozen string semantics: freeze/frozen? for TY_STRING
- Add sp_str_is_frozen_val / sp_str_freeze_val / sp_str_check_mutable helpers in the runtime (0xf1 = heap-frozen marker)
- frozen? for TY_STRING now does a runtime check instead of always returning true
- String.new / String.new(s) now create mutable heap copies via sp_str_dup_external so that String.new("abc").frozen? is false
- TY_STRING .freeze (statement and expression) updates the variable via sp_str_freeze_val so subsequent frozen? returns true
- <<, insert, prepend, replace, clear on TY_STRING local variables now call sp_str_check_mutable before mutating; raises FrozenError when the string was explicitly frozen via .freeze
Fixes i972.
Co-Authored-By: Claude Sonnet 4.6 [email protected]
Details
- Commit
- 86aadadc63a8
- Parent
- b75c5122a082
lib/sp_runtime.hmodifiedView file
@@ -1891,6 +1891,38 @@
18911891
return v;18921892
}18931893
1894+
/* 0xf1 = heap string frozen by an explicit .freeze call.1895+
Unlike 0xff (rodata literal) this marker lives in a malloc'd buffer1896+
so sp_str_freeze_val can set it. The frozen? predicate and mutation1897+
guards check for 0xf1; plain rodata 0xff literals are NOT reported1898+
as frozen (they behave as immutable value-semantics objects). */1899+
static inline mrb_bool sp_str_is_frozen_val(const char *s) {1900+
if (!s) return TRUE;1901+
return ((const unsigned char *)s)[-1] == 0xf1;1902+
}1903+
static inline const char *sp_str_freeze_val(const char *s) {1904+
if (!s) return s;1905+
unsigned char m = ((const unsigned char *)s)[-1];1906+
if (m == 0xfe || m == 0xfc) {1907+
((unsigned char *)s)[-1] = 0xf1;1908+
return s;1909+
}1910+
if (m == 0xff || m == 0xf1 || m != 0xfd) {1911+
/* rodata literal or already frozen: copy to heap and freeze */1912+
if (m == 0xf1) return s; /* already heap-frozen */1913+
size_t n = strlen(s);1914+
char *r = sp_str_alloc(n);1915+
memcpy(r, s, n);1916+
((unsigned char *)r)[-1] = 0xf1;1917+
return r;1918+
}1919+
return s;1920+
}1921+
static void __attribute__((noinline,cold)) sp_raise_frozen_string(void){sp_raise_cls("FrozenError","can't modify frozen String");}1922+
static inline void sp_str_check_mutable(const char *s) {1923+
if (sp_str_is_frozen_val(s)) sp_raise_frozen_string();1924+
}1925+
18941926
typedef struct{char*data;int64_t len;int64_t cap;}sp_String;18951927
/* Per-mutable-string freeze flag rides in the GC header alongside18961928
`marked`. sp_String_freeze sets it; the in-place mutators belowsrc/codegen.cmodifiedView file
Loading diff…