Commit 01b0272b

01b0272b2a47Merged

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

Description

codegen: mutating String methods on frozen literal raise FrozenError

"hello".insert(0,"X") / prepend / << / concat / mutating bang methods (chop!/upcase!/sub!/etc.) on a frozen string literal used to either silently no-op or return a new concatenated string. spinel treats all string literals as frozen; raise FrozenError per MRI.

Mutable strings (String.new("...")) still mutate via the mutable_str arm in compile_call_expr.

str_method_nil_arg_no_segv.rb's "foo".send(:<<) now raises FrozenError; updated expected to wrap in begin/rescue.

Refs #886

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

Details

Commit
01b0272b2a47
Parent
46981e9ca3ac

spinel_codegen.rbmodifiedView file

@@ -18248,7 +18248,11 @@
1824818248 return "(sp_String_append(" + rc + ", " + val + "), " + rc + ")"
1824918249 end
1825018250 if lt == "string"
18251- return "sp_str_concat(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"
18251+ # `s << x` on a frozen string literal raises FrozenError per MRI.
18252+ # spinel string literals are always frozen. The mutable_str arm
18253+ # above handles the legal case. Issue #886.
18254+ @needs_exc_class_hierarchy = 1
18255+ return "({ sp_raise_cls(\"FrozenError\", \"can't modify frozen String\"); " + compile_expr(recv) + "; })"
1825218256 end
1825318257 # Array `<<` is push, not bit-shift. The compile_call_expr path
1825418258 # also has a push branch for direct `arr.push(x)` style calls,
@@ -18860,6 +18864,20 @@
1886018864 if mname == "chomp!"
1886118865 return compile_string_method_expr(nid, "chomp", rc)
1886218866 end
18867+ # String mutating methods called on a frozen string literal (recv
18868+ # type "string", not "mutable_str"). MRI raises FrozenError;
18869+ # spinel string literals are always frozen. The mutable_str arm
18870+ # at compile_call_expr handles the legal case before reaching
18871+ # here. Issue #886. The expression still yields a value so
18872+ # downstream type inference doesn't break -- the raise is a
18873+ # non-returning C call inside a stmt-expression.
18874+ if mname == "insert" || mname == "prepend" || mname == "<<" || mname == "concat" || mname == "replace" || mname == "clear" ||
18875+ mname == "chop!" || mname == "upcase!" || mname == "downcase!" || mname == "swapcase!" || mname == "capitalize!" ||
18876+ mname == "sub!" || mname == "gsub!" || mname == "squeeze!" || mname == "strip!" || mname == "lstrip!" || mname == "rstrip!" ||
18877+ mname == "tr!" || mname == "tr_s!" || mname == "delete!" || mname == "reverse!" || mname == "succ!" || mname == "next!"
18878+ @needs_exc_class_hierarchy = 1
18879+ return "({ sp_raise_cls(\"FrozenError\", \"can't modify frozen String\"); " + rc + "; })"
18880+ end
1886318881 # String#<=> dispatches to strcmp clamped to -1/0/1.
1886418882 # Issue #900. Symmetric to the int / sym arms.
1886518883 if mname == "<=>"