From 36844a189c673fdec619ae9f4fb05fdbe181b23a Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:20:02 +0100 Subject: [PATCH 001/147] Dir.chdir guards its block against other threads, and wants HOME or LOGDIR A chdir block changes the whole process's directory until it ends, so MRI keeps a chdir lock: while one thread is inside Dir.chdir { } (or Dir#chdir, or Dir.fchdir with a block) a chdir from another thread raises RuntimeError "conflicting chdir during another chdir block", and a chdir without a block in the same thread warns, naming where the outer block was entered ("note: previous chdir was here"). IronRuby had neither, so another thread could move the directory out from under a block silently. Dir now keeps the same counter, owning thread and outer location per runtime. Dir.chdir without an argument goes to HOME, then LOGDIR, and is ArgumentError "HOME/LOGDIR not set" otherwise, as in MRI. IronRuby fell back to the profile folder, and the console host also set HOME at startup on every system. MRI only makes up HOME on Windows (rb_w32_sysinit), so the host does that only there, and ENV["HOME"] stays unset elsewhere when it was unset. Checked against CRuby 4.0.10: test_dir's test_class_chdir, test_instance_chdir and test_chdir_conflict pass; spec/core/dir has no new failures. --- Src/Libraries/Builtins/Dir.cs | 111 ++++++++++++++++++++++++++-- Src/Ruby/Hosting/RubyConsoleHost.cs | 6 ++ 2 files changed, 110 insertions(+), 7 deletions(-) diff --git a/Src/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index 0d716acce..38ef881da 100644 --- a/Src/Libraries/Builtins/Dir.cs +++ b/Src/Libraries/Builtins/Dir.cs @@ -127,7 +127,7 @@ private static void SetCurrentDirectory(PlatformAdaptationLayer/*!*/ pal, string [RubyMethod("chdir", RubyMethodAttributes.PublicSingleton)] public static object ChangeDirectory(ConversionStorage/*!*/ toPath, BlockParam block, RubyClass/*!*/ self, object dir) { var d = Protocols.CastToPath(toPath, dir); - return ChangeDirectory(self.Context.Platform, self.Context.DecodePath(d), d, block); + return ChangeDirectory(self.Context, self.Context.DecodePath(d), d, block); } /// @@ -135,31 +135,124 @@ public static object ChangeDirectory(ConversionStorage/*!*/ toPat /// [RubyMethod("chdir", RubyMethodAttributes.PublicSingleton)] public static object ChangeDirectory(BlockParam block, RubyClass/*!*/ self) { - string defaultDirectory = RubyUtils.GetHomeDirectory(self.Context.Platform); + // MRI's dir_s_chdir: HOME, then LOGDIR, and nothing else. On Windows MRI has set HOME + // at startup if it was missing, so the profile directory stands in for it there. + var pal = self.Context.Platform; + string defaultDirectory = RubyEnvironment.GetVariable(pal, "HOME") ?? RubyEnvironment.GetVariable(pal, "LOGDIR"); + if (defaultDirectory == null && Environment.OSVersion.Platform == PlatformID.Win32NT) { + defaultDirectory = RubyUtils.GetHomeDirectory(pal); + } if (defaultDirectory == null) { - throw RubyExceptions.CreateArgumentError("HOME / USERPROFILE not set"); + throw RubyExceptions.CreateArgumentError("HOME/LOGDIR not set"); } - return ChangeDirectory(self.Context.Platform, defaultDirectory, self.Context.EncodePath(defaultDirectory), block); + return ChangeDirectory(self.Context, defaultDirectory, self.Context.EncodePath(defaultDirectory), block); } - private static object ChangeDirectory(PlatformAdaptationLayer/*!*/ pal, string/*!*/ strDir, MutableString/*!*/ dir, BlockParam block) { - if (block == null) { + private static object ChangeDirectory(RubyContext/*!*/ context, string/*!*/ strDir, MutableString/*!*/ dir, BlockParam block) { + var pal = context.Platform; + if (!ChdirAloneBlock(context, block != null)) { SetCurrentDirectory(pal, strDir); return 0; } string current = pal.CurrentDirectory; + SetCurrentDirectory(pal, strDir); + ChdirEnter(context); try { - SetCurrentDirectory(pal, strDir); object result; block.Yield(dir, out result); return result; } finally { + ChdirLeave(context); SetCurrentDirectory(pal, current); } } + #region chdir blocks + + // MRI's chdir_lock: the working directory is the process's, so while one thread is in a + // chdir block another thread's chdir is an error, and a plain chdir inside the block is + // a warning. The process is shared by every runtime in it, but a runtime only knows its + // own threads, so each keeps its own. + private sealed class ChdirLock { + public readonly object Sync = new object(); + public System.Threading.Thread Thread; + public int Blocking; + public string Path; + public int Line; + } + + private static ChdirLock/*!*/ GetChdirLock(RubyContext/*!*/ context) { + return (ChdirLock)context.GetOrCreateLibraryData(typeof(ChdirLock), () => new ChdirLock()); + } + + /// + /// MRI's chdir_alone_block_p: whether this chdir is a block of its own, after refusing it + /// in a thread other than the one whose block is running, and warning about a chdir + /// without a block inside one. + /// + private static bool ChdirAloneBlock(RubyContext/*!*/ context, bool blockGiven) { + var chdirLock = GetChdirLock(context); + string path; + int line; + lock (chdirLock.Sync) { + if (chdirLock.Blocking == 0) { + return blockGiven; + } + if (chdirLock.Thread != System.Threading.Thread.CurrentThread) { + throw RubyExceptions.CreateRuntimeError("conflicting chdir during another chdir block"); + } + if (blockGiven) { + return true; + } + path = chdirLock.Path; + line = chdirLock.Line; + } + context.ReportWarning(path != null + ? String.Format("conflicting chdir during another chdir block\n{0}:{1}: note: previous chdir was here", path, line) + : "conflicting chdir during another chdir block"); + return false; + } + + private static void ChdirEnter(RubyContext/*!*/ context) { + var chdirLock = GetChdirLock(context); + string path = null; + int line = 0; + bool outermost; + lock (chdirLock.Sync) { + outermost = chdirLock.Blocking == 0; + } + // The outermost block's place is named in the warnings; finding it may walk the stack, + // which is not done holding the lock. + if (outermost && !RubyUtils.TryGetCallerSourceLocation(context, out path, out line)) { + path = null; + } + lock (chdirLock.Sync) { + if (chdirLock.Blocking == 0) { + chdirLock.Path = path; + chdirLock.Line = line; + } + chdirLock.Blocking++; + if (chdirLock.Thread == null) { + chdirLock.Thread = System.Threading.Thread.CurrentThread; + } + } + } + + private static void ChdirLeave(RubyContext/*!*/ context) { + var chdirLock = GetChdirLock(context); + lock (chdirLock.Sync) { + if (--chdirLock.Blocking == 0) { + chdirLock.Thread = null; + chdirLock.Path = null; + chdirLock.Line = 0; + } + } + } + + #endregion + // On Windows these four are MRI's rb_f_notimplement stubs (no chroot, fchdir, dirfd or // fdopendir there): NotImplementedError, and #respond_to? denies them. private static Exception/*!*/ Unimplemented(string/*!*/ function) { @@ -193,6 +286,8 @@ public static object ChangeDirectoryToDescriptor(BlockParam block, RubyClass/*!* throw Unimplemented("fchdir"); } + ChdirAloneBlock(self.Context, block != null); + var pal = self.Context.Platform; string current = block != null ? pal.CurrentDirectory : null; @@ -219,11 +314,13 @@ public static object ChangeDirectoryToDescriptor(BlockParam block, RubyClass/*!* return 0; } + ChdirEnter(self.Context); try { object result; block.Yield(out result); return result; } finally { + ChdirLeave(self.Context); if (savedFd >= 0 && Posix.FChDir(savedFd, out errno) == 0) { try { SyncCurrentDirectory(pal); diff --git a/Src/Ruby/Hosting/RubyConsoleHost.cs b/Src/Ruby/Hosting/RubyConsoleHost.cs index 0228e332c..421f9153a 100644 --- a/Src/Ruby/Hosting/RubyConsoleHost.cs +++ b/Src/Ruby/Hosting/RubyConsoleHost.cs @@ -147,7 +147,13 @@ private static void EnableVirtualTerminalProcessing() { [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)] private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode); + // MRI on Windows (rb_w32_sysinit) makes up HOME when it is missing, from USERPROFILE and + // friends; on other systems it leaves the environment alone, and Dir.chdir without an + // argument is then "HOME/LOGDIR not set". private static void SetHomeEnvironmentVariable() { + if (Environment.OSVersion.Platform != PlatformID.Win32NT) { + return; + } PlatformAdaptationLayer platform = PlatformAdaptationLayer.Default; string homeDir = RubyUtils.GetHomeDirectory(platform); platform.SetEnvironmentVariable("HOME", homeDir); From 2168f1d3b82e2a9d371fb5cb8f092a59efc3cf2f Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:20:34 +0100 Subject: [PATCH 002/147] Dir.open keeps its encoding: without a block, and refuses other keywords Dir.open(path, encoding: enc) without a block dropped the option, so the names it read came back in the filesystem encoding; only the block form and Dir.new kept it. And any keyword other than encoding: was ignored, where MRI's dir_initialize raises ArgumentError "unknown keyword: :x" ([Bug #8060]). The option reader every Dir constructor and Dir.entries/foreach share now collects the unknown keys and raises the same way. Checked against CRuby 4.0.10: test_dir's test_dir_enc and test_unknown_keywords pass; spec/core/dir has no new failures. --- Src/Libraries/Builtins/Dir.cs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/Src/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index 38ef881da..d78e7910f 100644 --- a/Src/Libraries/Builtins/Dir.cs +++ b/Src/Libraries/Builtins/Dir.cs @@ -66,18 +66,26 @@ private static RubyEncoding GetEncodingOption(RubyContext/*!*/ context, IDiction if (options == null) { return null; } + // It is the only keyword: MRI's dir_initialize refuses any other ([Bug #8060]). + RubyEncoding result = null; + var unknown = new List(); foreach (var entry in options) { var key = (entry.Key as RubySymbol); - if (key != null && key.ToString() == "encoding" && entry.Value != null) { - var given = entry.Value as RubyEncoding; - if (given != null) { - return given; + if (key == null || key.ToString() != "encoding") { + unknown.Add(context.Inspect(entry.Key).ToString()); + } else if (entry.Value != null) { + result = entry.Value as RubyEncoding; + if (result == null) { + var name = entry.Value as MutableString; + result = context.GetRubyEncoding(name ?? MutableString.Create(context.Inspect(entry.Value))); } - var name = entry.Value as MutableString; - return context.GetRubyEncoding(name ?? MutableString.Create(context.Inspect(entry.Value))); } } - return null; + if (unknown.Count > 0) { + throw RubyExceptions.CreateArgumentError( + (unknown.Count == 1 ? "unknown keyword: " : "unknown keywords: ") + String.Join(", ", unknown)); + } + return result; } [RubyConstructor] @@ -594,7 +602,7 @@ public static object Open(ConversionStorage/*!*/ toPath, BlockPar [RubyMethod("open", RubyMethodAttributes.PublicSingleton)] public static RubyDir/*!*/ Open(ConversionStorage/*!*/ toPath, RubyClass/*!*/ self, object dirname, [Keywords, Optional]IDictionary options) { - return new RubyDir(self, Protocols.CastToPath(toPath, dirname)); + return new RubyDir(self, Protocols.CastToPath(toPath, dirname), GetEncodingOption(self.Context, options)); } #endregion From 70f0d241d9d4e598ae77a0dc7815d0d645830625 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:20:34 +0100 Subject: [PATCH 003/147] Dir.glob drops a trailing backslash, and rereads an Array's length A pattern ending in a lone backslash ("a\\") kept the backslash when its literal part was unescaped, so it named a file "a\" and matched nothing; MRI's remove_backslashes drops it, and the pattern finds "a". Dir.glob(array) walked the Array with an enumerator, and an element whose #to_path empties the Array made it fail with a CLR IndexOutOfRangeException. MRI's dir_globs reads the length again for each element; so does this. Checked against CRuby 4.0.10: test_dir's test_glob and test_glob_array_with_destructive_element pass; spec/core/dir has no new failures. --- Src/Libraries/Builtins/Dir.cs | 7 +++++-- Src/Ruby/Builtins/Glob.cs | 6 ++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/Src/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index d78e7910f..57a37db14 100644 --- a/Src/Libraries/Builtins/Dir.cs +++ b/Src/Libraries/Builtins/Dir.cs @@ -490,8 +490,11 @@ private sealed class GlobOptions { // Dir.glob (but not Dir.[]) also accepts an Array of patterns; the results are // concatenated in pattern order. var all = new List(); - foreach (var p in patterns) { - all.AddRange(IronRuby.Builtins.Glob.GetMatches(context, ToGlobPattern(toPath, p, false), options.Flags, options.Base, options.Sort)); + // A pattern's #to_path may change the Array under us, so the length is read anew + // for every element, as MRI's dir_globs does. + for (int i = 0; i < patterns.Count; i++) { + var p = ToGlobPattern(toPath, patterns[i], false); + all.AddRange(IronRuby.Builtins.Glob.GetMatches(context, p, options.Flags, options.Base, options.Sort)); } return all; } diff --git a/Src/Ruby/Builtins/Glob.cs b/Src/Ruby/Builtins/Glob.cs index 24b75ddcb..94512c738 100644 --- a/Src/Ruby/Builtins/Glob.cs +++ b/Src/Ruby/Builtins/Glob.cs @@ -1250,10 +1250,8 @@ private static string Unescape(string/*!*/ path, int start) { unescaped.Append(c); } - if (inEscape) { - unescaped.Append('\\'); - } - + // A backslash with nothing after it escapes nothing and goes, as in MRI's + // remove_backslashes: "a\\" names "a". return unescaped.ToString(); } From f2d4f29e3cfe47fbce4a746cb17687cf947427e1 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:20:34 +0100 Subject: [PATCH 004/147] Dir.home("") is the current user's home, and takes a name with to_str MRI treats an empty user name like none at all and converts the name with to_str. IronRuby looked up a user called "" (ArgumentError "user doesn't exist") and refused anything but a String. Checked against CRuby 4.0.10: test_dir's test_home passes. --- Src/StdLib/ironruby/ruby4.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 47bd46b20..c9bbdd308 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -4665,6 +4665,12 @@ class ClosedQueueError < StopIteration; end unless defined?(ClosedQueueError) class << Dir # Dir.home / Dir.children / Dir.each_child / Dir.empty? postdate the 1.9 core. def home(user = nil) + # MRI converts the name with to_str, and an empty one is the current user, as nil is. + unless user.nil? + raise TypeError, "no implicit conversion of #{user.class} into String" unless user.respond_to?(:to_str) + user = user.to_str + user = nil if user.empty? + end if user.nil? dir = ENV['HOME'] if dir.nil? && File::ALT_SEPARATOR @@ -4690,7 +4696,6 @@ def home(user = nil) return File::ALT_SEPARATOR ? dir.tr("\\", "/") : dir.dup end - raise TypeError, "no implicit conversion of #{user.class} into String" unless user.is_a?(String) require 'etc' pw = (Etc.getpwnam(user) rescue nil) raise ArgumentError, "user #{user} doesn't exist" unless pw From 72d1c57360770d5ef93d2559a482ecd404a79ff4 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:23:39 +0100 Subject: [PATCH 005/147] Array#join separates nested empty arrays and starts US-ASCII after an array MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [[], 1].join("-") answered "1": the separators were put between the strings collected from the (flattened) elements, so an empty nested array contributed neither a string nor its separators. CRuby's ary_join_1 appends the separator before every element after the first of each array joined, nested ones included, and answers "-1" ([[[]], [], 1, [2, []]].join("-") is "--1-2-"). The result's encoding was the first collected string's. MRI starts in the first element's encoding when that is a string (or becomes one) and in US-ASCII when it is an array (ary_join_1_ary clears "first"), and appends the rest with rb_str_buf_append, which leaves the encoding alone for an empty or ASCII-only string: [[], "".force_encoding("UTF-8"), nil].join is US-ASCII ([ruby-core:39776]), [nil, u].join too, while [[], "あ"].join is UTF-8. Join now collects the separators with the strings in MRI's order, picks the starting encoding by that rule and lets MutableString#Append move it on. CRuby's TestArray#test_join passes; spec/core/array has no new failures; new IronRuby.Tests Array_JoinNested1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 26 +++++++ Src/Libraries/Extensions/IListOps.cs | 93 ++++++++++++------------ 3 files changed, 73 insertions(+), 47 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 00a941aed..6b7ed02b7 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1342,6 +1342,7 @@ public Tests(Driver/*!*/ driver) { Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, + Array_JoinNested1, String_DumpNonUnicode1, IO_PutsRecursiveToAry1, Hash_MutateInBlock1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index 9007000db..3014e2186 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -566,6 +566,32 @@ public void Array_JoinRecursive1() { # # ""12335"" +"); + } + + /// + /// Array#join separates the elements of nested arrays, empty ones included, and starts in US-ASCII when the + /// first element is an array, taking another encoding only from a string that is not ASCII (MRI's + /// ary_join_1_ary and rb_str_buf_append; CRuby's TestArray#test_join). + /// + public void Array_JoinNested1() { + TestOutput(@" +p [[], 1].join('-') +p [[[]], [], 1, [2, []]].join('-') +p [nil, 1, nil].join('-') +u = ''.force_encoding('UTF-8') +p [[], u, nil].join.encoding +p [[], ""\u3042"", nil].join.encoding +p [nil, u].join.encoding +p [u, [1]].join.encoding +", @" +""-1"" +""--1-2-"" +""-1-"" +# +# +# +# "); } } diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index bca2a32b3..3fdfcd275 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -2043,22 +2043,32 @@ private static Range RangeLike(RespondToStorage/*!*/ respondToStorage, #region join, to_s, inspect - private static void JoinRecursive(JoinConversionStorage/*!*/ conversions, IList/*!*/ list, List/*!*/ parts, - ref bool? isBinary, ref Dictionary seen) { + // nil.to_s, which is US-ASCII; it is only ever appended to the result, never handed out. + private static readonly MutableString/*!*/ NilJoinString = MutableString.CreateEmpty(RubyEncoding.Ascii).Freeze(); + + private static void JoinRecursive(JoinConversionStorage/*!*/ conversions, IList/*!*/ list, MutableString separator, + List/*!*/ parts, ref bool? isBinary, ref Dictionary seen) { // the length is read again on every step, as MRI's ary_join_1 does: a #to_str or #to_ary // may change the array for (int i = 0; i < list.Count; i++) { - JoinItem(conversions, list, list[i], parts, ref isBinary, ref seen); + if (i > 0 && separator != null) { + parts.Add(separator); + } + JoinItem(conversions, list, list[i], separator, parts, ref isBinary, ref seen); } } - private static void JoinItem(JoinConversionStorage/*!*/ conversions, IList/*!*/ list, object item, List/*!*/ parts, - ref bool? isBinary, ref Dictionary seen) { + /// + /// Adds the strings joins to, separators included, to . + /// Returns true if the item was an array (or converted to one) and false if it became a string. + /// + private static bool JoinItem(JoinConversionStorage/*!*/ conversions, IList/*!*/ list, object item, MutableString separator, + List/*!*/ parts, ref bool? isBinary, ref Dictionary seen) { { if (item == null) { - parts.Add(null); - return; + parts.Add(NilJoinString); + return false; } IList listItem = conversions.ToAry.Target(conversions.ToAry, item); @@ -2075,15 +2085,16 @@ private static void JoinItem(JoinConversionStorage/*!*/ conversions, IList/*!*/ } seen.Add(item, true); - JoinRecursive(conversions, listItem, parts, ref isBinary, ref seen); + JoinRecursive(conversions, listItem, separator, parts, ref isBinary, ref seen); seen.Remove(item); - return; + return true; } // try to_str first, then to_s: MutableString strItem = conversions.ToStr.Target(conversions.ToStr, item) ?? conversions.ToS.Target(conversions.ToS, item); parts.Add(strItem); isBinary = isBinary.HasValue ? (isBinary | strItem.IsBinary) : strItem.IsBinary; + return false; } } @@ -2108,59 +2119,47 @@ private static void JoinItem(JoinConversionStorage/*!*/ conversions, IList/*!*/ } break; } + + // The separators go in between the elements of every array joined, nested ones included, + // and an empty nested array still has its neighbours separated ([[], 1].join("-") is "-1"). + bool firstIsArray = false; int index = 0; for (; index < scanned && index < self.Count; index++) { var str = self[index] as MutableString; if (str == null) { break; } - JoinItem(conversions, self, str, parts, ref isBinary, ref seen); + if (index > 0 && separator != null) { + parts.Add(separator); + } + JoinItem(conversions, self, str, separator, parts, ref isBinary, ref seen); } for (; index < self.Count; index++) { - JoinItem(conversions, self, self[index], parts, ref isBinary, ref seen); - } - if (parts.Count == 0) { - return MutableString.CreateEmpty(RubyEncoding.Ascii); + if (index > 0 && separator != null) { + parts.Add(separator); + } + bool isArray = JoinItem(conversions, self, self[index], separator, parts, ref isBinary, ref seen); + if (index == 0) { + firstIsArray = isArray; + } } - if (separator != null && separator.IsBinary != isBinary && !separator.IsAscii()) { - isBinary = true; - } + // The result takes the encoding of the first element when that is a string (or became one), + // and is US-ASCII when it is an array (MRI's ary_join_1_ary clears ary_join_1's "first"). + // Everything after is appended the way rb_str_buf_append does it, so an empty or ASCII-only + // string leaves the encoding alone and the first one that is not ASCII brings its own: + // [[], "".force_encoding("UTF-8")].join is US-ASCII, [[], "\u3042"].join UTF-8. + RubyEncoding encoding = (parts.Count == 0 || firstIsArray) ? RubyEncoding.Ascii : parts[0].Encoding; - // calculate length: - // The result starts out in the first string's encoding, and the separator is appended - // to that, as in MRI: an incompatible pair is reported in that order. - MutableString any = null; - int length = (separator != null) ? (isBinary.HasValue && isBinary.Value ? separator.GetByteCount() : separator.GetCharCount()) * (parts.Count - 1) : 0; + int length = 0; + bool binary = isBinary.HasValue && isBinary.Value; for (int i = 0, n = parts.Count; i < n; i++) { - var part = parts[i]; - if (part != null) { - length += (isBinary.HasValue && isBinary.Value) ? part.GetByteCount() : part.GetCharCount(); - if (any == null) { - any = part; - } - } - } - any ??= separator; - - if (any == null) { - return MutableString.CreateEmpty(RubyEncoding.Ascii); + length += binary ? parts[i].GetByteCount() : parts[i].GetCharCount(); } - var result = isBinary.HasValue && isBinary.Value ? - MutableString.CreateBinary(length, any.Encoding) : - MutableString.CreateMutable(length, any.Encoding); - + var result = binary ? MutableString.CreateBinary(length, encoding) : MutableString.CreateMutable(length, encoding); for (int i = 0, n = parts.Count; i < n; i++) { - var part = parts[i]; - - if (separator != null && i > 0) { - result.Append(separator); - } - - if (part != null) { - result.Append(part); - } + result.Append(parts[i]); } return result; From 20d6c9bd6a10b296c20025d0f4698e74c9b8b856 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:23:55 +0100 Subject: [PATCH 006/147] Array#rfind counts its arguments before answering an Enumerator [1].rfind(1, 2) without a block answered an Enumerator, because the prelude returned to_enum before checking the argument count. CRuby's rb_scan_args counts them first and raises "wrong number of arguments (given 2, expected 0..1)" with or without a block (TestArray#test_rfind). The check now comes first. --- Src/StdLib/ironruby/ruby4.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 47bd46b20..3dd5a0d99 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -1698,12 +1698,14 @@ def bsearch(&block) index && self[index] end unless method_defined?(:bsearch) - # The Enumerator shows the ifnone argument only when one was given (MRI's rb_scan_args). + # The Enumerator shows the ifnone argument only when one was given (MRI's rb_scan_args). The + # arguments are counted first, as rb_scan_args counts them: rfind(1, 2) without a block is an + # ArgumentError, not an Enumerator. def rfind(*args, &block) - return to_enum(:rfind, *args) unless block if args.size > 1 ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..1)") end + return to_enum(:rfind, *args) unless block ifnone = args[0] index = size - 1 while index >= 0 From 0a9b62da439d4a82957ce7e959c879fa7a2cd7e6 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:30:38 +0100 Subject: [PATCH 007/147] IO#gets keeps the characters of EUC-JP and Shift_JIS whole A byte limit was stretched to the end of a character it cut only in UTF-8, so gets(1) on an EUC-JP stream answered "\xA4" where CRuby answers the whole "\xA4\xA2" (io.c relaxes the limit while rb_enc_precise_mbclen says the last character needs more). And a separator was found wherever its bytes were: "\xA4\xA4" in "\xA2\xA4\xA4\xA2" straddles two characters, which CRuby's rb_io_getline_0 does not count as a separator (rb_enc_left_char_head must land on it). RubyEncoding gains EndsInsideCharacter and IsCharacterBoundary, which read the bytes a character at a time with the multibyte encodings' own scanners (RubyOnlyEncodings.PreciseLengthAt, the one String#scrub uses); the buffered line reader uses them for the limit and for every separator match. Checked against CRuby 4.0.10 on files and pipes (test_io_m17n's test_gets_limit and test_gets_rs_char_boundary now pass); spec/core/io, spec/core/argf and Kernel#gets/readlines show only the known into/to message difference. --- Src/Ruby/Builtins/RubyBufferedStream.cs | 47 +++++++++---------- Src/Ruby/Builtins/RubyEncoding.cs | 61 +++++++++++++++++++++++++ Src/Ruby/Runtime/RubyOnlyEncodings.cs | 15 ++++++ 3 files changed, 98 insertions(+), 25 deletions(-) diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index c3240f536..267741428 100644 --- a/Src/Ruby/Builtins/RubyBufferedStream.cs +++ b/Src/Ruby/Builtins/RubyBufferedStream.cs @@ -707,24 +707,22 @@ private void SkipNewlines(bool preserveEndOfLines) { /// why a limit of 2 can return three bytes. /// private static bool EndsWithIncompleteCharacter(RubyEncoding/*!*/ encoding, MutableString/*!*/ str) { - // Only UTF-8 is self-synchronising in a way we can read off the bytes; in a - // single-byte encoding every byte is a character of its own anyway. - if (encoding.StrictEncoding.CodePage != 65001) { - return false; - } - - int count = str.GetByteCount(); - int head = count - 1; - while (head >= 0 && count - head < 4 && (str.GetByte(head) & 0xC0) == 0x80) { - head--; - } - if (head < 0) { - return false; - } + int start, count; + byte[] bytes = str.GetByteArray(out start, out count); + return encoding.EndsInsideCharacter(bytes, start, count); + } - int lead = str.GetByte(head); - int length = (lead >= 0xC2 && lead <= 0xDF) ? 2 : (lead >= 0xE0 && lead <= 0xEF) ? 3 : (lead >= 0xF0 && lead <= 0xF4) ? 4 : 1; - return count - head < length; + /// + /// Whether the line read so far ends with the separator, and the separator begins a + /// character of the line (MRI's rb_io_getline_0 checks rb_enc_left_char_head): in + /// EUC-JP the bytes "\xA4\xA4" also turn up as the second half of one character and the + /// first half of the next. + /// + private static bool EndsWithSeparator(MutableString/*!*/ str, byte[]/*!*/ sep, RubyEncoding/*!*/ encoding) { + int start, count; + byte[] bytes = str.GetByteArray(out start, out count); + return new ReadOnlySpan(bytes, start, count).EndsWith(sep) && + encoding.IsCharacterBoundary(bytes, start, count, count - sep.Length); } public MutableString ReadLine(MutableString/*!*/ separator, RubyEncoding/*!*/ encoding, bool preserveEndOfLines, int limit) { @@ -749,6 +747,11 @@ public MutableString ReadLine(MutableString/*!*/ separator, RubyEncoding/*!*/ en // A separator that ends past the searched bytes may start up to sep.Length - 1 bytes before their end. int from = Math.Max(0, searched - (sep.Length - 1)); int index = new ReadOnlySpan(_buffer, _bufferStart + from, window - from).IndexOf(sep); + while (index >= 0 && !encoding.IsCharacterBoundary(_buffer, _bufferStart, window, from + index)) { + // the separator's bytes straddle two characters: look again past them + int next = new ReadOnlySpan(_buffer, _bufferStart + from + index + 1, window - from - index - 1).IndexOf(sep); + index = (next >= 0) ? index + 1 + next : -1; + } if (index >= 0) { int length = from + index + sep.Length; return ConsumeLine(encoding, length, length, false); @@ -765,7 +768,7 @@ public MutableString ReadLine(MutableString/*!*/ separator, RubyEncoding/*!*/ en break; } result.Append((byte)b); - if (EndsWith(result, sep)) { + if (EndsWithSeparator(result, sep, encoding)) { break; } } @@ -797,7 +800,7 @@ private MutableString ReadLineNormalizingEoln(byte[]/*!*/ sep, RubyEncoding/*!*/ do { result.Append((byte)b); - if (b == sep[sep.Length - 1] && EndsWith(result, sep)) { + if (b == sep[sep.Length - 1] && EndsWithSeparator(result, sep, encoding)) { break; } @@ -816,12 +819,6 @@ private MutableString ReadLineNormalizingEoln(byte[]/*!*/ sep, RubyEncoding/*!*/ return result; } - private static bool EndsWith(MutableString/*!*/ str, byte[]/*!*/ suffix) { - int start, count; - byte[] bytes = str.GetByteArray(out start, out count); - return new ReadOnlySpan(bytes, start, count).EndsWith(suffix); - } - public override bool CanRead { get { return _stream.CanRead; } } diff --git a/Src/Ruby/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index fd2899041..6ebfbc182 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -676,6 +676,67 @@ public int GetPreciseCharacterLength(byte[]/*!*/ bytes, int count, out int maxLe return RubyOnlyEncodings.PreciseLength(StrictEncoding, bytes, count, out maxLength); } + /// + /// Whether bytes[start, start + count) stop part way through a character, read from the + /// start a character at a time as MRI's rb_enc_precise_mbclen does (a byte that begins + /// no character counts as one). The line readers stretch a byte limit that lands there. + /// Only UTF-8 and the multibyte encodings whose shape is known here can end inside a + /// character; in a single byte encoding every byte is one. + /// + public bool EndsInsideCharacter(byte[]/*!*/ bytes, int start, int count) { + if (count <= 0) { + return false; + } + if (StrictEncoding.CodePage == 65001) { + // UTF-8 synchronises itself: only the last character needs looking at + int head = start + count - 1; + while (head >= start && start + count - head < 4 && (bytes[head] & 0xC0) == 0x80) { + head--; + } + if (head < start) { + return false; + } + int lead = bytes[head]; + int length = (lead >= 0xC2 && lead <= 0xDF) ? 2 : (lead >= 0xE0 && lead <= 0xEF) ? 3 : (lead >= 0xF0 && lead <= 0xF4) ? 4 : 1; + return start + count - head < length; + } + + int end = start + count; + int p = start; + while (p < end) { + int length = RubyOnlyEncodings.PreciseLengthAt(StrictEncoding, bytes, p, end); + if (length == Int32.MinValue) { + return false; + } + if (length == 0) { + return true; + } + p += (length > 0) ? length : 1; + } + return false; + } + + /// + /// Whether bytes into bytes[start, start + count) a character + /// begins (MRI's rb_enc_left_char_head(s, p, e, enc) == p). In EUC-JP or Shift_JIS the + /// bytes of a separator can be found straddling two characters, which is no separator. + /// UTF-8 and the single byte encodings answer true: a well formed separator cannot + /// begin inside one of their characters. + /// + public bool IsCharacterBoundary(byte[]/*!*/ bytes, int start, int count, int offset) { + int end = start + count; + int target = start + offset; + int p = start; + while (p < target) { + int length = RubyOnlyEncodings.PreciseLengthAt(StrictEncoding, bytes, p, end); + if (length == Int32.MinValue) { + return true; + } + p += (length > 0) ? length : 1; + } + return p == target; + } + /// /// The smallest number of bytes a character of this encoding occupies. It is 1 for /// everything but UTF-16 and UTF-32, whose code units are 2 and 4 bytes wide; a run of diff --git a/Src/Ruby/Runtime/RubyOnlyEncodings.cs b/Src/Ruby/Runtime/RubyOnlyEncodings.cs index 22abcd76d..ddaff901d 100644 --- a/Src/Ruby/Runtime/RubyOnlyEncodings.cs +++ b/Src/Ruby/Runtime/RubyOnlyEncodings.cs @@ -199,6 +199,21 @@ internal static int PreciseLength(Encoding/*!*/ encoding, byte[]/*!*/ bytes, int return 0; } + /// + /// PreciseLength for the character at of bytes that end at + /// ; Int32.MinValue for an encoding this does not cover. + /// + internal static int PreciseLengthAt(Encoding/*!*/ encoding, byte[]/*!*/ bytes, int index, int end) { + var multiByte = encoding as MultiByteEncoding; + if (multiByte != null) { + return multiByte.PreciseLength(bytes, index, end); + } + if (encoding.CodePage == 54936) { + return ScanGb18030(bytes, index, end); + } + return Int32.MinValue; + } + internal static System.Collections.Generic.List FindScrubRuns(Encoding/*!*/ encoding, byte[]/*!*/ bytes, int count) { var multiByte = encoding as MultiByteEncoding; int maxLength; From 47f85dd275d1a8bafc996304b384c46df886f3c1 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:30:39 +0100 Subject: [PATCH 008/147] IO#gets refuses a separator in another encoding, and converts one it can use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CRuby's prepare_getline_args raises "encoding mismatch: EUC-JP IO with UTF-8 RS" for a separator that is not ASCII (or any separator, for an IO reading an ASCII-incompatible encoding) in an encoding other than the one the IO reads in. IronRuby read on and searched for the separator's bytes. And on a converting stream ("r:utf-8:iso-8859-1") CRuby looks for the separator in the converted text, so gets("\xFF" in ISO-8859-1) stops after the "ÿ" of the UTF-8 file; IronRuby converts lines only once they are read, and looked for the ISO-8859-1 byte in UTF-8 text. The separator is now looked for in the external encoding's spelling instead. Checked against CRuby 4.0.10 (test_io_m17n's test_nonascii_terminator and test_terminator_conversion pass); spec/core/io and spec/core/argf unchanged. --- Src/Libraries/Builtins/IoOps.cs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index c1484bbd8..ffffacad3 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -2501,9 +2501,39 @@ private static MutableString ReadLineOrParagraph(TranscodeStorage/*!*/ transcode if (converted) { return ReadLineFromPendingChars(transcode, universal, self, separator, limit); } + separator = SeparatorToRead(self, separator); return universalNewline ? ReadLineUniversal(self, separator, limit) : self.ReadLineOrParagraph(separator, limit); } + /// + /// The separator as the bytes to look for in what the stream reads. MRI's + /// prepare_getline_args refuses a separator that is not ASCII in an encoding other than + /// the one the stream reads in, and MRI looks for it in the converted text; the lines are + /// converted here only once read, so the separator is looked for in the external encoding + /// instead: "\xFF" in ISO-8859-1 is "\xC3\xBF" in a UTF-8 file read as ISO-8859-1. + /// + private static MutableString SeparatorToRead(RubyIO/*!*/ self, MutableString separator) { + if (separator == null || separator.IsEmpty) { + return separator; + } + RubyEncoding readEncoding = ReadEncoding(self); + bool ascii = separator.IsAscii(); + if (separator.Encoding != readEncoding && (!ascii || !readEncoding.IsAsciiIdentity) && + !ReferenceEquals(separator, self.Context.InputSeparator)) { + throw RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", + readEncoding.Name, separator.Encoding.Name); + } + if (ascii || self.Enc2 == null || self.Enc2.IsDummy || !self.Enc2.IsAsciiIdentity) { + return separator; + } + try { + return MutableString.CreateBinary(self.Enc2.StrictEncoding.GetBytes(separator.ConvertToString()), self.Enc2); + } catch (ArgumentException) { + // not a character of the external encoding: no line of the stream can end with it + return separator; + } + } + /// /// The line reader of a stream whose character buffer holds something (MRI's appendline /// under NEED_READCONV): the text is taken a character at a time, from the buffer and then From 8d30249075f0e162d17afa5b35c64d6d6ac23523 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:33:25 +0100 Subject: [PATCH 009/147] ENV refuses a name or value with a NUL or an ASCII-incompatible encoding ENV["a\0b"] = "x" set a variable whose name the C library would cut at the NUL, and ENV["a\0b"], ENV.fetch, ENV.key?, ENV.delete, ENV.assoc and the rest just looked it up. A name in UTF-16LE or ISO-2022-JP was a CompatibilityError on the store and nothing on the readers. MRI's get_env_cstr refuses both on every method that takes a name, and on a value being stored: ArgumentError "bad environment variable name: contains null byte" or "...: ASCII incompatible encoding: UTF-16LE" ("value" for the value). ENV's prelude half now checks the same way; key?/has_key?/include?/member? and values_at come to the prelude so that they do too. ENV.freeze froze nothing and answered ENV; MRI raises TypeError "cannot freeze ENV", and so does this. Checked against CRuby 4.0.10: test_env's non-Ractor tests all pass (the Ractor ones left time out under load); spec/core/env passes. --- Src/StdLib/ironruby/ruby4.rb | 49 +++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index c9bbdd308..691e26b00 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -7940,6 +7940,22 @@ def __env_str__(object) end private :__env_str__ + # MRI's get_env_cstr: a name or value goes to the C library as a C string, so one with a + # NUL in it, or in an encoding that is not ASCII-compatible, is refused before the + # environment is looked at -- by the readers as well as by the writers. + def __env_name__(object, what = "name") + string = __env_str__(object) + encoding = string.encoding + unless encoding.ascii_compatible? + ::Kernel.raise(::ArgumentError, "bad environment variable #{what}: ASCII incompatible encoding: #{encoding}") + end + if string.include?("\0") + ::Kernel.raise(::ArgumentError, "bad environment variable #{what}: contains null byte") + end + string + end + private :__env_name__ + # setenv(3) rejects a name that is empty or contains '='. The CLR reports that as its # own ArgumentException; MRI reports Errno::EINVAL naming the call. def __env_check_name__(name) @@ -7957,13 +7973,13 @@ def __env_check_name__(name) private :__clr_fetch__ def []=(name, value) - name = __env_str__(name) + name = __env_name__(name) if value.nil? # Deleting a name setenv(3) would have rejected is a no-op, not an error. __clr_store__(name, nil) unless name.empty? || name.include?("=") return nil end - value = __env_str__(value) + value = __env_name__(value, "value") __env_check_name__(name) __clr_store__(name, value) value @@ -7973,14 +7989,24 @@ def []=(name, value) end def [](name) - __clr_fetch__(__env_str__(name)) + __clr_fetch__(__env_name__(name)) + end + + def key?(name) + !__clr_fetch__(__env_name__(name)).nil? + end + alias :has_key? :key? + alias :include? :key? + + def values_at(*names) + names.map { |name| self[name] } end def fetch(name, *default) if default.size > 1 ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{default.size + 1}, expected 1..2)") end - name = __env_str__(name) + name = __env_name__(name) if block_given? && !default.empty? ::Kernel.warn("warning: block supersedes default value argument") end @@ -7994,7 +8020,7 @@ def fetch(name, *default) end def delete(name) - name = __env_str__(name) + name = __env_name__(name) value = __clr_fetch__(name) if value.nil? return block_given? ? yield(name) : nil @@ -8014,6 +8040,11 @@ def dup ::Kernel.raise(::TypeError, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash") end + # ENV is the process's environment, which no flag can make read-only. + def freeze + ::Kernel.raise(::TypeError, "cannot freeze ENV") + end + # MRI hands back an Enumerator rather than complaining about the missing block, # and the Enumerator knows how many pairs it will walk. def each(&block) @@ -8093,8 +8124,8 @@ def replace(other) end pairs = other.map do |key, value| - key = __env_str__(key) - value = __env_str__(value) + key = __env_name__(key) + value = __env_name__(value, "value") __env_check_name__(key) [key, value] end @@ -8133,7 +8164,7 @@ def select! def slice(*keys) result = {} keys.each do |key| - name = __env_str__(key) + name = __env_name__(key) value = __clr_fetch__(name) result[key] = value unless value.nil? end @@ -8146,7 +8177,7 @@ def except(*keys) end def assoc(key) - key = __env_str__(key) + key = __env_name__(key) value = __clr_fetch__(key) value.nil? ? nil : [key, value] end From cc15e35839049dd06dd528b1323d31b598b4b6bf Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:34:03 +0100 Subject: [PATCH 010/147] UnboundMethod#bind names the class by its #to_s "bind argument must be an instance of X" named X by its Ruby name, so an anonymous class that says what it is (EnvUtil.labeled_class) or a class with its own #to_s came out differently from CRuby, which formats the class with %PRIsVALUE, i.e. its #to_s: class Foo; def self.to_s = "FOOS"; def m; end; end Foo.instance_method(:m).bind(1) # CRuby: bind argument must be an instance of FOOS The super-type message already did this through a private helper in RubyOps, which however went through the class's ToStringSite - the CLR ToString, not #to_s - and for an anonymous class fell back to a null display name. Both now use RubyContext.GetModuleMessageName, which converts with #to_s as string interpolation does. Checked against CRuby 4.0.10 with a named class with #to_s, an anonymous one, and a plain one; spec/core/unboundmethod and spec/core/method pass. --- Src/Libraries/Builtins/UnboundMethod.cs | 2 +- Src/Ruby/Runtime/RubyContext.cs | 10 ++++++++++ Src/Ruby/Runtime/RubyOps.cs | 11 +---------- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 52234a9c6..770c30240 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -107,7 +107,7 @@ public static int GetArity(UnboundMethod/*!*/ self) { if (constraint.IsClass && !context.IsKindOf(target, constraint)) { throw RubyExceptions.CreateTypeError( - "bind argument must be an instance of {0}", constraint.GetNonNullName(context) + "bind argument must be an instance of {0}", context.GetModuleMessageName(constraint) ); } diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index d362174f9..11889bc17 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -2498,6 +2498,16 @@ public bool IsInstanceOf(object value, object classObject) { return GetClassDisplayName(obj); } + /// + /// A module as MRI writes it into a message with %PRIsVALUE: by its own #to_s (an anonymous + /// class with a singleton #to_s, as EnvUtil.labeled_class makes, shows that). A named class's + /// own #to_s is used too; one that returns no String gives the default #<Class:0x...>, as + /// string interpolation would. + /// + public string/*!*/ GetModuleMessageName(RubyModule/*!*/ module) { + return StringConversionSite.Target(StringConversionSite, module).ToString(); + } + private string/*!*/ GetClassName(object obj, bool display) { // doesn't create a RubyClass for .NET types diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 0fa4373a7..8198f9727 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -4377,15 +4377,6 @@ public static bool IsAdoptedClrRuleValid(RubyContext/*!*/ context, object/*!*/ t && expectedClass.Version.Method == expectedVersion; } - // MRI formats the expected module with %PRIsVALUE, i.e. its #to_s (an anonymous class with a - // singleton #to_s, as EnvUtil.labeled_class makes, shows that). A named class's own #to_s is - // used too, so the name is only the fallback for a #to_s that returns no String. - private static string/*!*/ SuperExpectedModuleName(RubyContext/*!*/ context, RubyModule/*!*/ module) { - var site = context.GetClassOf(module).ToStringSite; - var str = site.Target(site, module) as MutableString; - return str != null ? str.ToString() : module.GetDisplayName(context, true).ToString(); - } - // super call condition [Emitted] public static object GetSuperCallTarget(RubyScope/*!*/ scope, int targetId) { @@ -4435,7 +4426,7 @@ private static void RequireSuperSelf(RubyScope/*!*/ methodScope, object currentS var context = methodScope.RubyContext; if (!context.IsKindOf(currentSelf, declaringModule)) { throw RubyExceptions.CreateTypeError(String.Format("self has wrong type to call super in this context: {0} (expected {1})", - context.GetClassDisplayName(currentSelf), SuperExpectedModuleName(context, declaringModule))); + context.GetClassDisplayName(currentSelf), context.GetModuleMessageName(declaringModule))); } } From e003d0d6f873de1e17a5aa3c53e3dbef527ea7f5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:34:45 +0100 Subject: [PATCH 011/147] class X < nil is a TypeError, and so is inheriting an uninitialized class The class definition handed the Define*Class helpers null both for "no superclass written" and for a superclass expression that evaluated to nil, so `class C < nil` quietly made a subclass of Object. CRuby checks the value first (vm_find_or_create_class_by_id): class C < nil; end # superclass must be an instance of Class (given an instance of NilClass) A written superclass now goes through RubyOps.CheckSuperClass, emitted before the helper is called, so nil is checked as the value it is. rb_check_inheritable also refuses a class made by Class.allocate and never initialized ("can't inherit uninitialized class"), which RubyClass.CheckInheritable did not: Class.new(Class.allocate) returned a class. It is checked there now, for Class.new and `class X < S` alike. Checked against CRuby 4.0.10 (nil, false, an Integer, Class.allocate, and a reopened class with a nil superclass); TestClass#test_invalid_superclass and #test_uninitialized pass; spec/core/class and spec/language/class_spec pass. --- Src/Ruby/Builtins/RubyClass.cs | 3 +++ Src/Ruby/Compiler/Ast/Definitions/ClassDefinition.cs | 4 +++- Src/Ruby/Compiler/ReflectionCache.Generated.cs | 2 ++ Src/Ruby/Runtime/RubyOps.cs | 10 ++++++++++ 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Builtins/RubyClass.cs b/Src/Ruby/Builtins/RubyClass.cs index 30e612a75..c6d16d5cf 100644 --- a/Src/Ruby/Builtins/RubyClass.cs +++ b/Src/Ruby/Builtins/RubyClass.cs @@ -848,6 +848,9 @@ public void InitializeClassCopy(RubyClass/*!*/ rubyClass) { if (superClass == context.ClassClass) { throw RubyExceptions.CreateTypeError("can't make subclass of Class"); } + if (superClass.IsUninitializedAllocation) { + throw RubyExceptions.CreateTypeError("can't inherit uninitialized class"); + } return superClass; } diff --git a/Src/Ruby/Compiler/Ast/Definitions/ClassDefinition.cs b/Src/Ruby/Compiler/Ast/Definitions/ClassDefinition.cs index 60e5f5ce5..7b60aade7 100644 --- a/Src/Ruby/Compiler/Ast/Definitions/ClassDefinition.cs +++ b/Src/Ruby/Compiler/Ast/Definitions/ClassDefinition.cs @@ -41,7 +41,9 @@ public ClassDefinition(LexicalScope/*!*/ definedScope, ConstantVariable/*!*/ nam internal override MSA.Expression/*!*/ MakeDefinitionExpression(AstGenerator/*!*/ gen) { MSA.Expression transformedQualifier; MSA.Expression name = QualifiedName.TransformName(gen); - MSA.Expression transformedSuper = (_superClass != null) ? AstUtils.Box(_superClass.TransformRead(gen)) : AstUtils.Constant(null); + MSA.Expression transformedSuper = (_superClass != null) + ? (MSA.Expression)Methods.CheckSuperClass.OpCall(gen.CurrentScopeVariable, AstUtils.Box(_superClass.TransformRead(gen))) + : AstUtils.Constant(null); // Module#const_source_location reports the line of the `class` keyword: MSA.Expression sourcePath = gen.SourcePathConstant; diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 481a146fe..d01a589be 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -62,6 +62,8 @@ public static partial class Methods { private static MethodInfo _CanRescue; public static MethodInfo/*!*/ CheckSplatArity { get { return _CheckSplatArity ?? (_CheckSplatArity = CallInstruction.CacheAction(RubyOps.CheckSplatArity)); } } private static MethodInfo _CheckSplatArity; + public static MethodInfo/*!*/ CheckSuperClass { get { return _CheckSuperClass ?? (_CheckSuperClass = CallInstruction.CacheFunc(RubyOps.CheckSuperClass)); } } + private static MethodInfo _CheckSuperClass; public static MethodInfo/*!*/ ClearKeywordArguments { get { return _ClearKeywordArguments ?? (_ClearKeywordArguments = CallInstruction.CacheFunc(RubyOps.ClearKeywordArguments)); } } private static MethodInfo _ClearKeywordArguments; public static MethodInfo/*!*/ CompareDefaultException { get { return _CompareDefaultException ?? (_CompareDefaultException = CallInstruction.CacheFunc(RubyOps.CompareDefaultException)); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 8198f9727..76f6b44cb 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -1724,6 +1724,16 @@ private static void CheckConstantVisibility(RubyModule/*!*/ owner, string/*!*/ n return (superClassObject != null) ? RubyClass.CheckInheritable(ec, superClassObject) : ec.ObjectClass; } + /// + /// The superclass written after `class X <`, checked before the class is looked up or made + /// (vm_find_or_create_class_by_id). The Define*Class helpers take null for "none written", + /// so `class X < nil` must be refused here, where nil still means the value nil. + /// + [Emitted] + public static RubyClass/*!*/ CheckSuperClass(RubyScope/*!*/ scope, object superClassObject) { + return RubyClass.CheckInheritable(scope.RubyContext, superClassObject); + } + #endregion #region Constants From 203cfbf5d2151984a89f071ae01233cb20b91621 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:34:45 +0100 Subject: [PATCH 012/147] An implicit conversion refuses a respond_to? that takes 3 arguments When an object defines respond_to?, implicit conversions ([[x]].flatten asking for to_ary) call it with (name, true). CRuby's vm_respond_to looks at its arity first and raises for one that would need more: respond_to? must accept 1 or 2 arguments (requires 3) IronRuby called it with two arguments and reported the resulting "wrong number of arguments (given 2, expected 3)" instead. The conversion rule now raises CRuby's ArgumentError for such a respond_to? before calling it. TestObject#test_implicit_respond_to_arity_3 passes; spec/core/array/flatten passes. --- .../Runtime/Conversions/ProtocolConversionAction.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs b/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs index 18f4c4799..ed05c347a 100644 --- a/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs +++ b/Src/Ruby/Runtime/Conversions/ProtocolConversionAction.cs @@ -327,7 +327,17 @@ internal static void BuildConversion(MetaObjectBuilder/*!*/ metaBuilder, CallArg // slow path: invoke respond_to?, to_xxx and result validation. // MRI (vm_respond_to) passes include_all = true unless respond_to? takes only the name. - bool passIncludeAll = respondToMethod.Info.GetArity() != 1; + int respondToArity = respondToMethod.Info.GetArity(); + if (respondToArity > 2) { + // vm_respond_to: a respond_to? that would need more than (name, include_all) is refused + // rather than called (bug:6000). + metaBuilder.SetError(Ast.New( + typeof(ArgumentException).GetConstructor(new[] { typeof(string) }), + AstUtils.Constant(String.Format("respond_to? must accept 1 or 2 arguments (requires {0})", respondToArity)) + )); + return; + } + bool passIncludeAll = respondToArity != 1; for (int i = conversions.Length - 1; i >= 0; i--) { string toMethodName = conversions[i].ToMethodName; From fd8cf995f6dcb6f16e54eeac6e5560a7aa8e1c11 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:36:16 +0100 Subject: [PATCH 013/147] (self).m is not a private call The prism bridge unwrapped a parenthesized expression to what it held, so `(self).m` reached the compiler as a bare `self` receiver and was allowed to call a private method. MRI allows that only for `self` itself: class C; def run = (self).mv; private def mv = 1; end C.new.run # private method 'mv' called for an instance of C A parenthesized `self` now stays a one-statement BlockExpression, which compiles to the same value but is not a SelfReference, so the call, an attribute assignment and an index through it check visibility as any other receiver does. BlockExpression's assertion allows the one statement. Checked against CRuby 4.0.10 (self.m, (self).m, ((self)).m, (self).x =, (self)[0]); TestMethod#test_visibility passes; spec/language/private_spec, send_spec and class_spec pass; new IronRuby.Tests Visibility7. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MethodTests.cs | 27 +++++++++++++++++++ Src/Prism/PrismAstBridge.cs | 8 ++++-- .../Ast/Expressions/BlockExpression.cs | 3 ++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 00a941aed..23a8c9fdc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -856,6 +856,7 @@ public Tests(Driver/*!*/ driver) { Visibility4, Visibility5, Visibility6, + Visibility7, VisibilityCaching1, VisibilityCaching2, DefineMethodVisibility1, diff --git a/Src/IronRuby.Tests/Runtime/MethodTests.cs b/Src/IronRuby.Tests/Runtime/MethodTests.cs index 34a160c10..4181e9576 100644 --- a/Src/IronRuby.Tests/Runtime/MethodTests.cs +++ b/Src/IronRuby.Tests/Runtime/MethodTests.cs @@ -1216,6 +1216,33 @@ class C; include M; end "); } + /// + /// Only a bare `self` may receive a private call: `(self).m` names the same object but is + /// an ordinary receiver, and raises NoMethodError as in MRI. + /// + public void Visibility7() { + TestOutput(@" +class C + def run + r = [] + r << (self.mv rescue :err) + r << ((self).mv rescue :err) + r << (begin; (self).x = 1; rescue NoMethodError; :err; end) + r << ((self)[0] rescue :err) + r << (self[0] rescue :err) + r + end + private + def mv = 1 + def x=(v); end + def [](i) = :idx +end +p C.new.run +", @" +[1, :err, :err, :err, :idx] +"); + } + public void ModuleFunctionVisibility1() { TestOutput(@" module M diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 12644c563..ec238ed5c 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -639,8 +639,12 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.NilNode _: return Literal.Nil(span); case Pm.SelfNode _: return new SelfReference(span); - case Pm.ParenthesesNode parens: - return StatementsAsExpression(parens.Body, span); + case Pm.ParenthesesNode parens: { + var inner = StatementsAsExpression(parens.Body, span); + // `(self).m` is not a call with self as the receiver: MRI only lets a private method + // be called on a bare `self`, so the parentheses have to survive the unwrapping. + return inner is SelfReference ? new BlockExpression(MakeStatements(inner), span) : inner; + } case Pm.StatementsNode statements: return StatementsAsExpression(statements, span); case Pm.ImplicitNode implicitNode: diff --git a/Src/Ruby/Compiler/Ast/Expressions/BlockExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/BlockExpression.cs index 60d0eaa84..2ba1a8c48 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/BlockExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/BlockExpression.cs @@ -40,7 +40,8 @@ private BlockExpression() internal BlockExpression(Statements/*!*/ statements, SourceSpan location) : base(location) { Assert.NotNull(statements); - Debug.Assert(statements.Count > 1); + // One statement only for a parenthesized `self` (PrismAstBridge), which must not read as a bare one. + Debug.Assert(statements.Count >= 1); _statements = statements; } From 24953b8420e500dbccbc76d92f8cbfff5e0a725f Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:36:22 +0100 Subject: [PATCH 014/147] Method#== is false for a Method that has a singleton method MRI's method_eq compares CLASS_OF of the two Methods before anything else, so giving one Method object a singleton method makes it unequal to an otherwise identical one: m = o.method(:foo); def m.foo; end o.method(:foo) == m # false IronRuby compared receiver and body only. It now compares the immediate classes first (without creating a singleton class). TestMethod#test_eq passes; spec/core/method passes. --- Src/Libraries/Builtins/MethodOps.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index a1fef7c91..3a4568508 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -24,7 +24,12 @@ namespace IronRuby.Builtins { public static class MethodOps { [RubyMethod("==")] [RubyMethod("eql?")] - public static bool Equal(RubyMethod/*!*/ self, [NotNull]RubyMethod/*!*/ other) { + public static bool Equal(RubyContext/*!*/ context, RubyMethod/*!*/ self, [NotNull]RubyMethod/*!*/ other) { + // method_eq compares CLASS_OF first: a Method given a singleton method of its own is + // no longer equal to the one it was made like. + if (context.GetImmediateClassOf(self) != context.GetImmediateClassOf(other)) { + return false; + } // two method_missing-backed methods share one info, so only the name tells them apart return ReferenceEquals(self.Target, other.Target) && self.Info.IsEquivalentTo(other.Info) && (!self.IsMethodMissing || self.Name == other.Name); From 496e3e0f880a8ec68c099f0463936e3d6361b9ba Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:36:27 +0100 Subject: [PATCH 015/147] A method only respond_to_missing? vouches for is owned by the receiver's class obj.method(:foo) for a name respond_to_missing? answers makes a Method backed by method_missing, and its #owner reported the module that defines method_missing (BasicObject). CRuby's mnew_missing makes the method entry on the class the lookup started from, the receiver's singleton class if it has one: c = Class.new { def respond_to_missing?(n, _) = n == :foo } c2 = Class.new(c) c2.new.method(:foo).owner # c2 Method#owner now answers the receiver's immediate class for such a method, and #unbind keeps that class as the UnboundMethod's owner. Checked against CRuby 4.0.10 with a subclass and with a singleton class; TestMethod#test_owner_missing passes; spec/core/method and spec/core/unboundmethod pass. --- Src/Libraries/Builtins/MethodOps.cs | 11 ++++++++++- Src/Libraries/Builtins/UnboundMethod.cs | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 3a4568508..95dad9e76 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -71,6 +71,12 @@ public static int GetArity(RubyMethod/*!*/ self) { /// [RubyMethod("owner")] public static RubyModule/*!*/ GetOwner(RubyMethod/*!*/ self) { + // A method only respond_to_missing? vouches for belongs to the receiver's class (its + // singleton class if it has one), as mnew_missing makes it, not to the method_missing + // that would run it. + if (self.IsMethodMissing) { + return self.Info.Context.GetImmediateClassOf(self.Target); + } return self.Info.AliasOwner ?? self.Info.DeclaringModule ?? self.GetTargetClass(); } @@ -137,7 +143,10 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* [RubyMethod("unbind")] public static UnboundMethod/*!*/ Unbind(RubyMethod/*!*/ self) { - return new UnboundMethod(self.GetTargetClass(), self.Name, self.Info, self.IsMethodMissing); + return new UnboundMethod( + self.IsMethodMissing ? self.Info.Context.GetImmediateClassOf(self.Target) : self.GetTargetClass(), + self.Name, self.Info, self.IsMethodMissing + ); } internal static RubyMemberInfo/*!*/ BindGenericParameters(RubyContext/*!*/ context, RubyMemberInfo/*!*/ info, string/*!*/ name, object[]/*!*/ typeArgs) { diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 770c30240..2270ddfe3 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -165,6 +165,9 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet // the class the method was looked up on. [RubyMethod("owner")] public static RubyModule/*!*/ GetOwner(UnboundMethod/*!*/ self) { + if (self._isMethodMissing) { + return self._targetConstraint; + } return self._info.AliasOwner ?? self._info.DeclaringModule ?? self._targetConstraint; } From aee4526f11d359bf54d6ec6dbafef3ec606288d5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:36:33 +0100 Subject: [PATCH 016/147] Kernel#singleton_method's NameError carries the name and receiver The prelude raised its "undefined singleton method" NameError from a bare message, so #name was nil and #receiver raised. CRuby fills both in (rb_name_err_raise), and the test for Bug #22535 reads e.name. The error is now NameError.new(message, name, receiver: self). Checked against CRuby 4.0.10; TestMethod#test_singleton_method_not_interned_name passes; spec/core/kernel/singleton_method_spec passes. --- Src/StdLib/ironruby/ruby4.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 47bd46b20..3eadd6535 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -119,7 +119,7 @@ def singleton_method(name) unless defined # MRI names a class or module here by its #name, anything else by its #inspect. receiver = (::Module === self && self.name) || inspect - ::Kernel.raise(::NameError, "undefined singleton method '#{name}' for '#{receiver}'") + ::Kernel.raise(::NameError.new("undefined singleton method '#{name}' for '#{receiver}'", name, receiver: self)) end method(name) end unless method_defined?(:singleton_method) From c41cdec785947cac1691d4b60276d1226fa85cbb Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:36:44 +0100 Subject: [PATCH 017/147] Method#inspect writes modules with #inspect and names a bound module's method by the module Two differences from CRuby's method_inspect: - It writes every module with rb_inspect, so an anonymous class that says what it is (EnvUtil.labeled_class) appears as it says, "A#foo", where IronRuby printed "##foo". - A Method made by UnboundMethod#bind of a method a module owns has that module as its class (Bug #22321): module Mod; def foo; end; end class Cls; include Mod; end Cls.instance_method(:foo).bind(o) # # o.method(:foo) # # IronRuby printed Cls(Mod) for both. #bind now records the module on the Method (RubyMethod.LookupModule, kept by #dup), and #inspect starts from it. Checked against CRuby 4.0.10 for methods of classes and of modules, bound and unbound; TestMethod#test_inspect, #test_zsuper_method_removed and #test_zsuper_method_removed_higher_method pass; spec/core/method and spec/core/unboundmethod pass. --- Src/Libraries/Builtins/MethodOps.cs | 2 +- Src/Libraries/Builtins/UnboundMethod.cs | 34 +++++++++++++++++++------ Src/Ruby/Builtins/RubyMethod.cs | 8 ++++++ 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 95dad9e76..16ffd579c 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -107,7 +107,7 @@ public static object GetReceiver(RubyMethod/*!*/ self) { // whether or not one had been created yet, and MRI's description says so var module = self.Target as RubyModule; return UnboundMethod.ToS(context, self.Name, self.Info, - module != null ? module.GetOrCreateSingletonClass() : self.GetTargetClass(), "Method", + self.LookupModule ?? (module != null ? module.GetOrCreateSingletonClass() : self.GetTargetClass()), "Method", self.IsMethodMissing); } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 2270ddfe3..f764e1b23 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -111,9 +111,14 @@ public static int GetArity(UnboundMethod/*!*/ self) { ); } - return self._isMethodMissing - ? RubyMethod.CreateMethodMissing(target, self._info, self._name) - : new RubyMethod(target, self._info, self._name); + if (self._isMethodMissing) { + return RubyMethod.CreateMethodMissing(target, self._info, self._name); + } + var result = new RubyMethod(target, self._info, self._name); + if (!constraint.IsClass) { + result.LookupModule = constraint; + } + return result; } /// @@ -225,13 +230,13 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet var targetSingleton = targetModule as RubyClass; var targetAttached = (targetSingleton != null && targetSingleton.IsSingletonClass) ? targetSingleton.SingletonClassOf as RubyModule : null; if (attachedModule != null && targetAttached != null && !ReferenceEquals(targetAttached, attachedModule)) { - result.Append(targetAttached.GetDisplayName(context, false)); + result.Append(InspectModule(context, targetAttached)); result.Append('('); - result.Append(attachedModule.GetDisplayName(context, false)); + result.Append(InspectModule(context, attachedModule)); result.Append(')'); } else { result.Append(attachedModule != null - ? attachedModule.GetDisplayName(context, false) + ? InspectModule(context, attachedModule) : context.Inspect(attached)); } result.Append('.'); @@ -242,10 +247,10 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet origin = context.GetClassOf(originSingleton.SingletonClassOf); } - result.Append(origin.GetDisplayName(context, false)); + result.Append(InspectModule(context, origin)); if (!ReferenceEquals(origin, declaringModule)) { result.Append('('); - result.Append(declaringModule.GetDisplayName(context, false)); + result.Append(InspectModule(context, declaringModule)); result.Append(')'); } result.Append('#'); @@ -278,6 +283,19 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet return result; } + // method_inspect writes each module with rb_inspect, so an anonymous one that says what it is + // (EnvUtil.labeled_class) is shown by what it says rather than as #. + private static MutableString/*!*/ InspectModule(RubyContext/*!*/ context, RubyModule/*!*/ module) { + if (module.Name == null && !module.IsSingletonClass) { + try { + return context.Inspect(module); + } catch (Exception) { + // the name it would have had + } + } + return module.GetDisplayName(context, false); + } + [RubyMethod("of")] public static UnboundMethod/*!*/ BingGenericParameters(RubyContext/*!*/ context, UnboundMethod/*!*/ self, [NotNullItems]params object/*!*/[]/*!*/ typeArgs) { return new UnboundMethod(self.TargetConstraint, self.Name, MethodOps.BindGenericParameters(context, self.Info, self.Name, typeArgs)); diff --git a/Src/Ruby/Builtins/RubyMethod.cs b/Src/Ruby/Builtins/RubyMethod.cs index 10e4375d7..42036b023 100644 --- a/Src/Ruby/Builtins/RubyMethod.cs +++ b/Src/Ruby/Builtins/RubyMethod.cs @@ -46,6 +46,13 @@ public partial class RubyMethod : IDuplicable { /// private readonly string _methodMissingName; + /// + /// The module the method reads as looked up on, when that is not the receiver's class: + /// UnboundMethod#bind of a method a module owns makes a Method of that module, which + /// #inspect then shows as Mod#name rather than Cls(Mod)#name (Bug #22321). + /// + public RubyModule LookupModule { get; set; } + public bool IsMethodMissing { get { return _methodMissingName != null; } } @@ -85,6 +92,7 @@ private RubyMethod(object target, RubyMemberInfo/*!*/ info, string/*!*/ name, st object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers) { var result = new RubyMethod(_target, _info, _name, _methodMissingName); + result.LookupModule = LookupModule; context.CopyInstanceData(this, result, copySingletonMembers); return result; } From 0475f142daa4e0131ed78995abaf133703a50480 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:37:40 +0100 Subject: [PATCH 018/147] Regexp: [--0] is the range from '-' to '0' A range was handed to .NET spelled with its bounds as written, and a '-' bound is written \- there: [\--0], which .NET reads as '-', '-' and '0' rather than as a range. Onigmo reads [--0] (and [\--0]) as '-' to '0', which takes in '.' and '/'. The bounds are now spelled as \uXXXX code units, which .NET reads one way only. Checked against CRuby 4.0.10 (test_regexp's test_char_class); spec/core/regexp, spec/core/string, spec/core/matchdata and spec/language/regexp unchanged against master. --- Src/Ruby/Builtins/RegexpTransformer.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 7e7d7b5b6..ac27b75d5 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -2819,7 +2819,10 @@ private CharacterSet ParseCharacterGroupUnion() { // A range reaching past U+FFFF has non-BMP members, which CharacterSet emits // as surrogate pairs. ActionView's token pattern is one of these: // [0-9A-Za-z_\u0080-\u{10ffff}-]. - set = CharacterSet.MakeRange(low, high, (high < 0x10000) ? set.Text + "-" + rangeEnd.Text : null); + // The bounds are spelled as code units: .NET reads [\--0] as '-', '-' and '0' + // rather than as the range from '-' to '0' Onigmo makes of [--0]. + set = CharacterSet.MakeRange(low, high, (high < 0x10000) ? + "\\u" + low.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) + "-\\u" + high.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) : null); } result = result.Union(set); From 5b9f8894c6b6c383970fb1212864f17bc3fe26a2 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:37:40 +0100 Subject: [PATCH 019/147] Regexp: \8 and \9 past the last group are the digits themselves /\A\80\z/ matched nothing: a number of two digits or more that names no group was re-read as an octal escape, and 8 begins none. Onigmo's fetch_token takes an 8 or a 9 that is not a backreference as an ordinary character, so \80 matches "80" (while \78 is still "\a" followed by "8"). Checked against CRuby 4.0.10 (test_regexp's test_parse); spec/core/regexp and spec/language/regexp unchanged against master. --- Src/Ruby/Builtins/RegexpTransformer.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index ac27b75d5..158d3f949 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -1795,8 +1795,14 @@ private void ParseNumericEscape(int firstDigit) { if (value >= 10) { // Not a group that exists, and too long to be a forward reference: Ruby re-reads - // the digits as an octal escape, so \10 is "\b". + // the digits as an octal escape, so \10 is "\b". An 8 or a 9 begins no octal + // escape: Onigmo's fetch_token takes it as itself, so \80 is "80". _index = start; + if (firstDigit == '8' || firstDigit == '9') { + Skip(); + AppendEscaped(firstDigit); + return; + } AppendEscaped(ParseSingleByteCharacterEscape(Read())); return; } From 6cf2a036b0cf93029caed1b57e950c3d063be020 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:37:40 +0100 Subject: [PATCH 020/147] Regexp: \k finds a group whose name .NET cannot spell A group like (?<@bar>.) is given an encoded .NET name (__irn_0040bar), and \k<@bar> referred to it by its Ruby name, which .NET rejected as an unknown group ("Unrecognized escape sequence \k"). The reference is now spelled as the group is, as the duplicate-name case already did. Checked against CRuby 4.0.10 (test_regexp's test_named_capture); spec/core/regexp and spec/language/regexp unchanged against master. --- Src/Ruby/Builtins/RegexpTransformer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 158d3f949..0e730abc8 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -1909,7 +1909,8 @@ private void ParseBackreference() { _sb.Append("(?!)"); return; } - _sb.Append("\\k<").Append(name).Append('>'); + // spelled as the group is: (?<@bar>.) is a .NET group of another name + _sb.Append("\\k<").Append(DuplicateGroupName(name, 1)).Append('>'); } /// From d5982a7f88dcd16619cf5a1bbec282b2c75bdd34 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:37:54 +0100 Subject: [PATCH 021/147] Array, String and MatchData take a range end that fits in a long m[1..2**63-1] raised "bignum too big to convert into 'long'": the ends of a range were converted to a Fixnum, and IronRuby's Fixnum is 32 bits, so any end past 2**31 failed - with a message about a long. CRuby reads them with NUM2LONG, so anything that fits in a long is an end, however far past the list or string it lies; only a larger Integer is a RangeError. The ends of the range Array#[]/slice, String#[]/slice and MatchData#[] take are now clamped to the int range when they fit in a long (a list is shorter than that, so the answer does not change), and still raise beyond it. Checked against CRuby 4.0.10 (test_regexp's test_match_aref); spec/core/array, spec/core/string and spec/core/matchdata unchanged against master. --- Src/Libraries/Builtins/MutableStringOps.cs | 4 ++-- Src/Libraries/Extensions/IListOps.cs | 24 ++++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 3d91ece65..45183be92 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -122,7 +122,7 @@ private static bool InInclusiveRangeNormalized(int length, ref int index) { internal static bool NormalizeSubstringRange(ConversionStorage/*!*/ fixnumCast, Range/*!*/ range, int length, out int begin, out int count) { // Ruby 2.6/2.7 beginless and endless ranges: a missing bound is the // start resp. the end of the string, and an open end is never exclusive. - begin = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); + begin = (range.Begin == null) ? 0 : IListOps.CastToRangeComponent(fixnumCast, range.Begin); begin = IListOps.NormalizeIndex(length, begin); if (begin < 0 || begin > length) { @@ -135,7 +135,7 @@ internal static bool NormalizeSubstringRange(ConversionStorage/*!*/ fixnumC return true; } - int end = IListOps.NormalizeIndex(length, Protocols.CastToFixnum(fixnumCast, range.End)); + int end = IListOps.NormalizeIndex(length, IListOps.CastToRangeComponent(fixnumCast, range.End)); count = range.ExcludeEnd ? end - begin : end - begin + 1; return true; diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index bca2a32b3..6b7d36144 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -78,12 +78,32 @@ internal static bool NormalizeRange(int listCount, ref int start, ref int count) return true; } + /// + /// MRI reads the ends of a range with NUM2LONG: an Integer that fits in a long is an end + /// however far past the list it lies, and only a larger one is a RangeError. A list is + /// shorter than an int, so such an end is clamped to the int range: m[1..2**63-1] is + /// everything from the first group on. + /// + internal static int CastToRangeComponent(ConversionStorage/*!*/ fixnumCast, object value) { + if (value is long) { + long wide = (long)value; + return (wide < Int32.MinValue) ? Int32.MinValue : (wide > Int32.MaxValue - 1) ? Int32.MaxValue - 1 : (int)wide; + } + if (value is System.Numerics.BigInteger) { + var big = (System.Numerics.BigInteger)value; + if (big >= Int64.MinValue && big <= Int64.MaxValue) { + return (big.Sign < 0) ? Int32.MinValue : Int32.MaxValue - 1; + } + } + return Protocols.CastToFixnum(fixnumCast, value); + } + internal static bool NormalizeRange(ConversionStorage/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) { // A beginless range starts at 0 and an endless one runs to the end; both // endpoints became nil-able in 2.6/2.7 and used to raise TypeError here. - begin = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); + begin = (range.Begin == null) ? 0 : CastToRangeComponent(fixnumCast, range.Begin); bool endless = range.End == null; - int end = endless ? listCount : Protocols.CastToFixnum(fixnumCast, range.End); + int end = endless ? listCount : CastToRangeComponent(fixnumCast, range.End); begin = NormalizeIndex(listCount, begin); From 04d634ba90c1df1b9c3af1bc656d3103642b2efb Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:38:01 +0100 Subject: [PATCH 022/147] Regexp#to_s and #inspect answer in the regexp's encoding Both built their answer as a BINARY string, so /abc/.to_s was BINARY where CRuby's rb_reg_str_with_term makes it US-ASCII (the regexp's encoding), and a UTF-16 regexp's #to_s raised Encoding::CompatibilityError when its source was appended to the "(?-mix:" in BINARY. #inspect (rb_reg_desc) also escapes a character that is not ASCII when the regexp is not in default_internal (or default_external): /\/#{"\xF1"}/n shows "/\/\xF1/", an EUC-JP regexp "\x{A4A2}", a byte that begins no character "\xHH". It used to copy the bytes. RubyEncoding gains GetCharacterLengthAt (rb_enc_precise_mbclen at an offset) for the byte walk. Checked against CRuby 4.0.10 (test_regexp's test_to_s and test_inspect); spec/core/regexp, spec/core/string and spec/language/regexp unchanged against master. --- Src/Libraries/Builtins/RubyRegexOps.cs | 2 +- Src/Ruby/Builtins/RubyEncoding.cs | 30 ++++++++ Src/Ruby/Builtins/RubyRegex.cs | 95 +++++++++++++++++++++++++- 3 files changed, 123 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/RubyRegexOps.cs b/Src/Libraries/Builtins/RubyRegexOps.cs index 41364073f..4f9d90229 100644 --- a/Src/Libraries/Builtins/RubyRegexOps.cs +++ b/Src/Libraries/Builtins/RubyRegexOps.cs @@ -415,7 +415,7 @@ internal static RubyRegexOptions StringToRegexEncoding(MutableString encoding) { if (!self.IsInitialized) { return RubyUtils.ObjectToMutableString(context, self); } - return self.Inspect(); + return self.Inspect(context.DefaultInternalEncoding ?? context.DefaultExternalEncoding); } [RubyMethod("options")] diff --git a/Src/Ruby/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index 6ebfbc182..77b26894b 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -716,6 +716,36 @@ public bool EndsInsideCharacter(byte[]/*!*/ bytes, int start, int count) { return false; } + /// + /// The length of the character at of bytes that end at + /// , or -1 if no well formed character begins there (MRI's + /// rb_enc_precise_mbclen, MBCLEN_CHARFOUND_P). Every byte is a character of a single + /// byte encoding; the Unicode encodings other than UTF-8 are not covered. + /// + public int GetCharacterLengthAt(byte[]/*!*/ bytes, int index, int end) { + if (index >= end) { + return -1; + } + if (StrictEncoding.CodePage == 65001) { + int lead = bytes[index]; + int length = (lead < 0x80) ? 1 : (lead >= 0xC2 && lead <= 0xDF) ? 2 : (lead >= 0xE0 && lead <= 0xEF) ? 3 : (lead >= 0xF0 && lead <= 0xF4) ? 4 : -1; + if (length <= 1 || index + length > end) { + return (length == 1) ? 1 : -1; + } + try { + new UTF8Encoding(false, true).GetCharCount(bytes, index, length); + return length; + } catch (DecoderFallbackException) { + return -1; + } + } + int result = RubyOnlyEncodings.PreciseLengthAt(StrictEncoding, bytes, index, end); + if (result == Int32.MinValue) { + return 1; + } + return (result > 0) ? result : -1; + } + /// /// Whether bytes into bytes[start, start + count) a character /// begins (MRI's rb_enc_left_char_head(s, p, e, enc) == p). In EUC-JP or Shift_JIS the diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index f011a2cc0..012c6cbe7 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -1420,14 +1420,34 @@ public void WarnHistoricalBinaryMatch(RubyContext/*!*/ context, MutableString/*! return ToMutableString().ToString(); } + /// + /// #to_s, in the regexp's encoding as MRI's rb_reg_str_with_term has it: /abc/.to_s is + /// US-ASCII, and a UTF-16 regexp's is UTF-16 from its "(?-mix:" on. + /// public MutableString/*!*/ ToMutableString() { - return AppendTo(MutableString.CreateMutable(RubyEncoding.Binary)); + return AppendTo(MutableString.CreateMutable(Encoding)); } public MutableString/*!*/ Inspect() { - MutableString result = MutableString.CreateMutable(RubyEncoding.Binary); + return Inspect(null); + } + + /// + /// #inspect, which MRI's rb_reg_desc writes in the regexp's encoding (US-ASCII for one + /// that is not ASCII compatible). A character that is not ASCII is copied as it is only + /// when the regexp is in (default_internal, or else + /// default_external): otherwise it is escaped, so that /\xF1/n shows its byte as "\xF1". + /// + public MutableString/*!*/ Inspect(RubyEncoding resultEncoding) { + RubyEncoding encoding = Encoding; + MutableString result = MutableString.CreateMutable(encoding.IsAsciiIdentity ? encoding : RubyEncoding.Ascii); result.Append('/'); - AppendEscapeForwardSlash(result, _pattern); + if (resultEncoding != null && encoding.IsAsciiIdentity && !_pattern.IsAscii() && + (encoding != resultEncoding || _pattern.ContainsInvalidCharacters())) { + result.Append(EscapeNonAscii(_pattern, encoding)); + } else { + AppendEscapeForwardSlash(result, _pattern); + } result.Append('/'); AppendOptionString(result, true); if ((_options & RubyRegexOptions.FIXED) != 0) { @@ -1594,6 +1614,75 @@ private static int AppendOptionString(MutableString/*!*/ result, RubyRegexOption return count; } + /// + /// The escaping half of MRI's rb_reg_expr_str: a byte that begins no character is \xHH, + /// another character that is not ASCII is \uHHHH (\u{H...} past the BMP) in a Unicode + /// encoding and \xHH or \x{H...} of its bytes in any other, a '/' gets a backslash, an + /// unprintable ASCII character that is no space is \xHH, and a backslash and the + /// character after it go through as they are. + /// + private static MutableString/*!*/ EscapeNonAscii(MutableString/*!*/ pattern, RubyEncoding/*!*/ encoding) { + byte[] bytes = pattern.ToByteArray(); + var result = new List(bytes.Length + 16); + bool unicode = encoding.IsUnicodeEncoding; + int i = 0; + while (i < bytes.Length) { + byte b = bytes[i]; + if (b == '\\' && i + 1 < bytes.Length) { + int next = encoding.GetCharacterLengthAt(bytes, i + 1, bytes.Length); + int n = 1 + Math.Max(next, 1); + for (int j = 0; j < n; j++) { + result.Add(bytes[i + j]); + } + i += n; + continue; + } + if (b < 0x80) { + if (b == '/') { + result.Add((byte)'\\'); + result.Add(b); + } else if (b < 0x20 && (b < '\t' || b > '\r') || b == 0x7f) { + AppendAscii(result, "\\x" + b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)); + } else { + result.Add(b); + } + i++; + continue; + } + + int length = encoding.GetCharacterLengthAt(bytes, i, bytes.Length); + if (length <= 0) { + AppendAscii(result, "\\x" + b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)); + i++; + continue; + } + + int codepoint; + if (unicode) { + codepoint = Char.ConvertToUtf32(System.Text.Encoding.UTF8.GetString(bytes, i, length), 0); + AppendAscii(result, (codepoint < 0x10000) + ? "\\u" + codepoint.ToString("X4", System.Globalization.CultureInfo.InvariantCulture) + : "\\u{" + codepoint.ToString("X", System.Globalization.CultureInfo.InvariantCulture) + "}"); + } else { + codepoint = 0; + for (int j = 0; j < length; j++) { + codepoint = (codepoint << 8) | bytes[i + j]; + } + AppendAscii(result, (codepoint < 0x100) + ? "\\x" + codepoint.ToString("X2", System.Globalization.CultureInfo.InvariantCulture) + : "\\x{" + codepoint.ToString("X", System.Globalization.CultureInfo.InvariantCulture) + "}"); + } + i += length; + } + return MutableString.CreateBinary(result.ToArray(), encoding); + } + + private static void AppendAscii(List/*!*/ bytes, string/*!*/ text) { + foreach (char c in text) { + bytes.Add((byte)c); + } + } + private static int SkipToUnescapedForwardSlash(MutableString/*!*/ pattern, int patternLength, int i) { while (i < patternLength) { i = pattern.IndexOf('/', i); From 33a03f99445e41b365b37a23bdf7267530bf2140 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:40:48 +0100 Subject: [PATCH 023/147] Array#to_h hands a lambda block each pair as a plain block would rb_ary_to_h yields each element with rb_yield_force_blockarg, which binds even a lambda's parameters the way a plain block's are bound, so a two-parameter lambda takes the pair apart: [[1, 2]].to_h(&->(k, v) { [v, k] }) # {2 => 1} The prelude's #to_h yielded normally, and the lambda refused the one Array ("wrong number of arguments (given 1, expected 2)"). A lambda block now goes through __yield_force_blockarg__ (Enumerable, over the existing BlockParam.YieldForceBlockArg); any other block keeps the plain yield loop. Checked against CRuby 4.0.10 with a lambda, a plain block, a Symbol proc and break; spec/core/array/to_h_spec passes. A rough timing of to_h with and without a block showed no difference beyond the noise of a busy machine. --- Src/Libraries/Builtins/Enumerable.cs | 9 +++++++++ Src/StdLib/ironruby/ruby4.rb | 21 +++++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/Enumerable.cs b/Src/Libraries/Builtins/Enumerable.cs index 6b719f108..39d605543 100644 --- a/Src/Libraries/Builtins/Enumerable.cs +++ b/Src/Libraries/Builtins/Enumerable.cs @@ -120,6 +120,15 @@ public static object EnumYield([NotNull]BlockParam/*!*/ block, object self, [Not return result; } + // MRI's rb_yield_force_blockarg for one value, which Array#to_h hands its block: a lambda + // binds it as a plain block would (see BlockParam.YieldForceBlockArg). + [RubyMethod("__yield_force_blockarg__", RubyMethodAttributes.PrivateInstance)] + public static object YieldForceBlockArg([NotNull]BlockParam/*!*/ block, object self, object value) { + object result; + block.YieldForceBlockArg(value, out result); + return result; + } + #endregion internal static object Each(CallSiteStorage/*!*/ each, object self, Proc/*!*/ block) { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 3eadd6535..a1ba0e916 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -5028,8 +5028,11 @@ def cycle(*args) # block_given? per element made it 4.7x MRI), and each pair through rb_check_array_type, # which is Array.try_convert - an Array is taken as it is, without asking its #to_ary; a # #to_ary that answers something else is that method's TypeError. The index moves with - # #succ (see Array#sum). - def to_h + # #succ (see Array#sum). The block gets each element through rb_yield_force_blockarg, so a + # lambda's two parameters take a pair apart as a plain block's do (&->(k, v) { }); that path + # is the C# __yield_force_blockarg__, and only a lambda takes it. + def to_h(&block) + return __to_h_force_blockarg__(&block) if block && block.lambda? result = {} given = block_given? i = 0 @@ -5044,6 +5047,20 @@ def to_h result end + def __to_h_force_blockarg__(&block) + result = {} + i = 0 + while i < __ary_size__ + element = __yield_force_blockarg__(__ary_at__(i), &block) + pair = ::Array === element ? element : ::Array.try_convert(element) + __to_h_pair_error__(element, pair, i) unless pair && pair.size == 2 + result[pair[0]] = pair[1] + i = i.succ + end + result + end + private :__to_h_force_blockarg__ + def __to_h_pair_error__(element, pair, index) unless pair raise TypeError, "wrong element type #{__ir_class_of__(element)} at #{index} (expected array)" From 849b46e0fd4401f0043e5c3f36db0e7e33ae48af Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:41:41 +0100 Subject: [PATCH 024/147] yield *[x] to a lambda passes x whole, as yield x does RubyOps.YieldSplat0 handed a one-element splat to the dispatcher's splat path, which spread an Array element over a lambda's parameters: def y; yield(*[[1, 2]]); end y(&->(a, b = 0) { [a, b] }) # CRuby [[1, 2], 0], IronRuby [1, 2] y(&->(a, *b) { [a, b] }) # CRuby [[1, 2], []], IronRuby [1, [2]] A single splatted value is one argument, so it now goes through Yield1 like `yield x`: a proc still auto-splats it and a lambda takes it as it is. YieldSplat1 already did the same for an empty splat. A ruby2_keywords or keyword Hash keeps the splat path, which turns it back into keywords. Checked against CRuby 4.0.10 with lambdas of several shapes and a proc; spec/language/yield_spec and block_spec pass; new IronRuby.Tests Scenario_RubyProcYieldArgs5. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 28 ++++++++++++++++++++++++ Src/Ruby/Runtime/RubyOps.cs | 6 +++++ 3 files changed, 35 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 23a8c9fdc..f45e75db9 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -327,6 +327,7 @@ public Tests(Driver/*!*/ driver) { Scenario_RubyProcYieldArgs2, Scenario_RubyProcYieldArgs3, Scenario_RubyProcYieldArgs4, + Scenario_RubyProcYieldArgs5, Scenario_RubyProcCallArgs1, Scenario_RubyProcCallArgs2A, Scenario_RubyProcCallArgs2B, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index 3628d12ef..28a4dfeb4 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -1429,6 +1429,34 @@ public void Scenario_RubyProcYieldArgs4() { } + /// + /// yield *[x] passes the one argument x exactly as yield x does: a lambda takes an Array x + /// whole rather than having it taken apart over its parameters. + /// + public void Scenario_RubyProcYieldArgs5() { + TestOutput(@" +def y1; yield(*[[1, 2]]); end +def y2(a); yield(*a); end +p y1(&->(a) { a }) +p y1(&->(a, b = 0) { [a, b] }) +p y1(&->(a, *b) { [a, b] }) +p y1(&->(*a) { a }) +p y2([[1, 2]], &->(a, *b) { [a, b] }) +p y1 { |a, b = 0| [a, b] } +p((y1(&->(a, b) { }) rescue $!.message)) +p y2([1, 2], &->(a, b) { [a, b] }) +", @" +[1, 2] +[[1, 2], 0] +[[1, 2], []] +[[1, 2]] +[[1, 2], []] +[1, 2] +""wrong number of arguments (given 1, expected 2)"" +[1, 2] +"); + } + /// /// RHS is list, LHS is not simple, but contains splatting. /// diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 76f6b44cb..9cab79818 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -1189,6 +1189,12 @@ internal static object Yield(object[]/*!*/ args, Proc procArg, object self, Bloc [Emitted] public static object YieldSplat0(IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) { + // yield *[x] passes one argument, exactly as yield x does: a proc auto-splats an Array x + // and a lambda takes it whole, so ->(a, b = 0) {} gets [x, 0] rather than x taken apart. + // A ruby2_keywords Hash is keywords again once splatted, which only InvokeSplat knows. + if (splattee.Count == 1 && !(splattee[0] is Hash h && (h.IsRuby2KeywordsHash || h.IsKeywordArguments))) { + return Yield1(splattee[0], procArg, self, blockParam); + } object result; var proc = blockParam.Proc; RequireLambdaArity(proc, 0 + splattee.Count, splattee.Count > 0 ? splattee[splattee.Count - 1] : null); From 11bd734d6a7f1b411b4b9172660c474a896983de Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:42:04 +0100 Subject: [PATCH 025/147] Array range endpoints may be any long [1, 2][0..2**63 - 1] raised "bignum too big to convert into 'long'": the endpoints went through the Int32 conversion, and 2**63 - 1 is a long in IronRuby. CRuby's rb_range_beg_len reads them with NUM2LONG, so anything a long holds is just a position past the end of the array: a[0..max], a[1..max] = 9, a.slice!(0..max) work, and only an endpoint beyond a long is a RangeError (TestArray#test_range_with_len_max_end). Array#[], #[]=, #slice!, #fill and #values_at (and MatchData#[], which shares the normalisation) now clamp such an endpoint to the Int32 range and count in longs, so an end of Int32.MaxValue no longer overflows the length. #fill then refuses the length the way rb_ary_fill does ("argument too big", now also for a start past the largest array), and #values_at, whose answer is padded with nil to the range's length, raises rb_ary_store's "index N too big" instead of allocating forever. spec/core/array and spec/core/matchdata have no new failures; new IronRuby.Tests Array_RangeLongEnd1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 28 +++++++++ Src/Libraries/Extensions/IListOps.cs | 77 +++++++++++++++++------- 3 files changed, 83 insertions(+), 23 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 6b7ed02b7..851b50d3c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1343,6 +1343,7 @@ public Tests(Driver/*!*/ driver) { Range_Recursive1, Array_JoinRecursive1, Array_JoinNested1, + Array_RangeLongEnd1, String_DumpNonUnicode1, IO_PutsRecursiveToAry1, Hash_MutateInBlock1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index 3014e2186..84a30c83c 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -569,6 +569,34 @@ public void Array_JoinRecursive1() { "); } + /// + /// A range endpoint that fits a long but not an int is a position past the end of any list (MRI's + /// rb_range_beg_len reads it with NUM2LONG), not a RangeError; CRuby's TestArray#test_range_with_len_max_end. + /// + public void Array_RangeLongEnd1() { + TestOutput(@" +max = 2**63 - 1 +a = [1, 2] +p a[0..max], a[-1..max], a[max..], a[-max..1] +b = [1, 2, 3]; b[1..max] = 9; p b +b = [1, 2, 3]; p b.slice!(1..max), b +p(([1, 2].fill(0, 0..max) rescue $!)) +p(([1, 2].values_at(0..max) rescue $!)) +p((a[0..2**64] rescue $!)) +", @" +[1, 2] +[2] +nil +nil +[1, 9] +[2, 3] +[1] +# +# +# +"); + } + /// /// Array#join separates the elements of nested arrays, empty ones included, and starts in US-ASCII when the /// first element is an array, taking another encoding only from a string that is not ASCII (MRI's diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 3fdfcd275..c910c3c63 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -78,12 +78,36 @@ internal static bool NormalizeRange(int listCount, ref int start, ref int count) return true; } + /// + /// MRI's rb_range_beg_len reads the endpoints with NUM2LONG, so an Integer that fits a long but not + /// an int is a position no list reaches rather than an error: a[0..2**63 - 1] is all of a. Such an + /// endpoint is clamped to the int range; one past a long is still a RangeError. + /// + private static int CastToRangeEndpoint(ConversionStorage/*!*/ fixnumCast, object value) { + long l = CastToLongRangeEndpoint(fixnumCast, value); + return l > Int32.MaxValue ? Int32.MaxValue : l < Int32.MinValue ? Int32.MinValue : (int)l; + } + + private static long CastToLongRangeEndpoint(ConversionStorage/*!*/ fixnumCast, object value) { + if (value is long) { + return (long)value; + } + if (value is System.Numerics.BigInteger) { + var big = (System.Numerics.BigInteger)value; + if (big > Int64.MaxValue || big < Int64.MinValue) { + throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + } + return (long)big; + } + return Protocols.CastToFixnum(fixnumCast, value); + } + internal static bool NormalizeRange(ConversionStorage/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) { // A beginless range starts at 0 and an endless one runs to the end; both // endpoints became nil-able in 2.6/2.7 and used to raise TypeError here. - begin = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); + begin = (range.Begin == null) ? 0 : CastToRangeEndpoint(fixnumCast, range.Begin); bool endless = range.End == null; - int end = endless ? listCount : Protocols.CastToFixnum(fixnumCast, range.End); + int end = endless ? listCount : CastToRangeEndpoint(fixnumCast, range.End); begin = NormalizeIndex(listCount, begin); @@ -96,10 +120,9 @@ internal static bool NormalizeRange(ConversionStorage/*!*/ fixnumCast, int end = NormalizeIndex(listCount, end); } - count = (range.ExcludeEnd && !endless) ? end - begin : end - begin + 1; - if (endless) { - count = listCount - begin; - } + // in a long: an end of Int32.MaxValue would overflow the count + long longCount = (range.ExcludeEnd && !endless) ? (long)end - begin : (long)end - begin + 1; + count = endless ? listCount - begin : (int)Math.Max(Math.Min(longCount, Int32.MaxValue), Int32.MinValue); return true; } @@ -111,16 +134,17 @@ internal static bool NormalizeRange(ConversionStorage/*!*/ fixnumCast, int internal static void NormalizeRangeNoClamp(ConversionStorage/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) { + // in longs, as MRI's are: the endpoints may be anything a long holds (see CastToRangeEndpoint) object rawBegin = range.Begin; - begin = (rawBegin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, rawBegin); + long longBegin = (rawBegin == null) ? 0 : CastToLongRangeEndpoint(fixnumCast, rawBegin); bool endless = range.End == null; - int end = endless ? -1 : Protocols.CastToFixnum(fixnumCast, range.End); + long end = endless ? -1 : CastToLongRangeEndpoint(fixnumCast, range.End); bool excludeEnd = range.ExcludeEnd && !endless; - int originalBegin = begin; - if (begin < 0) { - begin += listCount; - if (begin < 0) { + long originalBegin = longBegin; + if (longBegin < 0) { + longBegin += listCount; + if (longBegin < 0) { throw RubyExceptions.CreateRangeError("{0}{1}{2} out of range", originalBegin, excludeEnd ? "..." : "..", endless ? "" : end.ToString(CultureInfo.InvariantCulture)); } @@ -129,14 +153,20 @@ internal static void NormalizeRangeNoClamp(ConversionStorage/*!*/ fixnumCas if (end < 0) { end += listCount; } - if (!excludeEnd) { + if (!excludeEnd && end < Int64.MaxValue) { end++; } - count = end - begin; - if (count < 0) { - count = 0; + long longCount = Math.Max(end - longBegin, 0); + + // The answer is padded with nil to the range's full length; one longer than an array + // may be is MRI's rb_ary_store error rather than an allocation that never ends. + if (longCount >= MaxArraySize) { + throw RubyExceptions.CreateIndexError("index {0} too big", longCount - 1); } + + begin = (int)longBegin; + count = (int)longCount; } private static bool InRangeNormalized(IList/*!*/ list, ref int index) { @@ -813,9 +843,9 @@ public static object SetElement(ConversionStorage/*!*/ arrayTryCast, Conv } private static void RangeToStartAndCount(ConversionStorage/*!*/ fixnumCast, Range/*!*/ range, int length, out int start, out int count) { - start = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); + start = (range.Begin == null) ? 0 : CastToRangeEndpoint(fixnumCast, range.Begin); bool endless = range.End == null; - int end = endless ? length : Protocols.CastToFixnum(fixnumCast, range.End); + int end = endless ? length : CastToRangeEndpoint(fixnumCast, range.End); int originalStart = start; start = start < 0 ? start + length : start; @@ -831,7 +861,7 @@ private static void RangeToStartAndCount(ConversionStorage/*!*/ fixnumCast, } end = end < 0 ? end + length : end; - count = Math.Max(range.ExcludeEnd ? end - start : end - start + 1, 0); + count = (int)Math.Min(Math.Max(range.ExcludeEnd ? (long)end - start : (long)end - start + 1, 0), Int32.MaxValue); } #endregion @@ -1520,7 +1550,7 @@ public static object Fill(ConversionStorage/*!*/ fixnumCast, BlockParam blo // start + length overflowed Int32 and produced a negative bound, after which the // loop below appended one element at a time until the process died. MRI reports // "argument too big" for a size it cannot represent; the CLR's is Int32.MaxValue. - if (length > 0 && (long)start + length > MaxArraySize) { + if (length >= 0 && (start >= MaxArraySize || length > MaxArraySize - start)) { throw RubyExceptions.CreateArgumentError("argument too big"); } @@ -1553,9 +1583,9 @@ public static object Fill(ConversionStorage/*!*/ fixnumCast, BlockParam blo private static void FillRange(ConversionStorage/*!*/ fixnumCast, IList/*!*/ self, Range/*!*/ range, out int begin, out int length) { - int rawBegin = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); + int rawBegin = (range.Begin == null) ? 0 : CastToRangeEndpoint(fixnumCast, range.Begin); bool endless = range.End == null; - int rawEnd = endless ? self.Count - 1 : Protocols.CastToFixnum(fixnumCast, range.End); + int rawEnd = endless ? self.Count - 1 : CastToRangeEndpoint(fixnumCast, range.End); begin = NormalizeIndex(self, rawBegin); if (begin < 0) { @@ -1563,9 +1593,10 @@ private static void FillRange(ConversionStorage/*!*/ fixnumCast, IList/*!*/ } int end = endless ? self.Count - 1 : NormalizeIndex(self, rawEnd); + // an end clamped to Int32.MaxValue makes a length that Fill reports as "argument too big" length = endless ? Math.Max(0, self.Count - begin) - : Math.Max(0, end - begin + (range.ExcludeEnd ? 0 : 1)); + : (int)Math.Min(Math.Max(0, (long)end - begin + (range.ExcludeEnd ? 0 : 1)), Int32.MaxValue); } public static object Fill([NotNull]BlockParam/*!*/ block, IList/*!*/ self, int start) { From b01c11b189af2c89cc4858cd1938beb293369231 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:42:44 +0100 Subject: [PATCH 026/147] A trace_var handler that assigns its variable does not fire itself trace_var(:$x, proc { $x *= 2 }) followed by $x = 5 recursed until the stack ran out: the handler's own assignment fired the handlers again. CRuby's rb_gvar_set marks the variable while its handlers run (block_trace) and fires nothing for an assignment made meanwhile, so $x ends up 10. The runtime now keeps the same mark, per thread and per runtime rather than per variable: without a GVL another thread's assignment during a handler should still be traced. CRuby's test/ruby/test_trace.rb hung at TestTrace#test_trace and so was never counted; it now runs to its end, 4 tests, 0 failures. New test TraceVar_AssignInHandler1 (output from CRuby 4.0.10). --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/HookTests.cs | 22 ++++++++++++++ Src/Ruby/Runtime/RubyContext.cs | 39 ++++++++++++++++++++----- 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 00a941aed..19a6716f1 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -546,6 +546,7 @@ public Tests(Driver/*!*/ driver) { Hooks3, MethodLookupCacheFull1, Hooks4, + TraceVar_AssignInHandler1, ClrFields1, ClrFields2, diff --git a/Src/IronRuby.Tests/Runtime/HookTests.cs b/Src/IronRuby.Tests/Runtime/HookTests.cs index d7507b964..c219e1120 100644 --- a/Src/IronRuby.Tests/Runtime/HookTests.cs +++ b/Src/IronRuby.Tests/Runtime/HookTests.cs @@ -391,6 +391,28 @@ public void Hooks4() { p names.map(&interned) ", @" [true, true, true, true, true, true, true, true, true] +"); + } + + /// + /// A trace_var handler that assigns the variable it traces does not fire itself again (MRI's + /// block_trace): it used to recurse until the stack ran out. The expected output is CRuby 4.0's. + /// + public void TraceVar_AssignInHandler1() { + TestOutput(@" +$x = 1 +trace_var(:$x, proc { $x *= 2 }) +$x = 5 +p $x +untrace_var(:$x) +log = [] +trace_var(:$y) { |v| log << v; $y = v + 1 if v < 10 } +$y = 1 +p $y, log +", @" +10 +2 +[1] "); } } diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index d362174f9..d41a7f456 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3428,17 +3428,42 @@ private void FireGlobalVariableTraces(RubyScope scope, string/*!*/ name, object handlers = registered.ToArray(); } - foreach (var handler in handlers) { - var command = handler as GlobalVariableTraceCommand; - if (command != null) { - RubyUtils.Evaluate(command.Code, command.Scope ?? scope, command.Self, null, null, 1); - } else { - var site = GetOrCreateSendSite>("call", RubyCallSignature.Simple(1)); - site.Target(site, handler, value); + // MRI's rb_gvar_set does not fire a variable's handlers while they are already running + // (gvar's block_trace), so that a handler may assign the variable it traces + // (trace_var(:$x) { $x *= 2 }) without recursing forever. MRI's flag is the variable's; + // without a GVL another thread's assignment should still fire, so here it is the thread's. + var running = _runningGlobalVariableTraces; + if (running == null) { + _runningGlobalVariableTraces = running = new List>(); + } + var entry = new KeyValuePair(this, name); + if (running.Contains(entry)) { + return; + } + + running.Add(entry); + try { + foreach (var handler in handlers) { + var command = handler as GlobalVariableTraceCommand; + if (command != null) { + RubyUtils.Evaluate(command.Code, command.Scope ?? scope, command.Self, null, null, 1); + } else { + var site = GetOrCreateSendSite>("call", RubyCallSignature.Simple(1)); + site.Target(site, handler, value); + } } + } finally { + running.Remove(entry); } } + /// + /// The globals whose trace_var handlers this thread is running, with their runtime (several + /// runtimes can share a process and a thread). + /// + [ThreadStatic] + private static List> _runningGlobalVariableTraces; + #endregion #region Global Variables: Special variables (thread-safe) From 9403cde58459d8d6726c1f39858ddd01f4c4cea5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:44:05 +0100 Subject: [PATCH 027/147] Marshal.load says TypeError for a name that is no class, and checks _load first A dump naming a constant that is defined but is not a class or module (C3 = nil) failed with ArgumentError "undefined class/module C3", and a 'u' record with instance variables (how a Time is dumped) whose class has no _load got as far as calling it, a NoMethodError. CRuby's rb_path_to_class raises TypeError "C3 does not refer to class/module" for the first and keeps the ArgumentError for a name that is not defined; r_object checks for _load ("class C3 needs to have method '_load'", a TypeError) before it reads the record, with or without instance variables. RubyContext.TryGetModule gets an overload that says which of the two failures it was, and Marshal resolves every class, module and old 'M' name through it. Messages checked against CRuby 4.0.10. test_marshal's test_change_class_name and test_unloadable_userdef pass; spec/core/marshal, struct, range and data show no new failures. --- Src/Libraries/Builtins/Marshal.cs | 32 ++++++++++++++++++++++--------- Src/Ruby/Runtime/RubyContext.cs | 12 ++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index e2c57d51e..9d7482dce 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1710,11 +1710,16 @@ private RubyClass ReadLoadableType() { if (theClass == null) { return ReadString(); } + CheckLoad(theClass); + return _sites.Load.Target(_sites.Load, theClass, ReadString()); + } + + // r_object checks for _load before it reads the string, with or without instance variables. + private void CheckLoad(RubyClass/*!*/ theClass) { if (!Context.ResolveMethod(theClass, "_load", VisibilityContext.AllVisible).Found) { throw RubyExceptions.CreateTypeError("class {0} needs to have method '_load'", theClass.GetDisplayName(Context, false).ToString()); } - return _sites.Load.Target(_sites.Load, theClass, ReadString()); } // MRI's TYPE_DATA: an object wrapping native data, rebuilt by #_load_data from the @@ -1767,11 +1772,22 @@ private RubyClass ReadLoadableType() { return ReadClassOrModule(typeFlag, Context.GetIdentifierEncoding().Encoding.GetString(name, 0, name.Length)); } - private object/*!*/ ReadClassOrModule(int typeFlag, string/*!*/ name) { + // MRI's rb_path_to_class: a name that is not defined is an ArgumentError, one that is + // defined as something other than a class or module (C3 = nil) a TypeError. + private RubyModule/*!*/ ResolvePath(string/*!*/ name) { RubyModule result; - if (!Context.TryGetModule(_globalScope, name, out result)) { + bool notModule; + if (!Context.TryGetModule(_globalScope, name, out result, out notModule)) { + if (notModule) { + throw RubyExceptions.CreateTypeError("{0} does not refer to class/module", name); + } throw RubyExceptions.CreateArgumentError("undefined class/module {0}", name); } + return result; + } + + private object/*!*/ ReadClassOrModule(int typeFlag, string/*!*/ name) { + RubyModule result = ResolvePath(name); bool isClass = result is RubyClass; if (isClass && typeFlag == 'm') { @@ -1861,6 +1877,9 @@ private RubyArray GetDataMembers(RubyClass/*!*/ dataClass) { // and _load is handed them along with it - that is how Time gets its zone and // its offset back. RubyClass theClass = ReadLoadableType(); + if (theClass != null) { + CheckLoad(theClass); + } MutableString data = ReadString(); // The object itself is entered in the link table only once those instance @@ -2227,12 +2246,7 @@ private object ReadAnObject(int typeFlag, int reservedRef) { private object/*!*/ ReadOldModule() { // Marshal format 4.6 and earlier wrote classes and modules with a single "M" tag. - string name = ReadString().ToString(); - RubyModule result; - if (!Context.TryGetModule(_globalScope, name, out result)) { - throw RubyExceptions.CreateArgumentError("undefined class/module {0}", name); - } - return result; + return ResolvePath(ReadString().ToString()); } internal object Load() { diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index d41a7f456..bc6f9a5ca 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -2626,6 +2626,17 @@ public MethodResolutionResult ResolveMethodWithRefinements(object target, string // thread-safe: public bool TryGetModule(RubyGlobalScope autoloadScope, string/*!*/ moduleName, out RubyModule result) { + bool notModule; + return TryGetModule(autoloadScope, moduleName, out result, out notModule); + } + + /// + /// tells the two failures of MRI's rb_path_to_class apart: a name + /// that is defined but is not a class or module (a TypeError there) from one that is not + /// defined (an ArgumentError). + /// + public bool TryGetModule(RubyGlobalScope autoloadScope, string/*!*/ moduleName, out RubyModule result, out bool notModule) { + notModule = false; using (ClassHierarchyLocker()) { result = _objectClass; int pos = 0; @@ -2645,6 +2656,7 @@ public bool TryGetModule(RubyGlobalScope autoloadScope, string/*!*/ moduleName, } result = tmp.Value as RubyModule; if (result == null) { + notModule = true; return false; } else if (pos2 < 0) { return true; From ffc9d873f1ccfcf3ffe8a92cdf29c14fae74388e Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:44:13 +0100 Subject: [PATCH 028/147] Marshal.load refuses an 'S' record for a class that is not a struct A Struct dump loaded after its constant had been rebound to a plain class made an instance of that class and dropped the members on the floor, and an 'S' record naming Range (GH-6832: dumped by a program that had made Range a Struct) loaded without a word. CRuby's r_object asks rb_struct_s_members first: "class S1 not a struct" (TypeError) for anything that is neither a Struct nor a Data, and for Range, a struct of begin, end and excl inside CRuby, "struct Range not compatible (:a for :begin)" or "(struct size differs)". ReadStruct now reads the class first and raises those, and an 'S' record for Range goes through the range loader with its members checked. Messages checked against CRuby 4.0.10. test_marshal's test_inconsistent_struct and test_load_range_as_struct pass; spec/core/marshal, struct, range and data show no new failures. --- Src/Libraries/Builtins/Marshal.cs | 32 +++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 9d7482dce..6d42af1c5 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1604,6 +1604,17 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { /// subclass's instance variables there). /// private object/*!*/ ReadRange(RubyClass/*!*/ theClass, int count, int objectRef) { + return ReadRange(theClass, count, objectRef, false); + } + + // MRI's Range is a struct of begin, end and excl, which an 'S' record has to name in that + // order (GH-6832: a Range dumped by a program that had redefined Range as a Struct). + private static readonly string[]/*!*/ RangeMembers = new[] { "begin", "end", "excl" }; + + private object/*!*/ ReadRange(RubyClass/*!*/ theClass, int count, int objectRef, bool asStruct) { + if (asStruct && count != RangeMembers.Length) { + throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", theClass.Name); + } var range = (Range)RubyUtils.CreateObject(theClass); if (objectRef >= 0) { _objects[objectRef] = range; @@ -1612,6 +1623,9 @@ private RubyEncoding ParseEncodingIVar(string/*!*/ name, object value) { bool excludeEnd = false, exclGiven = false; for (int i = 0; i < count; i++) { string name = ReadIdentifier(); + if (asStruct && name != RangeMembers[i]) { + throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, RangeMembers[i]); + } object value = ReadAnObject(false); switch (name) { case "begin": rangeBegin = value; break; @@ -1800,13 +1814,24 @@ private void CheckLoad(RubyClass/*!*/ theClass) { } private object/*!*/ ReadStruct(int objectRef) { - object instance = UnmarshalNewObject(); + RubyClass theClass = ReadType(); + if (theClass.IsSubclassOf(Context.GetClass(typeof(Range)))) { + return ReadRange(theClass, ReadInt32(), objectRef, true); + } + + // Data shares the Struct record, so which of the two this is can only be told from + // the class that was named in it. Anything else is not a struct at all, which MRI's + // rb_struct_s_members says before the object is made ([ruby-dev:31709]). + bool isStruct = theClass.IsSubclassOf(Context.GetClass(typeof(RubyStruct))); + if (!isStruct && GetDataMembers(theClass) == null) { + throw RubyExceptions.CreateTypeError("class {0} not a struct", theClass.Name); + } + + object instance = RubyUtils.CreateObject(theClass); if (objectRef >= 0) { _objects[objectRef] = instance; } - // Data shares the Struct record, so which of the two this is can only be told from - // the class that was named in it. if (!(instance is RubyStruct)) { return ReadData(instance); } @@ -1822,7 +1847,6 @@ private void CheckLoad(RubyClass/*!*/ theClass) { for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (name != names[i]) { - RubyClass theClass = Context.GetClassOf(obj); throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, names[i]); } obj[i] = ReadAnObject(false); From 7f5e4228b721c78f72c3dd430156136dd9bc1839 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:44:18 +0100 Subject: [PATCH 029/147] Marshal.load does not set instance variables on a class or module "\x04\bIc\x1bTestMarshal::TestClass\x06:\x0e@ivar_bug\"\bbug" set @ivar_bug on TestClass, and a dump could set Struct's __members__ the same way ([ruby-dev:31759]). CRuby's r_ivar and prohibit_ivar raise TypeError "can't override instance variable of class 'X'" (or module) before setting anything; the one thing allowed after a class or module name is the name's own encoding (r_encname), which a non-ASCII name is dumped with. ReadIVars now does the same for a RubyModule: encoding entries are taken, anything else raises. test_marshal's test_class_ivar, test_module_ivar and test_struct_invalid_members pass; the multibyte class and module name examples of spec/core/marshal still load. --- Src/Libraries/Builtins/Marshal.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 6d42af1c5..3fa1e43d1 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1948,6 +1948,21 @@ private RubyArray GetDataMembers(RubyClass/*!*/ dataClass) { private void ReadIVars(object obj) { int count = ReadInt32(); + // A dump does not get to set the instance variables of a class or module it names: the + // one thing that may follow its name is the name's encoding (MRI's r_encname, then + // prohibit_ivar), and the error comes before anything is set. + RubyModule module = obj as RubyModule; + if (module != null) { + for (int i = 0; i < count; i++) { + string name = ReadIdentifier(); + object value = ReadAnObject(false); + if (ParseEncodingIVar(name, value) == null) { + throw RubyExceptions.CreateTypeError("can't override instance variable of {0} '{1}'", + module.IsClass ? "class" : "module", module.GetDisplayName(Context, false).ToString()); + } + } + return; + } for (int i = 0; i < count; i++) { string name = ReadIdentifier(); object value = ReadAnObject(false); From 9a55ea499acb567cb36be88ec6aa668495423329 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:44:57 +0100 Subject: [PATCH 030/147] Array#zip reaches #to_ary and #each through method_missing [1].zip(obj), with obj answering everything through method_missing, raised "wrong argument type Object (must respond to :each)": the prelude asked respond_to? before converting or walking the argument. CRuby's take_items converts with rb_check_array_type and walks with rb_check_block_call, both of which go to method_missing for a method the object lacks (and call a private #each), and answers [[1, nil]] (TestArray#test_zip_method_missing_block, [Bug #22436]). With an empty receiver it never asks for #each, so [].zip(1) is []. The conversion is now Array.try_convert (which already follows rb_check_array_type), #each is called with __send__, and only a NoMethodError for #each on the argument itself becomes the TypeError. spec/core/array/zip_spec.rb, enumerable and lazy zip specs pass. --- Src/StdLib/ironruby/ruby4.rb | 43 ++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 3dd5a0d99..101afb10a 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -5101,32 +5101,47 @@ def uniq!(&block) # receiver's size) or any object with #each. alias :__zip_arrays__ :zip + # MRI's take_items: the argument is converted with rb_check_array_type and walked with + # rb_check_block_call, both of which reach a #to_ary or an #each that only method_missing + # answers, and call a private #each. With an empty receiver nothing is asked for #each. def zip(*others, &block) length = size converted = others.map do |other| if other.is_a?(Array) other - elsif other.respond_to?(:to_ary) - other.to_ary - elsif other.respond_to?(:each) - collected = [] - # several yielded values make one element, as Enumerator#next would pack them; - # MRI's take_i stops as soon as it has the receiver's length, without asking for one - # more (an Enumerator.produce is called exactly that many times) - if length > 0 - other.each do |*element| - collected << (element.size <= 1 ? element[0] : element) - break if collected.size >= length + elsif (array = ::Array.try_convert(other)) + array + elsif length == 0 + [] + else + if other.respond_to?(:each, true) + __zip_take__(other, length) + else + begin + __zip_take__(other, length) + rescue ::NoMethodError => e + ::Kernel.raise if e.name != :each || !e.receiver.equal?(other) + ::Kernel.raise(::TypeError, "wrong argument type #{__ir_message_type_name__(other)} (must respond to :each)") end end - collected - else - raise TypeError, "wrong argument type #{__ir_message_type_name__(other)} (must respond to :each)" end end __zip_arrays__(*converted, &block) end + def __zip_take__(other, length) + collected = [] + # several yielded values make one element, as Enumerator#next would pack them; + # MRI's take_i stops as soon as it has the receiver's length, without asking for one + # more (an Enumerator.produce is called exactly that many times) + other.__send__(:each) do |*element| + collected << (element.size <= 1 ? element[0] : element) + break if collected.size >= length + end + collected + end + private :__zip_take__ + private :__zip_arrays__ end From 21d7e130b171644f5d99f29a1f391ad12355f7a3 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:45:27 +0100 Subject: [PATCH 031/147] lf_newline, and newline decorators into UTF-16 and UTF-32 String#encode ignored lf_newline: true, and Encoding::Converter knew no lf_newline at all (no LF_NEWLINE_DECORATOR, no option, "newline: :lf" quietly made a universal_newline). CRuby's lf_newline turns CRLF and CR into LF like universal_newline but goes by its own name, in #convpath and in errors. Encoding::Converter also skipped its newline decorators for a destination that is not ASCII compatible: they worked on the converted bytes, where a UTF-16 "\n" is two bytes. CRuby puts the decorators on the UTF-8 side of such a conversion (rb_econv_decorate_at_last), so they now run on the characters before they are encoded, and #convpath lists them before the last leg: ["universal_newline", [UTF-8, UTF-16BE]], [[UTF-16BE, UTF-8], "universal_newline", [UTF-8, UTF-16LE]]. Checked against CRuby 4.0.10 (test_econv's test_search_convpath and test_transcode's test_newline_options now pass); spec/core/encoding, String#encode, IO#set_encoding/read/write and library/stringio unchanged against master. --- Src/Libraries/Builtins/EncodingConverter.cs | 151 ++++++++++++++++---- Src/Libraries/Builtins/MutableStringOps.cs | 11 +- 2 files changed, 134 insertions(+), 28 deletions(-) diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index b56dd9c92..5ad47f3e0 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -48,6 +48,8 @@ public class RubyConverter { internal const int UniversalNewlineFlag = 0x100; internal const int CrlfNewlineFlag = 0x1000; internal const int CrNewlineFlag = 0x2000; + internal const int LfNewlineFlag = 0x4000; + internal const int NewlineMask = UniversalNewlineFlag | CrlfNewlineFlag | CrNewlineFlag | LfNewlineFlag; internal const int XmlTextFlag = 0x8000; internal const int XmlAttrContentFlag = 0x10000; internal const int XmlAttrQuoteFlag = 0x100000; @@ -84,6 +86,9 @@ public class RubyConverter { [RubyConstant("CR_NEWLINE_DECORATOR")] public static readonly int CrNewlineDecorator = CrNewlineFlag; + [RubyConstant("LF_NEWLINE_DECORATOR")] + public static readonly int LfNewlineDecorator = LfNewlineFlag; + [RubyConstant("XML_TEXT_DECORATOR")] public static readonly int XmlTextDecorator = XmlTextFlag; @@ -135,7 +140,6 @@ public class RubyConverter { // set once the :xml => :attr decorator has written its opening quote, and once it has // written the closing one private bool _xmlQuoteOpened, _decoratorsFinished; - #endregion #region Construction @@ -221,6 +225,7 @@ private RubyEncoding/*!*/ ReplacementEncoding { if ((flags & UniversalNewlineFlag) != 0) { names.Add("universal_newline"); } if ((flags & CrlfNewlineFlag) != 0) { names.Add("crlf_newline"); } if ((flags & CrNewlineFlag) != 0) { names.Add("cr_newline"); } + if ((flags & LfNewlineFlag) != 0) { names.Add("lf_newline"); } if ((flags & XmlTextFlag) != 0) { names.Add("xml_text"); } if ((flags & XmlAttrContentFlag) != 0) { names.Add("xml_attr_content"); } if ((flags & XmlAttrQuoteFlag) != 0) { names.Add("xml_attr_quote"); } @@ -300,7 +305,7 @@ private static RubyEncoding[] ResolvePath(ConversionStorage/*!*/ /// private static void RequireOneNewlineDecorator(ConversionStorage/*!*/ toStr, object source, object destination, int flags) { - int newline = flags & (UniversalNewlineFlag | CrlfNewlineFlag | CrNewlineFlag); + int newline = flags & NewlineMask; if ((newline & (newline - 1)) != 0) { throw ConverterNotFound(EncodingName(toStr, source), EncodingName(toStr, destination), flags); } @@ -339,28 +344,29 @@ private static RubyEncoding FindEncoding(RubyContext/*!*/ context, object obj, s } // The escapers run before the newline decorators, and #convpath lists them in the - // order they run rather than in the order the options were given. - if ((flags & XmlTextFlag) != 0) { - result.Add(MutableString.CreateAscii("xml_text_escape").Freeze()); - } - if ((flags & XmlAttrContentFlag) != 0) { - result.Add(MutableString.CreateAscii("xml_attr_content_escape").Freeze()); - } - if ((flags & XmlAttrQuoteFlag) != 0) { - result.Add(MutableString.CreateAscii("xml_attr_quote").Freeze()); - } - if ((flags & UniversalNewlineFlag) != 0) { - result.Add(MutableString.CreateAscii("universal_newline").Freeze()); - } - if ((flags & CrlfNewlineFlag) != 0) { - result.Add(MutableString.CreateAscii("crlf_newline").Freeze()); - } - if ((flags & CrNewlineFlag) != 0) { - result.Add(MutableString.CreateAscii("cr_newline").Freeze()); + // order they run rather than in the order the options were given. MRI's + // rb_econv_decorate_at_last puts them on the UTF-8 side of a last leg into an + // encoding that is not ASCII compatible: [[UTF-8, UTF-16BE]] with + // universal_newline is ["universal_newline", [UTF-8, UTF-16BE]]. + int at = (path != null && !path[path.Length - 1].IsAsciiIdentity) ? result.Count - 1 : result.Count; + foreach (string name in DecoratorPathNames(flags)) { + result.Insert(at++, MutableString.CreateAscii(name).Freeze()); } return result; } + private static List/*!*/ DecoratorPathNames(int flags) { + var names = new List(); + if ((flags & XmlTextFlag) != 0) { names.Add("xml_text_escape"); } + if ((flags & XmlAttrContentFlag) != 0) { names.Add("xml_attr_content_escape"); } + if ((flags & XmlAttrQuoteFlag) != 0) { names.Add("xml_attr_quote"); } + if ((flags & UniversalNewlineFlag) != 0) { names.Add("universal_newline"); } + if ((flags & CrlfNewlineFlag) != 0) { names.Add("crlf_newline"); } + if ((flags & CrNewlineFlag) != 0) { names.Add("cr_newline"); } + if ((flags & LfNewlineFlag) != 0) { names.Add("lf_newline"); } + return names; + } + internal RubyArray/*!*/ ConvPath() { return MakeConvPath(_noConversion ? null : _path, _flags); } @@ -806,6 +812,27 @@ private string EncodeChars(char[]/*!*/ chars, int count, List/*!*/ written int size = (Char.IsHighSurrogate(chars[i]) && i + 1 < count && Char.IsLowSurrogate(chars[i + 1])) ? 2 : 1; int codepoint = size == 2 ? Char.ConvertToUtf32(chars[i], chars[i + 1]) : chars[i]; + if (NewlinesInCharacters) { + bool consumed; + string newline = TranslateNewline(codepoint, out consumed); + if (newline.Length != 0 && !Emit(AsciiInDestination(newline), written, limit)) { + if (consumed) { + i += size; + if (i < count) { + // the rest of the characters are still to be converted + _pendingOutput.AddRange(EncodeRemaining(chars, i, count)); + } + } else { + _pendingOutput.AddRange(EncodeRemaining(chars, i, count)); + } + return "destination_buffer_full"; + } + if (consumed) { + i += size; + continue; + } + } + string escape = XmlEscape(codepoint); if (escape != null) { if (!EmitInserted(AsciiInDestination(escape), written, limit)) { @@ -856,6 +883,73 @@ private string EncodeChars(char[]/*!*/ chars, int count, List/*!*/ written return null; } + /// + /// MRI runs the newline decorators on the UTF-8 side of a conversion into an + /// encoding that is not ASCII compatible (UTF-16, UTF-32): there they see the + /// characters, which is where they are applied here too, rather than to the bytes. + /// + private bool NewlinesInCharacters { + get { return (_flags & NewlineMask) != 0 && !DestinationEncoding.IsAsciiIdentity && !_noConversion; } + } + + /// + /// What the newline decorator makes of a character: the ASCII text to write for it, + /// and whether that text replaces it () or merely goes in + /// front of it - the LF a CR held back by universal_newline turns into, once the + /// character after it shows that it was no CRLF. + /// + private string/*!*/ TranslateNewline(int codepoint, out bool consumed) { + if ((_flags & (UniversalNewlineFlag | LfNewlineFlag)) != 0) { + string held = ""; + if (_pendingCarriageReturn) { + _pendingCarriageReturn = false; + held = "\n"; + if (codepoint == '\n') { + consumed = true; + return held; + } + } + if (codepoint == '\r') { + _pendingCarriageReturn = true; + consumed = true; + return held; + } + consumed = false; + return held; + } + if (codepoint == '\n') { + consumed = true; + return ((_flags & CrlfNewlineFlag) != 0) ? "\r\n" : "\r"; + } + consumed = false; + return ""; + } + + /// + /// The characters a full destination left unconverted, encoded as they are, to wait + /// in _pendingOutput with the rest of what did not fit. + /// + private byte[]/*!*/ EncodeRemaining(char[]/*!*/ chars, int index, int count) { + var bytes = new List(); + for (int i = index; i < count; i++) { + int c = chars[i]; + if (c == '\n' || c == '\r') { + bool consumed; + string newline = TranslateNewline(c, out consumed); + bytes.AddRange(AsciiInDestination(newline)); + if (consumed) { + continue; + } + } + try { + bytes.AddRange(EncodeCodepoint(chars, i, 1)); + } catch (EncoderFallbackException) { + bytes.AddRange(_replacementBytes); + } + } + return bytes.ToArray(); + } + private bool IsWideSource { get { switch (DecodeStageSource.CodePage) { @@ -1098,7 +1192,7 @@ private bool EmitFinish(List/*!*/ written, int limit) { if (_pendingCarriageReturn) { // a CR at the very end has nothing left to pair with: it is a newline _pendingCarriageReturn = false; - if (!Put(new byte[] { (byte)'\n' }, written, limit)) { + if (!Put(AsciiInDestination("\n"), written, limit)) { return false; } } @@ -1205,14 +1299,13 @@ private string XmlEscape(int codepoint) { } private byte[]/*!*/ ApplyNewlineDecorators(byte[]/*!*/ bytes) { - if ((_flags & (UniversalNewlineFlag | CrlfNewlineFlag | CrNewlineFlag)) == 0 || - !DestinationEncoding.IsAsciiIdentity) { + if ((_flags & NewlineMask) == 0 || !DestinationEncoding.IsAsciiIdentity) { return bytes; } var result = new List(bytes.Length + 8); foreach (byte b in bytes) { - if ((_flags & UniversalNewlineFlag) != 0) { + if ((_flags & (UniversalNewlineFlag | LfNewlineFlag)) != 0) { if (_pendingCarriageReturn) { _pendingCarriageReturn = false; result.Add((byte)'\n'); @@ -1400,12 +1493,18 @@ private static int ParseOptions(ConversionStorage>/* } break; + case "lf_newline": + if (Protocols.IsTrue(entry.Value)) { + flags |= LfNewlineFlag; + } + break; + case "newline": switch (SymbolName(entry.Value)) { case "universal": newlineOption = UniversalNewlineFlag; break; case "crlf": newlineOption = CrlfNewlineFlag; break; case "cr": newlineOption = CrNewlineFlag; break; - case "lf": newlineOption = UniversalNewlineFlag; break; + case "lf": newlineOption = LfNewlineFlag; break; default: throw RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", (object)SymbolName(entry.Value) ?? toHash.Context.Inspect(entry.Value)); @@ -1428,7 +1527,7 @@ private static int ParseOptions(ConversionStorage>/* // MRI's econv_opts: newline: wins over the *_newline: flags, with a warning if (newlineOption >= 0) { - const int newlineMask = UniversalNewlineFlag | CrlfNewlineFlag | CrNewlineFlag; + const int newlineMask = NewlineMask; if ((flags & newlineMask) != 0) { toHash.Context.ReportWarning(":newline option precedes other newline options", true); } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 45183be92..092a6ac56 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -2827,13 +2827,14 @@ private struct TranscodeSettings { internal MutableString Replacement; internal object Fallback; internal int XmlMode; // 0 none, 't' text, 'a' attr - internal int Newline; // 0 none, 'u' universal, 'r' cr, 'c' crlf + internal int Newline; // 0 none, 'u' universal, 'l' lf, 'r' cr, 'c' crlf /// The decorators, named and ordered as MRI's error messages list them. internal string/*!*/ DecoratorNames() { var names = new List(); switch (Newline) { case 'u': names.Add("universal_newline"); break; + case 'l': names.Add("lf_newline"); break; case 'c': names.Add("crlf_newline"); break; case 'r': names.Add("cr_newline"); break; } @@ -2920,7 +2921,7 @@ internal static TranscodeSettings Parse(RubyContext/*!*/ context, } else if (nlName == "crlf") { result.Newline = 'c'; } else if (nlName == "lf") { - result.Newline = 'u'; + result.Newline = 'l'; } else { throw RubyExceptions.CreateArgumentError("unexpected value for newline option: {0}", (object)nlName ?? context.Inspect(entry.Value)); @@ -2938,6 +2939,12 @@ internal static TranscodeSettings Parse(RubyContext/*!*/ context, case "crlf_newline": if (RubyOps.IsTrue(entry.Value)) { result.Newline = 'c'; } break; + + // MRI's lf_newline decorator: CRLF and CR become LF, as with + // universal_newline, under a name of its own + case "lf_newline": + if (RubyOps.IsTrue(entry.Value)) { result.Newline = 'l'; } + break; } } From 6d411781db8b4f0f4ee3df225ee43dcb090ce0fb Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:45:27 +0100 Subject: [PATCH 032/147] Encoding::Converter.new takes a conversion path, and a decorator by name Encoding::Converter.new([["iso-8859-1", "euc-jp"], "universal_newline"]) raised "wrong number of arguments": CRuby accepts the path #convpath answers with, a list of [source, destination] pairs and decorator names (econv_init's convpath form), and gives it back from #convpath. Its errors are CRuby's: "decoration failed: foo", "adding conversion failed: a to b", "not a 2-element array in convpath". Encoding::Converter.new("", "amp_escape") (or any other decorator's name) was "code converter not found": CRuby finds the decorators as transcoders from "" to their names, so such a converter runs just that decorator. amp_escape, which escapes only "&" and has no flag in CRuby, gets an internal one. The decorators of a path run where the options would put them, not necessarily where the path lists them. Checked against CRuby 4.0.10 (test_econv's test_s_new_convpath, test_xml_escape_text, test_xml_escape_attr_content, test_xml_escape_attr_quote and test_inspect_decorator_source_name now pass); spec/core/encoding/converter passes. --- Src/Libraries/Builtins/EncodingConverter.cs | 112 +++++++++++++++++++- 1 file changed, 108 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index 5ad47f3e0..cbd25fd38 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -56,6 +56,10 @@ public class RubyConverter { internal const int PartialInputFlag = 0x20000; internal const int AfterOutputFlag = 0x40000; + // amp_escape has no flag in MRI - it is only ever asked for by name, as + // Encoding::Converter.new("", "amp_escape") - so this one is IronRuby's own + internal const int AmpEscapeFlag = 0x10000000; + [RubyConstant("INVALID_MASK")] public static readonly int InvalidMask = InvalidMaskFlag; @@ -140,6 +144,13 @@ public class RubyConverter { // set once the :xml => :attr decorator has written its opening quote, and once it has // written the closing one private bool _xmlQuoteOpened, _decoratorsFinished; + + // what #convpath and #inspect say of a converter built from a conversion path + // (Encoding::Converter.new([...])) or from a decorator's name, which is not what the + // flags alone would say; null for any other + private RubyArray _explicitConvPath; + private string _explicitDescription; + #endregion #region Construction @@ -368,6 +379,9 @@ private static RubyEncoding FindEncoding(RubyContext/*!*/ context, object obj, s } internal RubyArray/*!*/ ConvPath() { + if (_explicitConvPath != null) { + return new RubyArray(_explicitConvPath); + } return MakeConvPath(_noConversion ? null : _path, _flags); } @@ -1285,7 +1299,7 @@ private bool NeedsOpeningQuote { /// private string XmlEscape(int codepoint) { if ((_flags & (XmlTextFlag | XmlAttrContentFlag)) == 0) { - return null; + return ((_flags & AmpEscapeFlag) != 0 && codepoint == '&') ? "&" : null; } bool attribute = (_flags & XmlAttrContentFlag) != 0; switch (codepoint) { @@ -1553,10 +1567,33 @@ private static int ParseOptions(ConversionStorage>/* [RubyConstructor] public static RubyConverter/*!*/ Create(ConversionStorage/*!*/ toStr, ConversionStorage>/*!*/ toHash, RubyClass/*!*/ self, - object source, object destination, [Optional]object options) { + object source, [Optional]object destination, [Optional]object options) { + + if (destination == Missing.Value) { + var convpath = source as IList; + if (convpath == null) { + throw RubyExceptions.CreateArgumentError("wrong number of arguments (given 1, expected 2..3)"); + } + return CreateFromConvPath(toStr, convpath); + } object replacement; int flags = ParseOptions(toHash, options, out replacement); + + // Encoding::Converter.new("", "amp_escape"): a decorator asked for by name, which + // MRI finds as a transcoder from "" to it + int decorator; + var sourceString = source as MutableString; + var destinationString = destination as MutableString; + if (sourceString != null && sourceString.IsEmpty && destinationString != null && + TryGetDecoratorFlag(destinationString.ToString(), out decorator)) { + var named = new RubyConverter(null, flags | decorator); + string name = destinationString.ToString(); + named._explicitConvPath = new RubyArray { MutableString.CreateAscii(name).Freeze() }; + named._explicitDescription = name; + return named; + } + RequireOneNewlineDecorator(toStr, source, destination, flags); var path = ResolvePath(toStr, source, destination, flags, true); @@ -1567,6 +1604,73 @@ private static int ParseOptions(ConversionStorage>/* return result; } + private static bool TryGetDecoratorFlag(string/*!*/ name, out int flag) { + switch (name) { + case "amp_escape": flag = AmpEscapeFlag; return true; + case "xml_text_escape": flag = XmlTextFlag; return true; + case "xml_attr_content_escape": flag = XmlAttrContentFlag; return true; + case "xml_attr_quote": flag = XmlAttrQuoteFlag; return true; + case "universal_newline": flag = UniversalNewlineFlag; return true; + case "crlf_newline": flag = CrlfNewlineFlag; return true; + case "cr_newline": flag = CrNewlineFlag; return true; + case "lf_newline": flag = LfNewlineFlag; return true; + default: flag = 0; return false; + } + } + + /// + /// Encoding::Converter.new(convpath): the conversion spelled out as MRI's #convpath + /// answers it, a list of [source, destination] pairs and decorator names. The pairs + /// are chained (each one searched for as Encoding::Converter.new would) and the + /// decorators added. #convpath gives the path back as it was asked for; the + /// decorators run where the options would put them, wherever they were listed. + /// + private static RubyConverter/*!*/ CreateFromConvPath(ConversionStorage/*!*/ toStr, IList/*!*/ convpath) { + var path = new List(); + var reported = new RubyArray(); + int flags = 0; + foreach (object item in convpath) { + var pair = item as IList; + if (pair != null) { + if (pair.Count != 2) { + throw RubyExceptions.CreateArgumentError("not a 2-element array in convpath"); + } + string sourceName = EncodingName(toStr, pair[0]); + string destinationName = EncodingName(toStr, pair[1]); + RubyEncoding from = FindEncoding(toStr.Context, pair[0], sourceName); + RubyEncoding to = FindEncoding(toStr.Context, pair[1], destinationName); + if (from == null || to == null || from == to || from.HasNoTranscoder || to.HasNoTranscoder) { + throw RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName); + } + RubyEncoding[] leg = RubyExceptions.ConversionPath(from, to); + if (path.Count != 0 && path[path.Count - 1] != leg[0]) { + throw RubyExceptions.CreateArgumentError("adding conversion failed: {0} to {1}", sourceName, destinationName); + } + for (int i = (path.Count == 0) ? 0 : 1; i < leg.Length; i++) { + path.Add(leg[i]); + } + for (int i = 0; i < leg.Length - 1; i++) { + reported.Add(new RubyArray { leg[i], leg[i + 1] }); + } + continue; + } + + string name = Protocols.CastToString(toStr, item).ToString(); + int decorator; + if (!TryGetDecoratorFlag(name, out decorator)) { + throw RubyExceptions.CreateArgumentError("decoration failed: {0}", name); + } + flags |= decorator; + reported.Add(MutableString.CreateAscii(name).Freeze()); + } + + var result = new RubyConverter(path.Count != 0 ? path.ToArray() : null, flags); + result._explicitConvPath = reported; + // MRI's #inspect names the encodings of such a converter but none of its decorators + result._explicitDescription = (path.Count != 0) ? Describe(path[0].Name, path[path.Count - 1].Name, 0) : "no-conversion"; + return result; + } + [RubyMethod("search_convpath", RubyMethodAttributes.PublicSingleton)] public static RubyArray/*!*/ SearchConvPath(ConversionStorage/*!*/ toStr, ConversionStorage>/*!*/ toHash, RubyClass/*!*/ self, @@ -1639,8 +1743,8 @@ public static RubyEncoding GetDestinationEncoding(RubyConverter/*!*/ self) { [RubyMethod("inspect")] public static MutableString/*!*/ Inspect(RubyConverter/*!*/ self) { - string description = self.IsNoConversion ? Describe("", "", self._flags) : - Describe(self.SourceEncoding.Name, self.DestinationEncoding.Name, self._flags); + string description = self._explicitDescription ?? (self.IsNoConversion ? Describe("", "", self._flags) : + Describe(self.SourceEncoding.Name, self.DestinationEncoding.Name, self._flags)); return MutableString.CreateBinary(Encoding.ASCII.GetBytes("#")); } From 74c9b87b1449a4be0d540d19c926385f3d04b588 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:45:36 +0100 Subject: [PATCH 033/147] String#encode reads broken UTF-16 and UTF-32 as CRuby does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "\xD8\x00\x00!".encode("UTF-8", "UTF-16BE", invalid: :replace) gave "�" and lost the "!": a source that did not decode was walked a byte at a time with .NET's decoder, which takes the unit after an unpaired high surrogate into the error. CRuby's from_UTF_16BE/LE and from_UTF_32BE/LE transcoders make a lone surrogate (or a UTF-32 unit past U+10FFFF) one invalid unit and read what follows a high surrogate again, so the answer is "�!"; the error's error_bytes and readagain_bytes say the same. Such a source is now decoded unit by unit the way those transcoders do (as Encoding::Converter already did, a byte at a time). Checked against CRuby 4.0.10 (test_transcode's test_invalid_replace now passes, and the InvalidByteSequenceError details match); String#encode and spec/core/encoding unchanged against master. --- Src/Libraries/Builtins/MutableStringOps.cs | 81 ++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 092a6ac56..5a8980bac 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -3205,6 +3205,10 @@ private static void TranscodeByCharacter( // fall through } + if (from.MinBytesPerChar > 1) { + return DecodeWideForTranscoding(bytes, from, to, replacement); + } + var result = new StringBuilder(bytes.Length); var decoder = strict.GetDecoder(); var chars = new char[8]; @@ -3277,6 +3281,83 @@ private static void TranscodeByCharacter( return result.ToString(); } + /// + /// UTF-16 and UTF-32 bytes that do not all decode, the way MRI's from_UTF_16BE/LE and + /// from_UTF_32BE/LE transcoders read them (Encoding::Converter's DecodeWideByte does the + /// same a byte at a time): a lone low surrogate is one invalid unit; a high surrogate + /// followed by anything but a low one is an invalid unit too, and what follows it is read + /// again (UTF-16BE knows it from the first byte after the surrogate, UTF-16LE from the + /// unit); a UTF-32 unit that is a surrogate or past U+10FFFF is invalid as a whole; and a + /// unit cut short by the end of the string is incomplete. .NET's decoder, fed a byte at a + /// time, takes the bytes after a bad surrogate into the error instead. + /// + private static string/*!*/ DecodeWideForTranscoding(byte[]/*!*/ bytes, RubyEncoding/*!*/ from, RubyEncoding/*!*/ to, + string replacement) { + + bool big = from.IsBigEndianUnicode; + int unitSize = from.MinBytesPerChar; + var result = new StringBuilder(bytes.Length / unitSize); + int i = 0; + while (i < bytes.Length) { + byte[] errorBytes = null, readAgain = null; + int length = 0; + bool incomplete = false; + + if (i + unitSize > bytes.Length) { + length = bytes.Length - i; + incomplete = true; + } else if (unitSize == 4) { + long value = big + ? ((long)bytes[i] << 24) | ((long)bytes[i + 1] << 16) | ((long)bytes[i + 2] << 8) | bytes[i + 3] + : ((long)bytes[i + 3] << 24) | ((long)bytes[i + 2] << 16) | ((long)bytes[i + 1] << 8) | bytes[i]; + if (value > 0x10ffff || value >= 0xd800 && value <= 0xdfff) { + length = 4; + } else { + result.Append(Char.ConvertFromUtf32((int)value)); + i += 4; + continue; + } + } else { + int unit = big ? (bytes[i] << 8) | bytes[i + 1] : (bytes[i + 1] << 8) | bytes[i]; + if (unit >= 0xdc00 && unit <= 0xdfff) { + length = 2; + } else if (unit < 0xd800 || unit > 0xdbff) { + result.Append((char)unit); + i += 2; + continue; + } else if (i + 2 >= bytes.Length) { + length = bytes.Length - i; + incomplete = true; + } else if (big && (bytes[i + 2] < 0xdc || bytes[i + 2] > 0xdf)) { + length = 2; + readAgain = new[] { bytes[i + 2] }; + } else if (i + 3 >= bytes.Length) { + length = bytes.Length - i; + incomplete = true; + } else { + int low = big ? (bytes[i + 2] << 8) | bytes[i + 3] : (bytes[i + 3] << 8) | bytes[i + 2]; + if (low < 0xdc00 || low > 0xdfff) { + length = 2; + readAgain = new[] { bytes[i + 2], bytes[i + 3] }; + } else { + result.Append((char)unit).Append((char)low); + i += 4; + continue; + } + } + } + + errorBytes = new byte[length]; + Array.Copy(bytes, i, errorBytes, 0, length); + if (replacement == null) { + throw RubyExceptions.CreateInvalidByteSequenceError(from, FirstLegDestination(from, to), errorBytes, readAgain, incomplete); + } + result.Append(replacement); + i += length; + } + return result.ToString(); + } + /// /// Invalid bytes fail on the first leg of the conversion, and MRI's error names that leg: /// EUC-JP to UTF-8 when the conversion was asked for from EUC-JP to ISO-8859-1. From 9e8e8e7b5ddca5d0285a1cbc850dcfbe877d356e Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:45:36 +0100 Subject: [PATCH 034/147] String#encode without a target replaces what does not convert With default_internal set, str.encode converts to it, and CRuby's str_transcode0 asks for invalid: :replace and undef: :replace when no target is given: "\xE3\x81\x82\x81".encode is "\xA4\xA2?" in EUC-JP. IronRuby raised Encoding::InvalidByteSequenceError. A string already in the target encoding is still left as it is (CRuby scrubs it only when invalid: :replace is given explicitly). Checked against CRuby 4.0.10 (test_transcode's test_noargument now passes); String#encode specs unchanged against master. --- Src/Libraries/Builtins/MutableStringOps.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 5a8980bac..45f9d899b 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -2783,6 +2783,12 @@ public static bool ValidEncoding(MutableString/*!*/ self) { var settings = TranscodeSettings.Parse(toStr.Context, toHash, options, to); + if (toEncoding == Missing.Value && from != to) { + // MRI's str_transcode0: #encode without a target converts to default_internal and + // replaces what does not convert rather than raising + settings.ReplaceInvalid = settings.ReplaceUndefined = true; + } + if (from == to && !settings.ReplaceInvalid && settings.XmlMode == 0 && settings.Newline == 0) { // Nothing to do, and in particular nothing to validate: MRI does not check the // bytes when the source and target encodings are the same. From 22884480264ba3fd7b7fc054655c19f152221e94 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:50:22 +0100 Subject: [PATCH 035/147] Array#inspect and Hash#inspect take the encoding of the first item only [nil, 1, "", "a"].inspect was UTF-8 where CRuby answers US-ASCII: the result gave way to the encoding of any inspected element that was not US-ASCII, ASCII only or not. CRuby's rb_ary_inspect copies the encoding of the first element's inspection and appends the rest as any string is appended, so ASCII only text leaves the encoding alone; Hash#inspect (inspect_i) does the same with the first key, a Symbol key's name standing for it. A key is now inspected once rather than twice for that. Checked against CRuby 4.0.10 (test_m17n's test_array_to_s and test_hash_to_s now pass); Array/Hash#inspect and #to_s, Struct, Kernel#p/#inspect, Set and pp specs unchanged against master. --- Src/Libraries/Extensions/IDictionaryOps.cs | 13 +++++++------ Src/Libraries/Extensions/IListOps.cs | 16 +++++++--------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/Src/Libraries/Extensions/IDictionaryOps.cs b/Src/Libraries/Extensions/IDictionaryOps.cs index 274f0c10a..29f917cf4 100644 --- a/Src/Libraries/Extensions/IDictionaryOps.cs +++ b/Src/Libraries/Extensions/IDictionaryOps.cs @@ -877,18 +877,22 @@ public static IDictionary ToHash(IDictionary/*!* return MutableString.CreateAscii("{...}"); } - // US-ASCII until an inspected key or value brings another encoding, as for Array#inspect. + // MRI's inspect_i: US-ASCII, then the encoding of the first key as it is written + // (a Symbol key's name, any other key's inspection), with the rest appended as + // any string is - ASCII only text leaves the encoding alone. MutableString str = MutableString.CreateMutable(RubyEncoding.Ascii); str.Append('{'); bool first = true; foreach (var entry in entries) { + object key = CustomStringDictionary.ObjToNull(entry.Key); + MutableString keyText = (key is RubySymbol) ? null : context.Inspect(key); if (first) { first = false; + str.ForceEncoding((keyText ?? ((RubySymbol)key).String).Encoding); } else { str.Append(", "); } - object key = CustomStringDictionary.ObjToNull(entry.Key); if (key is RubySymbol symbol) { // MRI's symbol_key_needs_quote: bare when the symbol inspects bare and the name // reads back as a label (not `a=`, `+`, `@a`, `$a`, `!`). @@ -899,7 +903,7 @@ public static IDictionary ToHash(IDictionary/*!* AppendInspected(str, bare ? inspected.GetSlice(1) : context.Inspect(symbol.String)); str.Append(": "); } else { - AppendInspected(str, context.Inspect(key)); + AppendInspected(str, keyText); str.Append(" => "); } AppendInspected(str, context.Inspect(entry.Value)); @@ -910,9 +914,6 @@ public static IDictionary ToHash(IDictionary/*!* } private static void AppendInspected(MutableString/*!*/ str, MutableString/*!*/ item) { - if (str.Encoding == RubyEncoding.Ascii && item.Encoding != RubyEncoding.Ascii) { - str.ForceEncoding(item.Encoding); - } str.Append(item); } diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index 6b7d36144..cee9f96b4 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -2231,24 +2231,22 @@ private static MutableString DefaultSeparator(RubyContext/*!*/ context) { if (handle == null) { return MutableString.CreateAscii("[...]"); } - // MRI starts the result off as US-ASCII and takes the encoding of the first - // element's inspection, so an empty array inspects as US-ASCII rather than as - // binary, and ["\u3042"] keeps the element's encoding. US-ASCII gives way to any - // other encoding, ASCII only content or not, which is how an array of strings - // inspects in the encoding the answer is going to be read in. + // MRI's rb_ary_inspect starts the result off as US-ASCII and takes the encoding + // of the first element's inspection, so an empty array inspects as US-ASCII + // rather than as binary, and ["\u3042"] keeps the element's encoding. The later + // elements are appended as any string is: ASCII only text leaves the encoding + // alone, so [nil, "a"] is still US-ASCII. MutableString str = MutableString.CreateMutable(RubyEncoding.Ascii); str.Append('['); bool first = true; foreach (object obj in self) { + var item = context.Inspect(obj); if (first) { first = false; + str.ForceEncoding(item.Encoding); } else { str.Append(", "); } - var item = context.Inspect(obj); - if (str.Encoding == RubyEncoding.Ascii && item.Encoding != RubyEncoding.Ascii) { - str.ForceEncoding(item.Encoding); - } str.Append(item); } str.Append(']'); From 8b23170323cf83787e0a900db2f0c2460f5eab77 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:51:50 +0100 Subject: [PATCH 036/147] Finalizers run with interrupts held back, as in CRuby A program that defines finalizers in a loop and gets SIGINT (test_gc's test_interrupt_in_finalizer, [Bug #10595]) never stopped: the main thread runs parked finalizers at its safe points, the Interrupt the trap delivered at the next safe point - inside the finalizer's own code - and it was reported as "warning: Exception in finalizer" and swallowed, every time. CRuby runs finalizers with the thread's pending interrupts masked (rb_gc_set_pending_interrupt), so the Interrupt is raised in the code the finalizer interrupted and ends the program. RunPendingFinalizers now runs each finalizer under RubyUtils.HoldInterrupts, which keeps trap handlers, Thread#raise and Thread#kill parked until it is done. The test passes (in 18 s on a loaded machine); spec/core/objectspace and gc show no new failures. --- Src/Libraries/Builtins/ObjectSpace.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/ObjectSpace.cs b/Src/Libraries/Builtins/ObjectSpace.cs index 018dcfef8..2aaad3f15 100644 --- a/Src/Libraries/Builtins/ObjectSpace.cs +++ b/Src/Libraries/Builtins/ObjectSpace.cs @@ -164,7 +164,17 @@ internal static void RunPendingFinalizers() { _pending.Dequeue(); RubyUtils.SafePointRequestDone(); } - invoker.RunOnMainThread(); + + // MRI runs finalizers with the thread's pending interrupts masked + // (rb_gc_set_pending_interrupt): a signal's Interrupt or a Thread#raise that + // arrives meanwhile is raised in the code the finalizer interrupted, not + // swallowed as an exception in the finalizer ([Bug #10595]). + int hold = RubyUtils.HoldInterrupts(); + try { + invoker.RunOnMainThread(); + } finally { + RubyUtils.ReleaseInterrupts(hold); + } } } finally { _draining = false; From e089ba07e65b4f72f09e299335ab73f3804c5e9b Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:51:50 +0100 Subject: [PATCH 037/147] cruby-test: exclude TestGc#test_latest_gc_info_need_major_by It loops until GC.latest_gc_info(:need_major_by) is set, which only CRuby's generational GC does, so on IronRuby it never ends and test_gc.rb was killed at the 600 s limit without a summary. With it excluded (and test_interrupt_in_finalizer fixed) the file runs to its end: 53 tests, 11 failures, 12 errors, 2 skips. --- Util/cruby-test/excludes/TestGc.rb | 1 + 1 file changed, 1 insertion(+) create mode 100644 Util/cruby-test/excludes/TestGc.rb diff --git a/Util/cruby-test/excludes/TestGc.rb b/Util/cruby-test/excludes/TestGc.rb new file mode 100644 index 000000000..14250974d --- /dev/null +++ b/Util/cruby-test/excludes/TestGc.rb @@ -0,0 +1 @@ +exclude(:test_latest_gc_info_need_major_by, "loops until GC.latest_gc_info(:need_major_by) is set, which only CRuby's generational GC (RGenGC) does; it never ends on IronRuby") From 4fe58c1cd985d27d5ffecd292f62c6c025fdd921 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:52:07 +0100 Subject: [PATCH 038/147] Marshal.dump's depth limit lets a string's encoding through MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Marshal.dump("あ", 1) raised "exceed depth limit": the string used up the one level, and its encoding, written as an instance variable, found none left. CRuby's w_encoding writes the encoding's value one level up, so the limit that lets a string through lets its encoding through too ([ruby-core:24100]), and the dump is "\x04\bI\"\b\xE3\x81\x82\x06:\x06ET". An array holding that string still exceeds a limit of 1. Checked against CRuby 4.0.10; test_marshal's test_limit passes. --- Src/Libraries/Builtins/Marshal.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 3fa1e43d1..2875845c2 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -422,6 +422,19 @@ private static bool IsAscii(byte[]/*!*/ data) { private static readonly byte[]/*!*/ _encodingIVarNameBytes = Encoding.ASCII.GetBytes(EncodingIVarName); private void WriteEncodingIVar(RubyEncoding/*!*/ encoding) { + // MRI's w_encoding gives the encoding's value a level of its own, so that the depth + // limit that lets a string through lets its encoding through too + // (Marshal.dump of a non-ASCII string with a limit of 1, [ruby-core:24100]). + if (_recursionLimit >= 0) { + _recursionLimit++; + } + WriteEncodingIVarValue(encoding); + if (_recursionLimit > 0) { + _recursionLimit--; + } + } + + private void WriteEncodingIVarValue(RubyEncoding/*!*/ encoding) { if (encoding == RubyEncoding.UTF8) { WriteSymbol(EncodingShortIVarName, _encodingShortIVarNameBytes, RubyEncoding.Binary); WriteAnObject(true); From faae22b3872c1f9797fb391502df5024a7c92781 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:52:07 +0100 Subject: [PATCH 039/147] Marshal.dump raises when a _dump changes the array or hash being dumped An element's _dump that cleared the array being dumped made the writer index past its end (System::IndexOutOfRangeException), and one that added a key to the hash being dumped gave a TypeError saying "Collection was modified". CRuby checks the array's length after each element ("array modified during dump", RuntimeError) and walks a hash as Hash#each does, so adding a key raises "can't add a new key into hash during iteration". WriteArray now walks by index and checks the length the same way; WriteHash walks the entries with TryGetNextEntry between BeginIteration and EndIteration, as Hash#key does. Messages checked against CRuby 4.0.10; test_marshal's test_modify_array_during_dump passes, and spec/core/marshal and hash show no new failures. --- Src/Libraries/Builtins/Marshal.cs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 2875845c2..f0b309a49 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -348,9 +348,15 @@ private void WriteRegex(RubyRegex/*!*/ value, RubyClass/*!*/ theClass) { private void WriteArray(RubyArray/*!*/ value, RubyClass/*!*/ theClass) { WriteSubclassData(value, theClass, typeof(RubyArray)); _writer.Write((byte)'['); - WriteInt32(value.Count); - foreach (object obj in value) { - WriteAnObject(obj); + // A _dump or marshal_dump the elements call may change the array; MRI checks its + // length after each element. + int count = value.Count; + WriteInt32(count); + for (int i = 0; i < value.Count; i++) { + WriteAnObject(value[i]); + if (value.Count != count) { + throw RubyExceptions.CreateRuntimeError("array modified during dump"); + } } } @@ -369,9 +375,18 @@ private void WriteHash(Hash/*!*/ value, RubyClass/*!*/ theClass) { char typeFlag = (value.DefaultValue != null) ? '}' : '{'; _writer.Write((byte)typeFlag); WriteInt32(value.Count); - foreach (KeyValuePair pair in value) { - WriteAnObject(pair.Key); - WriteAnObject(pair.Value); + // Walked as Hash#each walks it, which is what MRI's rb_hash_foreach amounts to: a + // _dump that adds a key meanwhile gets "can't add a new key into hash during iteration". + value.BeginIteration(); + try { + int index = 0; + object key, entryValue; + while (value.TryGetNextEntry(ref index, out key, out entryValue)) { + WriteAnObject(CustomStringDictionary.ObjToNull(key)); + WriteAnObject(entryValue); + } + } finally { + value.EndIteration(); } if (value.DefaultValue != null) { WriteAnObject(value.DefaultValue); From b41ca8d57264347e8a3c47dea27d9f57afe72979 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:52:07 +0100 Subject: [PATCH 040/147] Marshal.load refuses a Bignum record with a negative length "\x04\bl+\xfc\x00\x00\x00\x80" gave a System::OverflowException from allocating the digits of a negative number of words. CRuby raises ArgumentError "negative length". Checked against CRuby 4.0.10; with the "marshal data too short" the other case already gave, test_marshal's test_bignum_len_overflow passes. --- Src/Libraries/Builtins/Marshal.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index f0b309a49..6e88475e9 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1222,6 +1222,9 @@ private void CheckPreamble() { sign = 0; } int words = ReadInt32(); + if (words < 0) { + throw RubyExceptions.CreateArgumentError("negative length"); + } int dwords_lo = words / 2; int dwords_hi = (words + 1) / 2; uint[] bits = new uint[dwords_hi]; From 7c93c62e44cbecca4e499fffb4646dcd653e3de3 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:57:38 +0100 Subject: [PATCH 041/147] Marshal.load lets a symbol's instance variables link back to it "I" ":\vKernel" with an instance variable whose value links to symbol 0 (";\0", here the module an 'e' record extends an object with) failed with "bad symbol": the slot of a symbol with instance variables stayed empty until they had all been read. CRuby's r_symreal enters the symbol's bytes in the table before it reads them ([Bug #10991]), and the load answers :Kernel. The slot now holds the name while the instance variables are read; it is made a symbol only if a link asks for one. test_marshal's test_symlink_in_ivar passes. --- Src/Libraries/Builtins/Marshal.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 6e88475e9..b338a4b0b 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1499,8 +1499,11 @@ private static bool IsAscii(byte[]/*!*/ data, string/*!*/ text) { private Symbol/*!*/ ReadEncodedSymbol(bool symbol) { int count = ReadInt32(); byte[] data = ReadBytes(count); + // MRI's r_symreal enters the bytes in the symbol table before it reads the instance + // variables, so that a link among them to this very symbol finds it ([Bug #10991]). int slot = _symbols.Count; - _symbols[slot] = null; + // (Made a symbol only if such a link asks for one.) + _symbols[slot] = new Symbol(Context.GetIdentifierEncoding().Encoding.GetString(data, 0, data.Length), null); RubyEncoding encoding = RubyEncoding.Binary; int ivarCount = ReadInt32(); From 7911178457149c4ee28983d6fe40112b3cc6d64f Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:57:38 +0100 Subject: [PATCH 042/147] Marshal keeps the ruby2_keywords flag of a Hash A Hash.ruby2_keywords_hash dumped as a plain hash and loaded unflagged, so splatting it into a method taking keywords passed a positional argument instead. CRuby writes the flag as a pseudo instance variable "K" (true) after the encoding, in an 'I' record ("\x04\bI{\x06:\bkeyi/\x06:\x06KT"), and r_ivar sets the flag back, or raises "ruby2_keywords flag is given but a is not a Hash" on anything else. The writer and reader now do the same; the flag's value gets a level of the depth limit of its own, as in CRuby. Dumps and messages checked against CRuby 4.0.10. test_marshal_with_ruby2_keywords_hash passes up to its last assertion, which needs a "K" whose name is in UTF-7 to be a different identifier from "K" - IronRuby decodes identifiers to CLR strings and cannot tell them apart. --- Src/Libraries/Builtins/Marshal.cs | 33 +++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index b338a4b0b..4e7f086c7 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -119,6 +119,7 @@ public CallSite>/*!*/ Binmode { // (true => UTF-8, false => US-ASCII); everything else is spelled out by name under // ":encoding". ASCII-8BIT is represented by the absence of both. internal const string EncodingShortIVarName = "E"; + internal const string Ruby2KeywordsIVarName = "K"; // MRI's ARG_ENCODING_NONE option bit in a regexp record (/n) internal const int NoEncodingFlag = 0x20; internal const string EncodingIVarName = "encoding"; @@ -710,13 +711,33 @@ private void WriteStruct(RubyStruct/*!*/ obj, RubyClass/*!*/ theClass) { private void WriteIVars(object/*!*/ obj, string[]/*!*/ names, RubyEncoding encoding) { bool writeEncoding = NeedsEncodingIVar(encoding); - WriteInt32(names.Length + (writeEncoding ? 1 : 0)); + bool ruby2Keywords = IsRuby2KeywordsHash(obj); + WriteInt32(names.Length + (writeEncoding ? 1 : 0) + (ruby2Keywords ? 1 : 0)); if (writeEncoding) { WriteEncodingIVar(encoding); } + if (ruby2Keywords) { + // MRI's w_ivar: the flag of a Hash.ruby2_keywords_hash, as a pseudo instance + // variable "K" after the encoding, one level up as the encoding is. + WriteSymbol(Ruby2KeywordsIVarName, _ruby2KeywordsIVarNameBytes, RubyEncoding.Binary); + if (_recursionLimit >= 0) { + _recursionLimit++; + } + WriteAnObject(true); + if (_recursionLimit > 0) { + _recursionLimit--; + } + } WriteIVarPairs(obj, names); } + private static bool IsRuby2KeywordsHash(object obj) { + Hash hash = obj as Hash; + return hash != null && hash.IsRuby2KeywordsHash; + } + + private static readonly byte[]/*!*/ _ruby2KeywordsIVarNameBytes = Encoding.ASCII.GetBytes(Ruby2KeywordsIVarName); + /// /// A Set: MRI 4.0 writes its table as the "@hash" instance variable the Set of set.rb had, which /// the prelude's Set keeps in a hidden one. Any instance variables of the set's own go in an @@ -947,7 +968,7 @@ obj is RubyArray || obj is Hash || obj is RubyRegex || obj is RubyModule || } bool writeInstanceData = !isObjectRecord && !(obj is RubyModule) && - (instanceNames.Length > 0 || NeedsEncodingIVar(encoding)); + (instanceNames.Length > 0 || NeedsEncodingIVar(encoding) || IsRuby2KeywordsHash(obj)); if (writeInstanceData) { _writer.Write((byte)'I'); @@ -2008,6 +2029,14 @@ private void SetIVar(object obj, string/*!*/ name, object value) { RubyEncoding encoding = ParseEncodingIVar(name, value); if (encoding != null) { ForceMarshalEncoding(obj, encoding); + } else if (name == Ruby2KeywordsIVarName) { + // MRI's r_ivar: the flag Hash.ruby2_keywords_hash leaves, whatever its value + Hash hash = obj as Hash; + if (hash == null) { + throw RubyExceptions.CreateArgumentError("ruby2_keywords flag is given but {0} is not a Hash", + ((obj as MutableString) ?? RubyUtils.ObjectToMutableString(Context, obj)).ToString()); + } + hash.IsRuby2KeywordsHash = true; } else { Context.SetInstanceVariable(obj, name, value); } From 2defed4ad9f4b99de85a29e1f92e01dcb414b57b Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 15:57:43 +0100 Subject: [PATCH 043/147] Array#hash marks the elements whose #hash it calls A Struct whose #hash is [x, ""].hash, with two of them pointing at each other, overflowed the stack on a.hash: Array#hash and Hash#hash only noticed an Array or a Hash met again, and here the cycle runs through the structs. MRI's rb_hash calls an element's #hash under rb_exec_recursive_outer, so the element met again unwinds to the outermost call, and a.hash, b.hash and {a => obj}[b] all work (TestHash#test_recursive_hash_value_struct, [Bug #9151]). StructuralHash's ElementHash now enters every element on the recursion stack around its #hash call, except values that cannot lead back (nil, Integer, String, Symbol, Float, booleans) and Arrays and Hashes, which enter themselves. spec/core/array/hash_spec.rb, spec/core/hash and spec/core/struct have no new failures; new IronRuby.Tests Array_HashRecursiveElement1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 18 ++++++++++++++++++ Src/Libraries/Builtins/StructuralHash.cs | 18 +++++++++++++++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 851b50d3c..61e2e7c8d 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1344,6 +1344,7 @@ public Tests(Driver/*!*/ driver) { Array_JoinRecursive1, Array_JoinNested1, Array_RangeLongEnd1, + Array_HashRecursiveElement1, String_DumpNonUnicode1, IO_PutsRecursiveToAry1, Hash_MutateInBlock1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index 84a30c83c..6a75df2d7 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -569,6 +569,24 @@ public void Array_JoinRecursive1() { "); } + /// + /// Array#hash marks every element whose #hash it calls, as MRI's rb_hash does: a Struct whose #hash hashes + /// an array holding another Struct that points back recursed until the stack overflowed ([Bug #9151]). + /// + public void Array_HashRecursiveElement1() { + TestOutput(@" +s = Struct.new(:x) { def hash; [x, ''].hash; end } +a = s.new; b = s.new; a.x = b; b.x = a +p a.hash == b.hash +h = {}; h[[a, 'hello']] = 1; h[[b, 'world']] = 2; p h.size +o = Object.new; p [o, o].hash == [o, o].hash +", @" +true +2 +true +"); + } + /// /// A range endpoint that fits a long but not an int is a position past the end of any list (MRI's /// rb_range_beg_len reads it with NUM2LONG), not a RangeError; CRuby's TestArray#test_range_with_len_max_end. diff --git a/Src/Libraries/Builtins/StructuralHash.cs b/Src/Libraries/Builtins/StructuralHash.cs index 923e7f1b6..3ce23c25b 100644 --- a/Src/Libraries/Builtins/StructuralHash.cs +++ b/Src/Libraries/Builtins/StructuralHash.cs @@ -197,7 +197,23 @@ private static uint HashDigest(UnaryOpStorage/*!*/ hashStorage, ConversionStorag /// and one wider than a Fixnum is perfectly legal. /// private static uint ElementHash(CallSite>/*!*/ hashSite, ConversionStorage/*!*/ toInt, object item) { - object value = hashSite.Target(hashSite, item); + object value; + if (item == null || item is int || item is MutableString || item is RubySymbol || item is double || item is bool || + item is IList || item is Hash) { + // nothing of these can lead back here, except an Array or a Hash, which enter themselves + value = hashSite.Target(hashSite, item); + } else { + // Any other element may have a #hash of its own that hashes a structure leading back to it + // (a Struct whose #hash is [x, ""].hash, its x a Struct pointing back): MRI's rb_hash marks + // the element as rb_exec_recursive_outer does ([ruby-core:58567] [Bug #9151]). + var stack = _active; + Enter(stack, item); + try { + value = hashSite.Target(hashSite, item); + } finally { + stack.RemoveAt(stack.Count - 1); + } + } if (value is int) { return unchecked((uint)(int)value); } From 15989d3f39566f03df2dabde38c859bca5e44df2 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:14 +0100 Subject: [PATCH 044/147] A name in a destructured block parameter shadows the outer local The prism bridge resolved the names inside |(a, b)| the way an assignment target is resolved, so an outer local of the same name was found and the block assigned it: _ = 1; [[2]].each { |(_)| }; _ # CRuby 1, IronRuby 2 b = 1; [[2, 3]].each { |(b, c)| }; b # CRuby 1, IronRuby 2 They are parameters of the block, so they are now looked up in the block's own scope only and added there when missing. (A signature that LowerGeneralParameters binds by hand has defined them already, and gets those back.) Methods were not affected: `def m((x, y))` already had its own scope. Checked against CRuby 4.0.10; TestParse#test_shadowing_private_local_variable passes; spec/language/block_spec, lambda_spec and def_spec pass; new IronRuby.Tests Scenario_RubyBlockArgs7. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 30 ++++++++++++++++++++++++ Src/Prism/PrismAstBridge.cs | 8 ++++++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index f45e75db9..2edd8290c 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -338,6 +338,7 @@ public Tests(Driver/*!*/ driver) { Scenario_RubyBlockArgs4B, Scenario_RubyBlockArgs5, Scenario_RubyBlockArgs6, + Scenario_RubyBlockArgs7, Proc_RhsAndBlockArguments1, Block_ProcParams1, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index 28a4dfeb4..50cc1ce3b 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -1602,6 +1602,36 @@ def to_ary "); } + /// + /// A name inside a destructured block parameter |(a, b)| is a parameter of the block and + /// shadows an outer local of that name, as any other parameter does. + /// + public void Scenario_RubyBlockArgs7() { + TestOutput(@" +_ = 1; [[2]].each { |(_)| }; p _ +a = 1; [[2]].each { |(a)| }; p a +b = 1; [[2, 3]].each { |(b, c)| p c }; p b +f = 1; [[1, 2]].each { |x, (f)| p x }; p f +g = 1; [[2, 3]].each { |(_, g)| p g }; p g +p [[1, [2, 3]]].map { |a, (b, c)| [a, b, c] } +def m((x, y)) = [x, y] +x = 9 +p m([1, 2]), x +", @" +1 +1 +3 +1 +1 +1 +3 +1 +[[1, 2, 3]] +[1, 2] +9 +"); + } + public void RubyProcs1() { AssertOutput(delegate() { CompilerTest(@" diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index ec238ed5c..b891a21fb 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -1833,7 +1833,13 @@ private Arguments OptionalArguments(Pm.PmNode argumentsNode) { case Pm.LocalVariableTargetNode local: return CurrentScope.ResolveOrAddVariable(local.Name, span); case Pm.RequiredParameterNode requiredParam: - return CurrentScope.ResolveOrAddVariable(requiredParam.Name, span); + // a name inside a destructured parameter |(a, b)| is a parameter of the block like + // any other, and shadows an outer local of that name rather than assigning it; a + // lowered signature (LowerGeneralParameters) binds the ones it has defined already + LocalVariable parameter; + return CurrentScope.TryGetValue(requiredParam.Name, out parameter) + ? parameter + : CurrentScope.AddVariable(requiredParam.Name, span); case Pm.InstanceVariableTargetNode ivar: return new InstanceVariable(IvarName(ivar.Name), span); case Pm.GlobalVariableTargetNode gvar: From a0dd56c6493adb585db40db2a028b829ada0384a Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:15 +0100 Subject: [PATCH 045/147] #clone copies the singleton class of an object's singleton class A method defined on o.singleton_class.singleton_class was lost by o.clone: the copied singleton class did not get a singleton class of its own. MRI's rb_singleton_class_clone_and_attach clones that metaclass along with the singleton class: o.singleton_class.singleton_class.define_method(:s2) { :s2 } o.clone.singleton_class.s2 # :s2 CopyInstanceData now gives the copy a singleton class holding the original's methods when the original has a real (not dummy) one. TestClass#test_clone_when_method_exists_on_singleton_class_of_singleton_class passes; spec/core/kernel/clone_spec passes. --- Src/Ruby/Runtime/RubyContext.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 11889bc17..f5de2efbd 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3103,6 +3103,14 @@ public void CopyInstanceData(object source, object target, bool copySingletonMem // the singleton class's own instance variables go too, as in rb_singleton_class_clone CopyInstanceData(singleton, singletonDup, false); + // and so does a singleton class of the singleton class that holds methods + // (o.singleton_class.singleton_class.define_method), which + // rb_singleton_class_clone_and_attach clones along with it + var meta = singleton.ImmediateClass; + if (meta.IsSingletonClass && !meta.IsDummySingletonClass && ReferenceEquals(meta.SingletonClassOf, singleton)) { + singletonDup.GetOrCreateSingletonClass().InitializeMembersFrom(meta); + } + SetInstanceSingletonOfNoLock(target, ref targetData, singletonDup); } } From ba0ee4c503d76e4a44db954503e77f07f2526fee Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:26 +0100 Subject: [PATCH 046/147] A curried proc warns when a partial call is given a block MRI's curry_proc drops a block passed to a call that does not complete the arguments, and says so: b = lambda { |x, y, &blk| blk.call(x + y) }.curry b.call(2) { raise } # warning: given block not used IronRuby dropped it silently. MakeCurried now reports the warning. TestProc#test_curry_given_blocks and #test_curry_with_trace pass; spec/core/proc/curry_spec passes. --- Src/Libraries/Builtins/ProcOps.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index acf6041a3..286473238 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -319,6 +319,10 @@ private static void GetArgumentCountRange(Proc/*!*/ self, out int min, out int m RequireParameterCount(target, all.Count); return target.Call(procArg, all.ToArray()); } + // curry_proc: a block given to a call that does not complete the arguments is dropped + if (procArg != null) { + context.ReportWarning("given block not used"); + } return MakeCurried(context, target, arity, all); }); } From 2ff54c4a40fe5cca8475e37bf68854bf44bb779e Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:26 +0100 Subject: [PATCH 047/147] Method#to_proc#parameters of a core method is the method's A Method#to_proc proc of a method with no Ruby signature behind it (one written in C#) answered [[:rest]], the default for a proc without a parameter list. CRuby reports the method's own parameters: "".method(:empty?).to_proc.parameters # [] The dispatcher of such a proc now remembers the Method it wraps (BlockDispatcher.WrappedMethod), and Proc#parameters asks it when there is no signature of its own. TestProc#test_bound_parameters passes; spec/core/proc/parameters_spec and spec/core/method/to_proc_spec pass. --- Src/Libraries/Builtins/ProcOps.cs | 4 ++++ Src/Ruby/Builtins/RubyMethod.cs | 1 + Src/Ruby/Runtime/Calls/BlockDispatcher.cs | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 286473238..7b45732db 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -95,6 +95,10 @@ public static int GetArity(Proc/*!*/ self) { } var signature = self.Dispatcher.ParameterSignature; + if (signature == null && self.Dispatcher.WrappedMethod != null) { + // "".method(:empty?).to_proc says what the method says + return MethodOps.GetParameters(context, self.Dispatcher.WrappedMethod); + } if (signature == null) { // a proc with no Ruby source behind it (Symbol#to_proc, a CLR method) takes // whatever it is given diff --git a/Src/Ruby/Builtins/RubyMethod.cs b/Src/Ruby/Builtins/RubyMethod.cs index 42036b023..2342f351c 100644 --- a/Src/Ruby/Builtins/RubyMethod.cs +++ b/Src/Ruby/Builtins/RubyMethod.cs @@ -155,6 +155,7 @@ object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers _procDispatcher.SetMethod(block); _procDispatcher.ParameterSignature = _info.GetParameterSignature(); _procDispatcher.WrapsMethod = true; + _procDispatcher.WrappedMethod = this; } // A method binds its arguments strictly and `return` from it returns from the diff --git a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs index 8d012a7cd..18e326743 100644 --- a/Src/Ruby/Runtime/Calls/BlockDispatcher.cs +++ b/Src/Ruby/Runtime/Calls/BlockDispatcher.cs @@ -221,6 +221,12 @@ public bool WrapsMethod { internal set { _wrapsMethod = value; } } + /// + /// The method a Method#to_proc proc calls, whose #parameters the proc reports when the + /// method has no Ruby signature to give the dispatcher (a library method). + /// + public IronRuby.Builtins.RubyMethod WrappedMethod { get; internal set; } + /// /// The array the block's rest parameter is about to be given. See /// . From 2d93245f46328896f4a77eae28a8b7c588f5c3a5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:38 +0100 Subject: [PATCH 048/147] Proc#>> and #<< pass the keywords they are called with on A composed proc called with keywords handed them to the function it applies first as a plain Hash, so a lambda taking **kw refused it: f = ->(**kw) { kw.merge(a: 1) }; g = ->(kw) { kw.merge(a: 2) } (f >> g).call(a: 3) # CRuby {a: 2}; IronRuby ArgumentError (given 1, expected 0) MRI's compose procs pass the keywords on (RB_PASS_CALLED_KEYWORDS). A native proc (Proc.CreateNative, which composition and #curry make) now receives keywords as a ruby2_keywords-marked Hash, and composition turns it back into keywords for the first call: RestoreRuby2Keywords for a proc, SplatRuby2Keywords for the splatted #call on any other callable. A Hash passed positionally stays positional, as in CRuby. Checked against CRuby 4.0.10 with every case of TestProcKeywords #test_compose_keywords, which passes along with _method and _non_proc; spec/core/proc passes. --- Src/Libraries/Builtins/ProcOps.cs | 5 +++-- Src/Ruby/Builtins/Proc.cs | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index 7b45732db..2150e1126 100644 --- a/Src/Libraries/Builtins/ProcOps.cs +++ b/Src/Libraries/Builtins/ProcOps.cs @@ -341,7 +341,8 @@ private static void GetArgumentCountRange(Proc/*!*/ self, out int min, out int m RequireCallable(respondTo, other); return Proc.CreateNative(respondTo.Context, self.Kind, (blockParam, s, args, unsplat, procArg) => { - object intermediate = self.Call(procArg, unsplat.ToArray()); + // the keywords the composition was called with go on to the function applied first + object intermediate = self.Call(procArg, RubyOps.RestoreRuby2Keywords(unsplat.ToArray())); var site = callStorage.GetCallSite("call", 1); return site.Target(site, other, intermediate); }); @@ -358,7 +359,7 @@ private static void GetArgumentCountRange(Proc/*!*/ self, out int min, out int m // the block goes to whichever function is applied first, which for << is `other' var splatSite = splatStorage.GetCallSite("call", new RubyCallSignature(0, RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasBlock)); - object intermediate = splatSite.Target(splatSite, other, procArg, unsplat); + object intermediate = splatSite.Target(splatSite, other, procArg, (RubyArray)RubyOps.SplatRuby2Keywords(unsplat)); // through #call, so a lambda's arity is checked against the one value it gets var site = callStorage.GetCallSite("call", 1); return site.Target(site, self, intermediate); diff --git a/Src/Ruby/Builtins/Proc.cs b/Src/Ruby/Builtins/Proc.cs index d6464a207..1de8185a1 100644 --- a/Src/Ruby/Builtins/Proc.cs +++ b/Src/Ruby/Builtins/Proc.cs @@ -618,6 +618,10 @@ public object CallN(Proc procArg, object[]/*!*/ args) { BlockSignatureAttributes.HasUnsplatParameter | BlockSignatureAttributes.HasProcParameter, -1), body); result.Kind = kind; result.Dispatcher.ParameterSignature = NativeProcSignature; + // Keywords the proc is called with reach the body as a marked Hash, which the body can + // pass on as keywords (RubyOps.RestoreRuby2Keywords), as MRI's C procs pass the + // keywords they were called with on (RB_PASS_CALLED_KEYWORDS). + result.Dispatcher.Ruby2Keywords = true; return result; } From 2777db934694243af01e0a37651a2139f7b248f6 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:39 +0100 Subject: [PATCH 049/147] raise takes cause: out of other keywords and passes those on as a Hash Kernel#raise recognised `cause:` only when it was the one keyword, so `raise E, "foo" => "bar", foo: "bar", cause: c` handed the whole hash, cause included, to E.new. MRI's extract_raise_options removes `cause` and gives any keywords left to the exception as one positional Hash; an empty keyword splat is no argument at all: raise E, "k" => 1, cause: c # E.new({"k" => 1}), cause c raise E, foo: 1 # E.new({foo: 1}), not E.new(foo: 1) TryTakeCauseKeyword now does the same with the call site's keyword hash. Checked against CRuby 4.0.10 (including an #initialize that takes a required keyword, which CRuby refuses the same way); TestException#test_unknown_option passes; spec/core/kernel/raise_spec and spec/core/exception pass. --- Src/Libraries/Builtins/KernelOps.cs | 33 ++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index d2c033a49..fc06079da 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1346,22 +1346,39 @@ private static bool TryTakeCauseKeyword(ref object[]/*!*/ args, out object cause } var hash = args[args.Length - 1] as Hash; - if (hash == null || hash.Count != 1 || !hash.IsKeywordArguments) { + if (hash == null || !hash.IsKeywordArguments) { return false; } + // MRI's extract_raise_options: `cause:` is taken out of the keywords and any others are + // left to the exception's #initialize as one positional Hash (raise E, "k" => 1, cause: c). + // The call site made the hash for this call, so it is changed in place. + bool hasCause = false; foreach (var entry in hash) { var key = entry.Key as RubySymbol; - if (key == null || key.ToString() != "cause") { - return false; + if (key != null && key.ToString() == "cause") { + cause = entry.Value; + hasCause = true; + break; + } + } + if (hasCause) { + foreach (var key in new List(hash.Keys)) { + var symbol = key as RubySymbol; + if (symbol != null && symbol.ToString() == "cause") { + hash.Remove(key); + } } - cause = entry.Value; } - var rest = new object[args.Length - 1]; - Array.Copy(args, rest, rest.Length); - args = rest; - return true; + if (hash.Count == 0) { + var rest = new object[args.Length - 1]; + Array.Copy(args, rest, rest.Length); + args = rest; + } else { + hash.IsKeywordArguments = false; + } + return hasCause; } private static void SetCause(RubyContext/*!*/ context, Exception/*!*/ exception, bool hasCause, object cause) { From 6107982b380cd6009a015403d8453f632808b4b8 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:00:46 +0100 Subject: [PATCH 050/147] $@ asks the exception's own #backtrace $@ returned the backtrace IronRuby had stored, never calling #backtrace. MRI's errat_getter is rb_get_backtrace($!): an exception class that overrides #backtrace is asked, and what it answers is checked like rb_check_backtrace - nil, a String (made an Array), or an Array of Strings, anything else a TypeError: class E < StandardError; def backtrace = :x; end begin; raise E; rescue; $@; end # backtrace must be an Array of String or an Array of Thread::Backtrace::Location The stored backtrace is still read directly when #backtrace is the core method. TestException#test_wrong_backtrace passes; spec/language/predefined_spec and spec/core/exception pass. --- Src/Ruby/Runtime/RubyContext.cs | 37 +++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index f5de2efbd..325c78014 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3500,13 +3500,42 @@ internal Exception SetCurrentException(object value) { return _currentException = e; } - internal RubyArray GetCurrentExceptionBacktrace() { - // Under certain circumstances MRI invokes "backtrace" method, but it is quite unstable (crashes sometimes). - // Therefore we don't call the method and return the backtrace immediately. + /// + /// $@ is MRI's rb_get_backtrace($!): the stored backtrace unless the exception's class + /// overrides #backtrace, in which case whatever that answers, checked as rb_check_backtrace + /// does (nil, a String, or an Array of Strings). + /// + internal object GetCurrentExceptionBacktrace() { Exception e = _currentException; - return (e != null) ? RubyExceptionData.GetInstance(e).Backtrace : null; + if (e == null) { + return null; + } + + var method = GetClassOf(e).ResolveMethod("backtrace", VisibilityContext.AllVisible).Info; + if (method == null || method is RubyLibraryMethodInfo && method.DeclaringModule == ExceptionClass) { + return RubyExceptionData.GetInstance(e).Backtrace; + } + + if (_backtraceSite == null) { + System.Threading.Interlocked.CompareExchange(ref _backtraceSite, + CallSite>.Create(RubyCallAction.Make(this, "backtrace", 0)), null); + } + object backtrace = _backtraceSite.Target(_backtraceSite, e); + if (backtrace == null) { + return null; + } + if (backtrace is MutableString) { + return RubyArray.Create(backtrace); + } + var array = backtrace as RubyArray; + if (array == null || !CollectionUtils.TrueForAll(array, (item) => item is MutableString)) { + throw RubyExceptions.CreateTypeError("backtrace must be an Array of String or an Array of Thread::Backtrace::Location"); + } + return array; } + private CallSite> _backtraceSite; + internal RubyArray SetCurrentExceptionBacktrace(object value) { // first check availability of the current exception: Exception e = _currentException; From c5314e9a7736c175c6cfc723406244fdb66fa913 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:04:07 +0100 Subject: [PATCH 051/147] A write or a seek after #ungetc gives back the pushed-back bytes too MRI's io_unread, which runs before a write, a flush or a seek from the current position, moves the file back by the whole read buffer, and what #ungetc put there is in that buffer. IronRuby moved back by the read-ahead only, so after read(3) and ungetc("c") a write landed at 3 where #pos had said 2 ("abcZ" where MRI makes "abZd"), and seek(0, IO::SEEK_CUR) went forward to 3. A buffer that would reach back before the start of the file is not given back, as MRI's lseek fails there and the position stays. Checked against CRuby 4.0.10 with snippets for read/ungetc/write, read-all/ ungetc/write and seek(n, SEEK_CUR); Util/ungetc-matrix.rb shows no new difference; spec/core/io has no new failures. --- Src/Ruby/Builtins/RubyBufferedStream.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index c3240f536..4fbed9dfc 100644 --- a/Src/Ruby/Builtins/RubyBufferedStream.cs +++ b/Src/Ruby/Builtins/RubyBufferedStream.cs @@ -223,7 +223,15 @@ protected override void Dispose(bool disposing) { public override long Seek(long pos, SeekOrigin origin) { if (origin == SeekOrigin.Current) { if (_pushBackPreservesPosition) { - pos -= ReadAheadCount; + // MRI's io_unread gives the whole read buffer back to the file, what #ungetc + // put in front of it included, so the position is the one #pos reports. A + // buffer reaching back past the start of the file is not given back at all + // (its lseek fails), and the position stays where the file is. + long back = _bufferCount; + if (_stream.CanSeek && _stream.Position < back) { + back = 0; + } + pos -= back; } else { origin = SeekOrigin.Begin; pos += Position; @@ -246,7 +254,7 @@ private void FlushRead() { // Unwind cached data. Seek already reckons "current" from the position reads have // reached rather than from the one the underlying stream is at, so this asks to stay // where it is - subtracting the read-ahead here would take it off twice. - if (ReadAheadCount > 0) { + if (ReadAheadCount > 0 || (_bufferCount > 0 && _pushBackPreservesPosition && _stream.CanSeek)) { Seek(0, SeekOrigin.Current); } From 9863a93da3bfcb8a865fd69060c37d49f6339c16 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:04:07 +0100 Subject: [PATCH 052/147] IO.copy_stream writes through its destination IO, and asks for #to_io only of files Three things MRI's copy_stream_body does that IronRuby did not: - An IO destination is written as IO#write would write it: what was read ahead (or pushed back with #ungetc) is given back first, and a file opened for appending is written at its end. IronRuby wrote to the underlying stream at whatever position it had, so copying into File.open(path, "ab") overwrote the start of the file, and test_copy_stream_dst_rbuf got "abcxyz". - #to_io is asked only of an IO, a String or an object with #to_path (a Tempfile). An object with #readpartial/#write and a #to_io as well - a wrapper that transforms what goes through it - is used through those methods; IronRuby went around it to the IO. - A path is opened as File.open opens it, so a missing directory is ENOENT rather than the CLR's ENOTDIR, and the destination is O_TRUNC'd. The destination is written raw (RubyIO.WriteRawBytes), as MRI sets it to binary mode first. Checked against CRuby 4.0.10: test_io's copy_stream tests pass except the socket one that needs fork and test_copy_stream_no_busy_wait (a nonblocking pipe is polled; it was skipped in the full run before, as other threads were alive); spec/core/io has no new failures. Io_UnreadPushedBack1 covers this and the previous commit. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 41 +++++++++++++++++++++++++++ Src/Libraries/Builtins/IoOps.cs | 35 +++++++++++++++++------ Src/Ruby/Builtins/RubyIO.cs | 25 ++++++++++++++-- 4 files changed, 90 insertions(+), 12 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 00a941aed..89cd46047 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1068,6 +1068,7 @@ public Tests(Driver/*!*/ driver) { Io_LineReaders2, Io_LineReaders3, Io_UngetcConverted1, + Io_UnreadPushedBack1, Io_WideLineReaders1, Io_Timeout1, Io_Timeout2, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 468b9d377..d26856bb2 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -870,6 +870,47 @@ def t(label) "); } + /// + /// A seek from the current position, or a write, after a read gives the whole read buffer back to the file, + /// what #ungetc put in front of it included (MRI's io_unread), so it lands where #pos said the stream was. A + /// buffer reaching back past the start of the file is not given back. IO.copy_stream writes through its + /// destination IO the same way, and to the end of a file opened for appending. + /// + public void Io_UnreadPushedBack1() { + TestOutput(@" +require 'ruby4' +require 'tmpdir' +dir = Dir.mktmpdir +f = File.join(dir, 'f') +def t(f, mode = 'w+b') + File.open(f, mode) { |io| io.write ""abcd\n""; io.rewind; yield io; io.rewind; p io.read } +end +t(f) { |io| io.read(3); io.ungetc 'c'; io.write 'Z' } +t(f) { |io| io.read(3); io.ungetc 'xy'; io.seek(0, IO::SEEK_CUR); p io.pos } +t(f) { |io| io.read; io.ungetc 'c'; io.write 'Z' } +t(f) { |io| io.ungetc 'xy'; io.write 'Z' } +t(f) { |io| io.read(2); io.ungetc 'q'; io.seek(1, IO::SEEK_CUR); p io.read(1) } +r, w = IO.pipe +w << 'xyz'; w.close +t(f) { |io| io.read(3); io.ungetc 'c'; IO.copy_stream(r, io) } +g = File.join(dir, 'g') +File.write(g, 'foo') +File.write(f, 'preface') +File.open(f, 'ab') { |io| IO.copy_stream(g, io) } +p File.read(f) +", @" +""abZd\n"" +1 +""abcd\n"" +""abcdZ"" +""Zbcd\n"" +""c"" +""abcd\n"" +""abxyz"" +""prefacefoo"" +"); + } + /// /// The line readers of a stream that converts from a wide encoding (UTF-16, UTF-32) look for the separator in /// the text they converted, as MRI's do: the byte of a "\n" is half of that character there, or part of diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index c1484bbd8..840f6ca45 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -3376,21 +3376,25 @@ public static object CopyStream( CallSite> readSite = null; bool readPartial = false; long restorePosition = -1; + RubyIO dstIO = null; try { // Each side on its own: an IO (or what #to_io gives, as for a Tempfile) is read or // written as that IO - a File is not reopened by its path, which used to truncate and // overwrite a file opened only for reading - and anything else is a path or an object // with #readpartial / #read / #write. + // MRI's copy_stream_body asks for #to_io only of what could name a file - an IO, a + // String or an object with #to_path (a Tempfile) - so a wrapper with #readpartial + // and #write is used through those even when it can also give its IO away. var toPathSite = toPath.GetSite(TryConvertToPathAction.Make(toPath.Context)); - RubyIO srcIO = TryToIO(respondTo, toIoStorage, context, src, false); + RubyIO srcIO = MayNameFile(respondTo, src) ? TryToIO(respondTo, toIoStorage, context, src, false) : null; if (srcIO != null) { srcIO.RequireByteReadable(); srcStream = srcIO.GetReadableStream(); } else { var srcPath = toPathSite.Target(toPathSite, src); if (srcPath != null) { - srcStream = self.Context.Platform.OpenInputFileStream(context.DecodePath(srcPath), FileMode.Open, FileAccess.Read, FileShare.Read); + srcStream = RubyFile.OpenFileStream(context, context.DecodePath(srcPath), IOMode.ReadOnly); ownsSrc = true; } else if (Protocols.RespondTo(respondTo, src, "readpartial")) { // MRI prefers #readpartial, which signals the end with EOFError @@ -3401,14 +3405,17 @@ public static object CopyStream( } } - RubyIO dstIO = TryToIO(respondTo, toIoStorage, context, dst, false); + dstIO = MayNameFile(respondTo, dst) ? TryToIO(respondTo, toIoStorage, context, dst, false) : null; if (dstIO != null) { - dstStream = dstIO.GetWritableStream(); + // written through the IO, which gives back what it had read ahead and goes to + // the end of a file opened for appending + dstIO.GetWritableStream(); } else { var dstPath = toPathSite.Target(toPathSite, dst); if (dstPath != null) { - // Create, not Truncate: MRI's copy_stream makes the destination when it is not there. - dstStream = self.Context.Platform.OpenInputFileStream(context.DecodePath(dstPath), FileMode.Create, FileAccess.ReadWrite, FileShare.Read); + // O_WRONLY|O_CREAT|O_TRUNC, as MRI opens a destination it is given by name. + dstStream = RubyFile.OpenFileStream(context, context.DecodePath(dstPath), + IOMode.WriteOnly | IOMode.CreateIfNotExists | IOMode.Truncate); ownsDst = true; } else { writeSite = writeStorage.GetCallSite("write", 1); @@ -3469,7 +3476,13 @@ public static object CopyStream( break; } - if (dstStream != null) { + if (dstIO != null) { + if (userBuffer != null) { + dstIO.WriteRawBytes(userBuffer, 0, bytesRead); + } else { + dstIO.WriteRawBytes(buffer, 0, bytesRead); + } + } else if (dstStream != null) { if (userBuffer != null) { dstStream.Write(userBuffer, 0, bytesRead); } else { @@ -3497,12 +3510,16 @@ public static object CopyStream( } if (ownsDst) { dstStream.Dispose(); - } else if (dstStream != null) { - dstStream.Flush(); + } else if (dstIO != null && !dstIO.Closed) { + dstIO.Flush(); } } } + private static bool MayNameFile(RespondToStorage/*!*/ respondTo, object obj) { + return obj is RubyIO || obj is MutableString || Protocols.RespondTo(respondTo, obj, "to_path"); + } + #endregion public static IOWrapper/*!*/ CreateIOWrapper(RespondToStorage/*!*/ respondToStorage, object io, FileAccess access) { diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index e4dd3890c..b24f1c193 100644 --- a/Src/Ruby/Builtins/RubyIO.cs +++ b/Src/Ruby/Builtins/RubyIO.cs @@ -706,8 +706,27 @@ public int WriteBytes(MutableString/*!*/ buffer, int index, int count) { return WriteBytes(null, buffer, index, count); } - // TODO: transcoding + /// + /// Bytes as they are, whatever the newline mode: IO.copy_stream sets its destination to + /// binary mode first (io_ascii8bit_binmode). The read-ahead is given back and an + /// appending IO goes to the end, as for any write. + /// + public int WriteRawBytes(byte[]/*!*/ buffer, int index, int count) { + ContractUtils.RequiresNotNull(buffer, "buffer"); + return WriteBytes(buffer, null, index, count, true); + } + + public int WriteRawBytes(MutableString/*!*/ buffer, int index, int count) { + ContractUtils.RequiresNotNull(buffer, "buffer"); + return WriteBytes(null, buffer, index, count, true); + } + private int WriteBytes(byte[] bytes, MutableString str, int index, int count) { + return WriteBytes(bytes, str, index, count, PreserveEndOfLines); + } + + // TODO: transcoding + private int WriteBytes(byte[] bytes, MutableString str, int index, int count, bool preserveEndOfLines) { var stream = GetWritableStream(); UnreadPendingChars(); @@ -717,9 +736,9 @@ private int WriteBytes(byte[] bytes, MutableString str, int index, int count) { try { if (bytes != null) { - return stream.WriteBytes(bytes, index, count, PreserveEndOfLines); + return stream.WriteBytes(bytes, index, count, preserveEndOfLines); } else { - return stream.WriteBytes(str, index, count, PreserveEndOfLines); + return stream.WriteBytes(str, index, count, preserveEndOfLines); } } catch (ObjectDisposedException) { throw RubyExceptions.CreateEBADF(); From 11db3cc6f72a26d9936bdcbc6dc1ea3bba499033 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:04:14 +0100 Subject: [PATCH 053/147] IO#readpartial converts its buffer with to_str readpartial takes no keywords, so readpartial(1, exception: false) hands it a Hash as the buffer; MRI's StringValue makes that a TypeError ("no implicit conversion of Hash into String"), and an object with #to_str is converted. IronRuby called #encoding on whatever it got, a NoMethodError. Checked against CRuby 4.0.10: test_io's test_readpartial_bad_args passes. --- Src/StdLib/ironruby/ruby4.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 691e26b00..ee57c6178 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -11439,6 +11439,15 @@ def __fill_buffer__(outbuf, data) def readpartial(maxlen, outbuf = nil) maxlen = ::Kernel.Integer(maxlen) + # MRI's StringValue: readpartial takes no keywords, so readpartial(1, exception: false) + # hands it a Hash for the buffer, which is a TypeError. + unless outbuf.nil? || ::String === outbuf + converted = ::String.try_convert(outbuf) + unless converted + ::Kernel.raise(::TypeError, "no implicit conversion of #{__ir_conversion_result_name__(outbuf)} into String") + end + outbuf = converted + end ::Kernel.raise(::ArgumentError, "negative length #{maxlen} given") if maxlen < 0 if maxlen == 0 # Even a zero-length readpartial looks at the stream, so a closed one is an error. From fec956eab8fe64bbf6d9e0870e715ef7fa93a8ab Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:07:23 +0100 Subject: [PATCH 054/147] Queue and ConditionVariable have no #initialize_copy and no plain Marshal form Thread::Queue.new.dup answered a second, empty queue, and so did ConditionVariable#dup. CRuby undefines #initialize_copy on both (their state is C data that can be neither shared nor copied), so #dup and #clone raise "undefined method 'initialize_copy' for an instance of Thread::Queue" ([Bug #9440]). The classes now carry [UndefineMethod("initialize_copy")]. A class made with Queue.dup (or ConditionVariable.dup) that removes #marshal_dump was dumped as an empty 'o' record, because the dup counts as a Ruby class whose superclass is Object. CRuby refuses it with "no _dump_data is defined for class X" ([Bug #9674]); Marshal now does so for any Queue or ConditionVariable that reaches the plain-object path. TestThreadQueue#test_dup/test_dump and TestThreadConditionVariable's pass; spec/core/queue, sizedqueue, conditionvariable and marshal have no new failures. --- Src/Libraries/Builtins/Marshal.cs | 6 ++++++ Src/Libraries/Thread/RubyConditionVariable.cs | 4 +++- Src/Libraries/Thread/RubyQueue.cs | 3 +++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index e2c57d51e..f93a223db 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -956,6 +956,12 @@ obj is RubyArray || obj is Hash || obj is RubyRegex || obj is RubyModule || } else if (obj is Exception) { WriteException((Exception)obj, instanceNames); } else { + // A Queue or a ConditionVariable gets here only when its class has no #marshal_dump + // (Queue's own says "can't dump"), such as a Queue.dup that removed it: a Ruby class + // as far as the class chain says, backed by C data all the same ([Bug #9674]). + if (obj is IronRuby.StandardLibrary.Threading.RubyQueue || obj is IronRuby.StandardLibrary.Threading.RubyConditionVariable) { + throw RubyExceptions.CreateTypeError("no _dump_data is defined for class {0}", _context.GetClassDisplayName(obj)); + } RequireDumpableAsObject(theClass); WriteObject(obj); if (isSet) { diff --git a/Src/Libraries/Thread/RubyConditionVariable.cs b/Src/Libraries/Thread/RubyConditionVariable.cs index 0b24b3d42..297a9cfc9 100644 --- a/Src/Libraries/Thread/RubyConditionVariable.cs +++ b/Src/Libraries/Thread/RubyConditionVariable.cs @@ -27,9 +27,11 @@ namespace IronRuby.StandardLibrary.Threading { /// Thread::ConditionVariable. Built on the same per-thread sleep signal as Thread.stop, exactly like /// MRI: that is what makes Thread#run and Thread#wakeup end a #wait (a Monitor condition could not /// be woken that way), and it gives #signal the FIFO order the specs require. The old implementation - /// used an AutoResetEvent plus a 1ms sleep per waiter in #broadcast and lost wakeups. + /// used an AutoResetEvent plus a 1ms sleep per waiter in #broadcast and lost wakeups. Like Queue, + /// it has no #initialize_copy ([Bug #9440]). /// [RubyClass("ConditionVariable", DefineIn = typeof(ThreadOps))] + [UndefineMethod("initialize_copy")] public class RubyConditionVariable { /// MRI's #<Thread::ConditionVariable:0x...>, rather than the CLR type name. diff --git a/Src/Libraries/Thread/RubyQueue.cs b/Src/Libraries/Thread/RubyQueue.cs index f01ee954a..17649a40b 100644 --- a/Src/Libraries/Thread/RubyQueue.cs +++ b/Src/Libraries/Thread/RubyQueue.cs @@ -26,8 +26,11 @@ namespace IronRuby.StandardLibrary.Threading { /// /// Thread::Queue - an unbounded blocking queue. Waits are Monitor waits, so Thread#kill and /// Thread#raise (which are delivered with Thread.Interrupt on .NET Core) unblock them. + /// MRI undefines #initialize_copy, so #dup and #clone are a NoMethodError ([Bug #9440]) rather + /// than a second queue. /// [RubyClass("Queue", DefineIn = typeof(ThreadOps))] + [UndefineMethod("initialize_copy")] public class RubyQueue { /// MRI's #<Thread::Queue:0x...>, rather than the CLR type name. From 0f1233d2fb6a8c51722f78da176f56cb0f52461c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:07:51 +0100 Subject: [PATCH 055/147] Encoding::Converter#primitive_convert refuses the source string as its buffer primitive_convert(s, s) read and wrote the same MutableString at once and produced garbage. CRuby's econv_primitive_convert raises ArgumentError "cannot convert into the source string" for this. The source and destination are also converted with to_str now, as in CRuby. Checked against CRuby 4.0 and with test_econv; spec/core/encoding/converter shows no new failures against master. --- Src/Libraries/Builtins/EncodingConverter.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index cbd25fd38..45d9eeaf3 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -1769,12 +1769,18 @@ public static object PrimitiveConvert( ConversionStorage>/*!*/ toHash, RubyContext/*!*/ context, RubyConverter/*!*/ self, - MutableString source, - [NotNull]MutableString/*!*/ destination, + [DefaultProtocol]MutableString source, + [DefaultProtocol, NotNull]MutableString/*!*/ destination, [Optional]object byteOffset, [Optional]object byteLimit, [Optional]object options) { + // MRI's econv_primitive_convert reads the source and writes the destination in + // place, so the two cannot be one string + if (ReferenceEquals(source, destination)) { + throw RubyExceptions.CreateArgumentError("cannot convert into the source string"); + } + int? offset = ToOptionalInt(toInt, byteOffset); int? limit = ToOptionalInt(toInt, byteLimit); object replacement; From e928a44767fbc876520d60a980d80573cae32a07 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:07:51 +0100 Subject: [PATCH 056/147] Opening an ASCII-incompatible encoding for reading needs binmode File.open(path, "r:UTF-16LE") without "b" opened the file in text mode, where newline handling cannot see the line ends of a wide encoding. CRuby's validate_enc_binmode raises ArgumentError "ASCII incompatible encoding needs binmode" for a readable stream whose external encoding is not ASCII compatible, unless it is binmode or converts to an internal encoding. File#initialize and IO#initialize now check the same. Checked against CRuby 4.0 and with test_io_m17n; spec/core/io, file/open, file/new and library/stringio and csv show no new failures against master. --- Src/Libraries/Builtins/FileOps.cs | 1 + Src/Libraries/Builtins/IoOps.cs | 1 + Src/Ruby/Builtins/IOMode.cs | 13 +++++++++++++ 3 files changed, 15 insertions(+) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 133bfb4fc..f2a1c3234 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -117,6 +117,7 @@ internal static bool Exists(RubyContext/*!*/ context, MutableString/*!*/ path) { permissions = p.Value; } } + info.RequireBinmodeForAsciiIncompatible(); self.ConversionOptions = RubyIOOps.AddTextModeDecorator(context, info, options); // descriptor or path: diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index ffffacad3..29a36a7aa 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -171,6 +171,7 @@ public static class WaitWritable { if (!desc.HasValue) { throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(descriptor), "Integer"); } + info.RequireBinmodeForAsciiIncompatible(); Reinitialize(self, desc.Value, info); self.ConversionOptions = AddTextModeDecorator(context, info, options); diff --git a/Src/Ruby/Builtins/IOMode.cs b/Src/Ruby/Builtins/IOMode.cs index a2dc6cf2b..355b282cd 100644 --- a/Src/Ruby/Builtins/IOMode.cs +++ b/Src/Ruby/Builtins/IOMode.cs @@ -85,6 +85,19 @@ public IOInfo(IOMode? mode, RubyEncoding externalEncoding, RubyEncoding internal _textOrBinarySpecified = textOrBinarySpecified; } + /// + /// MRI's validate_enc_binmode: a stream that reads an encoding that is not ASCII + /// compatible (UTF-16, UTF-32, ISO-2022-JP) without converting it has to be in binary + /// mode, since text mode's newline handling cannot see its line ends. + /// + public void RequireBinmodeForAsciiIncompatible() { + if (_externalEncoding == null || _internalEncoding != null || !Mode.CanRead() || + (Mode & IOMode.PreserveEndOfLines) != 0 || _externalEncoding.IsAsciiIdentity) { + return; + } + throw RubyExceptions.CreateArgumentError("ASCII incompatible encoding needs binmode"); + } + public static IOInfo Parse(RubyContext/*!*/ context, MutableString/*!*/ modeAndEncoding) { if (!modeAndEncoding.IsAscii()) { throw IOModeEnum.IllegalMode(modeAndEncoding.ToAsciiString()); From 929a63d02b63e58b106d9998b61bb2cf7339e734 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:07:51 +0100 Subject: [PATCH 057/147] String#slice(//) checks the string and sets $~ The empty regexp returned an empty string without matching, so a string with an invalid byte sequence did not raise and $~ was left alone. CRuby matches it as any other regexp: "\xff".force_encoding("UTF-8")[//] raises ArgumentError and "abc"[//] sets $~. The shortcut is gone. Checked against CRuby 4.0 and with test_string; spec/core/string shows no new failures against master. --- Src/Libraries/Builtins/MutableStringOps.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 45f9d899b..380ee4ab7 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1224,10 +1224,6 @@ public static MutableString GetSubstring(MutableString/*!*/ self, [NotNull]Mutab [RubyMethod("[]")] [RubyMethod("slice")] public static MutableString GetSubstring(RubyScope/*!*/ scope, MutableString/*!*/ self, [NotNull]RubyRegex/*!*/ regex) { - if (regex.IsEmpty) { - return self.CreateDerived(); - } - MatchData match = RegexpOps.Match(scope, regex, self); if (match == null) { return null; From 76b1973e4c7a31d4bd3c0b86a266451fbc872760 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:07:51 +0100 Subject: [PATCH 058/147] String#[]= takes a range end that fits in a long s[0..2**62] = "x" raised RangeError (bignum too big to convert into 'long') because the end went through the Fixnum conversion. CRuby clamps an end that fits in a long and replaces to the end of the string. The end now goes through IListOps.CastToRangeComponent like Array's and String#[]'s, and the "out of range" message quotes the end as written. Checked against CRuby 4.0 and with test_string; spec/core/string shows no new failures against master. --- Src/Libraries/Builtins/MutableStringOps.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 380ee4ab7..462ea99d9 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1465,7 +1465,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index int length = GetCharacterLength(self); int begin = (range.Begin == null) ? 0 : Protocols.CastToFixnum(fixnumCast, range.Begin); - int end = (range.End == null) ? length : Protocols.CastToFixnum(fixnumCast, range.End); + int end = (range.End == null) ? length : IListOps.CastToRangeComponent(fixnumCast, range.End); int normalizedBegin = begin < 0 ? begin + length : begin; @@ -1473,7 +1473,7 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index // MRI quotes the range as it was written, not as it was normalized - and an // endless one without its missing end. throw RubyExceptions.CreateRangeError("{0}{1}{2} out of range", begin, - range.ExcludeEnd ? "..." : "..", (range.End == null) ? (object)"" : end); + range.ExcludeEnd ? "..." : "..", range.End ?? ""); } end = end < 0 ? end + length : end; From f33b94e30155603a86f7309f2e6801dd04f614e3 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:11:05 +0100 Subject: [PATCH 059/147] spawn and exec raise EBADF for `fd => :close` when fd is not open MRI closes the named descriptors in the child, after its dup2s, and a close(2) that fails fails the call: exec("cmd", 1000 => :close) with no descriptor 1000 raises Errno::EBADF "Bad file descriptor - close", and so does spawn (whose child exits 127). IronRuby ran the command: glibc's posix_spawn ignores a failing close action, and __exec__ never looked at what close(2) said. The prelude now checks each close action before anything runs - a descriptor some dup2 action makes counts as open, as it is by the time MRI's close runs. Checked against CRuby 4.0.10 with exec, spawn, a close next to a dup2 to the same descriptor and an Array key; spec/core/process and spec/core/kernel spawn_spec/exec_spec pass. --- Src/StdLib/ironruby/ruby4.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index ee57c6178..153f658a4 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -8939,6 +8939,17 @@ def self.__spawn_actions__(options) actions.concat(copies) actions.concat(deferred) + + # MRI closes in the child after its dup2s, and a close(2) that fails there fails the + # spawn or the exec: `1000 => :close` with no descriptor 1000 is EBADF. posix_spawn's + # close action ignores that failure, so it is found here, where a descriptor some dup2 + # makes is open by the time its close runs. + targets = actions.select { |action| action[0] == SPAWN_DUP2 }.map { |action| action[1] } + actions.each do |action| + next unless action[0] == SPAWN_CLOSE + fd = action[1] + raise Errno::EBADF, "close" if !targets.include?(fd) && __native_fd__(fd) < 0 + end actions end From df72c99f50841189ef65aadea6a69b42ef5297f4 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:11:05 +0100 Subject: [PATCH 060/147] Dir_ChdirRelative1 silences the conflicting chdir warning Since the chdir lock, a Dir.chdir without a block inside a Dir.chdir block warns "conflicting chdir during another chdir block", as CRuby does, and the test runs with warnings counted. What it checks is where the relative chdirs land, so it turns warnings off. --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 021168890..30520254e 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -1462,6 +1462,8 @@ public void Dir_ChdirRelative1() { require 'fileutils' root = File.join(Dir.tmpdir, ""ir-chdir-#{Process.pid}"") FileUtils.mkdir_p(File.join(root, 'a', 'a', 'a')) +# a chdir without a block inside a chdir block warns, as in CRuby +$VERBOSE = nil Dir.chdir(File.join(root, 'a', 'a')) do Dir.chdir('..') p File.basename(File.dirname(Dir.pwd)) == File.basename(root) From fdd718f4728183ec6c35fe4d51d86c4aa001134b Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:15 +0100 Subject: [PATCH 061/147] Time's exact-number conversion sees delegators, and names the class by to_s Time.utc(2000) + SimpleDelegator.new(1) raised "can't convert SimpleDelegator into an exact number": num_exact asked for #to_r and #to_int by looking the methods up, and a delegator only answers them through method_missing. CRuby's num_exact uses rb_check_funcall and rb_respond_to, which ask #respond_to? and so see respond_to_missing?. Its error names the class through %PRIsVALUE, that is #to_s, so a class whose to_s says "Inexact" is named that, not #. RubyTimeOps.RespondTo falls back to #respond_to?(name, true) when the method is not defined, and the error message takes the class's #to_s. test_time's test_plus_type and test_num_exact_error pass; spec/core/time shows no new failures. --- Src/Libraries/Builtins/RubyTimeOps.cs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 31c0329bc..f7b2396af 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -64,7 +64,26 @@ private static object Invoke(RubyContext/*!*/ context, ref CallSite> _respondToSite; + private static CallSite> _toSSite; + + /// + /// num_exact_fail's "can't convert X into an exact number": X is the class of the value as + /// %PRIsVALUE prints it, through #to_s, so that a class with a name of its own shows it. + /// + private static Exception/*!*/ MakeExactNumberError(RubyContext/*!*/ context, object value) { + object name = Invoke(context, ref _toSSite, "to_s", context.GetClassOf(value)); + return RubyExceptions.CreateTypeError("can't convert {0} into an exact number", + name is MutableString ? name.ToString() : context.GetClassName(value)); } // MRI's time.c makes these Rationals itself (quov, rb_rational_new) rather than calling @@ -165,7 +184,7 @@ internal static ExactNum ToExact(RubyContext/*!*/ context, object value) { } } - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(value)); + throw MakeExactNumberError(context, value); } /// From dd0067335ee0dad50d5f3ca3a5d4f793c3758a24 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:26 +0100 Subject: [PATCH 062/147] Time.utc ignores the seventh of eight arguments, and range-checks seconds as an int Time.gm(2000, 1, 1, 0, 0, "0", :foo, :foo) - the eight values a parsedate result has - raised "can't convert Symbol into an exact number": the seventh was taken for microseconds. CRuby's time_arg reads a usec only in the 7-argument form; with 8 the seventh is a zone and the eighth a wday, both ignored. Seconds outside int were an ArgumentError "argument out of range" where CRuby's obj2ubits makes them an int first: RangeError "integer 1099511627776 too big to convert to 'int'", and for a Bignum "bignum too big to convert into 'long'", the message every int component now gives. Messages checked against CRuby 4.0.10 for minutes and seconds of 2**40, -(2**40), 2**70 and 2**40+0.5. The 8-argument assertions of test_time's test_utc_or_local pass (it still fails later, on a year beyond int); spec/core/time shows no new failures. --- Src/Libraries/Builtins/RubyTimeOps.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index f7b2396af..20833cd98 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -223,6 +223,10 @@ private static int ToInt32(object value) { } private static int ToInt32(BigInteger value) { + // rb_num2int goes through rb_num2long, which has its own message for a Bignum + if (value > Int64.MaxValue || value < Int64.MinValue) { + throw RubyExceptions.CreateRangeError("bignum too big to convert into 'long'"); + } if (value > Int32.MaxValue || value < Int32.MinValue) { throw RubyExceptions.CreateRangeError(String.Format(CultureInfo.InvariantCulture, "integer {0} too {1} to convert to 'int'", value, value.Sign < 0 ? "small" : "big")); @@ -1010,7 +1014,9 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { int minute = GetComponent(context, components, 4, 0); ExactNum second = (components.Length > 5 && components[5] != null) ? ToExactComponent(context, components[5]) : ExactNum.Zero; - if (components.Length > 6 && components[6] != null) { + // MRI's time_arg: only the 7-argument form has a usec; with 8 the seventh is the zone of + // a parsedate result (and the eighth its wday), and both are ignored. + if (components.Length == 7 && components[6] != null) { ExactNum usec = ToExactComponent(context, components[6]); if (usec.Sign < 0 || usec.CompareTo(ExactNum.FromInteger(RubyTime.MicrosecondsPerSecond)) >= 0) { throw RubyExceptions.CreateArgumentError("subsecx out of range"); @@ -1018,6 +1024,9 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { // An explicit microsecond argument supersedes any fraction of the seconds argument. second = ExactNum.FromInteger(second.Floor()) + usec / ExactNum.FromInteger(RubyTime.MicrosecondsPerSecond); } + // obj2ubits: the whole seconds are an int first, a RangeError beyond it, and only then + // checked against 0...60 (an ArgumentError) + ToInt32(second.Floor()); return AssembleTime(context, year, month, day, hour, minute, second, kind, ExactNum.Zero, null, false, preferDst); } From 502ced3568353ccaaeeef9ed60faaed48985d9dc Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:34 +0100 Subject: [PATCH 063/147] A UTC offset string uses colons throughout or not at all Time#getlocal("-02:3040") and ("+0910:35") were taken as -02:30:40 and +09:10:35. CRuby's utc_offset_arg accepts +HH, +HHMM, +HHMMSS, +HH:MM and +HH:MM:SS and raises ArgumentError for a mix ('"+HH:MM", "-HH:MM", "UTC" or "A".."I","K".."Z" expected for utc_offset: -02:3040'). The pattern now has the two forms as alternatives. Checked against CRuby 4.0.10; test_time's test_getlocal_utc_offset passes. --- Src/Libraries/Builtins/RubyTimeOps.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 20833cd98..6dde60e8f 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -239,7 +239,9 @@ private static int ToInt32(BigInteger value) { #region UTC offset parsing private static readonly Regex/*!*/ _offsetPattern = new Regex( - @"^(?[+-])(?\d\d)(:?(?\d\d)(:?(?\d\d))?)?$", RegexOptions.CultureInvariant); + // MRI's utc_offset_arg: +HH, +HHMM, +HHMMSS, +HH:MM or +HH:MM:SS - colons throughout or + // not at all ("-02:3040" is an error) + @"^(?[+-])(?\d\d)(?:(?\d\d)(?\d\d)?|:(?\d\d)(?::(?\d\d))?)?$", RegexOptions.CultureInvariant); /// /// Parses the utc_offset / :in argument. Returns false if the value isn't a String From a7566edaaf0dd23d43118fc6f3ffc8ffe5346cac Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:34 +0100 Subject: [PATCH 064/147] Time#initialize refuses a Time that is already initialized Time.now.send(:initialize, 2013, 3, 14) changed the time in place. CRuby raises TypeError "already initialized Time" (with the receiver's class, "already initialized T2" for a subclass), [Bug #8099]; only a Time.allocate'd one, or a subclass instance whose initialize calls super, gets set. RubyTime keeps whether its instant has been set: every constructor but the allocator's sets it, and the two Time#initialize overloads check and then set it. dup, clone, Marshal round trips and subclasses with and without initialize behave as on CRuby 4.0.10 (compared output). test_time's test_reinitialize passes; spec/core/time shows no new failures. --- Src/Libraries/Builtins/RubyTime.cs | 16 +++++++++++++++- Src/Libraries/Builtins/RubyTimeOps.cs | 10 ++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/RubyTime.cs b/Src/Libraries/Builtins/RubyTime.cs index 8fadb4308..8c2671fe4 100644 --- a/Src/Libraries/Builtins/RubyTime.cs +++ b/Src/Libraries/Builtins/RubyTime.cs @@ -197,9 +197,23 @@ public RubyTime(DateTime dateTime) { InitializeFromDateTime(dateTime); } - // Used by derived Ruby classes. + // Used by derived Ruby classes, and by Time.allocate: the one Time that #initialize may + // still set. public RubyTime() : this(0, ExactNum.Zero, RubyTimeZoneKind.Local, ExactNum.Zero) { + _initialized = false; + } + + // MRI's time_init_* (time_modify) refuses a Time whose instant has been set: "already + // initialized Time" ([Bug #8099]). Every constructor but the allocator's sets one. + private bool _initialized = true; + + internal bool IsInitialized { + get { return _initialized; } + } + + internal void MarkInitialized() { + _initialized = true; } public RubyTime(long ticks, DateTimeKind kind) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 6dde60e8f..fc54222ed 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -532,14 +532,24 @@ private static object GetInOption(IDictionary options, bool allo // Reinitialization. Not called when a factory/non-default ctor is called. [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static RubyTime/*!*/ Reinitialize(RubyContext/*!*/ context, RubyTime/*!*/ self) { + RequireUninitialized(context, self); self.CopyFrom(NowInternal(context, context.GetClassOf(self), null)); + self.MarkInitialized(); return self; } + private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ self) { + if (self.IsInitialized) { + throw RubyExceptions.CreateTypeError("already initialized {0}", context.GetClassOf(self).Name); + } + } + [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] [ReceivesKeywords] public static RubyTime/*!*/ Reinitialize(RubyContext/*!*/ context, RubyTime/*!*/ self, [NotNull]params object[]/*!*/ args) { + RequireUninitialized(context, self); self.CopyFrom(CreateFromComponents(context, context.GetClassOf(self), args)); + self.MarkInitialized(); return self; } From 3a50aeafe030e86d7069e37f72b71f6ae60f0e23 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:45 +0100 Subject: [PATCH 065/147] Time.new takes a date string with a zone and no time of day Time.new("2021-12-25+09:00") and ("2021-12-25 +09:00") raised "no time information". CRuby's time_init_parse reads a time of day only when a space or T is followed by a digit, takes whatever follows as the zone, and says "no time information" only when there is neither a time nor a zone: both strings are midnight at +09:00, and "2021-12-25T" is midnight in military zone T. The parser now does the same. Checked against CRuby 4.0.10 for those and for "2021-12", "2021-12-25 00 +09:00" and "2021 +09:00". test_time's test_new_from_string gets past them; spec/core/time shows no new failures. --- Src/Libraries/Builtins/RubyTimeOps.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index fc54222ed..720ea6876 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -688,13 +688,17 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s } year = ToInt32(BigInteger.Parse(text.Substring(pos, digits), CultureInfo.InvariantCulture)); pos += digits; + bool hasTime = false; if (pos < end && text[pos] == '-') { month = TwoDigits(text, ref pos, "mon"); if (pos < end && text[pos] == '-') { day = TwoDigits(text, ref pos, "mday"); } - if (pos < end && (text[pos] == ' ' || text[pos] == 'T')) { + // a space or T introduces the time of day only when a digit follows; otherwise + // what follows is the zone (MRI: "2021-12-25 +09:00", or "2021-12-25+09:00") + if (pos + 1 < end && (text[pos] == ' ' || text[pos] == 'T') && IsAsciiDigit(text[pos + 1])) { + hasTime = true; int timePart = pos + 1; hour = TwoDigits(text, ref pos, "hour"); if (pos < end && text[pos] == '.') { @@ -727,10 +731,10 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s } else { throw RubyExceptions.CreateArgumentError("missing min part: {0}", text.Substring(timePart, Math.Min(end, pos + 1) - timePart)); } - } else { - // a date without a time of day is not a Time - throw RubyExceptions.CreateArgumentError("no time information"); } + } else { + // only a year + hasTime = true; } if (pos < end && IsAsciiSpace(text[pos])) { @@ -755,6 +759,11 @@ private static void ParseTimeText(RubyContext/*!*/ context, MutableString/*!*/ s throw RubyExceptions.CreateArgumentError("can't parse at: {0}", text.Substring(pos)); } } + + // a date without a time of day or a zone is not a Time + if (!hasTime && zoneText == null) { + throw RubyExceptions.CreateArgumentError("no time information"); + } } /// From c215f58e73b373cddcec3567f98972af0b8b5b64 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:45 +0100 Subject: [PATCH 066/147] Time._load reads Ruby 1.9.1's submicro, and carries month 13..16 into the next year A Time dumped by Ruby 1.9.1 keeps the nanoseconds beyond the microsecond in a "submicro" instance variable, two bytes of BCD digits; they were dropped, so the time loaded as ...00.123456 instead of .123456789 ([ruby-dev:40133]). And a dump whose four month bits hold 12..15 was "marshaled time format differ"; CRuby's time_mload carries such a month into the next year (Ruby 3.1 wrote Time.utc(2022, 4, 1) that way). _load now reads submicro when there is no nano_num, as time_mload does, and wraps the month. test_time's test_marshal_nsec_191 and test_marshal_broken_month pass; spec/core/time and marshal show no new failures. --- Src/Libraries/Builtins/RubyTimeOps.cs | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 720ea6876..44dd93738 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -1226,6 +1226,35 @@ private static uint GetUint(byte[] data, int start) { return (((((((uint)data[start + 3] << 8) + (uint)data[start + 2]) << 8) + (uint)data[start + 1]) << 8) + (uint)data[start + 0]); } + /// + /// Ruby 1.9.1 wrote the nanoseconds beyond the microsecond as "submicro": two bytes of BCD + /// digits, hundreds and tens in the first, units in the high half of the second. MRI's + /// time_mload still reads it when there is no nano_num, and stops at the first nibble + /// that is not a digit. + /// + private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!*/ time) { + object value; + MutableString submicro; + if (!context.TryGetInstanceVariable(time, "submicro", out value) || (submicro = value as MutableString) == null) { + return ExactNum.Zero; + } + byte[] bytes = submicro.ConvertToBytes(); + int[] scale = { 100, 10, 1 }; + int nsec = 0; + for (int i = 0; i < 3; i++) { + int b = i / 2; + if (b >= bytes.Length) { + break; + } + int digit = (i % 2 == 0) ? bytes[b] >> 4 : bytes[b] & 0xf; + if (digit >= 10) { + return ExactNum.Zero; + } + nsec += digit * scale[i]; + } + return ExactNum.Make(nsec, RubyTime.NanosecondsPerSecond); + } + [RubyMethod("_load", RubyMethodAttributes.PrivateSingleton)] public static RubyTime/*!*/ Load(RubyContext/*!*/ context, RubyClass/*!*/ self, [NotNull]MutableString/*!*/ time) { byte[] data = time.ConvertToBytes(); @@ -1253,6 +1282,8 @@ private static uint GetUint(byte[] data, int start) { // The remainder is in nanoseconds; the time itself counts seconds. extraSubsec = ExactNum.Make(num, den * 1000000000); } + } else { + extraSubsec = ReadSubmicro(context, time); } if ((data[3] & 0x80) == 0) { @@ -1268,6 +1299,12 @@ private static uint GetUint(byte[] data, int start) { bool isUtc = (data[3] & 0x40) != 0; int year = 1900 + (int)((dword1 >> 14) & 0xffff); int month = 1 + (int)((dword1 >> 10) & 0x0f); + // the four bits hold 0...15; MRI's time_mload carries a month past December into + // the next year (and a dump of Time.utc(2022, 4, 1) by Ruby 3.1 has one) + if (month > 12) { + month -= 12; + year++; + } int day = (int)((dword1 >> 5) & 0x01f); int hour = (int)(dword1 & 0x01f); From 118d07692144291e69c6eaf2051b045c40e49ad2 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:12:45 +0100 Subject: [PATCH 067/147] Time#strftime warns about an empty format under -w CRuby's time_strftime says "strftime called with empty format string" through rb_warning, so under -w (or $VERBOSE = true) only; IronRuby said nothing. It now reports the same verbose-only warning. test_time's test_strftime passes. --- Src/Libraries/Builtins/RubyTimeOps.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 44dd93738..a4270bee7 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -1870,6 +1870,10 @@ internal static string GetZoneAbbreviation(RubyContext/*!*/ context, RubyTime/*! if (!format.Encoding.IsAsciiIdentity) { throw RubyExceptions.CreateArgumentError("format should have ASCII compatible encoding"); } + if (format.IsEmpty) { + // MRI's time_strftime: rb_warning, shown under -w only + context.ReportWarning("strftime called with empty format string", true); + } MutableString result = MutableString.CreateMutable(format.Encoding); Strftime.Format(context, result, self, format.ConvertToString(), 0); return result; From b5b40061c54afe2e88b476f06beb59f3332b5f55 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:17:48 +0100 Subject: [PATCH 068/147] Thread#join takes any Integer and #to_f, and a negative limit does not wait t.join(2**62) raised "no implicit conversion of Integer into Float" (the long case was missing), so did t.join(obj) for an object with #to_f, and t.join(-Float::INFINITY) or t.join(-2**63) waited forever: a limit below Int32.MinValue milliseconds was taken as no limit at all. CRuby's thread_join_m converts with rb_num2dbl: Integers and Floats as they are, a String, true or false a TypeError ("no implicit conversion to float from string"), anything else through #to_f, and a negative limit is a join that does not wait (TestThread#test_join_limit_*, test_join_argument_conversion). Join now does the same, sending the other objects through the to_f conversion, and treats a limit of zero or less (or NaN) as no wait. The messages match CRuby's for Symbol, String, true, Object and a #to_f that answers an Integer; spec/core/thread passes. --- Src/Libraries/Builtins/ThreadOps.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 267689287..8e7385c46 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -881,21 +881,27 @@ private static bool JoinWithSafePoints(Thread/*!*/ self, int timeout) { /// Float conversion the other values do. /// [RubyMethod("join")] - public static Thread Join(RubyContext/*!*/ context, Thread/*!*/ self, object timeout) { + public static Thread Join(ConversionStorage/*!*/ floatConversion, RubyContext/*!*/ context, Thread/*!*/ self, object timeout) { if (timeout == null) { return Join(context, self); } - // MRI's time-interval conversion, not Float(): a String is a TypeError here rather - // than the ArgumentError that Float("bar") would raise. + // MRI's rb_num2dbl, not Float(): any Integer (2**62 is a long here) or Float as it is, a String, + // true or false a TypeError rather than the ArgumentError that Float("bar") would raise, and + // anything else - a Rational, an object with #to_f - through #to_f. double seconds; if (timeout is int) { seconds = (int)timeout; } else if (timeout is double) { seconds = (double)timeout; + } else if (timeout is long) { + seconds = (long)timeout; } else if (timeout is System.Numerics.BigInteger) { seconds = (double)(System.Numerics.BigInteger)timeout; + } else if (timeout is MutableString || timeout is bool) { + throw RubyExceptions.CreateTypeError("no implicit conversion to float from {0}", + timeout is bool ? ((bool)timeout ? "true" : "false") : "string"); } else { - throw RubyExceptions.CreateImplicitConversionError(context.GetClassDisplayName(timeout), "Float"); + seconds = Protocols.CastToFloat(floatConversion, timeout); } return Join(context, self, seconds); } @@ -916,8 +922,10 @@ private static void RequireOtherThread(RubyContext/*!*/ context, Thread/*!*/ sel RequireOtherThread(context, self); if (!(self.ThreadState == ThreadState.AbortRequested || self.ThreadState == ThreadState.Aborted)) { + // a negative limit, -Float::INFINITY included, does not wait at all (MRI's thread_join + // with a limit of 0); one past what a wait can take is no limit double ms = seconds * 1000; - int timeout = (ms < Int32.MinValue || ms > Int32.MaxValue) ? Timeout.Infinite : (int)ms; + int timeout = (ms <= 0 || Double.IsNaN(ms)) ? 0 : ms > Int32.MaxValue ? Timeout.Infinite : (int)ms; bool joined = JoinWithSafePoints(self, timeout); if (!joined) { return null; From 13df1171c0b2c09dc11750cc5c8044a3543d988c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:18:26 +0100 Subject: [PATCH 069/147] Time#dst? asks a timezone object's #dst? A Time made with a timezone object (Time.new(..., zone), Time.at(..., in: zone), or loaded by Marshal through find_timezone) was never dst?, since only the local zone's rule was consulted. CRuby's zone_set_dst asks the zone's #dst? with the wall-clock reading whenever it fixes the offset, and keeps false when the zone has no #dst?. The two places that apply a zone object, and Time._load's find_timezone, now ask it and keep the answer on the Time; +, round and Time.at(time) carry it over, as they carry the zone object. test_time_tz's DummyTZ test_dst? and test_fractional_second (which picks the expected offset by dst?) pass for America/Los_Angeles, and test_marshal still does; spec/core/time shows no new failures. --- Src/Libraries/Builtins/RubyTime.cs | 11 ++++++++++- Src/Libraries/Builtins/RubyTimeOps.cs | 23 ++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/RubyTime.cs b/Src/Libraries/Builtins/RubyTime.cs index 8c2671fe4..441169029 100644 --- a/Src/Libraries/Builtins/RubyTime.cs +++ b/Src/Libraries/Builtins/RubyTime.cs @@ -279,6 +279,7 @@ internal void CopyFrom(RubyTime/*!*/ other) { _zoneKind = other._zoneKind; _fixedOffset = other._fixedOffset; _zoneObject = other._zoneObject; + _zoneDst = other._zoneDst; _localOffset = other._localOffset; _localZoneName = other._localZoneName; _localDst = other._localDst; @@ -443,7 +444,15 @@ public long UtcOffsetSeconds { } public bool IsDaylightSavingTime { - get { return _zoneKind == RubyTimeZoneKind.Local && _localDst; } + get { return (_zoneKind == RubyTimeZoneKind.Local && _localDst) || (_zoneObject != null && _zoneDst); } + } + + // What the timezone object's #dst? said about this time (see RubyTimeOps.AskZoneDst). + private bool _zoneDst; + + internal bool ZoneDst { + get { return _zoneDst; } + set { _zoneDst = value; } } /// The instant, in UTC. diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index a4270bee7..436498259 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -421,7 +421,22 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) throw RubyExceptions.CreateArgumentError("utc_offset out of range"); } - return instant.WithZone(RubyTimeZoneKind.FixedOffset, ExactNum.FromInteger(offsetSeconds), zoneObject); + var result = instant.WithZone(RubyTimeZoneKind.FixedOffset, ExactNum.FromInteger(offsetSeconds), zoneObject); + result.ZoneDst = AskZoneDst(context, zoneObject, new RubyTime(localSeconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero)); + return result; + } + + private static CallSite> _dstSite; + + /// + /// MRI's zone_set_dst: a Time with a timezone object is dst? when the zone's #dst?, given the + /// wall-clock reading, says so - and not when the zone has no #dst?. + /// + private static bool AskZoneDst(RubyContext/*!*/ context, object/*!*/ zoneObject, RubyTime/*!*/ wallClock) { + if (!RespondTo(context, zoneObject, "dst?")) { + return false; + } + return Protocols.IsTrue(Invoke(context, ref _dstSite, "dst?", zoneObject, wallClock)); } #endregion @@ -910,6 +925,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { var result = new RubyTime(utcSeconds, fraction, RubyTimeZoneKind.FixedOffset, ExactNum.FromInteger(offsetSeconds)); result.ZoneObject = zoneObject; + result.ZoneDst = AskZoneDst(context, zoneObject, asUtc); return result; } @@ -973,6 +989,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { instant = new RubyTime(other.Seconds, other.Subsec, other.ZoneKind, other.ZoneKind == RubyTimeZoneKind.FixedOffset ? other.UtcOffsetExact : ExactNum.Zero); instant.ZoneObject = other.ZoneObject; + instant.ZoneDst = other.ZoneDst; } else { instant = RubyTime.FromExactSeconds(seconds, kind, offset); if (zoneObject != null) { @@ -1177,6 +1194,8 @@ private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, i } if (found != null) { result.ZoneObject = found; + result.ZoneDst = AskZoneDst(context, found, + new RubyTime(result.Seconds + result.UtcOffsetSeconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero)); } } return result; @@ -1342,6 +1361,7 @@ private static ExactNum ReadSubmicro(RubyContext/*!*/ context, MutableString/*!* var time = RubyTime.FromExactSeconds(result, self.ZoneKind, self.ZoneKind == RubyTimeZoneKind.FixedOffset ? self.UtcOffsetExact : ExactNum.Zero); time.ZoneObject = self.ZoneObject; + time.ZoneDst = self.ZoneDst; return time; } @@ -1662,6 +1682,7 @@ public static bool IsSaturday(RubyTime/*!*/ self) { var time = RubyTime.FromExactSeconds(result, self.ZoneKind, self.ZoneKind == RubyTimeZoneKind.FixedOffset ? self.UtcOffsetExact : ExactNum.Zero); time.ZoneObject = self.ZoneObject; + time.ZoneDst = self.ZoneDst; time.InheritLocalZone(self); return time; } From 7fdd3e608b26308c8d8bc0b5c61c085bb8dfc1e8 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:19:10 +0100 Subject: [PATCH 070/147] IO#reopen takes File.open's options, and takes the other IO's encodings reopen(path, mode, binmode: true), reopen(path, autoclose: false) and reopen(path, encoding: "ASCII-8BIT") were ArgumentError "given 3" or a TypeError for the Hash taken as the mode; MRI's rb_io_reopen extracts the mode and encodings from them as File.open does ([Feature #7103]). The two path overloads become one that takes an Integer or String mode and the options, and keeps the stream's own access mode when neither gives one. Reopened to another IO, an IO now takes that IO's encodings, conversion options and binary mode, as MRI's io_reopen copies fptr->encs and the mode: a UTF-16LE file reopened to a UTF-8 one reads UTF-8, and a binmode'd one is no longer binmode?. Checked against CRuby 4.0.10: test_io's reopen tests all pass; spec/core/io reopen_spec and binmode_spec, spec/core/file/open_spec pass. --- Src/Libraries/Builtins/IoOps.cs | 50 +++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 840f6ca45..aeed71765 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -363,9 +363,20 @@ private static RubyIO TryToIO(RespondToStorage/*!*/ respondToStorage, } // A reopened IO answers the other one's path, as MRI copies it with the descriptor. - // MRI also gives it the other one's class, which leaves its singleton class behind. + // MRI also gives it the other one's class, which leaves its singleton class behind, + // and the other one's encodings and conversion options (io_reopen copies fptr->encs). private static void CopyPath(RubyIO/*!*/ self, RubyIO/*!*/ source) { self.Context.ReplaceClrObjectClass(self, self.Context.GetClassOf(source)); + self.CopyEncodingsFrom(source); + self.ConversionOptions = source.ConversionOptions; + // and its binary mode: the prelude's IO#binmode records it in this hidden variable + string binmode = RubyUtils.GetCoreStateInstanceVariableName("@__binmode__"); + object sourceBinmode; + if (self.Context.TryGetInstanceVariable(source, binmode, out sourceBinmode)) { + self.Context.SetInstanceVariable(self, binmode, sourceBinmode); + } else { + self.Context.TryRemoveInstanceVariable(self, binmode, out sourceBinmode); + } var file = self as RubyFile; var sourceFile = source as RubyFile; @@ -378,13 +389,34 @@ private static void CopyPath(RubyIO/*!*/ self, RubyIO/*!*/ source) { [RubyMethod("reopen")] public static RubyIO/*!*/ Reopen(RespondToStorage/*!*/ respondToStorage, CallSiteStorage>/*!*/ toIoStorage, ConversionStorage/*!*/ toPath, - RubyIO/*!*/ self, object path, [DefaultProtocol, Optional, NotNull]MutableString mode) { + ConversionStorage/*!*/ toInt, ConversionStorage>/*!*/ toHash, + ConversionStorage/*!*/ toStr, + RubyIO/*!*/ self, object path, [Optional]object mode, [Keywords, Optional]IDictionary options) { + // An IO to reopen to is taken as it is: MRI ignores the options then. var source = TryToIO(respondToStorage, toIoStorage, self.Context, path); if (source != null) { return Reopen(self, source); } - return Reopen(toPath, self, path, mode != null ? IOInfo.Parse(self.Context, mode) : new IOInfo(ReopenMode(self.Mode))); + + // The mode is open(2) flags or a mode string, and the options are File.open's + // (encoding:, binmode:, mode: ..., [Feature #7103]); reopen(path, binmode: true) may + // come with them as the second argument. + object _ = Missing.Value; + Protocols.TryConvertToOptions(toHash, ref options, ref mode, ref _); + IOInfo info = new IOInfo(); + if (mode != Missing.Value && mode != null) { + var toIntSite = toInt.GetSite(TryConvertToFixnumAction.Make(self.Context)); + int? flags = toIntSite.Target(toIntSite, mode); + info = flags.HasValue ? new IOInfo(IOModeNative.ToIOMode(flags.Value)) : IOInfo.Parse(self.Context, Protocols.CastToString(toStr, mode)); + } + if (options != null) { + info = info.AddOptions(toStr, options); + } + if (!info.HasMode) { + info = new IOInfo(ReopenMode(self.Mode), info.ExternalEncoding, info.InternalEncoding); + } + return Reopen(toPath, self, path, info); } /// @@ -402,18 +434,6 @@ private static IOMode ReopenMode(IOMode mode) { return mode; } - [RubyMethod("reopen")] - public static RubyIO/*!*/ Reopen(RespondToStorage/*!*/ respondToStorage, - CallSiteStorage>/*!*/ toIoStorage, ConversionStorage/*!*/ toPath, - RubyIO/*!*/ self, object path, int mode) { - - var source = TryToIO(respondToStorage, toIoStorage, self.Context, path); - if (source != null) { - return Reopen(self, source); - } - return Reopen(toPath, self, path, new IOInfo(IOModeNative.ToIOMode(mode))); - } - private static RubyIO/*!*/ Reopen(ConversionStorage/*!*/ toPath, RubyIO/*!*/ io, object pathObj, IOInfo info) { MutableString path = Protocols.CastToPath(toPath, pathObj); Stream newStream = RubyFile.OpenFileStream(io.Context, path.ToString(path.Encoding.Encoding), info.Mode); From a0182fef2e083e2db910f5bbe6be3eefd4888b7b Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:19:37 +0100 Subject: [PATCH 071/147] Module#using and #refine check where and how they are called as CRuby does Three differences from CRuby's mod_using and rb_mod_refine: - `using` in a class body opened inside a method (`class << self; using M; end` in a test method) was refused as "not permitted in methods": the check looked for any method scope up the chain. MRI looks at the calling frame, and a class body is a frame of its own; a block in the method (Module.new { using M }) is not. The walk now stops at a module body. - Module.new.send(:using, M) inside some other module's body activated the refinements; MRI raises "Module#using is not called on self". - refine(String, &a_proc) took the proc; MRI requires a literal block ("can't pass a Proc as a block to Module#refine"). Checked against CRuby 4.0.10 for each case; TestRefinement #test_module_using_invalid_self, #test_refine_with_proc and #test_refine_frozen_class pass; spec/core/module/refine_spec, using_spec and spec/core/main pass. --- Src/Libraries/Builtins/ModuleOps.cs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 56a74f219..9f00373fa 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -204,6 +204,9 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { if (block == null) { throw RubyExceptions.CreateArgumentError("no block given"); } + if (!block.IsLiteralBlock) { + throw RubyExceptions.CreateArgumentError("can't pass a Proc as a block to Module#refine"); + } RubyModule refinement = self.GetOrCreateRefinement(refinedModule); @@ -221,9 +224,20 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { /// [RubyMethod("using", RubyMethodAttributes.PrivateInstance)] public static RubyModule/*!*/ Using(RubyScope/*!*/ scope, RubyModule/*!*/ self, object module) { - // MRI refuses it anywhere inside a method body, blocks and module bodies included - if (scope.GetInnerMostMethodScope() != null) { - throw RubyExceptions.CreateRuntimeError("Module#using is not permitted in methods"); + // MRI refuses it inside a method body and the blocks in it (a module_eval or Module.new + // block included), but a class body opened in a method (`class << self`) is a frame of + // its own and may use it + for (RubyScope s = scope; s != null; s = s.Parent) { + if (s.Kind == ScopeKind.Method || s.Kind == ScopeKind.BlockMethod) { + throw RubyExceptions.CreateRuntimeError("Module#using is not permitted in methods"); + } + if (s.Kind == ScopeKind.Module || s.Kind == ScopeKind.TopLevel) { + break; + } + } + // and only on the module whose body (or module_eval block) is running + if (!ReferenceEquals(scope.SelfObject, self)) { + throw RubyExceptions.CreateRuntimeError("Module#using is not called on self"); } ActivateRefinements(scope, module); return self; From 66fc556389a30203ee2f45379c41c9fe9ac93a52 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:19:37 +0100 Subject: [PATCH 072/147] A refinement's method binds only to instances of the refined class UnboundMethod#bind constrained a method by the module that defines it, and a refinement is a module, so its methods bound to any object. MRI binds them to what the refinement refines: r = Module.new { refine(A) { def foo = super } } r.refinements[0].instance_method(:foo).bind(B.new) # bind argument must be an instance of A Bind now takes the refined module as the constraint for a refinement's method. Checked against CRuby 4.0.10 (a refined class, a refined module); TestRefinement#test_unbound_refine_method passes; spec/core/unboundmethod passes. --- Src/Libraries/Builtins/UnboundMethod.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index f764e1b23..1ba68d3f5 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -104,6 +104,10 @@ public static int GetArity(UnboundMethod/*!*/ self) { public static RubyMethod/*!*/ Bind(UnboundMethod/*!*/ self, object target) { RubyContext context = self._targetConstraint.Context; RubyModule constraint = self._info.DeclaringModule ?? self._targetConstraint; + // a refinement's method binds to what the refinement refines (Feature #14223) + if (constraint.IsRefinement && constraint.RefinedModule != null) { + constraint = constraint.RefinedModule; + } if (constraint.IsClass && !context.IsKindOf(target, constraint)) { throw RubyExceptions.CreateTypeError( From 106248a0eeee7e48099dfe2f497f99c3ee4a0a19 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:22:19 +0100 Subject: [PATCH 073/147] Killing the main thread exits the program Thread.kill(Thread.current) (or Thread.exit, or main.kill from another thread) on the main thread threw the CLR ThreadExitSignal all the way out, and the program died with "Exception of type 'IronRuby.Runtime.RubyUtils+ThreadExitSignal' was thrown" and status 1. CRuby's rb_thread_kill calls rb_exit(EXIT_SUCCESS) for the main thread: a SystemExit in the thread that asks, which runs ensure clauses and at_exit handlers and ends the program with status 0 (TestThread#test_kill_main_thread). Thread#kill/exit/terminate, Thread.kill and Thread.exit now raise that SystemExit when the target is the main thread and it is not already being killed. spec/core/thread, spec/core/kernel/exit_spec.rb and spec/core/process/exit_spec.rb pass. --- Src/Libraries/Builtins/ThreadOps.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 8e7385c46..be04ceca8 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -940,9 +940,21 @@ private static void RequireOtherThread(RubyContext/*!*/ context, Thread/*!*/ sel return self; } + /// + /// MRI's rb_thread_kill: killing the main thread - from itself or from any other - is exit(0) in the + /// thread that asks, a SystemExit that runs the ensure clauses and at_exit handlers and ends the + /// program with status 0, rather than the unwinding of a thread that nothing would report. + /// [RubyMethod("kill")] [RubyMethod("exit")] [RubyMethod("terminate")] + public static Thread Kill(RubyContext/*!*/ context, Thread/*!*/ self) { + if (ReferenceEquals(self, context.MainThread) && self.IsAlive && !RubyThreadInfo.FromThread(self).ExitRequested) { + throw new SystemExit(0, "exit"); + } + return Kill(self); + } + public static Thread Kill(Thread/*!*/ self) { RubyThreadInfo.RegisterCurrentThread(); RubyThreadInfo info = RubyThreadInfo.FromThread(self); @@ -1782,14 +1794,14 @@ public static object GlobalReportOnException(object self, object value) { #endregion [RubyMethod("kill", RubyMethodAttributes.PublicSingleton)] - public static Thread/*!*/ KillThread(object self, [NotNull]Thread/*!*/ thread) { - return Kill(thread); + public static Thread/*!*/ KillThread(RubyContext/*!*/ context, object self, [NotNull]Thread/*!*/ thread) { + return Kill(context, thread); } /// Thread.exit / Thread.stop take no argument and act on the current thread. [RubyMethod("exit", RubyMethodAttributes.PublicSingleton)] - public static Thread/*!*/ ExitCurrentThread(object self) { - return Kill(Thread.CurrentThread); + public static Thread/*!*/ ExitCurrentThread(RubyContext/*!*/ context, object self) { + return Kill(context, Thread.CurrentThread); } /// From 10535a2bafa8e9072f698c1b653045e4c06e1cef Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:25:54 +0100 Subject: [PATCH 074/147] Thread#inspect names a Thread subclass A thread made by a subclass of Thread inspected as #: the name came from the CLR type of the System.Threading.Thread, not from the Ruby class that adopted it, although #class answered the subclass. CRuby writes the thread's class (TestThread#test_inspect, test_status_and_stop_p), and when that name is not ASCII the answer is UTF-8, as it already was for a thread's name. Inspect now takes the class from GetClassOf and appends its name as a UTF-8 string, so an ASCII-only answer stays binary as before. spec/core/thread passes. --- Src/Libraries/Builtins/ThreadOps.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index be04ceca8..4fbae00d5 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -786,7 +786,9 @@ public static ThreadGroup Group(Thread/*!*/ self) { MutableString result = MutableString.CreateMutable(RubyEncoding.Binary); result.Append("#<"); - result.Append(context.GetClassDisplayName(self)); + // The class is the one the thread was made by, a Thread subclass's included (the CLR thread is + // adopted by it), and a name that is not ASCII makes the answer UTF-8, as the name of a thread does. + result.Append(MutableString.Create(context.GetClassOf(self).GetNonNullName(context), RubyEncoding.UTF8)); result.Append(':'); RubyUtils.AppendFormatHexObjectId(result, RubyUtils.GetObjectId(context, self)); From 40cbad41ffe6bf35f5adc6ba265b6bcbdb45b5c1 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:16 +0100 Subject: [PATCH 075/147] File.basename refuses a suffix in an ASCII-incompatible encoding MRI's rb_file_s_basename runs check_path_encoding on the suffix as on the path: File.basename("foo.ext", ".*".encode("utf-16le")) is Encoding::CompatibilityError "path name must be ASCII-compatible (UTF-16LE): \".*\"". IronRuby compared the decoded text and answered "foo". Checked against CRuby 4.0.10: test_file_exhaustive's test_basename_encoding passes; spec/core/file passes. --- Src/Libraries/Builtins/FileOps.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 133bfb4fc..d5edffbad 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -620,7 +620,14 @@ public static int Rename(ConversionStorage/*!*/ toPath, RubyClass [RubyMethod("basename", RubyMethodAttributes.PublicSingleton)] public static MutableString/*!*/ BaseName(ConversionStorage/*!*/ toPath, RubyClass/*!*/ self, object path, [DefaultProtocol, NotNull, Optional]MutableString suffix) { - return BaseName(Protocols.CastToPath(toPath, path), suffix); + var strPath = Protocols.CastToPath(toPath, path); + // MRI's check_path_encoding: the suffix is looked for among the path's bytes, so it + // has to be ASCII-compatible as the path does. + if (suffix != null && !suffix.Encoding.IsAsciiIdentity) { + throw new EncodingCompatibilityError(String.Format("path name must be ASCII-compatible ({0}): \"{1}\"", + suffix.Encoding.Name, suffix.ToStringWithEscapedInvalidCharacters(suffix.Encoding))); + } + return BaseName(strPath, suffix); } private static MutableString/*!*/ BaseName(MutableString/*!*/ path, MutableString suffix) { From 0695acc2d7950b07025b25db47d2b9e178e5bffe Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:27 +0100 Subject: [PATCH 076/147] Marshal.dump takes an object's instance variables before writing any An object whose @bar's marshal_dump removes the object's @baz ([Bug #15968]) was dumped with @baz nil: the names were taken up front but each value only when its turn came. CRuby walks them with rb_ivar_foreach_buffered, which takes names and values together before writing, so @baz keeps the value it had. WriteIVarPairs now does the same. test_marshal's test_marshal_dump_removing_instance_variable passes (and test_marshal_dump_adding_instance_variable still does). --- Src/Libraries/Builtins/Marshal.cs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 4e7f086c7..1e244cead 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -750,14 +750,19 @@ private void WriteSetObject(object setTable) { } private void WriteIVarPairs(object/*!*/ obj, string[]/*!*/ names) { - var identifierEncoding = _context.GetIdentifierEncoding(); - foreach (string name in names) { - object value; - if (!_context.TryGetInstanceVariable(obj, name, out value)) { - value = null; + // The values are taken before any is written, as MRI's rb_ivar_foreach_buffered takes + // them: a marshal_dump one of them runs may remove another, which is still written + // with the value it had ([Bug #15968]). + object[] values = new object[names.Length]; + for (int i = 0; i < names.Length; i++) { + if (!_context.TryGetInstanceVariable(obj, names[i], out values[i])) { + values[i] = null; } - WriteSymbol(name, identifierEncoding); - WriteAnObject(value); + } + var identifierEncoding = _context.GetIdentifierEncoding(); + for (int i = 0; i < names.Length; i++) { + WriteSymbol(names[i], identifierEncoding); + WriteAnObject(values[i]); } } From c766ce533e55c59b36094676d209db6119a48798 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:27 +0100 Subject: [PATCH 077/147] Marshal.load copies the data's instance variables onto a marshal_load'ed object A class whose marshal_dump returns a string carrying instance variables lost them on the way back. CRuby's r_object for a 'U' record calls marshal_load and then r_copy_ivar: each instance variable of the data that the object does not have yet is set on it - a FrozenError if marshal_load froze the object ([Bug #8276]). ReadUsingMarshalLoad now does the same. Checked against CRuby 4.0.10; test_marshal's test_marshal_load_ivar and test_marshal_dump_ivar pass, and spec/core/marshal shows no new failures. --- Src/Libraries/Builtins/Marshal.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 1e244cead..fc033399b 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -1833,7 +1833,20 @@ private void CheckLoad(RubyClass/*!*/ theClass) { throw RubyExceptions.CreateTypeError("instance of {0} needs to have method 'marshal_load'", Context.GetClassOf(obj).GetDisplayName(Context, false).ToString()); } - _sites.MarshalLoad.Target(_sites.MarshalLoad, obj, ReadAnObject(false)); + object data = ReadAnObject(false); + _sites.MarshalLoad.Target(_sites.MarshalLoad, obj, data); + + // MRI's r_copy_ivar: the instance variables the dumped data carried, and which + // #marshal_load did not set itself, go onto the object - a FrozenError if + // #marshal_load froze it ([Bug #8276]). + if (data != null && Context.HasInstanceVariables(data)) { + foreach (string name in Context.GetInstanceVariableNames(data)) { + object value, existing; + if (!Context.TryGetInstanceVariable(obj, name, out existing) && Context.TryGetInstanceVariable(data, name, out value)) { + Context.SetInstanceVariable(obj, name, value); + } + } + } return obj; } From 95d9db0b36d8e4e4bd057ea1477ea75764a98d99 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:29 +0100 Subject: [PATCH 078/147] File#lstat describes the path the File was opened with MRI's rb_file_lstat is lstat(2) of the File's path, so a File opened through a symbolic link answers lstat.symlink? true; IronRuby answered #lstat with the same fstat as #stat. A File with no path is still fstat'd. Checked against CRuby 4.0.10: test_file_exhaustive's test_lstat passes; spec/core/file passes. --- Src/Libraries/Builtins/FileOps.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index d5edffbad..c14ee2174 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1803,12 +1803,24 @@ public static MutableString FileType(ConversionStorage/*!*/ toPat return RubyStatOps.Create(self.Context, self.Context.DecodePath(Protocols.CastToPath(toPath, path)), false); } - [RubyMethod("lstat")] [RubyMethod("stat")] public static FileSystemInfo Stat(RubyFile/*!*/ self) { return RubyStatOps.Create(self); } + /// + /// MRI's rb_file_lstat: lstat(2) of the path the File was opened with, so a File opened + /// through a symbolic link describes the link. A File with no path is fstat'd. + /// + [RubyMethod("lstat")] + public static FileSystemInfo LStat(RubyFile/*!*/ self) { + self.RequireOpen(); + if (self.Path == null) { + return RubyStatOps.Create(self); + } + return RubyStatOps.Create(self.Context, self.Path, false); + } + [RubyMethod("birthtime")] public static RubyTime BirthTime(RubyContext/*!*/ context, RubyFile/*!*/ self) { return RubyStatOps.BirthTime(RubyStatOps.Create(self)); From c23a73fa048a8ca2cbfa459fe76a853b94463e8d Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:29 +0100 Subject: [PATCH 079/147] File.expand_path leaves the base alone beside an absolute path File.expand_path("/", "~nosuchuser") is "/" in MRI: the directory argument is only expanded when the path needs it, so its "~user" is never looked up. IronRuby expanded it first and raised ArgumentError "user nosuchuser doesn't exist". The base is still converted (to_path, encoding) in either case. Checked against CRuby 4.0.10: test_file_exhaustive's test_expand_path_home_dir_string passes; spec/core/file passes. --- Src/Libraries/Builtins/FileOps.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index c14ee2174..21beae5d9 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -912,14 +912,17 @@ private static string StripPathCharacters(string path) { MutableString pathStr = Protocols.CastToPath(toPath, path); RequireUsablePathEncoding(context, pathStr); - string result = RubyUtils.ExpandPath( - context.Platform, - ExpandTilde(context, DecodePathLike(context, pathStr)), - (basePath == null) - ? null - : ExpandTilde(context, DecodeBasePath(context, Protocols.CastToPath(toPath, basePath), pathStr)), - false - ); + // The base is converted whatever the path, but it is only expanded - "~name" looked + // up - when the path needs it: MRI's expand_path ignores it beside an absolute path. + string expanded = ExpandTilde(context, DecodePathLike(context, pathStr)); + string expandedBase = null; + if (basePath != null) { + string decodedBase = DecodeBasePath(context, Protocols.CastToPath(toPath, basePath), pathStr); + if (!RubyUtils.IsAbsolutePath(expanded)) { + expandedBase = ExpandTilde(context, decodedBase); + } + } + string result = RubyUtils.ExpandPath(context.Platform, expanded, expandedBase, false); return EncodePathLike(context, result, pathStr); } From 5b4c369909c9aa6ae248bbde8d82c7b087a19aad Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:26:29 +0100 Subject: [PATCH 080/147] File.open with a mode and a mode: option says "mode specified twice" File.open("a", "w", mode: "rw+") is ArgumentError "mode specified twice" in MRI, which refuses the second mode before reading it; IronRuby parsed it first and complained "invalid access mode rw+". Checked against CRuby 4.0.10: test_file's test_file_open_double_mode passes; spec/core/file and spec/core/io/reopen_spec pass. --- Src/Ruby/Builtins/IOMode.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Builtins/IOMode.cs b/Src/Ruby/Builtins/IOMode.cs index a2dc6cf2b..33be54a93 100644 --- a/Src/Ruby/Builtins/IOMode.cs +++ b/Src/Ruby/Builtins/IOMode.cs @@ -102,10 +102,12 @@ public static IOInfo Parse(RubyContext/*!*/ context, MutableString/*!*/ modeAndE } public IOInfo AddModeAndEncoding(RubyContext/*!*/ context, MutableString/*!*/ modeAndEncoding) { - IOInfo info = Parse(context, modeAndEncoding); + // MRI refuses a second mode before it reads it: File.open(f, "w", mode: "rw+") is + // "mode specified twice", not the "invalid access mode" the second one would be. if (_mode.HasValue) { throw RubyExceptions.CreateArgumentError("mode specified twice"); } + IOInfo info = Parse(context, modeAndEncoding); if (!HasEncoding) { return info; From 71e66990cd70b39bd309d17a66641836b96bfd17 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:29:50 +0100 Subject: [PATCH 081/147] Marshal.dump(ARGF) is a TypeError, as in CRuby Marshal.dump(ARGF) wrote "\x04\bo:\x0FARGF_CLASS\x00", an object of a class no load can find (the prelude removes the constant). CRuby's ARGF is native data: "no _dump_data is defined for class ARGF.class". ARGF's class gets the private marshal_dump that raises it, as the prelude's Fiber and ObjectSpace::WeakKeyMap have. The ARGF assertion of test_marshal's test_singleton passes (it goes on to fail on ENV); spec/core/argf shows no new failures. --- Src/StdLib/ironruby/argf.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Src/StdLib/ironruby/argf.rb b/Src/StdLib/ironruby/argf.rb index f54b05504..b5365fb91 100644 --- a/Src/StdLib/ironruby/argf.rb +++ b/Src/StdLib/ironruby/argf.rb @@ -562,6 +562,15 @@ def name alias_method :inspect, :name end +# CRuby's ARGF is native data Marshal cannot write; this one is a Ruby object, which +# Marshal.dump wrote as an instance of a class no load could find. +ARGF_CLASS.class_eval do + def marshal_dump + ::Kernel.raise(::TypeError, "no _dump_data is defined for class #{self.class}") + end + private :marshal_dump +end + Object.send(:remove_const, :ARGF) if Object.const_defined?(:ARGF, false) ARGF = ARGF_CLASS.new ARGF.send(:replace_argv!, ARGV) From ef36b15ec7b9fbe46e4036bbf2e6cbbbc9486fbe Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:30:35 +0100 Subject: [PATCH 082/147] method_missing called with a name that is not a Symbol is an ArgumentError `1.instance_eval { method_missing(1) }` matched no overload of BasicObject#method_missing (they take a Symbol), so it raised whatever the binder made of that. rb_method_missing checks the name first: ArgumentError: method name must be a Symbol but Integer is given A catch-all overload now raises that. Checked against CRuby 4.0.10; TestObject#test_method_missing gets past those assertions (it still fails on a later one, an undefined method_missing); spec/core/basicobject passes but for the known into/to errors in instance_eval_spec. --- Src/Libraries/Builtins/BasicObjectOps.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Src/Libraries/Builtins/BasicObjectOps.cs b/Src/Libraries/Builtins/BasicObjectOps.cs index 08913286c..a7b050054 100644 --- a/Src/Libraries/Builtins/BasicObjectOps.cs +++ b/Src/Libraries/Builtins/BasicObjectOps.cs @@ -77,6 +77,13 @@ public static object MethodMissing(object/*!*/ self) { throw RubyExceptions.CreateArgumentError("no method name given"); } + // rb_method_missing checks the name before anything else + [RubyMethod("method_missing", RubyMethodAttributes.PrivateInstance)] + public static object MethodMissing(RubyContext/*!*/ context, object/*!*/ self, object name, params object[]/*!*/ args) { + throw RubyExceptions.CreateArgumentError("method name must be a Symbol but {0} is given", + context.GetClassOf(name).GetNonNullName(context)); + } + #endregion #region __send__ From e63046ae32d6750be80756fe55a2040095f30696 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:30:35 +0100 Subject: [PATCH 083/147] Warning.warn names nil as nil and refuses an ASCII-incompatible message Warning.warn(nil) said "wrong argument type NilClass (expected String)"; MRI's Check_Type says "nil". And a UTF-16 message was written out as-is, where rb_warning_s_warn calls rb_must_asciicompat and raises Encoding::CompatibilityError. Both now match. Checked against CRuby 4.0.10; TestException#test_warning_warn_invalid_argument passes; spec/core/warning and spec/core/kernel/warn_spec pass. --- Src/Libraries/Builtins/WarningOps.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/WarningOps.cs b/Src/Libraries/Builtins/WarningOps.cs index a8059aca1..a27753407 100644 --- a/Src/Libraries/Builtins/WarningOps.cs +++ b/Src/Libraries/Builtins/WarningOps.cs @@ -67,8 +67,11 @@ public static object Warn(RubyContext/*!*/ context, object self, object message, MutableString str = message as MutableString; if (str == null) { - throw RubyExceptions.CreateTypeError("wrong argument type {0} (expected String)", - context.GetClassDisplayName(message)); + throw RubyExceptions.CreateUnexpectedTypeError(context, message, "String"); + } + // rb_must_asciicompat + if (!str.Encoding.IsAsciiIdentity) { + throw RubyExceptions.CreateAsciiIncompatibleEncodingError(str.Encoding); } object category; From 748b73f6b4a90cb777f6ed8c002a885825e71ee4 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:30:35 +0100 Subject: [PATCH 084/147] eval of a string opening with a UTF-8 BOM reads it as UTF-8 eval("\xEF\xBB\xBF'a'.encoding") from a binary string returned ASCII-8BIT: the eval took the string's encoding. MRI's parser skips a leading UTF-8 BOM and switches the source to UTF-8 (parser_prepare), so the literal is UTF-8. Eval now does the same when the string is ASCII-compatible and opens with the BOM. Checked against CRuby 4.0.10; TestParse#test_utf8_bom passes; spec/core/kernel/eval_spec, spec/language/encoding_spec and magic_comment_spec pass. --- Src/Ruby/Runtime/RubyUtils.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 8a54f20e0..38656d7eb 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -1464,6 +1464,11 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop return Evaluate(code, targetScope, self, module, null, file, line); } + private static bool StartsWithUtf8Bom(MutableString/*!*/ code) { + return code.Encoding.IsAsciiIdentity && code.GetByteCount() >= 3 + && code.GetByte(0) == 0xEF && code.GetByte(1) == 0xBB && code.GetByte(2) == 0xBF; + } + public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScope, object self, RubyModule module, RubyModule lexicalConstantModule, MutableString file, int line) { Assert.NotNull(code, targetScope); @@ -1480,7 +1485,9 @@ public static object Evaluate(MutableString/*!*/ code, RubyScope/*!*/ targetScop // we want to create a new top-level local scope: var options = CreateCompilerOptionsForEval(targetScope, methodScope, module != null, line); - options.EvalSourceEncoding = code.Encoding; + // A UTF-8 BOM opening the string makes the code UTF-8 whatever the string's encoding, as + // MRI's parser_prepare does (eval "\xEF\xBB\xBF..." from a binary or US-ASCII file). + options.EvalSourceEncoding = StartsWithUtf8Bom(code) ? RubyEncoding.UTF8 : code.Encoding; string path = file != null ? file.ConvertToString() : DefaultEvalFileName(context); var source = CreateRubySourceUnit(context, code, (line <= 0) ? EncodeEvalLineOffset(path, line - 1) : path); From d0f834848ba77f5323f3352bcd5eb51d83e2237a Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:30:35 +0100 Subject: [PATCH 085/147] A magic comment naming "external" or "locale" is an invalid encoding `# coding = external` was looked up the way Encoding.find looks names up, which resolves the special names to the default encodings, so the comment was accepted. MRI's parser uses rb_enc_find_index, which does not know them, and raises "unknown or invalid encoding in the magic comment". The lookup now uses the plain encoding name table. Checked against CRuby 4.0.10 (eval and a file); TestParse#test_magic_comment gets past those assertions (a later one wants the source line in the message); spec/language/magic_comment_spec and encoding_spec pass. --- Src/Ruby/Runtime/RubyContext.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 325c78014..7bb419ae5 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -5227,7 +5227,9 @@ public override Encoding/*!*/ DefaultEncoding { if (Tokenizer.TryParseEncodingHeader(reader, out encodingName, out line)) { // A name Ruby does not know is as wrong as an encoding the comment itself could not // be written in (UTF-16LE): MRI reports both as an ArgumentError, worded so. - var rubyEncoding = FindRubyEncoding(encodingName); + // "external", "locale" and the like are names Encoding.find resolves, not encodings: + // the parser does not know them (rb_enc_find_index there fails the same way). + var rubyEncoding = RubyEncoding.FindByName(encodingName); if (rubyEncoding == null || !rubyEncoding.IsAsciiIdentity) { throw new ArgumentException(String.Format("{0}:{1}: unknown or invalid encoding in the magic comment", path, line)); } From c18b2eb225b1dcabc0f44a30a34358914f26f815 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:34:48 +0100 Subject: [PATCH 086/147] A new thread starts with its creator's handle_interrupt masks A thread made inside Thread.handle_interrupt(RuntimeError => :never) took a Thread#raise RuntimeError at once, in the middle of whatever it was doing. CRuby's thread_create_core copies the creating thread's pending_interrupt_mask_stack into the new thread, so the raise waits until the thread asks for it (Thread.handle_interrupt(Object => :immediate) {} once Thread.pending_interrupt?), which TestThread#test_handle_interrupted? relies on. Thread.new now captures the creator's masks (an array copy of its [ThreadStatic] list) and the new thread installs them before it checks for a raise that came before it ran. spec/core/thread passes; new IronRuby.Tests Thread_HandleInterruptInherited1, run three times. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 37 ++++++++++++++++++++++++ Src/Libraries/Builtins/ThreadOps.cs | 9 ++++-- Src/Ruby/Runtime/RubyUtils.cs | 17 +++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 61e2e7c8d..200e5949f 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1154,6 +1154,7 @@ public Tests(Driver/*!*/ driver) { WeakMap_NoBlock1, Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, + Thread_HandleInterruptInherited1, Thread_RaiseBetweenBlockCallsMeetsRescue1, Thread_KillBehindRaise1, Thread_KillBehindRescuedRaise1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 6dbadd78a..daa0a3117 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -156,6 +156,43 @@ Thread.pass until ready } } + /// + /// A thread starts with the Thread.handle_interrupt masks of the thread that created it, as MRI's + /// thread_create_core copies them: a Thread#raise at a thread made inside a :never block waits for + /// the thread to ask for it (CRuby's TestThread#test_handle_interrupted?). + /// + public void Thread_HandleInterruptInherited1() { + TestOutput(@" +require 'ruby4' +q = Thread::Queue.new +Thread.handle_interrupt(RuntimeError => :never) { + done = false + th = Thread.new { + q.push :started + begin + begin + Thread.pass until done + rescue + q.push :early + end + begin + Thread.handle_interrupt(Object => :immediate) {} if Thread.pending_interrupt? + rescue RuntimeError + q.push :deferred + end + end + } + q.pop + th.raise + done = true + th.join + p q.pop +} +", @" +:deferred +"); + } + /// /// Thread#raise reaches the fiber the thread is running, wherever its fibers are in a switch. /// Every fiber is a CLR thread of its own; the interrupt used to be routed to the fiber that diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 4fbae00d5..7f8043a27 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -1340,6 +1340,8 @@ internal sealed class ThreadStarter { // a Ractor's main thread runs this instead of yielding StartRoutine, in a group of its own internal Func Body; internal ThreadGroup Group; + // the creator's Thread.handle_interrupt masks, which the thread starts with + internal object InterruptMasks; } /// @@ -1396,7 +1398,8 @@ private static Action CreateThreadTerminator(RubyContext context) { context.ThreadTerminator = CreateThreadTerminator(context); } s.Creator = Thread.CurrentThread; - Thread result = new Thread(new ThreadStart(() => RubyThreadStart(context, s.StartRoutine, s.Args, s.Group ?? group, s.Creator, s.Body)), + s.InterruptMasks = RubyUtils.CaptureInterruptMasks(); + Thread result = new Thread(new ThreadStart(() => RubyThreadStart(context, s.StartRoutine, s.Args, s.Group ?? group, s.Creator, s.Body, s.InterruptMasks)), RubyUtils.ThreadStackSize); if (subclass != null) { context.AdoptClrObject(result, subclass); @@ -1478,11 +1481,13 @@ private static void WaitForCreatorToBlock(Thread creator) { } private static void RubyThreadStart(RubyContext/*!*/ context, BlockParam startRoutine, object[] args, ThreadGroup group, - Thread creator, Func body) { + Thread creator, Func body, object interruptMasks) { RubyThreadInfo info = RubyThreadInfo.FromThread(Thread.CurrentThread); info.CreatedFromRuby = true; info.Group = group; + // before anything can be delivered, a Thread#raise that came before the thread ran included + RubyUtils.InheritInterruptMasks(interruptMasks); try { // Thread#kill / Thread#raise may have been called before the thread got a chance to run. diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 8a54f20e0..a59fa47b1 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -2360,6 +2360,23 @@ public static void PushInterruptMask(RubyModule[]/*!*/ classes, int[]/*!*/ timin masks.Add(new InterruptMask { Classes = classes, Timings = timings }); } + /// + /// The current thread's masks, for a thread it creates to start with: MRI's thread_create_core + /// copies the creator's mask stack, so a thread made inside Thread.handle_interrupt(X => :never) + /// defers an X raised at it as its creator would. Null when there is none. + /// + public static object CaptureInterruptMasks() { + var masks = _interruptMasks; + return (masks == null || masks.Count == 0) ? null : masks.ToArray(); + } + + /// Gives the current (new) thread the masks took. + public static void InheritInterruptMasks(object masks) { + if (masks != null) { + _interruptMasks = new List((InterruptMask[])masks); + } + } + public static void PopInterruptMask() { var masks = _interruptMasks; if (masks != null && masks.Count > 0) { From 3355d692796c603a0226311a9694dfccb1e75097 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:35:21 +0100 Subject: [PATCH 087/147] Marshal keeps the modules prepended to an object's singleton class An object whose singleton class had a module prepended was dumped without it ([Bug #8041]). CRuby's w_extended walks the singleton's ancestors and writes the prepended modules, then an 'e' record naming the object's own class for the singleton's origin, then the extended modules ("\x04\be:\tMod1e:\rMyObjecto..."); r_object prepends the modules named before that class record to the loaded object's singleton class, and raises "prepended class X differs from class Y" when the class is not the object's. The writer and reader now do the same; the dump is byte for byte CRuby's. An object that also extends a module, which CRuby 4.0.10 cannot load back ("prepended class MyObject differs from class MyObject"), loads here with both. test_marshal's test_object_prepend passes in all three classes; spec/core/marshal shows no new failures. --- Src/Libraries/Builtins/Marshal.cs | 48 +++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index fc033399b..8948802d0 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -801,6 +801,23 @@ private void CheckSingleton(RubyClass/*!*/ immediate) { private void WriteExtendedModules(RubyClass/*!*/ theClass) { if (theClass.IsSingletonClass) { + // MRI's w_extended walks the singleton's ancestors: the modules prepended to it come + // first, then the singleton's origin, written as the object's class ([Bug #8041]), then + // the extended ones. + var prepends = theClass.GetPrepends(); + if (prepends.Length > 0) { + foreach (var prepended in prepends) { + if (prepended.Name == null) { + throw RubyExceptions.CreateTypeError("can't dump anonymous class {0}", + prepended.GetDisplayName(_context, false) + ); + } + _writer.Write((byte)'e'); + WriteModuleName(prepended); + } + _writer.Write((byte)'e'); + WriteModuleName(theClass.GetNonSingletonClass()); + } foreach (var mixin in theClass.GetMixins()) { _writer.Write((byte)'e'); // MRI reaches an extended module through its iclass and reports an @@ -2062,21 +2079,48 @@ private void SetIVar(object obj, string/*!*/ name, object value) { private object/*!*/ ReadExtended(int objectRef) { string extensionName = ReadIdentifier(); - RubyModule module = ReadClassOrModule('m', extensionName) as RubyModule; + RubyModule module = ResolvePath(extensionName); int typeFlag = _reader.ReadByte(); + // A class among the 'e' records is the singleton's origin (see WriteExtendedModules): the + // modules named before it were prepended to the singleton, not extended. It has to be the + // object's own class. + RubyClass originClass = module as RubyClass; + if (originClass != null) { + object instance = ReadAnObject(typeFlag, objectRef); + RubyClass actual = Context.GetClassOf(instance); + if (actual != originClass) { + throw RubyExceptions.CreateArgumentError("prepended class {0} differs from class {1}", + extensionName, actual.GetDisplayName(Context, false).ToString()); + } + _prependedBelow = true; + return instance; + } + // MRI extends a user-marshaled object as soon as it is allocated, so that its // #marshal_load already sees the module (see ReadUsingMarshalLoad). if (typeFlag == 'U') { _pendingExtension = module; } object obj = ReadAnObject(typeFlag, objectRef); - if (typeFlag != 'U') { + + // Only the 'e' record right inside this one says whether the origin marker is + // further in; anything else read meanwhile may have left the flag set. + bool prepend = typeFlag == 'e' && _prependedBelow; + if (prepend) { + RubyUtils.RequireDefinableSingleton(obj); + Context.GetOrCreateSingletonClass(obj).PrependModules(module); + } else if (typeFlag != 'U') { ModuleOps.ExtendObject(module, obj); } + _prependedBelow = prepend; return obj; } + // Set by the 'e' record of an object's class, and passed out through the 'e' records + // around it: those name modules prepended to the object's singleton class. + private bool _prependedBelow; + private RubyModule _pendingExtension; private object/*!*/ ReadUserClass(int objectRef) { From 6f3ec68507a34ea1a460230e3f99c9eb78c62908 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:38:42 +0100 Subject: [PATCH 088/147] Marshal.load(freeze: true) keeps an extended string's modules With freeze: true, a String that the dump extended with a module came back as the deduplicated plain string, without the module. CRuby hands a frozen loaded string to rb_fstring, which only interns a bare string and merely freezes one with a singleton class. Deduplicate now leaves a string with a singleton class alone, as it already did one with instance variables or of a subclass. test_marshal's TestMarshalFreeze test_extend_string and test_string_subclass_extend pass; spec/core/marshal shows no new failures. --- Src/Libraries/Builtins/Marshal.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 8948802d0..6e2c1a70b 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -2400,8 +2400,11 @@ private object ReadAnObject(int typeFlag, int reservedRef) { /// variables or a singleton class is its own object. /// private MutableString/*!*/ Deduplicate(MutableString/*!*/ str) { - // only a plain String joins the table; an instance of a subclass keeps its class - if (Context.HasInstanceVariables(str) || str.GetType() != typeof(MutableString)) { + // only a plain String joins the table; an instance of a subclass keeps its class, and + // one an 'e' record extended its singleton class (rb_fstring only freezes a string + // that is not bare) + if (Context.HasInstanceVariables(str) || str.GetType() != typeof(MutableString) + || Context.GetImmediateClassOf(str).IsSingletonClass) { return str; } From 59eda3957e9e9139405c2e198c6e11379faf3409 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:41:59 +0100 Subject: [PATCH 089/147] An IO-like object's #read may answer more than it was asked for Marshal.load and Psych read an IO-like object (one with #read but no CLR stream) through IOWrapper, which copied whatever #read answered into its buffer: an object answering more bytes than the length asked for ran past the buffer's end, an ArgumentError from Buffer.BlockCopy ("Offset and length were out of bounds..."). CRuby's marshal reader keeps such extra bytes in its buffer and reads on from them. IOWrapper now copies what was asked for and keeps the rest for the next read; a read flush seeks back over them too. A dump read from an object whose #read answers all of it at once loads. (test_marshal's test_load_overread still fails: it relies on CRuby reading single bytes with #getbyte, which IronRuby's reader does not.) spec/core/marshal and spec/library/yaml show no new failures. --- Src/Ruby/Runtime/IOWrapper.cs | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/Src/Ruby/Runtime/IOWrapper.cs b/Src/Ruby/Runtime/IOWrapper.cs index 1843e8d0d..d3206c525 100644 --- a/Src/Ruby/Runtime/IOWrapper.cs +++ b/Src/Ruby/Runtime/IOWrapper.cs @@ -126,8 +126,10 @@ private void FlushWrite() { } private void FlushRead() { - if (_canSeek && (_readPos < _readLen)) { - Seek(this._readPos - this._readLen, SeekOrigin.Current); + int unread = (_readLen - _readPos) + (_surplus != null ? _surplus.Length - _surplusPos : 0); + _surplus = null; + if (_canSeek && unread > 0) { + Seek(-unread, SeekOrigin.Current); } _readPos = 0; _readLen = 0; @@ -185,17 +187,39 @@ public override int ReadByte() { } private int ReadFromObject(byte[]/*!*/ buffer, int offset, int count) { + // What a #read gave beyond the count it was asked for comes first. + if (_surplus != null) { + int taken = Math.Min(count, _surplus.Length - _surplusPos); + Buffer.BlockCopy(_surplus, _surplusPos, buffer, offset, taken); + _surplusPos += taken; + if (_surplusPos == _surplus.Length) { + _surplus = null; + } + return taken; + } + // TODO: conversion MutableString result = (MutableString)_readSite.Target(_readSite, _obj, count); if (result == null) { return 0; } else { + // An IO-like object's #read may answer more than it was asked for (MRI's marshal + // reader keeps the rest); copied whole, it ran past the end of the buffer. byte[] readdata = result.ConvertToBytes(); - Buffer.BlockCopy(readdata, 0, buffer, offset, readdata.Length); - return readdata.Length; + int length = Math.Min(readdata.Length, count); + Buffer.BlockCopy(readdata, 0, buffer, offset, length); + if (readdata.Length > count) { + _surplus = readdata; + _surplusPos = count; + } + return length; } } + // The bytes a #read answered beyond what was asked for, from _surplusPos on; null if none. + private byte[] _surplus; + private int _surplusPos; + public override long Seek(long offset, SeekOrigin origin) { if (!_canSeek) { throw new NotSupportedException(); From dca6df5c2d5041439e19a395363f94a47ba66334 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:45:08 +0100 Subject: [PATCH 090/147] IO#gets and friends refuse a separator the IO's encoding cannot read IO#gets, #readlines and #each_line with a separator in an encoding incompatible with the IO's (a UTF-16LE IO with a UTF-8 "\n" separator) read on as if the bytes matched. MRI's prepare_getline_args raises ArgumentError "encoding mismatch: UTF-16LE IO with UTF-8 RS" unless the encodings are the same, or the separator is ASCII-only and the IO's encoding is ASCII-compatible (or not set). The line readers now make the same check before reading. The default separator $/ is exempt, as it is in MRI, where it is converted to the IO's encoding. Checked with test_io.rb's test_readline_incompatible_rs and spec/core/io (no new failures). --- Src/Libraries/Builtins/IoOps.cs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index aeed71765..2cdbaa2c8 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -2376,6 +2376,7 @@ private static void CheckLineLimit(int limit, string/*!*/ methodName) { private static RubyArray/*!*/ ReadLines(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ universal, RubyContext/*!*/ context, RubyIO/*!*/ self, MutableString separator, int limit, bool chomp) { CheckLineLimit(limit, "readlines"); + CheckSeparatorEncoding(context, self, separator); RubyArray result = new RubyArray(); // no dynamic call, doesn't modify $_ scope variable: @@ -2678,6 +2679,28 @@ public static object Getc(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ /// MRI's io_read_encoding: the encoding of what the reads hand out, which is the /// internal one when the stream has one. /// + /// + /// MRI's prepare_getline_args: a separator has to be in the encoding the stream reads, + /// or be ASCII and the stream's encoding ASCII-compatible, or the line readers raise + /// "encoding mismatch: UTF-32LE IO with UTF-8 RS". The default "\n" is exempt: it is + /// looked for in the stream's encoding. + /// + private static void CheckSeparatorEncoding(RubyContext/*!*/ context, RubyIO/*!*/ self, MutableString separator) { + if (separator == null) { + return; + } + RubyEncoding io = ReadEncoding(self); + RubyEncoding rs = separator.Encoding; + if (io == rs || (separator.IsAscii() && (separator.IsEmpty || io.IsAsciiIdentity))) { + return; + } + if (ReferenceEquals(separator, context.InputSeparator) && separator.IsAscii() && separator.GetByteCount() == 1 + && separator.GetByte(0) == (byte)'\n') { + return; + } + throw RubyExceptions.CreateArgumentError("encoding mismatch: {0} IO with {1} RS", io.Name, rs.Name); + } + private static RubyEncoding/*!*/ ReadEncoding(RubyIO/*!*/ self) { return (self.Enc2 != null ? self.Enc : GetExternalEncoding(self)) ?? self.Context.DefaultExternalEncoding; } @@ -2992,6 +3015,7 @@ public static MutableString Gets(TranscodeStorage/*!*/ transcode, TranscodeStora private static MutableString Gets(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ universal, RubyScope/*!*/ scope, RubyIO/*!*/ self, MutableString separator, int limit, bool chomp) { + CheckSeparatorEncoding(scope.RubyContext, self, separator); bool converted; MutableString result = ReadLineOrParagraph(transcode, universal, self, IsUniversalNewline(universal, self), separator, limit, out converted); if (result != null) { @@ -3317,6 +3341,7 @@ private static object Each(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!* private static object Each(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ universal, RubyContext/*!*/ context, BlockParam block, RubyIO/*!*/ self, MutableString separator, int limit, bool chomp) { self.RequireReadable(); CheckLineLimit(limit, "each_line"); + CheckSeparatorEncoding(context, self, separator); bool universalNewline = IsUniversalNewline(universal, self); MutableString line; From 36fc27e8b1b0af993c7864a952887741818c58d3 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:45:17 +0100 Subject: [PATCH 091/147] IO.new takes its mode from the descriptor, and makes an adopted one close-on-exec IO.new(IO.sysopen(path, "w")) without a mode came out read-only, so a write raised IOError "not opened for writing". MRI asks fcntl(F_GETFL) for the access mode of a descriptor given without one. An adopted descriptor above 2 (one inherited, or made with fcntl(F_DUPFD)) also stayed inheritable, where MRI's IO.new runs rb_maygvl_fd_fix_cloexec on it. A descriptor IronRuby opened now takes its access mode from its stream's CanRead/CanWrite when no mode is given, and an adopted one above 2 is set close-on-exec. Checked with test_io.rb's test_sysopen and test_cloexec, and spec/core/io (no new failures). --- Src/Libraries/Builtins/IoOps.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 2cdbaa2c8..7705e032b 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -205,6 +205,16 @@ public static class WaitWritable { Stream stream = GetDescriptorStream(io.Context, descriptor); + // So does one IronRuby opened, when no mode is given: MRI asks fcntl(F_GETFL), and + // IO.new(IO.sysopen(path, "w")) or IO.new(1) is for writing. The stream says what the + // descriptor was opened for. + if (known && !info.HasMode && stream != null) { + IOMode access = stream.CanRead + ? (stream.CanWrite ? IOMode.ReadWrite : IOMode.ReadOnly) + : (stream.CanWrite ? IOMode.WriteOnly : IOMode.ReadOnly); + mode = (mode & ~IOMode.ReadWriteMask) | access; + } + // A mode the caller spelled out has to agree with what the descriptor was opened // for; MRI answers EINVAL when it does not. Only for a descriptor IronRuby opened - // an adopted one has just told us its mode and cannot disagree with itself. @@ -218,6 +228,16 @@ public static class WaitWritable { io.SetStream(stream); io.SetFileDescriptor(descriptor); + // MRI's IO.new runs rb_maygvl_fd_fix_cloexec: a descriptor above the standard three + // that this process was handed, or made with fcntl(F_DUPFD), is close-on-exec from + // now on, as every descriptor Ruby opens is. + if (!known) { + int native = io.KernelDescriptor; + if (native > 2) { + RubyProcess.SetCloseOnExec(native); + } + } + if (info.HasEncoding) { io.SetEncodings(info.ExternalEncoding, info.InternalEncoding); } else if ((mode & IOMode.PreserveEndOfLines) != 0) { From 6ecc36ed7a75e57f571fd0b785985e412e9ed8ce Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:45:23 +0100 Subject: [PATCH 092/147] IO.pipe takes binmode: true IO.pipe(binmode: true) ignored the option: neither end said binmode? and, without an encoding argument, both read UTF-8 strings. MRI's rb_io_s_pipe makes both ends binmode, and ASCII-8BIT ones when no encoding is given (rb_io_ascii8bit_binmode). The prelude's IO.pipe now calls #binmode on both ends without an encoding argument, and marks them binmode only when one is given. Checked with test_io.rb's test_binmode_pipe and spec/core/io/pipe_spec.rb. --- Src/StdLib/ironruby/ruby4.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 153f658a4..bb5b243b6 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -11520,6 +11520,18 @@ def pipe(*args, **options) end end + # MRI's rb_io_s_pipe: binmode: true makes both ends binmode?, and without an encoding + # argument both read and write bytes (rb_io_ascii8bit_binmode). + if options && options[:binmode] + if args[0].nil? + read_end.binmode + write_end.binmode + else + read_end.__send__(:__ir_set_hidden_ivar__, :@__binmode__, true) + write_end.__send__(:__ir_set_hidden_ivar__, :@__binmode__, true) + end + end + return [read_end, write_end] unless block_given? begin yield(read_end, write_end) From c297c1231485d2c34b1c0d41a70b977d7a026e06 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:45:28 +0100 Subject: [PATCH 093/147] An IO's path belongs to the object, and follows it through #reopen IO#path and IO#inspect answered "" for any IO on descriptor 0, so IO.for_fd(0, autoclose: false).path was "" where MRI gives nil and inspects it as "fd 0". An IO reopened to a path, or to a File, kept no path at all, and File#path and File#inspect raised TypeError on such an IO (it is an IO, not a RubyFile, after reopen). MRI keeps the name in fptr->pathv: set on STDIN, STDOUT and STDERR at startup, copied by io_reopen, set by IO#reopen(path). STDIN, STDOUT and STDERR now carry their names in the hidden path variable IO.new's path: option already used, #reopen copies or sets it, IO#inspect reads it instead of asking for the console stream type, and File#path, #to_path and #inspect answer for an IO by its path. Checked with test_io.rb's test_explicit_path and reopen tests, test_file.rb, and spec/core/io and spec/core/file (no new failures). --- Src/Libraries/Builtins/FileOps.cs | 19 ++++++++- Src/Libraries/Builtins/IoOps.cs | 64 +++++++++++++++++++++---------- Src/StdLib/ironruby/ruby4.rb | 14 +++---- 3 files changed, 67 insertions(+), 30 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 21beae5d9..e6a333f65 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1842,7 +1842,13 @@ public static object FileSize(RubyFile/*!*/ self) { return RubyStatOps.Size(RubyStatOps.Create((RubyIO)self)); } [RubyMethod("inspect")] - public static MutableString/*!*/ Inspect(RubyFile/*!*/ self) { + public static MutableString/*!*/ Inspect(RubyIO/*!*/ self) { + // an IO reopened to a File is a File that is not a RubyFile + var file = self as RubyFile; + return file != null ? Inspect(file) : RubyIOOps.Inspect(self); + } + + private static MutableString/*!*/ Inspect(RubyFile/*!*/ self) { var result = MutableString.CreateMutable(self.Context.GetPathEncoding()). Append("#<"). Append(self.Context.GetClassOf(self).GetName(self.Context)). @@ -1860,7 +1866,16 @@ public static object FileSize(RubyFile/*!*/ self) { [RubyMethod("path")] [RubyMethod("to_path")] - public static MutableString GetPath(RubyFile/*!*/ self) { + public static MutableString GetPath(RubyIO/*!*/ self) { + // An IO reopened to a File becomes a File without being a RubyFile: its path is the + // one the IO keeps. + if (!(self is RubyFile)) { + return RubyIOOps.GetIOPath(self); + } + return GetPath((RubyFile)self); + } + + private static MutableString GetPath(RubyFile/*!*/ self) { self.RequireInitialized(); if (self.Path == null) { return null; diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 7705e032b..c10975e00 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -382,6 +382,31 @@ private static RubyIO TryToIO(RespondToStorage/*!*/ respondToStorage, return self; } + private static readonly string IOPathVariable = RubyUtils.GetCoreStateInstanceVariableName("@__io_path__"); + + /// + /// MRI's fptr->pathv for an IO that is not a RubyFile: what IO.new(fd, path:) was told, + /// "" and the like for the standard streams, the path an IO was reopened to. + /// + internal static MutableString GetIOPath(RubyIO/*!*/ io) { + var file = io as RubyFile; + if (file != null) { + return file.Path != null ? io.Context.EncodePath(file.Path) : null; + } + object path; + io.Context.TryGetInstanceVariable(io, IOPathVariable, out path); + return path as MutableString; + } + + private static void SetIOPath(RubyIO/*!*/ io, MutableString path) { + object old; + if (path != null) { + io.Context.SetInstanceVariable(io, IOPathVariable, path); + } else { + io.Context.TryRemoveInstanceVariable(io, IOPathVariable, out old); + } + } + // A reopened IO answers the other one's path, as MRI copies it with the descriptor. // MRI also gives it the other one's class, which leaves its singleton class behind, // and the other one's encodings and conversion options (io_reopen copies fptr->encs). @@ -403,6 +428,8 @@ private static void CopyPath(RubyIO/*!*/ self, RubyIO/*!*/ source) { if (file != null && sourceFile != null) { file.Path = sourceFile.Path; file.PathEncoding = sourceFile.PathEncoding; + } else if (file == null) { + SetIOPath(self, GetIOPath(source)); } } @@ -457,6 +484,10 @@ private static IOMode ReopenMode(IOMode mode) { private static RubyIO/*!*/ Reopen(ConversionStorage/*!*/ toPath, RubyIO/*!*/ io, object pathObj, IOInfo info) { MutableString path = Protocols.CastToPath(toPath, pathObj); Stream newStream = RubyFile.OpenFileStream(io.Context, path.ToString(path.Encoding.Encoding), info.Mode); + // reopened by path, an IO answers that path (a File keeps its own) + if (!(io is RubyFile)) { + SetIOPath(io, path.Clone()); + } if (io.Closed) { // Reopening a closed stream with a path is how it is brought back to life, so // this one needs a descriptor again rather than the IOError a read would get. @@ -1530,28 +1561,19 @@ public static bool Sync(RubyIO/*!*/ self, bool sync) { result.Append(self.Context.GetClassOf(self).GetName(self.Context)); result.Append(':'); if (self.Initialized) { - switch (self.ConsoleStreamType) { - case ConsoleStreamType.Input: result.Append(""); break; - case ConsoleStreamType.Output: result.Append(""); break; - case ConsoleStreamType.ErrorOutput: result.Append(""); break; - case null: { - // A stream that knows its path shows it; one that does not shows its - // descriptor, which a closed stream no longer has. - object path; - self.Context.TryGetInstanceVariable(self, RubyUtils.GetCoreStateInstanceVariableName("@__io_path__"), out path); - var pathString = path as MutableString; - if (pathString != null) { - result.Append(pathString); - if (self.Closed) { - result.Append(" (closed)"); - } - } else if (self.Closed) { - result.Append("(closed)"); - } else { - result.Append("fd ").Append(self.GetFileDescriptor().ToString(CultureInfo.InvariantCulture)); - } - break; + // A stream that knows its path shows it - the standard streams know theirs as + // "" and so on, as MRI's fptr->pathv - and one that does not shows its + // descriptor, which a closed stream no longer has: IO.for_fd(0) is "fd 0". + var pathString = GetIOPath(self); + if (pathString != null) { + result.Append(pathString); + if (self.Closed) { + result.Append(" (closed)"); } + } else if (self.Closed) { + result.Append("(closed)"); + } else { + result.Append("fd ").Append(self.GetFileDescriptor().ToString(CultureInfo.InvariantCulture)); } } else { RubyUtils.AppendFormatHexObjectId(result, RubyUtils.GetObjectId(self.Context, self)); diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index bb5b243b6..f78eea8c1 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -11741,16 +11741,16 @@ def fdatasync # IO#path answers the path the stream was opened with - File overrides it with the # real one - and the standard streams answer the names MRI gives them. An IO built - # from a descriptor keeps whatever path: it was told about. + # from a descriptor keeps whatever path: it was told about, and IO.for_fd(0) none: + # the name belongs to the object, as MRI's fptr->pathv, not to the descriptor. def path - case fileno - when 0 then "" - when 1 then "" - when 2 then "" - else @__io_path__ - end + @__io_path__ end unless method_defined?(:path) + { STDIN => "", STDOUT => "", STDERR => "" }.each do |io, name| + io.__send__(:__ir_set_hidden_ivar__, :@__io_path__, name.freeze) + end + alias :to_path :path unless method_defined?(:to_path) # Positional read/write, done by saving and restoring the file position since From 96365449eaa4d3166d25e8074146c0fa510c442c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:50:02 +0100 Subject: [PATCH 094/147] IronRuby.Tests: Marshal_LoadChecks1, and Time_LoadZone1 follows the month carry Marshal_LoadChecks1 covers the Marshal.load checks and dump formats of the preceding Marshal commits (a name that is no class, _load looked for first, an 'S' record for a non-struct and for Range, a class's instance variables, a prepended singleton module, the ruby2_keywords flag, an array a _dump empties), with CRuby 4.0.10's output. Time_LoadZone1 asserted that a dumped month of 16 is "marshaled time format differ"; CRuby 4.0.10 carries it into the next year (2001-04-01 00:00:00 UTC), as Time._load now does. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/MiscTests.cs | 51 +++++++++++++++++++++---- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 19a6716f1..42591b1dc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1025,6 +1025,7 @@ public Tests(Driver/*!*/ driver) { Marshal_LoadFloat1, Marshal_SetIVars1, Marshal_NameError1, + Marshal_LoadChecks1, Integer_SqrtPowDigits1, Prelude_DataStructErrors1, Prelude_AliasNames1, diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 021168890..f7e237829 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -1856,13 +1856,9 @@ p Marshal.load(dump).zone p e.class end -# 2000-16-01: the month is out of range +# 2000-16-01: a month past December is carried into the next year, as time_mload does bad = [0x80000000 | (100 << 14) | (15 << 10) | (1 << 5), 0].pack('VV') -begin - Time.send(:_load, bad) -rescue TypeError => e - p e.message -end +p Time.send(:_load, bad).utc ", @" 2000-01-01 12:00:00 +0100 true @@ -1872,7 +1868,7 @@ p e.message ""XST"" ""XST"" ZoneFailure -""marshaled time format differ"" +2001-04-01 00:00:00 UTC "); } @@ -3540,6 +3536,47 @@ p Marshal.dump(NoMethodError.new) == ""\x04\bo:\x12NoMethodError\n:\tmesg0:\abt0 "); } + /// + /// Marshal.load's checks on what a dump names, as MRI's r_object makes them: a constant that is not a class is a + /// TypeError, _load is looked for first, an 'S' record needs a Struct (Range's members are begin, end, excl), and a + /// class's instance variables are not set. The modules prepended to a singleton class, the ruby2_keywords flag + /// of a Hash, and an array a _dump empties are dumped as MRI dumps them. The expected output is CRuby 4.0's. + /// + public void Marshal_LoadChecks1() { + TestOutput(@" +require 'ruby4' +class C3; def _dump(s) = ""foo""; end +m = Marshal.dump(C3.new) +p((Marshal.load(m) rescue $!)) +Object.send(:remove_const, :C3); C3 = nil +p((Marshal.load(m) rescue $!)) +S1 = Struct.new(:a); s = Marshal.dump(S1.new(1)) +Object.send(:remove_const, :S1); S1 = Class.new +p((Marshal.load(s) rescue $!)) +p((Marshal.load(""\x04\bS:\nRange\b:\x06a0:\x06b0:\x06c0"") rescue $!)) +class K; end +p((Marshal.load(""\x04\bIc\x06K\x06:\a@ai\x06"") rescue $!)); p K.instance_variables +module Mod1; end +o = Object.new; o.singleton_class.prepend(Mod1) +d = Marshal.dump(o); p d +l = Marshal.load(d); p l.singleton_class.ancestors.first(2) == [Mod1, l.singleton_class] +h = Hash.ruby2_keywords_hash({k: 1}); p Hash.ruby2_keywords_hash?(Marshal.load(Marshal.dump(h))) +a = []; x = Object.new; def x._dump(l) = ($a.clear; ""x""); $a = a; a << x << nil +p((Marshal.dump(a) rescue $!)) +", @" +# +# +# +# +# +[] +""\x04\be:\tMod1e:\vObjecto;\x06\x00"" +true +true +# +"); + } + /// /// Data.new reports a missing member before an unknown keyword, as MRI's rb_data_initialize_m does, and Data.define /// and Struct.new refuse only setter names (rb_is_attrset_id) as members, so `[]=` is allowed. All in the prelude. From 002a4fcb61589cc65475e2c05c0ef17731712af8 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:50:46 +0100 Subject: [PATCH 095/147] Thread#raise on the current thread respects Thread.handle_interrupt Thread.current.raise inside Thread.handle_interrupt(Object => :on_blocking) raised at once. CRuby's rb_threadptr_raise queues the exception on the current thread as on any other and then checks for interrupts, so a mask holds it back: under :on_blocking until the next blocking operation (the sleep in TestThread#test_handle_interrupt_blocking), under :never until the mask is gone, and Thread.pending_interrupt? is true meanwhile. RaiseException now throws only when the exception's timing is :immediate and parks it for the current thread otherwise, where the existing safe points deliver it. The results of raising under :on_blocking and :never and without a mask match CRuby's; spec/core/thread, spec/core/fiber and spec/core/kernel/raise_spec.rb pass. --- Src/Libraries/Builtins/ThreadOps.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 7f8043a27..d9c392118 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -1114,9 +1114,16 @@ public static void RaiseException(RespondToStorage/*!*/ respondToStorage, UnaryO Exception e = KernelOps.CreateExceptionToRaise(respondToStorage, storage0, storage1, setBackTraceStorage, context, args, false); // Inside a fiber the current Ruby thread is the fiber's owner; raising on it means - // raising here, not nudging the thread the fiber was started from. + // raising here, not nudging the thread the fiber was started from. MRI's rb_threadptr_raise + // queues the exception on the current thread as on any other and checks for interrupts at once, + // so a Thread.handle_interrupt mask holds it back here too: until the next blocking operation + // under :on_blocking, until the mask is gone under :never. if (self == RubyUtils.CurrentRubyThread) { - throw e; + if (RubyUtils.GetInterruptTiming(e) == RubyUtils.InterruptImmediate) { + throw e; + } + RubyUtils.ParkAsyncException(Thread.CurrentThread, e); + return; } RaiseAsyncException(context, self, e); From 9af56d19d16908be138a071129644e8fbb06c908 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:50:46 +0100 Subject: [PATCH 096/147] A masked Thread#raise does not end a sleep A thread sleeping (Kernel#sleep, Thread.stop, a timed sleep) inside Thread.handle_interrupt(X => :never) woke up when an X was raised at it: the interrupt and the Run() that follows it ended the wait, the parked exception stayed masked, and the sleep returned as if woken, so the block ran on to its end and the thread died of the exception there. CRuby's sleep_forever and sleep_hrtime check interrupts and go back to sleep while the thread is still meant to, so the exception stays queued (Thread.pending_interrupt? true) and the sleep lasts (TestThread#test_pending_interrupt? and test_handle_interrupted?, which failed about one run in three). The sleep now goes on waiting when what woke it was only an exception that is still parked, i.e. masked; a Thread#run/#wakeup (and a ConditionVariable's Wake, which may come before the sleep starts) is recorded and ends it as before, a kill or an unmasked exception is thrown as before, and a timed sleep waits out what is left of its time. Checked against CRuby for sleep, Thread.stop, sleep(n), #wakeup, #kill and ConditionVariable#wait under a :never mask, 20 runs each; spec/core/thread, mutex, conditionvariable, queue, sizedqueue, fiber, kernel/sleep_spec, library/monitor and library/timeout have no new failures. --- Src/Libraries/Builtins/ThreadOps.cs | 80 ++++++++++++++++++++++------- 1 file changed, 62 insertions(+), 18 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index d9c392118..18719a8d4 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -146,6 +146,9 @@ internal static bool ForwardAsyncException(Thread/*!*/ from, Thread/*!*/ to) { // Guarded by _sleepLock, which makes "is it sleeping? then wake it" (Run) and "the sleep is // over; drop a wake-up it did not take" (EndSleep) happen one after the other. private bool _isSleeping; + // Set by a Run() or Wake() for the current (or, for Wake, the coming) sleep, as opposed to the + // RunForInterrupt that follows a Thread#raise; guarded by _sleepLock, cleared when the sleep ends. + private bool _wokenByRun; private readonly object/*!*/ _sleepLock = new object(); private RubyThreadInfo(Thread thread) { @@ -524,17 +527,19 @@ internal void Sleep() { // One parked since that look found no sleep to end (RunForInterrupt); one parked // from now on does. RubyUtils.CheckAsyncException(); - _inManagedWait = true; - try { - _runSignal.WaitOne(); - } catch (ThreadInterruptedException) { - // Thread#kill / Thread#raise nudged us: deliver the parked exception. If there is none - // the interrupt was spurious and the sleep simply ends (MRI's sleep is also allowed to - // return early). The RunForInterrupt that follows the interrupt finds the exception - // still parked or not: if it does, the end of the sleep drops its wake-up. - _inManagedWait = wasWaiting; - RubyUtils.TranslateThreadInterrupt(); - } + do { + _inManagedWait = true; + try { + _runSignal.WaitOne(); + } catch (ThreadInterruptedException) { + // Thread#kill / Thread#raise nudged us: deliver the parked exception. If there is none + // the interrupt was spurious and the sleep simply ends (MRI's sleep is also allowed to + // return early). The RunForInterrupt that follows the interrupt finds the exception + // still parked or not: if it does, the end of the sleep drops its wake-up. + _inManagedWait = wasWaiting; + RubyUtils.TranslateThreadInterrupt(); + } + } while (WokenForMaskedInterrupt()); } finally { EndSleep(wasSleeping); _inManagedWait = wasWaiting; @@ -550,13 +555,21 @@ internal bool Sleep(int milliseconds) { bool wasSleeping = BeginSleep(); try { RubyUtils.CheckAsyncException(); - _inManagedWait = true; - try { - return _runSignal.WaitOne(milliseconds); - } catch (ThreadInterruptedException) { - _inManagedWait = wasWaiting; - RubyUtils.TranslateThreadInterrupt(); - return false; + long deadline = Environment.TickCount64 + milliseconds; + while (true) { + _inManagedWait = true; + try { + if (!_runSignal.WaitOne(milliseconds)) { + return true; + } + } catch (ThreadInterruptedException) { + _inManagedWait = wasWaiting; + RubyUtils.TranslateThreadInterrupt(); + } + if (!WokenForMaskedInterrupt()) { + return false; + } + milliseconds = (int)Math.Max(0, deadline - Environment.TickCount64); } } finally { EndSleep(wasSleeping); @@ -574,6 +587,29 @@ private bool BeginSleep() { } } + /// + /// Whether the wait that has just ended was ended for nothing but a Thread#raise that a + /// Thread.handle_interrupt mask holds back, so that the sleep goes on: MRI's sleep_forever and + /// sleep_hrtime check interrupts and sleep again while the thread is still meant to sleep, and a + /// masked exception stays queued (Thread.pending_interrupt? is true) rather than ending + /// Thread.stop or sleep. A Thread#run or #wakeup ends the sleep as always. + /// + private bool WokenForMaskedInterrupt() { + // throws what may be delivered here and now + RubyUtils.CheckAsyncException(); + using (new RubyUtils.UninterruptedLock(_sleepLock)) { + if (_wokenByRun) { + return false; + } + if (RubyUtils.HasPendingAsyncException(_thread)) { + // drop the RunForInterrupt wake-up, if it has not been taken, or the next wait ends at once + _runSignal.Reset(); + return true; + } + return false; + } + } + /// /// Ends a sleep, and drops a Run() it did not take. Thread#raise and Thread#kill interrupt /// the thread and then Run() it, for a sleep the interrupt cannot reach yet; a Run() that @@ -587,6 +623,7 @@ private void EndSleep(bool wasSleeping) { _isSleeping = wasSleeping; if (!wasSleeping) { _runSignal.Reset(); + _wokenByRun = false; } } } @@ -594,6 +631,7 @@ private void EndSleep(bool wasSleeping) { internal void Run() { using (new RubyUtils.UninterruptedLock(_sleepLock)) { if (_isSleeping) { + _wokenByRun = true; _runSignal.Set(); } } @@ -619,6 +657,9 @@ internal void RunForInterrupt() { /// registers a waiter before it releases the mutex, so a #signal can arrive first. /// internal void Wake() { + using (new RubyUtils.UninterruptedLock(_sleepLock)) { + _wokenByRun = true; + } _runSignal.Set(); } @@ -627,6 +668,9 @@ internal void Wake() { /// out or an exception ended the wait - so that it does not cut the next sleep short. /// internal void ClearWake() { + using (new RubyUtils.UninterruptedLock(_sleepLock)) { + _wokenByRun = false; + } _runSignal.Reset(); } } From 82cf3bdc66f3e3e95432863501ea48ff53d81221 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:50:52 +0100 Subject: [PATCH 097/147] A frozen ThreadGroup takes and gives up no thread ThreadGroup#freeze changed nothing: a thread of a frozen group could start new threads, a frozen group took threads, and a thread left one. CRuby's thgroup_add refuses, in this order, a frozen group ("can't move to the frozen thread group"), an enclosed one, a thread whose group is frozen ("can't move from the frozen thread group") or enclosed - even when the thread is in the group already - and thread_create_core refuses a new thread when its creator's group is frozen ("can't start a new thread (frozen ThreadGroup)") (TestThreadGroup#test_frozen_thgroup). ThreadGroup#add and Thread.new now do the same; the messages match CRuby's. spec/core/threadgroup and spec/core/thread pass. --- Src/Libraries/Builtins/ThreadGroup.cs | 22 ++++++++++++++++------ Src/Libraries/Builtins/ThreadOps.cs | 4 ++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadGroup.cs b/Src/Libraries/Builtins/ThreadGroup.cs index ba527bd6f..b13e5dba4 100644 --- a/Src/Libraries/Builtins/ThreadGroup.cs +++ b/Src/Libraries/Builtins/ThreadGroup.cs @@ -21,18 +21,28 @@ namespace IronRuby.Builtins { public class ThreadGroup { private bool _enclosed; + /// + /// MRI's thgroup_add: a frozen or enclosed group will not take a thread, and the thread's own + /// group will not let it go if it is frozen or enclosed - in that order, and even when the thread + /// is in the group already. + /// [RubyMethod("add")] - public static ThreadGroup/*!*/ Add([NotNull]ThreadGroup/*!*/ self, [NotNull]Thread/*!*/ thread) { + public static ThreadGroup/*!*/ Add(RubyContext/*!*/ context, [NotNull]ThreadGroup/*!*/ self, [NotNull]Thread/*!*/ thread) { ThreadOps.RubyThreadInfo info = ThreadOps.RubyThreadInfo.FromThread(thread); - // An enclosed group will not let a thread leave it, and will not take one either. - ThreadGroup current = info.Group; - if (current != null && current != self && current._enclosed) { - throw new ThreadError("can't move from the enclosed thread group"); + if (context.IsObjectFrozen(self)) { + throw new ThreadError("can't move to the frozen thread group"); } - if (self._enclosed && current != self) { + if (self._enclosed) { throw new ThreadError("can't move to the enclosed thread group"); } + ThreadGroup current = info.Group ?? Default; + if (context.IsObjectFrozen(current)) { + throw new ThreadError("can't move from the frozen thread group"); + } + if (current._enclosed) { + throw new ThreadError("can't move from the enclosed thread group"); + } info.Group = self; return self; diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 18719a8d4..d11d15ac6 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -1444,6 +1444,10 @@ private static Action CreateThreadTerminator(RubyContext context) { } RubyThreadInfo creator = RubyThreadInfo.FromThread(Thread.CurrentThread); ThreadGroup group = creator.Group; + // MRI's thread_create_core: a new thread joins its creator's group, which must be able to take it + if (group != null && context.IsObjectFrozen(group)) { + throw new ThreadError("can't start a new thread (frozen ThreadGroup)"); + } ThreadStarter s = starter = new ThreadStarter(); if (context.ThreadTerminator == null) { context.ThreadTerminator = CreateThreadTerminator(context); From 3cf3f783ed3b1b4dbe47cc5a40c9e2989c79b541 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 16:58:21 +0100 Subject: [PATCH 098/147] A timed sleep answers whether it was woken again The previous commit (a masked Thread#raise does not end a sleep) took RubyThreadInfo.Sleep(ms)'s comment at its word, "returns true if the full timeout elapsed", and made it answer that. Its callers - ConditionVariable#wait, Mutex#sleep, Kernel#sleep - read the answer as "woken", which is what it always was, so a #wait that timed out answered 0 instead of nil (TestThreadConditionVariable#test_condvar_timed_wait). Sleep(ms) answers true when woken again, false on a timeout or an interrupt with nothing to deliver, as before; a timed sleep with Timeout.Infinite keeps waiting without a deadline; and the comment says what it does. test_thread_cv passes but for the deadlock test it always missed; Mutex#sleep(0.1) is nil, woken it is the seconds slept. --- Src/Libraries/Builtins/ThreadOps.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index d11d15ac6..f5e7a09e9 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -547,7 +547,8 @@ internal void Sleep() { } /// - /// Same as Sleep() but with a timeout; returns true if the full timeout elapsed. + /// Same as Sleep() but with a timeout (or Timeout.Infinite); returns false if the full timeout + /// elapsed (or an interrupt ended the sleep with nothing to deliver), true if it was woken. /// internal bool Sleep(int milliseconds) { RubyUtils.CheckAsyncException(); @@ -558,18 +559,23 @@ internal bool Sleep(int milliseconds) { long deadline = Environment.TickCount64 + milliseconds; while (true) { _inManagedWait = true; + bool woken; try { - if (!_runSignal.WaitOne(milliseconds)) { - return true; + woken = _runSignal.WaitOne(milliseconds); + if (!woken) { + return false; } } catch (ThreadInterruptedException) { _inManagedWait = wasWaiting; RubyUtils.TranslateThreadInterrupt(); + woken = false; } if (!WokenForMaskedInterrupt()) { - return false; + return woken; + } + if (milliseconds != Timeout.Infinite) { + milliseconds = (int)Math.Max(0, deadline - Environment.TickCount64); } - milliseconds = (int)Math.Max(0, deadline - Environment.TickCount64); } } finally { EndSleep(wasSleeping); From 3fd3566873830c0dde41c9ee7bf3d44993290a50 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 17:55:09 +0100 Subject: [PATCH 099/147] Regexp: only a '-' bound of a range is spelled as a code unit 0475f142 spelled the bounds of every class range as \uXXXX so that .NET would not read [\--0] as three members. Only a '-' bound needs that; the rest keep the spelling they were written in, which is what RegexTransform1 pins ([a-z] stays [a-z]) and what makes a translated pattern readable. --- Src/IronRuby.Tests/Runtime/RegexTests.cs | 2 +- Src/Ruby/Builtins/RegexpTransformer.cs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 4cc42f22a..62770c6a1 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -189,7 +189,7 @@ public void RegexTransform1() { TestCorrectPatternTranslation(@"[\001-\7]", "[\u0001-\u0007]"); TestCorrectPatternTranslation(@"[\u{2a}-\u{2b}]", "[\\*-\\+]"); TestCorrectPatternTranslation(@"[x-]", @"[x\-]"); - TestCorrectPatternTranslation(@"[---]", @"[\--\-]"); + TestCorrectPatternTranslation(@"[---]", @"[\u002d-\u002d]"); TestCorrectPatternTranslation(@"[\u{1 2 40}-\u{60 3 4}]", "[\u0001\u0002\u0040-\u0060\u0003\u0004]"); TestCorrectPatternTranslation(@"[\u{1 2 40}-\u0060]", "[\u0001\u0002\u0040-\u0060]"); TestCorrectPatternTranslation(@"[\u{1 2 40}-z]", "[\u0001\u0002\u0040-z]"); diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index 0e730abc8..86b820f84 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -2826,10 +2826,12 @@ private CharacterSet ParseCharacterGroupUnion() { // A range reaching past U+FFFF has non-BMP members, which CharacterSet emits // as surrogate pairs. ActionView's token pattern is one of these: // [0-9A-Za-z_\u0080-\u{10ffff}-]. - // The bounds are spelled as code units: .NET reads [\--0] as '-', '-' and '0' + // A '-' bound is spelled as a code unit: .NET reads [\--0] as '-', '-' and '0' // rather than as the range from '-' to '0' Onigmo makes of [--0]. - set = CharacterSet.MakeRange(low, high, (high < 0x10000) ? - "\\u" + low.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) + "-\\u" + high.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) : null); + set = CharacterSet.MakeRange(low, high, (high >= 0x10000) ? null : + (low == '-' || high == '-') ? + "\\u" + low.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) + "-\\u" + high.ToString("x4", System.Globalization.CultureInfo.InvariantCulture) : + set.Text + "-" + rangeEnd.Text); } result = result.Union(set); From acbe45ffc0959bf282dc8927874f2a1314855577 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:29:56 +0100 Subject: [PATCH 100/147] IO#dup of IO.popen(cmd, "r+") keeps its write half The copy of a two-way popen could not close_write: it raised "closing non-duplex IO for writing". IO#initialize_copy dup(2)'d only the IO's primary descriptor, the reading pipe, into a plain FileStream, so the copy was an IO that read and could not be written through its own pipe. MRI's dup of such an IO dups the tied write IO as well, so the copy reads and writes and closes either half independently (test_io's test_dup: f.dup; both write; both close_write; f.read is "foo\nbar\n"). initialize_copy now dup(2)s both pipes of a DuplexStream - the halves the IO still has open - makes them close-on-exec and builds a new DuplexStream over two DescriptorStreams, with the writer's AutoFlush carried over. If a dup fails the first one is closed and the old single-descriptor path is taken. Checked against CRuby 4.0.10: test_dup's sequence, dup after close_write and after close_read; spec/core/io, spec/core/file/stat and spec/library/stringio have the same single (expected into/to) error as before. --- Src/Libraries/Builtins/IoOps.cs | 18 ++++++++++-- Src/Ruby/Builtins/RubyIO.cs | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 974be3e4b..574ff0e09 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -262,8 +262,22 @@ public static class WaitWritable { // original and then reopening it back from the copy works - which is the whole // point of saving a stream before redirecting it. Sharing the table entry meant // the copy and the original were the same descriptor, so the save was a no-op. - int duplicated = RubyIO.TryDuplicateDescriptor(source); - if (duplicated >= 0) { + // IO.popen(cmd, "r+") reads one pipe and writes another. MRI's copy dups both (the + // write half is a second IO tied to the first), so that the copy can close_write; + // duplicating only the reading pipe made it a read-only IO that refused to. + int duplexRead, duplexWrite; + Stream duplex = RubyIO.TryDuplicateDuplex(source, out duplexRead, out duplexWrite); + int duplicated = (duplex != null) ? -1 : RubyIO.TryDuplicateDescriptor(source); + if (duplex != null) { + if (duplexRead >= 0) { + RubyProcess.SetCloseOnExec(duplexRead); + } + if (duplexWrite >= 0) { + RubyProcess.SetCloseOnExec(duplexWrite); + } + stream = duplex; + descriptor = self.Context.AllocateFileDescriptor(stream); + } else if (duplicated >= 0) { // dup(2) hands back a descriptor without FD_CLOEXEC whatever the original had; // MRI's #dup sets it, so a child never inherits a copy nobody meant to give it. RubyProcess.SetCloseOnExec(duplicated); diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index b24f1c193..d7a523ce5 100644 --- a/Src/Ruby/Builtins/RubyIO.cs +++ b/Src/Ruby/Builtins/RubyIO.cs @@ -974,6 +974,57 @@ public static int TryDuplicateDescriptor(RubyIO/*!*/ io) { return (descriptor < 0 || !_hasFileControl) ? -1 : sys_dup(descriptor); } + /// + /// dup(2) of both pipes of IO.popen(cmd, "r+"), so that a copy of it can close its + /// writing half as MRI's does (MRI's dup copies the tied write IO too). Answers null when + /// the IO is not such a pair, or when a half it still uses has no descriptor to + /// duplicate; the caller then falls back to duplicating the one descriptor. The new + /// descriptors are handed back so that the caller can make them close-on-exec. + /// + public static System.IO.Stream TryDuplicateDuplex(RubyIO/*!*/ io, out int readDescriptor, out int writeDescriptor) { + readDescriptor = writeDescriptor = -1; + var duplex = io.GetStream().BaseStream as DuplexStream; + if (duplex == null || !_hasFileControl) { + return null; + } + + bool reads = io.Mode.CanRead() && duplex.Reader != null; + bool writes = io.Mode.CanWrite() && duplex.Writer != null; + int readSource = reads ? DescriptorOf(duplex.Reader.BaseStream) : -1; + int writeSource = writes ? DescriptorOf(duplex.Writer.BaseStream) : -1; + if ((reads && readSource < 0) || (writes && writeSource < 0) || (!reads && !writes)) { + return null; + } + + if (reads) { + readDescriptor = sys_dup(readSource); + if (readDescriptor < 0) { + return null; + } + } + if (writes) { + writeDescriptor = sys_dup(writeSource); + if (writeDescriptor < 0) { + if (readDescriptor >= 0) { + sys_close(readDescriptor); + readDescriptor = -1; + } + return null; + } + } + + StreamReader reader = reads ? new StreamReader(new DescriptorStream(readDescriptor, true, false, true)) : null; + StreamWriter writer = null; + if (writes) { + writer = new StreamWriter(new DescriptorStream(writeDescriptor, false, true, true)); + writer.AutoFlush = duplex.Writer.AutoFlush; + } + return new DuplexStream(reader, writer); + } + + [DllImport("libc", EntryPoint = "close", SetLastError = true)] + private static extern int sys_close(int fd); + /// The operating system descriptor a stream reads and writes, or -1. public static int DescriptorOf(System.IO.Stream stream) { var known = stream as IDescriptorStream; From 0353f5051a58e9d622c9cde676281e894d294ce9 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:30:14 +0100 Subject: [PATCH 101/147] IO#ungetc and #ungetbyte refuse to push back past the read buffer Pushing back in a loop grew the read buffer without end: 200 ungetc's of 1000 bytes each all succeeded (test_io's test_ungetc expects an IOError). MRI's io_ungetbyte fits what is pushed back into the read buffer: its capacity is IO_RBUF_CAPA_MIN (8192) once anything was read, or the first push-back's length when that is longer and came first, and a push-back that would not fit beside the bytes already buffered raises IOError "ungetbyte failed". CRuby 4.0.10 fails the 9th of those 1000-byte ungetc's on a fresh pipe, accepts a first ungetc of 20000 bytes and then refuses one more byte. RubyBufferedStream now keeps that capacity and checks it in RequirePushBackRoom, which #ungetc (on a stream that does not convert; the character buffer already had its own limit) and #ungetbyte call before pushing anything. The prelude's #ungetbyte of a String pushes its bytes through a new __ir_ungetbytes__, so that the whole String is checked at once, as MRI does, instead of a byte at a time. The read paths that put back bytes they read themselves are unchanged. Checked against CRuby 4.0.10 with the cases above; spec/core/io, spec/core/file/stat and spec/library/stringio give the same results as before. --- Src/Libraries/Builtins/IoOps.cs | 15 ++++++++++++++- Src/Ruby/Builtins/RubyBufferedStream.cs | 23 +++++++++++++++++++++++ Src/Ruby/Builtins/RubyIO.cs | 5 +++++ Src/StdLib/ironruby/ruby4.rb | 2 +- 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 574ff0e09..f1b1c59ea 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -3263,9 +3263,21 @@ internal static void ChompLine(MutableString/*!*/ line, MutableString separator) [RubyMethod("__ir_ungetc__", RubyMethodAttributes.PrivateInstance)] public static void SetPreviousByte(RubyIO/*!*/ self, [DefaultProtocol]int b) { self.RequireByteReadable(); + self.RequirePushBackRoom(1); self.PushBack(unchecked((byte)b)); } + // #ungetbyte of a String: its bytes, all of them or none, as MRI's io_ungetbyte. + [RubyMethod("__ir_ungetbytes__", RubyMethodAttributes.PrivateInstance)] + public static void PushBackBytes(RubyIO/*!*/ self, [NotNull]MutableString/*!*/ bytes) { + self.RequireByteReadable(); + byte[] data = bytes.ToByteArray(); + if (data.Length > 0) { + self.RequirePushBackRoom(data.Length); + PushBack(self, data, 0, data.Length); + } + } + // What IO#read (ruby4.rb) puts before the rest of the stream: the text in the character // buffer, as bytes, or nil when there is none. Reading everything reaches the end of the // stream, where MRI frees the buffer. @@ -3293,7 +3305,8 @@ public static void PushBackText(RubyIO/*!*/ self, [NotNull]MutableString/*!*/ te private static void PushBackText(RubyIO/*!*/ self, byte[]/*!*/ bytes) { if (NeedsReadConversion(self)) { self.PushBackChars(bytes, 0, bytes.Length); - } else { + } else if (bytes.Length > 0) { + self.RequirePushBackRoom(bytes.Length); PushBack(self, bytes, 0, bytes.Length); } } diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index f29b18eab..b48d337d9 100644 --- a/Src/Ruby/Builtins/RubyBufferedStream.cs +++ b/Src/Ruby/Builtins/RubyBufferedStream.cs @@ -43,6 +43,13 @@ public class RubyBufferedStream : Stream { private bool _pushBackPreservesPosition; + // MRI's rbuf.capa: how many bytes the read buffer holds, unread and pushed back together. + // It is IO_RBUF_CAPA_MIN once anything was read, or the first #ungetc's length when that + // is longer and came first; 0 until then. Past it #ungetc raises, so that pushing back in + // a loop fails instead of growing the buffer forever. + private int _pushBackCapacity; + private const int MinPushBackCapacity = 8192; + // Whether something was written since the last flush or seek. Writes go straight to the // underlying stream, but MRI would still hold them in its write buffer, and that is what // IO#syswrite and IO#sysseek warn about. @@ -151,6 +158,9 @@ private int LoadBuffer(int count) { if (_buffer == null) { Debug.Assert(_bufferCount == 0 && _bufferStart == 0); _buffer = new byte[_defaultBufferSize]; + if (_pushBackCapacity == 0) { + _pushBackCapacity = MinPushBackCapacity; + } } else if (_bufferStart + _bufferCount + count > _buffer.Length) { // shift left: Buffer.BlockCopy(_buffer, _bufferStart, _buffer, 0, _bufferCount); @@ -177,6 +187,19 @@ private int ReadAheadCount { get { return _bufferCount - _pushedBackCount; } } + /// + /// MRI's io_ungetbyte: whether count more bytes fit in the read buffer beside those + /// already there; IOError "ungetbyte failed" if not. + /// + public void RequirePushBackRoom(int count) { + if (_pushBackCapacity == 0) { + _pushBackCapacity = Math.Max(count, MinPushBackCapacity); + } + if (_pushBackCapacity < _bufferCount + count) { + throw RubyExceptions.CreateIOError("ungetbyte failed"); + } + } + public void PushBack(byte b) { if (_bufferStart > 0) { _buffer[--_bufferStart] = b; diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index d7a523ce5..25a6ed8a7 100644 --- a/Src/Ruby/Builtins/RubyIO.cs +++ b/Src/Ruby/Builtins/RubyIO.cs @@ -1351,6 +1351,11 @@ public void PushBack(byte b) { GetStream().PushBack(b); } + /// #ungetc and #ungetbyte refuse to grow the read buffer past its capacity. + public void RequirePushBackRoom(int count) { + GetStream().RequirePushBackRoom(count); + } + #endregion public override string/*!*/ ToString() { diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index c5458f674..e06ff9766 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -11689,7 +11689,7 @@ def ungetbyte(byte) end byte = byte.to_str end - byte.bytes.reverse_each { |b| __ir_ungetc__(b) } + __ir_ungetbytes__(byte) end nil end unless method_defined?(:ungetbyte) From 60086dd479b17eea1eb594f4f69fbed686fa5c38 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:31:11 +0100 Subject: [PATCH 102/147] A frozen String gets a singleton class unless it is interned RubyUtils.CanDefineSingletonMethod refused every frozen String, so 'abc'.dup.freeze.singleton_class raised "can't define singleton" and `def s.foo` on such a string a TypeError. MRI's singleton_class_of refuses only an interned one (FL_FSTR): any other frozen String gets a singleton class, and defining a method in it raises FrozenError, as for any frozen object. MutableString gets an IsInterned bit, set by FreezeInterned on the strings MRI keeps in its fstring table or hands out as one: frozen string literals and everything else RubyOps.InternFrozenString shares (String#-@, Marshal.load(freeze: true)), Symbol#name, Module#name, nil/true/false.to_s, MutableString.FrozenEmpty, and the frozen copy a Hash makes of a bare String key (rb_hash_key_str; marked only, not added to the table, which is never swept). The refusal now tests that bit. String#-@ on a frozen string with a singleton class answers it as it is, as rb_fstring does with a string that is not bare, instead of putting it in the table. Checked against CRuby 4.0.10 with a script covering dup.freeze, String.new.freeze, literals with and without the magic comment, Symbol#to_s/#name, -str, hash keys, nil/true/false.to_s, Module#name, Marshal freeze: and def/define_singleton_method/extend on a frozen string (same output); ruby/spec core/string, core/kernel, core/symbol, core/hash, core/marshal, language/def and singleton_class show no new failures. --- Src/Libraries/Builtins/FalseClass.cs | 2 +- Src/Libraries/Builtins/MutableStringOps.cs | 7 ++++++- Src/Libraries/Builtins/NilClassOps.cs | 2 +- Src/Libraries/Builtins/TrueClass.cs | 2 +- Src/Ruby/Builtins/MutableString.cs | 20 +++++++++++++++++++- Src/Ruby/Builtins/RubyModule.cs | 4 ++-- Src/Ruby/Builtins/RubySymbol.cs | 2 +- Src/Ruby/Runtime/RubyOps.cs | 2 +- Src/Ruby/Runtime/RubyUtils.cs | 12 ++++++++++-- 9 files changed, 42 insertions(+), 11 deletions(-) diff --git a/Src/Libraries/Builtins/FalseClass.cs b/Src/Libraries/Builtins/FalseClass.cs index 52235f1bb..5a553a41c 100644 --- a/Src/Libraries/Builtins/FalseClass.cs +++ b/Src/Libraries/Builtins/FalseClass.cs @@ -24,7 +24,7 @@ public static class FalseClass : Object { #region Public Instance Methods /// One frozen string, answered again every time - as in MRI. - private static readonly MutableString/*!*/ _FalseString = MutableString.CreateAscii("false").Freeze(); + private static readonly MutableString/*!*/ _FalseString = MutableString.CreateAscii("false").FreezeInterned(); [RubyMethodAttribute("to_s")] [RubyMethodAttribute("inspect")] diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 462ea99d9..7166d556f 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1776,7 +1776,12 @@ private static MutableString CaseMapInPlace(MutableString/*!*/ self, CaseMapping // frozen string literals and "literal".freeze come from, so -str can answer the very // object a literal evaluates to. [RubyMethod("__ir_fstring__", RubyMethodAttributes.PrivateInstance)] - public static MutableString/*!*/ InternFrozen(MutableString/*!*/ self) { + public static MutableString/*!*/ InternFrozen(RubyContext/*!*/ context, MutableString/*!*/ self) { + // A frozen string with a singleton class is not bare: MRI's rb_fstring answers it + // as it is, without putting it in the table (where it would be refused one). + if (self.IsFrozen && context.GetImmediateClassOf(self).IsSingletonClass) { + return self; + } return RubyOps.InternFrozenString(self.IsFrozen ? self : self.Clone()); } diff --git a/Src/Libraries/Builtins/NilClassOps.cs b/Src/Libraries/Builtins/NilClassOps.cs index 8b8e175ac..64573a10e 100644 --- a/Src/Libraries/Builtins/NilClassOps.cs +++ b/Src/Libraries/Builtins/NilClassOps.cs @@ -106,7 +106,7 @@ public static MutableString Inspect(object self) { /// a spec checks that two calls hand back the very same one. /// // US-ASCII, as MRI's nil.to_s is - private static readonly MutableString/*!*/ _EmptyString = MutableString.Create(String.Empty, RubyEncoding.Ascii).Freeze(); + private static readonly MutableString/*!*/ _EmptyString = MutableString.Create(String.Empty, RubyEncoding.Ascii).FreezeInterned(); [RubyMethodAttribute("to_s")] public static MutableString/*!*/ ToString(object self) { diff --git a/Src/Libraries/Builtins/TrueClass.cs b/Src/Libraries/Builtins/TrueClass.cs index c4c8cddef..bad299f81 100644 --- a/Src/Libraries/Builtins/TrueClass.cs +++ b/Src/Libraries/Builtins/TrueClass.cs @@ -24,7 +24,7 @@ public static class TrueClass : Object { #region Public Instance Methods /// One frozen string, answered again every time - as in MRI. - private static readonly MutableString/*!*/ _TrueString = MutableString.CreateAscii("true").Freeze(); + private static readonly MutableString/*!*/ _TrueString = MutableString.CreateAscii("true").FreezeInterned(); [RubyMethodAttribute("to_s")] [RubyMethodAttribute("inspect")] diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index d373aabd8..f1f60cb4f 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -135,6 +135,11 @@ private int SharedAsciiChar { // so nothing beyond the bit has to be remembered. private const uint IsChilledSymbolStringFlag = 1 << 13; + // In MRI's fstring table (RubyOps.InternFrozenString), or one of the frozen strings the + // runtime hands out from a static (nil.to_s, Symbol#name): MRI refuses such a string a + // singleton class ("can't define singleton"), which it gives any other frozen String. + private const uint IsInternedFlag = 1 << 15; + private const uint MutationGuardFlags = IsFrozenFlag | CopyOnWriteFlag | IsChilledFlag | IsTemporarilyLockedFlag; @@ -148,7 +153,7 @@ private int SharedAsciiChar { // The instance is frozen so that it can be shared, but it should not be used in places where // it will be accessible from user code as the user code could try to mutate it. - public static readonly MutableString FrozenEmpty = CreateEmpty().Freeze(); + public static readonly MutableString FrozenEmpty = CreateEmpty().FreezeInterned(); #region Constructors @@ -1198,6 +1203,19 @@ void IRubyObjectState.Freeze() { return this; } + /// + /// Freezes the string and marks it interned: it is shared - by the fstring table, or by a + /// static every runtime reads - and so can have no singleton class (see IsInternedFlag). + /// + public MutableString/*!*/ FreezeInterned() { + _flags |= IsFrozenFlag | IsInternedFlag; + return this; + } + + public bool IsInterned { + get { return (_flags & IsInternedFlag) != 0; } + } + public void RequireNotFrozen() { if (IsFrozen) { throw RubyExceptions.CreateStringFrozenError(this); diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 356371987..16c7c94c9 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -4172,12 +4172,12 @@ public MutableString GetNameString(RubyContext/*!*/ context) { // another runtime sees the name decorated with the runtime id; not worth caching if (context != _context) { - return MutableString.CreateMutable(GetName(context), context.GetIdentifierEncoding()).Freeze(); + return MutableString.CreateMutable(GetName(context), context.GetIdentifierEncoding()).FreezeInterned(); } var result = _nameString; if (result == null) { - _nameString = result = MutableString.CreateMutable(_name, context.GetIdentifierEncoding()).Freeze(); + _nameString = result = MutableString.CreateMutable(_name, context.GetIdentifierEncoding()).FreezeInterned(); } return result; } diff --git a/Src/Ruby/Builtins/RubySymbol.cs b/Src/Ruby/Builtins/RubySymbol.cs index 10697bbfa..5aa5dee49 100644 --- a/Src/Ruby/Builtins/RubySymbol.cs +++ b/Src/Ruby/Builtins/RubySymbol.cs @@ -44,7 +44,7 @@ public Proc MethodInvoker { /// The String Symbol#name answers - one per symbol, frozen. public MutableString/*!*/ FrozenName { - get { return _frozenName ?? (_frozenName = MutableString.Create(_string).Freeze()); } + get { return _frozenName ?? (_frozenName = MutableString.Create(_string).FreezeInterned()); } } internal RubySymbol(MutableString/*!*/ str, int id, int runtimeId) { diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 9cab79818..6ae758e27 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -3364,7 +3364,7 @@ public int GetHashCode(MutableString str) { } private static MutableString/*!*/ InternFrozenStringLiteral(MutableString/*!*/ str) { - return _frozenStringLiterals.GetOrAdd(str.Freeze(), str); + return _frozenStringLiterals.GetOrAdd(str.FreezeInterned(), str); } /// diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index c04730e3d..c257e133d 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -177,8 +177,11 @@ public static bool CanDefineSingletonMethod(object obj) { return false; } + // MRI refuses only an interned String (rb_special_singleton_class_of's FL_FSTR test): + // any other frozen one gets a singleton class, and defining a method in it raises + // FrozenError. var str = obj as MutableString; - return str == null || !str.IsFrozen; + return str == null || !str.IsInterned; } public static void RequireDefinableSingleton(object obj) { @@ -1355,7 +1358,12 @@ public static object SetHashElement(RubyContext/*!*/ context, IDictionary Date: Sun, 22 Nov 2026 18:31:14 +0100 Subject: [PATCH 103/147] File::Stat can be allocated, copied and reinitialized File::Stat had no allocator: File::Stat.allocate raised "allocator undefined", and with it every path that allocates first - #dup and #clone of a stat, and #initialize_copy called on an existing stat (test_file's test_uninitialized, test_file_exhaustive's test_stat_init, test_object's test_bad_initialize_copy for File.stat). In CRuby 4.0.10 File::Stat.allocate gives an uninitialized stat whose readers raise TypeError "uninitialized File::Stat" and whose #inspect is "#"; #initialize stats a path into it, #initialize_copy copies another File::Stat (TypeError "initialize_copy should take same class object" otherwise, FrozenError on a frozen receiver). StatInfo, the object behind File::Stat, gets a public parameterless constructor - the allocator - and its stat result becomes assignable. Every reader already goes through D() or L(), which now refuse an uninitialized stat; #initialize, #initialize_copy and the uninitialized #inspect are added. Checked against CRuby 4.0.10 for each case above; the three CRuby tests pass (test_bad_initialize_copy now stops at the Regexp case, past File.stat); spec/core/file/stat has no failures. --- Src/Libraries/Builtins/FileOps.cs | 69 ++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 29e93ccfe..c562abc33 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1898,18 +1898,37 @@ private static MutableString GetPath(RubyFile/*!*/ self) { /// is unavailable) File::Stat keeps using bare FileInfo/DirectoryInfo /// and the legacy approximations below. /// - internal sealed class StatInfo : FileSystemInfo { - internal readonly Posix.StatData Data; + public sealed class StatInfo : FileSystemInfo { + // Not readonly: File::Stat.allocate makes one with neither, which #initialize or + // #initialize_copy fills in later, as MRI's stat_memsize/rb_stat_init_copy do. + internal Posix.StatData Data; // Off Unix there is no statx result to hold, so the FileInfo/DirectoryInfo the // old implementation used rides along instead. File::Stat is this class either // way, which is what makes File.stat(...).instance_of?(File::Stat) true. - internal readonly FileSystemInfo Legacy; + internal FileSystemInfo Legacy; // Off Unix: an lstat of a symbolic link (or junction), which the BCL object cannot say // by itself - File.symlink? and File.lstat(...).symlink? read it. internal bool IsLink; + /// File::Stat.allocate: a stat of nothing yet, which every reader refuses. + public StatInfo() { + OriginalPath = FullPath = ""; + } + + internal bool IsInitialized { + get { return Data != null || Legacy != null; } + } + + internal void CopyFrom(StatInfo/*!*/ other) { + Data = other.Data; + Legacy = other.Legacy; + IsLink = other.IsLink; + OriginalPath = other.OriginalPath; + FullPath = other.FullPath; + } + internal StatInfo(string/*!*/ path, Posix.StatData/*!*/ data) { Data = data; OriginalPath = path; @@ -2114,13 +2133,21 @@ private static FileSystemInfo TryGetLink(string/*!*/ path) { private static Posix.StatData D(FileSystemInfo/*!*/ self) { var si = self as StatInfo; - return si != null ? si.Data : null; + return si != null ? Initialized(si).Data : null; } /// The System.IO object behind an off-Unix File::Stat, if there is one. private static FileSystemInfo L(FileSystemInfo self) { var si = self as StatInfo; - return si != null ? si.Legacy : self; + return si != null ? Initialized(si).Legacy : self; + } + + // MRI's get_stat: a File::Stat that File::Stat.allocate made and nothing filled in. + private static StatInfo/*!*/ Initialized(StatInfo/*!*/ self) { + if (!self.IsInitialized) { + throw RubyExceptions.CreateTypeError("uninitialized File::Stat"); + } + return self; } [RubyConstructor] @@ -2128,6 +2155,34 @@ private static FileSystemInfo L(FileSystemInfo self) { return Create(self.Context, Protocols.CastToPath(toPath, path)); } + // Only reached by an instance File::Stat.allocate made (File::Stat.new is the + // constructor above); MRI's rb_stat_init stats the path into it. + [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] + public static StatInfo/*!*/ Reinitialize(ConversionStorage/*!*/ toPath, StatInfo/*!*/ self, object path) { + RubyContext context = toPath.Context; + FileSystemInfo info = Create(context, Protocols.CastToPath(toPath, path)); + var stat = info as StatInfo ?? new StatInfo(info); + self.CopyFrom(stat); + return self; + } + + // MRI's rb_stat_init_copy: the copy answers what the original does. + [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)] + public static StatInfo/*!*/ InitializeCopy(RubyContext/*!*/ context, StatInfo/*!*/ self, object other) { + if (ReferenceEquals(self, other)) { + return self; + } + if (context.IsObjectFrozen(self)) { + throw RubyExceptions.CreateObjectFrozenError(context, self); + } + var source = other as StatInfo; + if (source == null || context.GetClassOf(other) != context.GetClassOf(self)) { + throw RubyExceptions.CreateTypeError("initialize_copy should take same class object"); + } + self.CopyFrom(source); + return self; + } + [RubyMethod("<=>")] public static int Compare(FileSystemInfo/*!*/ self, [NotNull]FileSystemInfo/*!*/ other) { var a = D(self); @@ -2538,6 +2593,10 @@ public static bool IsZeroLength(FileSystemInfo/*!*/ self) { [RubyMethod("inspect")] public static MutableString/*!*/ Inspect(RubyContext/*!*/ context, FileSystemInfo/*!*/ self) { + var si = self as StatInfo; + if (si != null && !si.IsInitialized) { + return MutableString.CreateAscii("#<" + context.GetClassName(self) + ": uninitialized>"); + } return MutableString.CreateAscii(String.Format(CultureInfo.InvariantCulture, "#", FormatDev(DeviceId(self)), From 96d099523be3d1dfc6eb54ad79008af259441fcd Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:35:27 +0100 Subject: [PATCH 104/147] cruby-test runner loads tempfile, as CRuby's init.rb does test_enum's test_sum builds a SimpleDelegator without requiring delegate. It works on CRuby because tool/test/init.rb loads iseq_loader_checker, whose first lines require tempfile (and with it delegate) before it touches RubyVM. runner.rb leaves that checker out, so the test failed with NameError on IronRuby only. The runner now requires tempfile itself. test_sum passes; the rest of test_enum is unchanged. --- Util/cruby-test/runner.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Util/cruby-test/runner.rb b/Util/cruby-test/runner.rb index fe35af7ea..1bca4c859 100644 --- a/Util/cruby-test/runner.rb +++ b/Util/cruby-test/runner.rb @@ -21,6 +21,9 @@ $LOAD_PATH.push File.expand_path("lib", __dir__) require 'test/unit' +# CRuby's init.rb loads iseq_loader_checker, which requires tempfile before it reaches for +# RubyVM, and so delegate: test_enum's test_sum uses SimpleDelegator without requiring it. +require 'tempfile' # The leak checker reports file descriptors, threads and Tempfiles a test left behind. It only # prints, it fails no test, and it finds the owners with ObjectSpace.each_object(IO), which From e485005ba2ae669ac59f677e561b07a03ec0b7bd Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:45:29 +0100 Subject: [PATCH 105/147] Time, Thread#raise and two message helpers call through their runtime's sites RubyTimeOps kept its dynamic call sites (to_r, to_int, <=>, >, <, utc_to_local, find_timezone, dst?...) in static fields, and so did ThreadOps (exception, for Thread#raise), RubyExceptions (Module#name in NameError messages) and RubyUtils (instance_variables_to_inspect). A site is bound to the RubyContext that made it, and several runtimes can share a process (hosting, IronRuby.create_engine): every runtime after the first called through the first one's site, which resolved methods of CLR-backed values (Integer, Float...) in the first runtime's classes and kept that runtime alive. With engine 2 redefining Integer#> and Integer#<, Time.at(0) <=> obj, whose #<=> answers 5, gave -1 there instead of 1. They now use RubyContext.GetOrCreateSendSite, the runtime's own table of sites by name and signature, as KernelOps#send and others already do. No other static CallSite fields are left in Src/Libraries or Src/Ruby (the remaining static helpers take the site as an argument or make context-free shared actions). HostingTimeSitesPerRuntime1 is the case above with two engines; it and ConstantCaching_CrossRuntime1 pass. ruby/spec core/time, core/marshal, core/exception, core/thread/raise, core/kernel/inspect show no new failures, and test_time has none either. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/HostingTests.cs | 27 +++++++++ Src/Libraries/Builtins/RubyTimeOps.cs | 69 ++++++++-------------- Src/Libraries/Builtins/ThreadOps.cs | 4 +- Src/Ruby/Runtime/RubyExceptions.cs | 5 +- Src/Ruby/Runtime/RubyUtils.cs | 6 +- 6 files changed, 60 insertions(+), 52 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0841f56ec..c248c78dc 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -760,6 +760,7 @@ public Tests(Driver/*!*/ driver) { ClrClosedInterfaceExtensions2, HostingDefaultOptions1, HostingEncodingOption1, + HostingTimeSitesPerRuntime1, Interactive1, Interactive2, diff --git a/Src/IronRuby.Tests/Runtime/HostingTests.cs b/Src/IronRuby.Tests/Runtime/HostingTests.cs index 6603852ff..629dd74de 100644 --- a/Src/IronRuby.Tests/Runtime/HostingTests.cs +++ b/Src/IronRuby.Tests/Runtime/HostingTests.cs @@ -507,6 +507,33 @@ public void HostingDefaultOptions1() { AssertExceptionThrown(() => Engine.Execute("}")); } + /// + /// The call sites Time's methods make their dynamic calls through belong to the runtime + /// that calls them. They were statics, bound to the first runtime to get there: a second + /// one in the process saw the first one's Integer#> when Time#<=> read the answer of + /// the other object's #<=>. + /// + public void HostingTimeSitesPerRuntime1() { + const string code = @" +class Other + def <=>(o) = 5 +end +Time.at(0) <=> Other.new +"; + var engine1 = Ruby.CreateEngine(); + var engine2 = Ruby.CreateEngine(); + Assert((int)engine1.Execute(code) == -1); + + engine2.Execute(@" +class Integer + def >(o) = false + def <(o) = true +end +"); + Assert((int)engine2.Execute(code) == 1); + Assert((int)engine1.Execute(code) == -1); + } + /// /// -E takes "locale" besides the names of real encodings, as MRI's does; "external" and /// "filesystem", which Encoding.find knows, are unknown encoding names there. diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 436498259..7b78784c8 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -38,28 +38,15 @@ public static class RubyTimeOps { #region Dynamic call helpers - private static CallSite> _numeratorSite; - private static CallSite> _denominatorSite; - private static CallSite> _toRSite; - private static CallSite> _toIntSite; - private static CallSite> _toStrSite; - private static CallSite> _toISite; - private static CallSite> _localToUtcSite; - private static CallSite> _utcToLocalSite; - private static CallSite> _compareSite; - private static CallSite> _greaterSite; - private static CallSite> _lessSite; - private static CallSite> _findTimezoneSite; - private static CallSite> _abbrSite; - private static CallSite> _nameSite; - - private static object Invoke(RubyContext/*!*/ context, ref CallSite> site, string/*!*/ name, object target) { - var s = RubyUtils.GetCallSite(ref site, context, name, 0); + // The sites are the runtime's own (RubyContext.GetOrCreateSendSite), not statics: a site is + // bound to the RubyContext that made it, and several runtimes can share the process. + private static object Invoke(RubyContext/*!*/ context, string/*!*/ name, object target) { + var s = context.GetOrCreateSendSite>(name, RubyCallSignature.WithImplicitSelf(0)); return s.Target(s, target); } - private static object Invoke(RubyContext/*!*/ context, ref CallSite> site, string/*!*/ name, object target, object arg) { - var s = RubyUtils.GetCallSite(ref site, context, name, 1); + private static object Invoke(RubyContext/*!*/ context, string/*!*/ name, object target, object arg) { + var s = context.GetOrCreateSendSite>(name, RubyCallSignature.WithImplicitSelf(1)); return s.Target(s, target, arg); } @@ -69,19 +56,17 @@ private static bool RespondTo(RubyContext/*!*/ context, object obj, string/*!*/ } // MRI's rb_check_funcall and rb_respond_to ask #respond_to?, and so see a method an // object answers through method_missing and respond_to_missing? (a SimpleDelegator). - var site = RubyUtils.GetCallSite(ref _respondToSite, context, "respond_to?", 2); + var site = context.GetOrCreateSendSite>( + "respond_to?", RubyCallSignature.WithImplicitSelf(2)); return Protocols.IsTrue(site.Target(site, obj, context.EncodeIdentifier(name), true)); } - private static CallSite> _respondToSite; - private static CallSite> _toSSite; - /// /// num_exact_fail's "can't convert X into an exact number": X is the class of the value as /// %PRIsVALUE prints it, through #to_s, so that a class with a name of its own shows it. /// private static Exception/*!*/ MakeExactNumberError(RubyContext/*!*/ context, object value) { - object name = Invoke(context, ref _toSSite, "to_s", context.GetClassOf(value)); + object name = Invoke(context, "to_s", context.GetClassOf(value)); return RubyExceptions.CreateTypeError("can't convert {0} into an exact number", name is MutableString ? name.ToString() : context.GetClassName(value)); } @@ -151,8 +136,8 @@ private static bool IsRational(RubyContext/*!*/ context, object value) { } private static ExactNum FromRational(RubyContext/*!*/ context, object value) { - object n = Invoke(context, ref _numeratorSite, "numerator", value); - object d = Invoke(context, ref _denominatorSite, "denominator", value); + object n = Invoke(context, "numerator", value); + object d = Invoke(context, "denominator", value); return ExactNum.Make(ToBigInteger(n), ToBigInteger(d)); } @@ -170,7 +155,7 @@ internal static ExactNum ToExact(RubyContext/*!*/ context, object value) { } if (value != null && !(value is MutableString) && RespondTo(context, value, "to_r") && RespondTo(context, value, "to_int")) { - object converted = Invoke(context, ref _toRSite, "to_r", value); + object converted = Invoke(context, "to_r", value); if (TryToExactSimple(converted, out result)) { return result; } @@ -178,7 +163,7 @@ internal static ExactNum ToExact(RubyContext/*!*/ context, object value) { return FromRational(context, converted); } } else if (value != null && !(value is MutableString) && RespondTo(context, value, "to_int")) { - object converted = Invoke(context, ref _toIntSite, "to_int", value); + object converted = Invoke(context, "to_int", value); if (TryToExactSimple(converted, out result)) { return result; } @@ -256,7 +241,7 @@ private static bool TryParseOffsetString(RubyContext/*!*/ context, object value, if (value == null || value is RubyTime || !RespondTo(context, value, "to_str")) { return false; } - str = Invoke(context, ref _toStrSite, "to_str", value) as MutableString; + str = Invoke(context, "to_str", value) as MutableString; if (str == null) { return false; } @@ -365,7 +350,7 @@ private static RubyTimeZoneKind ResolveZone(RubyContext/*!*/ context, RubyClass // A subclass may provide .find_timezone to turn a name into a timezone object. bool nameLike = zone is MutableString; if (nameLike && owner != null && RespondTo(context, owner, "find_timezone")) { - object found = Invoke(context, ref _findTimezoneSite, "find_timezone", owner, zone); + object found = Invoke(context, "find_timezone", owner, zone); if (found != null) { zoneObject = found; return RubyTimeZoneKind.FixedOffset; @@ -394,7 +379,7 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) return time.Seconds; } if (value != null && RespondTo(context, value, "to_i")) { - return (long)ToExact(context, Invoke(context, ref _toISite, "to_i", value)).Floor(); + return (long)ToExact(context, Invoke(context, "to_i", value)).Floor(); } throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(value)); } @@ -409,7 +394,7 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) } var utcView = new RubyTime(instant.Seconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero); - object mapped = Invoke(context, ref _utcToLocalSite, "utc_to_local", zoneObject, utcView); + object mapped = Invoke(context, "utc_to_local", zoneObject, utcView); RubyTime mappedTime = mapped as RubyTime; long localSeconds = (mappedTime != null) @@ -426,8 +411,6 @@ private static long ZoneResultToSeconds(RubyContext/*!*/ context, object value) return result; } - private static CallSite> _dstSite; - /// /// MRI's zone_set_dst: a Time with a timezone object is dst? when the zone's #dst?, given the /// wall-clock reading, says so - and not when the zone has no #dst?. @@ -436,7 +419,7 @@ private static bool AskZoneDst(RubyContext/*!*/ context, object/*!*/ zoneObject, if (!RespondTo(context, zoneObject, "dst?")) { return false; } - return Protocols.IsTrue(Invoke(context, ref _dstSite, "dst?", zoneObject, wallClock)); + return Protocols.IsTrue(Invoke(context, "dst?", zoneObject, wallClock)); } #endregion @@ -808,7 +791,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { MutableString str = value as MutableString; if (str == null && !(value is int) && value != null && RespondTo(context, value, "to_str")) { - str = Invoke(context, ref _toStrSite, "to_str", value) as MutableString; + str = Invoke(context, "to_str", value) as MutableString; } if (str != null) { @@ -916,7 +899,7 @@ private static int GetMonth(RubyContext/*!*/ context, object value) { } var asUtc = new RubyTime(wallSeconds, ExactNum.Zero, RubyTimeZoneKind.Utc, ExactNum.Zero); - long utcSeconds = ZoneResultToSeconds(context, Invoke(context, ref _localToUtcSite, "local_to_utc", zoneObject, asUtc)); + long utcSeconds = ZoneResultToSeconds(context, Invoke(context, "local_to_utc", zoneObject, asUtc)); long offsetSeconds = wallSeconds - utcSeconds; if (offsetSeconds <= -86400 || offsetSeconds >= 86400) { @@ -1144,7 +1127,7 @@ private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, i // A timezone object names itself. One that cannot - no #name method - takes // the whole time down with it, which is what MRI does too. context.SetInstanceVariable(result, "zone", - Invoke(context, ref _nameSite, "name", self.ZoneObject)); + Invoke(context, "name", self.ZoneObject)); } else { // A time made with a numeric offset has no zone to name, and MRI writes nil. // On Windows the name is the localized one ("Mitteleuropäische Zeit"), as in #zone. @@ -1188,7 +1171,7 @@ private static int GetYear(RubyContext/*!*/ context, object[]/*!*/ components, i if (zoneName != null && RespondTo(context, owner, "find_timezone")) { object found; try { - found = Invoke(context, ref _findTimezoneSite, "find_timezone", owner, zoneName); + found = Invoke(context, "find_timezone", owner, zoneName); } catch (Exception e) when (!(e is StackUnwinder) && context.IsInstanceOf(e, context.StandardErrorClass)) { found = null; } @@ -1401,17 +1384,17 @@ public static object CompareTo(RubyContext/*!*/ context, RubyTime/*!*/ self, obj } // MRI asks the other object to compare itself against us and inverts the answer. - object result = Invoke(context, ref _compareSite, "<=>", other, self); + object result = Invoke(context, "<=>", other, self); if (result == null) { return null; } - object greater = Invoke(context, ref _greaterSite, ">", result, ScriptingRuntimeHelpers.Int32ToObject(0)); + object greater = Invoke(context, ">", result, ScriptingRuntimeHelpers.Int32ToObject(0)); if (RubyOps.IsTrue(greater)) { return ScriptingRuntimeHelpers.Int32ToObject(-1); } - object less = Invoke(context, ref _lessSite, "<", result, ScriptingRuntimeHelpers.Int32ToObject(0)); + object less = Invoke(context, "<", result, ScriptingRuntimeHelpers.Int32ToObject(0)); if (RubyOps.IsTrue(less)) { return ScriptingRuntimeHelpers.Int32ToObject(1); } @@ -1876,7 +1859,7 @@ internal static string GetZoneAbbreviation(RubyContext/*!*/ context, RubyTime/*! return zoneName.ConvertToString(); } if (zoneObject != null && RespondTo(context, zoneObject, "abbr")) { - var abbr = Invoke(context, ref _abbrSite, "abbr", zoneObject, self) as MutableString; + var abbr = Invoke(context, "abbr", zoneObject, self) as MutableString; if (abbr != null) { return abbr.ConvertToString(); } diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index f5e7a09e9..0faffdb5f 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -1089,8 +1089,6 @@ public static object Priority(Thread/*!*/ self, [DefaultProtocol]int priority) { #endregion #region raise, fail - private static CallSite> _exceptionSite; - private static void RaiseAsyncException(RubyContext/*!*/ context, Thread thread, Exception exception) { // MRI delivers the interrupt to the thread's running fiber, and each fiber here is a // CLR thread of its own. @@ -1131,7 +1129,7 @@ private static void RaiseAsyncException(RubyContext/*!*/ context, Thread thread, // rethrow semantics, preserves the backtrace associated with the exception: RubyUtils.ParkAsyncException(thread, exception, e => { // MRI raises exception.exception in the target thread - var site = RubyUtils.GetCallSite(ref _exceptionSite, context, "exception", 0); + var site = context.GetOrCreateSendSite>("exception", RubyCallSignature.WithImplicitSelf(0)); return site.Target(site, e) as Exception; }); } diff --git a/Src/Ruby/Runtime/RubyExceptions.cs b/Src/Ruby/Runtime/RubyExceptions.cs index b8cb8a955..5a513954b 100644 --- a/Src/Ruby/Runtime/RubyExceptions.cs +++ b/Src/Ruby/Runtime/RubyExceptions.cs @@ -653,8 +653,6 @@ private static bool IsTooBigToInspect(object/*!*/ obj) { return "an instance of " + MessageTypeName(className); } - private static CallSite> _NameSite; - /// /// What the module answers to #name, which is what MRI builds this message out of - a /// class can define its own #name and MRI shows that one. The built-in #name is not @@ -676,7 +674,8 @@ private static string RubyName(RubyContext/*!*/ context, RubyModule/*!*/ module) _disableMethodMissingMessageFormatting = true; try { - var site = RubyUtils.GetCallSite(ref _NameSite, context, "name", 0); + // the runtime's own site: a static one would stay bound to the first runtime + var site = context.GetOrCreateSendSite>("name", RubyCallSignature.WithImplicitSelf(0)); var name = site.Target(site, module) as MutableString; return (name != null) ? name.ConvertToString() : null; } catch (Exception) { diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index c257e133d..4af0962fb 100644 --- a/Src/Ruby/Runtime/RubyUtils.cs +++ b/Src/Ruby/Runtime/RubyUtils.cs @@ -198,8 +198,6 @@ public static bool HasSingletonClass(object obj) { } - private static CallSite> _InstanceVariablesToInspectSite; - /// /// Ruby 4.0 lets an object name the instance variables its #inspect shows, by answering an /// array of names from a private #instance_variables_to_inspect. A name that the object @@ -228,7 +226,9 @@ public static bool HasSingletonClass(object obj) { return vars; } - var site = GetCallSite(ref _InstanceVariablesToInspectSite, context, "instance_variables_to_inspect", 0); + // the runtime's own site: a static one would stay bound to the first runtime + var site = context.GetOrCreateSendSite>( + "instance_variables_to_inspect", RubyCallSignature.WithImplicitSelf(0)); object names = site.Target(site, obj); if (names == null) { return vars; From 51c4b29a7c1e7bc4acdb492f3cfad61304a00519 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:45:34 +0100 Subject: [PATCH 106/147] Time.new converts precision: before it parses the string Time.new(str, precision: obj) parsed str first and converted obj afterwards. MRI's time_init_parse converts the precision first, and that conversion can change the string: test_time's test_new_from_string_modified_by_precision has #to_int clear it and expects "can't parse: \"\"", where IronRuby reported the original string's malformed seconds. The precision is now read before the string is. Checked against CRuby 4.0.10 (that case, a String precision with a bad and with a good time string, and a precision cutting the fraction short: same output); test_time passes the test, and ruby/spec core/time shows no new failures. --- Src/Libraries/Builtins/RubyTimeOps.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Src/Libraries/Builtins/RubyTimeOps.cs b/Src/Libraries/Builtins/RubyTimeOps.cs index 7b78784c8..a05c65113 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -619,12 +619,8 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ throw RubyExceptions.CreateArgumentError("time string should have ASCII compatible encoding"); } - string text = str.ConvertToString(); - int year, month = 1, day = 1, hour = 0, minute = 0; - ExactNum second = ExactNum.Zero; - string fraction = null, zoneText = null; - ParseTimeText(context, str, text, out year, ref month, ref day, ref hour, ref minute, ref second, ref fraction, ref zoneText); - + // MRI's time_init_parse converts precision: before it reads the string, which the + // conversion can change (#to_int may even clear it). int precision = 9; bool precisionGiven; object precisionValue = GetOption(options, "precision", out precisionGiven); @@ -638,6 +634,12 @@ private static void RequireUninitialized(RubyContext/*!*/ context, RubyTime/*!*/ } } + string text = str.ConvertToString(); + int year, month = 1, day = 1, hour = 0, minute = 0; + ExactNum second = ExactNum.Zero; + string fraction = null, zoneText = null; + ParseTimeText(context, str, text, out year, ref month, ref day, ref hour, ref minute, ref second, ref fraction, ref zoneText); + if (fraction != null) { string digits = fraction; if (precision >= 0 && digits.Length > precision) { From 9e372880744b211e304510134ae5294d136ccba6 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:45:34 +0100 Subject: [PATCH 107/147] Time#strftime raises ERANGE for a width it cannot hold A width such as "%2147483647z" made Strftime pad to two billion characters and the process ran out of memory (NoMemoryError at best). MRI grows its buffer to at most strftime_size_limit - 1 MiB per byte of the format - and raises Errno::ERANGE naming the format beyond it ("Numerical result out of range - %2147483647z"); a width past INT_MAX makes the directive an unknown one, copied through verbatim. Strftime now checks the room a directive will take (twice the width on top of what is written, as NEEDS does) against that limit before padding, for the directives that pad: a known one, where '-' turns the padding of numbers and names off but not of %N, %L, %z and the compound directives. A width that does not fit an int copies the directive through. Checked against CRuby 4.0.10 with 20 formats (INT_MAX and smaller widths on z, Y, d, S, c, N, L, A, an unknown directive, '-' and '_' flags, %E/%O combinations, a width past INT_MAX): same output. test_time's test_strftime_padding passes; ruby/spec core/time shows no new failures. --- Src/Libraries/Builtins/Strftime.cs | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Src/Libraries/Builtins/Strftime.cs b/Src/Libraries/Builtins/Strftime.cs index 1ee55ffae..6b9f52602 100644 --- a/Src/Libraries/Builtins/Strftime.cs +++ b/Src/Libraries/Builtins/Strftime.cs @@ -95,10 +95,14 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, while (i < format.Length && format[i] >= '0' && format[i] <= '9') { i++; } + bool widthTooBig = false; if (i > widthStart) { int width; if (Int32.TryParse(format.Substring(widthStart, i - widthStart), NumberStyles.None, CultureInfo.InvariantCulture, out width)) { modifiers.Width = width; + } else { + // MRI: a width past INT_MAX makes the directive an unknown one + widthTooBig = true; } } @@ -124,6 +128,19 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, char directive = format[i]; i++; + if (widthTooBig) { + result.Append(format.Substring(start, i - start)); + continue; + } + + if (modifiers.Width > 0 && PadsToWidth(directive, modifiers) && + result.Length + 2L * modifiers.Width > SizeLimit(format.Length)) { + // MRI's strftime grows its buffer to at most strftime_size_limit and raises + // ERANGE, naming the format, rather than going on: "%2147483647d" would + // otherwise ask for a 4 GB string. + throw RubyExceptions.CreateErrno(context, RubyErrno.GetNumber("ERANGE"), format); + } + string piece = FormatDirective(context, time, directive, modifiers, modifiers.Width, depth); if (piece == null) { // Unknown directive: Ruby copies the whole thing through verbatim. @@ -134,6 +151,29 @@ internal static void Format(RubyContext/*!*/ context, MutableString/*!*/ result, } } + /// + /// MRI's strftime_size_limit: 1 MiB of output for each byte of the format, 1 KiB at least. + /// + private static long SizeLimit(int formatLength) { + return Math.Max(1024L, formatLength * (1024L * 1024L)); + } + + /// + /// Whether the directive makes room for its width (MRI's NEEDS(precision)): a known one, + /// except that '-' turns the padding of a number or a name off. %N, %L, %z and the + /// compound directives take the width whatever the flags. + /// + private static bool PadsToWidth(char directive, Modifiers modifiers) { + if (modifiers.Colons > 0 && directive != 'z' || + modifiers.Alt == 'E' && "cCxXyY".IndexOf(directive) < 0 || modifiers.Alt == 'O' && "deHImMSuUVwWy".IndexOf(directive) < 0) { + return false; + } + if ("NLzcDxFrRTXv".IndexOf(directive) >= 0) { + return true; + } + return modifiers.Pad != '-' && "%ntaAhbBpPCdeHkIljmMSuwyYGgVUWsZ".IndexOf(directive) >= 0; + } + private static string FormatDirective(RubyContext/*!*/ context, RubyTime/*!*/ time, char directive, Modifiers modifiers, int width, int depth) { if (modifiers.Colons > 0 && directive != 'z') { return null; From 7d95f958d3ae8d29c0c5248b120888928f8d536f Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:45:34 +0100 Subject: [PATCH 108/147] Marshal.load reads an IO-like source no further than the dump Marshal.load of an object that is not an IO (a StringIO, a Zlib::GzipReader, anything with #getbyte and #read) went through an IOWrapper that called #read for 4 KB at a time, so it consumed whatever followed the dump: two dumps written one after the other into a StringIO could not be loaded one after the other (the second load raised EOFError, the StringIO's pos was past both). It also never used #getbyte, so test_marshal's test_load_overread* sources, whose #getbyte holds the header, failed with "incompatible marshal file format". MRI reads such a source a byte at a time with #getbyte (r_byte) and a string's bytes with #read of their exact count (r_bytes1), reading ahead only while load_arg.readable says more records are certainly coming - the rest of an Array's, Hash's or Struct's elements - and keeping whatever #read answers beyond what it asked for (r_byte1_buffered, r_bytes1_buffered). IOSourceStream does the same, and MarshalReader keeps its Readable count as r_object0 keeps readable. A #getbyte that answers nil raises EOFError, a #read that answers short "marshal data too short", as in MRI; a source lacking either method is "instance of IO needed". Checked against CRuby 4.0.10: two dumps and a tail read back from one StringIO (same objects and positions), and a logging IO-like object is left exactly after the dump. test_marshal's test_load_overread and test_load_overread_string_body pass; ruby/spec core/marshal, library/stringio and library/zlib show no new failures. --- Src/Libraries/Builtins/Marshal.cs | 180 +++++++++++++++++++++++++++++- 1 file changed, 174 insertions(+), 6 deletions(-) diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index de5cf6659..a59890aa4 100644 --- a/Src/Libraries/Builtins/Marshal.cs +++ b/Src/Libraries/Builtins/Marshal.cs @@ -24,6 +24,7 @@ using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronRuby.Runtime.Calls; +using IronRuby.Runtime.Conversions; using System.Globalization; using System.Text; @@ -109,6 +110,150 @@ public CallSite>/*!*/ ProcCall { public CallSite>/*!*/ Binmode { get { return RubyUtils.GetCallSite(ref _binmode, Context, "binmode", 0); } } + + private CallSite> _getbyte; + private CallSite> _read; + private CallSite> _stringCast; + + public CallSite>/*!*/ Getbyte { + get { return RubyUtils.GetCallSite(ref _getbyte, Context, "getbyte", 0); } + } + + public CallSite>/*!*/ Read { + get { return RubyUtils.GetCallSite(ref _read, Context, "read", 1); } + } + + public CallSite>/*!*/ StringCast { + get { return RubyUtils.GetCallSite(ref _stringCast, ConvertToStrAction.Make(Context)); } + } + } + + /// + /// An IO-like object (a StringIO, a Zlib::GzipReader...) read the way MRI's marshal.c reads + /// one: a byte by #getbyte (r_byte) and a string's bytes by #read with their count + /// (r_bytes1), so that the object is left right after the dump. Only while the loader + /// knows that more is coming - the rest of an Array's, Hash's or Struct's elements, which + /// it counts in Readable as load_arg.readable does - does it read ahead, and then keeps + /// whatever #read gave beyond what it asked for (r_byte1_buffered, r_bytes1_buffered). + /// + internal sealed class IOSourceStream : Stream { + private const int DefaultBufferSize = 8192; // BUFSIZ + + private readonly ReaderSites/*!*/ _sites; + private readonly object _io; + private byte[]/*!*/ _buffer = new byte[DefaultBufferSize]; + private int _offset; + private int _length; + + /// load_arg.readable: a lower bound on the records still to come. + internal long Readable; + + internal IOSourceStream(ReaderSites/*!*/ sites, object io) { + _sites = sites; + _io = io; + } + + public override bool CanRead { get { return true; } } + public override bool CanSeek { get { return false; } } + public override bool CanWrite { get { return false; } } + public override long Length { get { throw new NotSupportedException(); } } + public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } + public override void SetLength(long value) { throw new NotSupportedException(); } + public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } + + private static Exception/*!*/ TooShort() { + return RubyExceptions.CreateArgumentError("marshal data too short"); + } + + private byte[]/*!*/ CallRead(long count) { + var site = _sites.Read; + object result = site.Target(site, _io, Protocols.Normalize(count)); + if (result == null) { + throw TooShort(); + } + var cast = _sites.StringCast; + return cast.Target(cast, result).ToByteArray(); + } + + public override int ReadByte() { + if (Readable > 0 || _length > 0) { + if (_length == 0) { + int readable = (int)Math.Min(Readable, _buffer.Length); + byte[] data = CallRead(readable); + if (data.Length < readable) { + throw TooShort(); + } + if (data.Length > _buffer.Length) { + _buffer = new byte[data.Length]; + } + Buffer.BlockCopy(data, 0, _buffer, 0, data.Length); + _offset = 0; + _length = data.Length; + } + _length--; + return _buffer[_offset++]; + } + + var site = _sites.Getbyte; + object b = site.Target(site, _io); + if (b == null) { + throw new EOFError("end of file reached"); + } + if (b is MutableString str) { + // NUM2CHR takes a String's first byte + return str.IsEmpty ? 0 : str.GetByte(0); + } + if (b is int i) { + return i & 0xff; + } + if (b is BigInteger big) { + return (int)(big & 0xff); + } + throw RubyExceptions.CreateTypeConversionError(_sites.Context.GetClassDisplayName(b), "Integer"); + } + + public override int Read(byte[]/*!*/ buffer, int offset, int count) { + if (count == 0) { + return 0; + } + + if (Readable == 0 && _length == 0) { + byte[] data = CallRead(count); + if (data.Length != count) { + throw TooShort(); + } + Buffer.BlockCopy(data, 0, buffer, offset, count); + return count; + } + + if (count <= _length) { + Buffer.BlockCopy(_buffer, _offset, buffer, offset, count); + _offset += count; + _length -= count; + return count; + } + + int buffered = _length; + int need = count - buffered; + long readable = Math.Min(Readable + 1, _buffer.Length); + byte[] more = CallRead(Math.Max(need, readable)); + if (more.Length < need) { + throw TooShort(); + } + Buffer.BlockCopy(_buffer, _offset, buffer, offset, buffered); + Buffer.BlockCopy(more, 0, buffer, offset + buffered, need); + + int rest = more.Length - need; + if (rest > _buffer.Length) { + _buffer = new byte[rest]; + } + Buffer.BlockCopy(more, need, _buffer, 0, rest); + _offset = 0; + _length = rest; + return count; + } } @@ -1209,6 +1354,16 @@ public Symbol(string str, RubySymbol sym) { internal bool FromStream { get; set; } + // An IO-like source, read as MRI reads one; null for a String or an IO. + internal IOSourceStream IOSource { get; set; } + + // load_arg.readable, which only an IO-like source has a use for. + private void AddReadable(long delta) { + if (IOSource != null) { + IOSource.Readable += delta; + } + } + private RubyContext/*!*/ Context { get { return _globalScope.Context; } } @@ -1493,18 +1648,24 @@ private static bool IsAscii(byte[]/*!*/ data, string/*!*/ text) { if (count < 0) { throw RubyExceptions.CreateArgumentError("negative array size (or size too big)"); } + AddReadable(count - 1); for (int i = 0; i < count; i++) { result.Add(ReadAnObject(false)); + AddReadable(-1); } + AddReadable(1); return result; } private Hash/*!*/ ReadHash(int typeFlag, Hash/*!*/ result) { int count = ReadInt32(); + AddReadable((count - 1) * 2L); for (int i = 0; i < count; i++) { object key = ReadAnObject(false); result[key] = ReadAnObject(false); + AddReadable(-2); } + AddReadable(2); if (typeFlag == '}') { result.DefaultValue = ReadAnObject(false); } @@ -1940,13 +2101,16 @@ private void CheckLoad(RubyClass/*!*/ theClass) { throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", Context.GetClassOf(obj).Name); } + AddReadable((count - 1) * 2L); for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (name != names[i]) { throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", theClass.Name, name, names[i]); } obj[i] = ReadAnObject(false); + AddReadable(-2); } + AddReadable(2); return obj; } @@ -1962,13 +2126,16 @@ private void CheckLoad(RubyClass/*!*/ theClass) { if (members != null && count != members.Count) { throw RubyExceptions.CreateTypeError("struct {0} not compatible (struct size differs)", dataClass.Name); } + AddReadable((count - 1) * 2L); for (int i = 0; i < count; i++) { string name = ReadIdentifier(); if (members != null && name != members[i].ToString()) { throw RubyExceptions.CreateTypeError("struct {0} not compatible (:{1} for :{2})", dataClass.Name, name, members[i]); } Context.SetInstanceVariable(instance, RubyUtils.GetHiddenInstanceVariableName(name), ReadAnObject(false)); + AddReadable(-2); } + AddReadable(2); Context.FreezeObject(instance); return instance; } @@ -2433,6 +2600,9 @@ internal object Load() { throw new EOFError("end of file reached"); } throw RubyExceptions.CreateArgumentError("marshal data too short", e); + } catch (EOFError) { + // an IO-like source's #getbyte answered nil (MRI's r_byte: rb_eof_error) + throw; } catch (IOException e) { throw RubyExceptions.CreateArgumentError("marshal data too short", e); } @@ -2574,18 +2744,16 @@ public static object Load(ReaderSites/*!*/ sites, RespondToStorage/*!*/ respondT object block; bool freeze = ParseLoadOptions(self.Context, proc, options, out block); - Stream stream = null; - if (source != null && Protocols.RespondTo(respondToStorage, source, "getbyte")) { - stream = RubyIOOps.CreateIOWrapper(respondToStorage, source, FileAccess.Read); - } - if (stream == null || !stream.CanRead) { + if (source == null || !Protocols.RespondTo(respondToStorage, source, "getbyte") || + !Protocols.RespondTo(respondToStorage, source, "read")) { throw RubyExceptions.CreateTypeError("instance of IO needed"); } SetBinaryMode(sites.Binmode, respondToStorage, source); + var stream = new IOSourceStream(sites, source); BinaryReader reader = new BinaryReader(stream); - MarshalReader loader = new MarshalReader(sites, reader, scope.GlobalScope, block, freeze) { FromStream = true }; + MarshalReader loader = new MarshalReader(sites, reader, scope.GlobalScope, block, freeze) { FromStream = true, IOSource = stream }; return loader.Load(); } From 1b8c229810264aa6e550cf70fa40b37ce99c4593 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:46:35 +0100 Subject: [PATCH 109/147] String#undump finds the force_encoding form without a backtracking regexp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit undump matched its input against /\A(".*")(?:\.dup)?\.force_encoding\("([^"]+)"\)\z/m. A greedy .* under /m backtracks through the whole string on .NET, so test_string's test_undump, which passes a 10 MB encoding name, spent 10-85 seconds in that one match (CRuby: microseconds) and timed the file out under load. The suffix is now found with end_with? and rindex: only the last .force_encoding(" can leave a name with no '"' in it, so this picks the same split the regexp did. Checked against MRI's str_undump on the way: - it checks the whole string for non-ASCII before it checks for a NUL, so "a\0bä" is "non-ASCII character detected", not "string contains null byte" (and the Ruby scan over every character is gone: ascii_only? and include? do it); - a '"' that ends the body early, with no force_encoding suffix after it, is the "not wrapped with..." format error, not a bare "invalid dumped string"; - an empty encoding name is "dumped string has unknown encoding name". A table of 20 dumped forms gives CRuby 4.0.10's results except one, which is String#inspect of a UTF-16LE string of odd length. test_string's undump tests pass (19 s, was over 120 s alone) and spec/core/string/{undump,dump}_spec.rb pass. --- Src/StdLib/ironruby/ruby4.rb | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index c5458f674..1d4a0f703 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -3926,9 +3926,18 @@ def __ir_require_unfrozen__ def undump s = self forced = nil - if (m = /\A(".*")(?:\.dup)?\.force_encoding\("([^"]+)"\)\z/m.match(s)) - s = m[1] - forced = m[2] + # The '"...".force_encoding("name")' form, with an optional .dup, found with + # string searches: only the last .force_encoding(" can leave a name without + # a '"'. A greedy /\A(".*")...\z/m backtracks through all of a long string + # on .NET (test_undump passes a 10 MB name). + if s.end_with?('")') && (k = s.rindex('.force_encoding("')) + head = s[0, k] + name = s[(k + 17)...-2] + head = head[0...-4] if head.end_with?('".dup') + if head.length >= 2 && head.start_with?('"') && head.end_with?('"') && !name.include?('"') + s = head + forced = name + end end if s.start_with?('"') && !s.end_with?('"') && s.count('"') < 2 ::Kernel.raise(::RuntimeError, "unterminated dumped string") @@ -3942,14 +3951,10 @@ def undump body = s[1...-1] ::Kernel.raise(::RuntimeError, "invalid dumped string") if body.nil? # The dumped form is plain ASCII; a NUL or a non-ASCII character in it means - # it did not come from #dump. - body.each_char do |ch| - if ch == "\0" - ::Kernel.raise(::RuntimeError, "string contains null byte") - elsif ch.ord > 0x7f - ::Kernel.raise(::RuntimeError, "non-ASCII character detected") - end - end + # it did not come from #dump. MRI's str_undump checks the whole string for + # non-ASCII first and for a NUL after, wherever each one is. + ::Kernel.raise(::RuntimeError, "non-ASCII character detected") unless body.ascii_only? + ::Kernel.raise(::RuntimeError, "string contains null byte") if body.include?("\0") out = +"" unicode_escape = false hex_escape = false # a \x escape of a non-ASCII byte @@ -3957,7 +3962,9 @@ def undump while i < body.length c = body[i] if c == '"' - ::Kernel.raise(::RuntimeError, "invalid dumped string") + # MRI's str_undump ends the string at the first unescaped '"': what is + # left has to be the .force_encoding suffix, and here it was not. + ::Kernel.raise(::RuntimeError, "invalid dumped string; not wrapped with '\"' nor '\"...\".force_encoding(\"...\")' form") elsif c == "\\" i += 1 e = body[i] From 754660942df94b24bb2237b5c6927e1d97e6a71e Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:49:48 +0100 Subject: [PATCH 110/147] Prelude_AliasNames1 expects rfind(1, 2) to be an ArgumentError 20d6c9bd made Array#rfind count its arguments before answering an Enumerator, as CRuby's rb_scan_args does; CRuby 4.0.10 says "wrong number of arguments (given 2, expected 0..1)" for [1, 2, 3].rfind(1, 2) without a block. The test still pinned the old Enumerator. --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index ccbf2438b..958144bac 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3629,7 +3629,7 @@ public void Prelude_AliasNames1() { require 'ruby4' p 1.then, 1.yield_self, 1.method(:yield_self).name, 1.method(:yield_self).original_name p Kernel.instance_method(:then) == Kernel.instance_method(:yield_self), Kernel.instance_method(:then).parameters -p [1, 2, 3].rfind, [1, 2, 3].rfind(nil), [1, 2, 3].rfind(1, 2), [1, 2, 3].rfind(-> { 9 }) { false } +p [1, 2, 3].rfind, [1, 2, 3].rfind(nil), ([1, 2, 3].rfind(1, 2) rescue $!), [1, 2, 3].rfind(-> { 9 }) { false } p (1..2).collect_concat, (1..2).flat_map p [3].lazy.filter { 1 }, [3].lazy.find_all { 1 }, [3].lazy.select { 1 } p [3].lazy.collect { 1 }, [3].lazy.map { 1 }, [3].lazy.collect_concat { [1] } @@ -3644,7 +3644,7 @@ p Kernel.instance_method(:then) == Kernel.instance_method(:yield_self), Kernel.i [] # # -# +# 9 # # From 3b3c45954ee0eaafeaa0d7d2871f01d8be2e052d Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:54:18 +0100 Subject: [PATCH 111/147] Methods of a cloned class or module look constants up in the clone A method copied by Module#clone or #dup kept the lexical scope it was written in, so a constant it named was looked up in the original: CloneTest1 = CloneTest.clone; class CloneTest1; TEST = :c1; end made CloneTest1.new.foo raise NameError (or find the original's TEST). CRuby rewrites the cref of each method it copies (rb_vm_rewrite_cref), putting the clone where the original was ([Bug #15877]). InitializeMembersFrom now gives a method written in the body of the module being copied a copy of that module scope, with the clone as its module, and the same parent. The method body is compiled per declaring module already (RubyMethodBody.GetDelegate), so the clone's methods get a compilation, and constant caches, of their own. Methods written elsewhere (a block, another body, `def self.m') keep their scope, which is what CRuby does too. test_constant_access_from_method_in_cloned_class and _module of CRuby's test_class/test_module pass; ruby/spec core/module, core/class and Kernel#clone/#dup unchanged. New test CloneConstantLookup1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/CloningTests.cs | 31 ++++++++++++++++++++++ Src/Ruby/Builtins/RubyModule.cs | 24 +++++++++++++++-- Src/Ruby/Runtime/RubyScope.cs | 8 ++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0841f56ec..5968313ff 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1215,6 +1215,7 @@ public Tests(Driver/*!*/ driver) { ClassDuplication7, Clone1, Dup1, + CloneConstantLookup1, Structs1, MetaModules1, MetaModulesDuplication1, diff --git a/Src/IronRuby.Tests/Runtime/CloningTests.cs b/Src/IronRuby.Tests/Runtime/CloningTests.cs index 6dae1198f..da88fb02b 100644 --- a/Src/IronRuby.Tests/Runtime/CloningTests.cs +++ b/Src/IronRuby.Tests/Runtime/CloningTests.cs @@ -153,6 +153,37 @@ p o.clone.singleton_class.instance_variables [:@k] 2 [] +"); + } + + /// + /// A method of a cloned class or module looks its constants up in the clone, which CRuby's clone + /// arranges by rewriting the method's cref ([Bug #15877]). + /// + public void CloneConstantLookup1() { + TestOutput(@" +class C + def foo; TEST; end + def bar; defined?(TEST) ? TEST : :none; end +end +C1 = C.clone +C2 = C.clone +class C1; TEST = :c1; end +class C2; TEST = :c2; end +p C1.new.foo, C2.new.foo, C1.new.bar, C.new.bar +module M + def foo; TEST; end +end +M1 = M.dup +M1.const_set(:TEST, :m1) +o = Object.new.extend(M1) +p o.foo +", @" +:c1 +:c2 +:c1 +:none +:m1 "); } } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 356371987..9ebdeb9fa 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -879,10 +879,30 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { _methodsState = module._methodsState; if (module._methods != null) { _methods = new Dictionary(module._methods.Count); + Dictionary rewrittenScopes = null; foreach (var method in module._methods) { // the undefined/hidden markers are shared singletons, not copied (Integer.dup copies undef'd .new): - _methods[method.Key] = (method.Value.IsUndefined || method.Value.IsHidden || method.Value.IsInteropMember) ? - method.Value : method.Value.Copy(method.Value.Flags, this); + if (method.Value.IsUndefined || method.Value.IsHidden || method.Value.IsInteropMember) { + _methods[method.Key] = method.Value; + continue; + } + + // A method written in the body of the module being copied looks its constants up in the copy, as + // CRuby's rb_vm_rewrite_cref makes it do: the copy gets the same scope with the copy in place of + // the original module ([Bug #15877]). Methods written elsewhere (in a block, in another module's + // body, the singleton methods of a `def self.m') keep the scope they were written in. + var rubyMethod = method.Value as RubyMethodInfo; + var moduleScope = (rubyMethod != null) ? rubyMethod.DeclaringScope as RubyModuleScope : null; + if (moduleScope != null && moduleScope.Module == module) { + rewrittenScopes ??= new Dictionary(); + RubyScope scope; + if (!rewrittenScopes.TryGetValue(moduleScope, out scope)) { + rewrittenScopes[moduleScope] = scope = moduleScope.CopyFor(this); + } + _methods[method.Key] = rubyMethod.CopyWithScope(scope, this); + } else { + _methods[method.Key] = method.Value.Copy(method.Value.Flags, this); + } } } else { _methods = null; diff --git a/Src/Ruby/Runtime/RubyScope.cs b/Src/Ruby/Runtime/RubyScope.cs index 760a9a91a..111f800a6 100644 --- a/Src/Ruby/Runtime/RubyScope.cs +++ b/Src/Ruby/Runtime/RubyScope.cs @@ -1618,6 +1618,14 @@ internal RubyModuleScope(RubyScope/*!*/ parent, RubyModule/*!*/ module) { InRescue = parent.InRescue; MethodAttributes = RubyMethodAttributes.PublicInstance; } + + /// + /// This scope with in place of its module: the lexical scope of the + /// methods a clone of the module gets (see RubyModule.InitializeMembersFrom). + /// + internal RubyModuleScope/*!*/ CopyFor(RubyModule/*!*/ module) { + return new RubyModuleScope(_parent, module); + } } /// From 6ddd64e9d96fb0a1e43d4ff1422db2cc0a711c1a Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:54:31 +0100 Subject: [PATCH 112/147] A call of an undefined method_missing is answered as BasicObject's would After undef_method(:method_missing), obj.method_missing raised NoMethodError for 'method_missing' itself. CRuby's method_missing() finds no method_missing to call and goes to raise_method_missing with the call's own arguments: no arguments is ArgumentError "no method name given", a name that is not a Symbol is refused ("method name must be a Symbol but String is given"), and method_missing(:foo, 1) is the NoMethodError for foo with args [1] (test_object's test_method_missing). When a call of method_missing finds nothing at all, the binder now calls BasicObject#method_missing with the call's arguments, which says exactly that. Any other missing method is reported as before. test_method_missing of CRuby's test_object passes; ruby/spec core/basicobject and language unchanged. New test UndefMethodMissing1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/UndefTests.cs | 20 ++++++++++++++++++++ Src/Ruby/Runtime/Calls/RubyCallAction.cs | 11 +++++++++++ 3 files changed, 32 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 5968313ff..050d9f228 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -847,6 +847,7 @@ public Tests(Driver/*!*/ driver) { UndefMethodLookup3, UndefMethodLookup4, UndefMethodLookup6, + UndefMethodMissing1, UndefCoreMethodWarnings1, RemoveBasicObjectInitialize1, MethodAdded1, diff --git a/Src/IronRuby.Tests/Runtime/UndefTests.cs b/Src/IronRuby.Tests/Runtime/UndefTests.cs index a65ec0e48..40f3f16fd 100644 --- a/Src/IronRuby.Tests/Runtime/UndefTests.cs +++ b/Src/IronRuby.Tests/Runtime/UndefTests.cs @@ -319,6 +319,26 @@ puts e.message }, @" false undefined method 'initialize' for an instance of Object +"); + } + + /// + /// A call of method_missing where it has been undefined is answered as BasicObject#method_missing would answer it: + /// MRI's method_missing() goes to raise_method_missing with the call's own arguments. + /// + public void UndefMethodMissing1() { + TestOutput(@" +c = Class.new { undef_method(:method_missing) } +o = c.new +begin; o.method_missing; rescue NameError, ArgumentError => e; p [e.class, e.message]; end +begin; o.method_missing(""foo""); rescue NameError, ArgumentError => e; p [e.class, e.message]; end +begin; o.method_missing(:foo, 1); rescue NameError, ArgumentError => e; p [e.class, e.name, e.args]; end +begin; o.bar; rescue NameError, ArgumentError => e; p [e.class, e.name]; end +", @" +[ArgumentError, ""no method name given""] +[ArgumentError, ""method name must be a Symbol but String is given""] +[NoMethodError, :foo, [1]] +[NoMethodError, :bar] "); } } diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 25ca12807..22633ce2c 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -930,6 +930,17 @@ internal static bool BuildMethodMissingCall(MetaObjectBuilder/*!*/ metaBuilder, return true; case MethodMissingBinding.Fallback: + // A call of method_missing itself where it has been undefined: MRI's method_missing() goes to + // raise_method_missing with the call's own arguments, which is what BasicObject#method_missing + // does with them (`no method name given' for none, a name that is not a Symbol refused). + if (defaultFallback && methodName == Symbols.MethodMissing && incompatibleVisibility == RubyMethodVisibility.None) { + var basicMethodMissing = args.RubyContext.BasicObjectClass.GetMethod(Symbols.MethodMissing) as RubyLibraryMethodInfo; + if (basicMethodMissing != null) { + basicMethodMissing.BuildCall(metaBuilder, args, Symbols.MethodMissing); + return true; + } + } + // method_missing is defined in Kernel: if (defaultFallback && args.Signature.IsVariableCall) { metaBuilder.SetError(Methods.MakeUndefinedLocalOrMethodError.OpCall( From 07cce21fdec06c88db6171abe9137a783ef90aa5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:54:46 +0100 Subject: [PATCH 113/147] A library block breaking after its method returned is an unexpected break Enumerable#first's block, kept by an #each that stores the block it is given and called after first has returned, raised LocalJumpError "break from proc-closure". The block is written in C#, MRI's C block, which breaks with rb_iter_break: with no frame to break to, CRuby says "unexpected break" ([ruby-dev:45041], test_enum's test_first). A Ruby block's orphaned break is still "break from proc-closure", as in CRuby. BlockParam.Break tells a library block by its scope (the context's empty scope, which only Proc.Create gives a block) and words the error so when the frame that converted it is no longer active. The second half of test_first, an Enumerator whose generator yields to first's block from another thread, still differs (ThreadError): a Proc does not know which thread converted it, and adding that to every Proc is out of proportion. ruby/spec language/break, core/enumerable and core/proc unchanged. New test LibraryBlockOrphanBreak1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 24 ++++++++++++++++++++++++ Src/Ruby/Runtime/BlockParam.cs | 8 ++++++-- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 050d9f228..bda7edbc4 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1191,6 +1191,7 @@ public Tests(Driver/*!*/ driver) { PreludeKeywordsArity1, LibraryKeywordsStored1, BlockKeywordsPositional1, + LibraryBlockOrphanBreak1, PreludeKeywordsYielder1, SymbolProcKeywords1, ToIntToStrConversion1, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index 50cc1ce3b..c9a8a9016 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -2356,6 +2356,30 @@ def i(x, &b) 3 10 2 +"); + } + + /// + /// A block a library method wrote in C# is MRI's C block: called after that method has returned, its break has + /// nowhere to go, which MRI calls an "unexpected break" ([ruby-dev:45041]); a Ruby block's is "from proc-closure". + /// + public void LibraryBlockOrphanBreak1() { + TestOutput(@" +o = Object.new +class << o + include Enumerable + attr_reader :block + def each(&block); @block = block; self; end +end +p o.first +begin; o.block.call(1); rescue LocalJumpError => e; p e.message, e.reason; end +def m; proc { break }; end +begin; m.call; rescue LocalJumpError => e; p e.message; end +", @" +nil +""unexpected break"" +:break +""break from proc-closure"" "); } } diff --git a/Src/Ruby/Runtime/BlockParam.cs b/Src/Ruby/Runtime/BlockParam.cs index 010e50b06..902623393 100644 --- a/Src/Ruby/Runtime/BlockParam.cs +++ b/Src/Ruby/Runtime/BlockParam.cs @@ -336,8 +336,12 @@ public object Break(object returnValue) { // proc whose home frame is gone (e.g. Proc#call on an orphaned block), or one running // on another thread than the call it would break out of (Thread.new { break }): - if (_proc.Converter == null || (_threadId != 0 && _threadId != Environment.CurrentManagedThreadId)) { - throw new LocalJumpError("break from proc-closure", "break", returnValue); + if (_proc.Converter == null || (_threadId != 0 && _threadId != Environment.CurrentManagedThreadId) + || (_proc.LocalScope.IsEmpty && !_proc.Converter.IsActiveMethod)) { + // A block a library method wrote in C# is MRI's C block, which breaks with rb_iter_break: called after + // that method has returned (Enumerable#first's, kept by an #each that stores its block), it has no + // frame to break to, and MRI says so as for a break anywhere else outside of one ([ruby-dev:45041]). + throw new LocalJumpError(_proc.LocalScope.IsEmpty ? "unexpected break" : "break from proc-closure", "break", returnValue); } // unwind to proc converter: From c402e3ed92a2182feea742241334b72cc4834669 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:55:03 +0100 Subject: [PATCH 114/147] An unknown magic comment encoding is reported with the line it is on eval("# coding: foo\n", nil, "x.rb", 3) raised ArgumentError "x.rb:1: unknown or invalid encoding in the magic comment": the line was counted from 1 whatever eval was given, and the message stopped there. CRuby's (pm_parse_process_error) is prism's argument-level error, "x.rb:3: unknown or invalid encoding in the magic comment" followed by the source line with the encoding name marked under it, as a syntax error's message shows it (test_parse's test_magic_comment). The encoding is found unknown while the source is read, where neither the eval's line nor the layout is at hand, so the reader hands its bytes on with the error, and the parser, which knows the line, has prism format them. The message is colored as a SyntaxError's is when $stderr is a terminal. load and a main script give the same message as before plus the picture of the line, as CRuby does. test_magic_comment of CRuby's test_parse passes; ruby/spec core/kernel/eval and language unchanged. SyntaxError_MessageLocation1 now expects the picture and covers the eval line. --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 4 ++- Src/Prism/PrismAstBridge.cs | 36 ++++++++++++++++++++++++- Src/Ruby/Runtime/RubyContext.cs | 14 +++++++++- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index ccbf2438b..a6d8b59b6 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -3992,8 +3992,9 @@ public void SyntaxError_MessageLocation1() { File.write(bad, ""x = 1\n"" * 49 + ""x = )\n"") begin; load bad; rescue SyntaxError => e; p e.message.start_with?(""#{bad}:50: ""), e.path == bad; end File.write(bad, ""# encoding: bogus\np 1\n"") - begin; load bad; rescue ArgumentError => e; p e.message == ""#{bad}:1: unknown or invalid encoding in the magic comment"", e.backtrace.grep(/Parse/); end + begin; load bad; rescue ArgumentError => e; p e.message == ""#{bad}:1: unknown or invalid encoding in the magic comment\n> 1 | # encoding: bogus\n | ^~~~~\n 2 | p 1\n"", e.backtrace.grep(/Parse/); end end +begin; eval(""# coding: foo\n"", nil, 'm.rb', 3); rescue ArgumentError => e; p e.message; end begin; eval(""1\n1 +"", nil, 'q.rb', 3); rescue SyntaxError => e; p e.message, e.path; end begin; eval(""1 +"", nil, 'z.rb', -5); rescue SyntaxError => e; p e.message; end ", @" @@ -4001,6 +4002,7 @@ public void SyntaxError_MessageLocation1() { true true [] +""m.rb:3: unknown or invalid encoding in the magic comment\n> 3 | # coding: foo\n | ^~~\n"" ""q.rb:4: syntax errors found\n 3 | 1\n> 4 | 1 +\n | ^ unexpected end-of-input, assuming it is closing the parent top level context\n | ^ unexpected end-of-input; expected an expression after the operator\n"" ""q.rb"" ""z.rb:-5: syntax errors found\n> -5 | 1 +\n | ^ unexpected end-of-input, assuming it is closing the parent top level context\n | ^ unexpected end-of-input; expected an expression after the operator\n"" diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index b891a21fb..095c94bb4 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -98,7 +98,16 @@ public static SourceUnitTree Parse(SourceUnit/*!*/ sourceUnit, RubyCompilerOptio } bool timed = PhaseTimer.Enter(PhaseTimer.Bridge); try { - string code = sourceUnit.GetCode(); + string code; + try { + code = sourceUnit.GetCode(); + } catch (ArgumentException e) when (e.Data[RubyContext.InvalidMagicCommentSourceKey] is byte[] source) { + string message = MagicCommentErrorMessage(source, sourceUnit.Path, options.InitialLocation.Line); + if (message == null) { + throw; + } + throw new ArgumentException(message); + } // Prism, told this is the main script, would skip a #! line without "ruby" in it to // look for one that has; a binstub that names IronRuby's launcher is already Ruby. if (mainScript && (commandLine & 0x20) == 0 && RubyUtils.ShebangNamesIronRuby(code)) { @@ -248,6 +257,31 @@ public static SourceUnitTree ParseText(string/*!*/ code, string path, List + /// The ArgumentError MRI raises for a magic comment naming an encoding it does not know: prism's + /// "file:line: unknown or invalid encoding in the magic comment" followed by the line, marked under the + /// name, the way a syntax error's is (MRI's pm_parse_process_error). Null if prism does not see it so. + /// + private static string MagicCommentErrorMessage(byte[]/*!*/ source, string path, int startLine) { + int lineOffset = RubyUtils.DecodeEvalLineOffset(ref path); + int formatType = 1; + if (!Console.IsErrorRedirected) { + formatType = String.IsNullOrEmpty(Environment.GetEnvironmentVariable("NO_COLOR")) ? 3 : 2; + } + byte[] formatted; + try { + var options = PrismParser.BuildOptionsData(path, (startLine <= 0 ? 1 : startLine) + lineOffset, null); + if (PrismSerialize.ErrorsFormat(source, options, formatType, out formatted) != 1) { + return null; + } + } catch (Exception) { + return null; + } + // the buffer starts with the name of the source's encoding and a NUL + int start = Array.IndexOf(formatted, (byte)0) + 1; + return System.Text.Encoding.UTF8.GetString(formatted, start, formatted.Length - start); + } + /// /// What a SyntaxError says after its "file:line: ": prism's layout of the errors (see /// PrismParser.FormatErrors) without the location prism puts in front of it, which the diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index da311b460..3c312c742 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -5239,6 +5239,11 @@ public override Encoding/*!*/ DefaultEncoding { return encoding.IsAsciiIdentity ? encoding.StrictEncoding : RubyEncoding.UTF8.StrictEncoding; } + /// + /// The key of the source bytes in the Data of the ArgumentException a magic comment naming no encoding raises. + /// + public const string InvalidMagicCommentSourceKey = "IronRuby.InvalidMagicCommentSource"; + private SourceCodeReader/*!*/ ReadSource(Stream/*!*/ stream, Encoding/*!*/ defaultEncoding, string path) { long initialPosition = stream.Position; var reader = new StreamReader(stream, BinaryEncoding.Instance, true); @@ -5268,7 +5273,14 @@ public override Encoding/*!*/ DefaultEncoding { // the parser does not know them (rb_enc_find_index there fails the same way). var rubyEncoding = RubyEncoding.FindByName(encodingName); if (rubyEncoding == null || !rubyEncoding.IsAsciiIdentity) { - throw new ArgumentException(String.Format("{0}:{1}: unknown or invalid encoding in the magic comment", path, line)); + var error = new ArgumentException(String.Format("{0}:{1}: unknown or invalid encoding in the magic comment", path, line)); + // MRI's message goes on with prism's picture of the line, numbered from where an eval starts: the parser, + // which knows that line, draws it from these bytes (PrismAstBridge.Parse). + stream.Seek(initialPosition, SeekOrigin.Begin); + var source = new MemoryStream(); + stream.CopyTo(source); + error.Data[InvalidMagicCommentSourceKey] = source.ToArray(); + throw error; } rubyPreambleEncoding = rubyEncoding.StrictEncoding; } From 30dab3f230c599402d7ca58736d3b20776a16a1f Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 18:58:57 +0100 Subject: [PATCH 115/147] yield x, **h with h empty does not auto-splat x for a block with optional parameters def a(arg, kw); yield arg, **kw; end; a([1, 2, 3], {}) { |a, b = 0| } gave the block a = 1, b = 2: the empty keywords were dropped and the one argument left was auto-splatted. CRuby passes [1, 2, 3] and 0. The call still had keywords, and setup_parameters_complex allows no auto-splat for a call with keywords (allow_autosplat = !kw_flag); only a block of plain parameters, which vm_callee_setup_block_arg sets up, auto-splats it ({|a, b|} gets 1, 2 either way). test_proc's test_proc_autosplat. `yield x, **h' is now compiled to RubyOps.YieldKeywordSplat1, which yields x without auto-splatting when h turned out empty and the block has an optional, rest, block or keyword parameter, and otherwise does what YieldSplat1 did. Only that shape (one positional argument and a **splat) is handled; `yield *a, **h' still auto-splats. test_proc_autosplat of CRuby's test_proc passes; ruby/spec language and core/proc unchanged. New test YieldEmptyKeywordSplat1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 29 +++++++++++++++++++ Src/Ruby/Compiler/Ast/Arguments.cs | 8 +++++ .../Compiler/ReflectionCache.Generated.cs | 2 ++ Src/Ruby/Runtime/RubyOps.cs | 18 ++++++++++++ 5 files changed, 58 insertions(+) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index bda7edbc4..af4be866a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1191,6 +1191,7 @@ public Tests(Driver/*!*/ driver) { PreludeKeywordsArity1, LibraryKeywordsStored1, BlockKeywordsPositional1, + YieldEmptyKeywordSplat1, LibraryBlockOrphanBreak1, PreludeKeywordsYielder1, SymbolProcKeywords1, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index c9a8a9016..b3b948838 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -2359,6 +2359,35 @@ def i(x, &b) "); } + /// + /// `yield x, **h' with h empty passes x alone, but from a call with keywords: MRI auto-splats x only for a block of + /// plain parameters (vm_callee_setup_block_arg), not for one with an optional, rest, block or keyword parameter. + /// + public void YieldEmptyKeywordSplat1() { + TestOutput(@" +def y(h); yield [1, 2], **h; end +h = {} +p y(h) { |a, b| [a, b] } +p y(h) { |a, b = 0| [a, b] } +p y(h) { |a, *r| [a, r] } +p y(h) { |a, &b| a } +p y(h) { |a, k: 1| [a, k] } +p y(h, &->(a, b = 0) { [a, b] }) +p y({x: 1}) { |a, b = 0| [a, b] } +def z; yield [1, 2], **{}; end +p z { |a, b = 0| [a, b] } +", @" +[1, 2] +[[1, 2], 0] +[[1, 2], []] +[1, 2] +[[1, 2], 1] +[[1, 2], 0] +[[1, 2], {x: 1}] +[[1, 2], 0] +"); + } + /// /// A block a library method wrote in C# is MRI's C block: called after that method has returned, its break has /// nowhere to go, which MRI calls an "unexpected break" ([ruby-dev:45041]); a Ruby block's is "from proc-closure". diff --git a/Src/Ruby/Compiler/Ast/Arguments.cs b/Src/Ruby/Compiler/Ast/Arguments.cs index a48f191bf..b758ea71e 100644 --- a/Src/Ruby/Compiler/Ast/Arguments.cs +++ b/Src/Ruby/Compiler/Ast/Arguments.cs @@ -16,6 +16,7 @@ using System; using MSA = System.Linq.Expressions; +using System.Collections; using System.Collections.Generic; using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -59,6 +60,13 @@ internal void TransformToCall(AstGenerator/*!*/ gen, CallSiteBuilder/*!*/ siteBu internal MSA.Expression/*!*/ TransformToYield(AstGenerator/*!*/ gen, MSA.Expression/*!*/ bfcVariable, MSA.Expression/*!*/ selfExpression) { var args = new List(); var splatted = TransformToCallInternal(gen, args); + // `yield x, **h': whether x may be auto-splatted depends on h being given at all (RubyOps.YieldKeywordSplat1) + if (args.Count == 1 && _expressions.Length == 2 && _expressions[1] is KeywordArgumentSplat) { + return Methods.YieldKeywordSplat1.OpCall( + AstUtils.Box(args[0]), AstUtils.Convert(splatted, typeof(IList)), AstFactory.NullOfProc, + AstUtils.Box(selfExpression), bfcVariable + ); + } return AstFactory.YieldExpression(gen.Context, args, splatted, null, null, bfcVariable, selfExpression); } diff --git a/Src/Ruby/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index d01a589be..0ff2ed538 100644 --- a/Src/Ruby/Compiler/ReflectionCache.Generated.cs +++ b/Src/Ruby/Compiler/ReflectionCache.Generated.cs @@ -754,6 +754,8 @@ public static partial class Methods { private static MethodInfo _Yield3; public static MethodInfo/*!*/ Yield4 { get { return _Yield4 ?? (_Yield4 = CallInstruction.CacheFunc(RubyOps.Yield4)); } } private static MethodInfo _Yield4; + public static MethodInfo/*!*/ YieldKeywordSplat1 { get { return _YieldKeywordSplat1 ?? (_YieldKeywordSplat1 = CallInstruction.CacheFunc(RubyOps.YieldKeywordSplat1)); } } + private static MethodInfo _YieldKeywordSplat1; public static MethodInfo/*!*/ YieldN { get { return _YieldN ?? (_YieldN = CallInstruction.CacheFunc(RubyOps.YieldN)); } } private static MethodInfo _YieldN; public static MethodInfo/*!*/ YieldSplat0 { get { return _YieldSplat0 ?? (_YieldSplat0 = CallInstruction.CacheFunc(RubyOps.YieldSplat0)); } } diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 9cab79818..946d48b25 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -1226,6 +1226,24 @@ public static object YieldSplat1(object arg1, IList/*!*/ splattee, Proc procArg, return result; } + /// + /// `yield x, **h': the splat is the one-or-zero element array of the keywords (KeywordArgumentSplat). With h empty x + /// is all that is passed, but by a call that had keywords, which MRI auto-splats only for a block of plain parameters + /// (vm_callee_setup_block_arg); any other - {|a, b = 1|}, {|a, *r|}, {|a, &b|} - takes x as it is + /// (setup_parameters_complex allows no auto-splat for a call with keywords). + /// + [Emitted] + public static object YieldKeywordSplat1(object arg1, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) { + if (splattee.Count == 0) { + var proc = blockParam.Proc; + var dispatcher = proc.Dispatcher; + if (proc.Kind != ProcKind.Lambda && (dispatcher.Arity < 0 || dispatcher.HasProcParameter || dispatcher.ChecksKeywords)) { + return YieldNoAutoSplat1(arg1, procArg, self, blockParam); + } + } + return YieldSplat1(arg1, splattee, procArg, self, blockParam); + } + [Emitted] public static object YieldSplat2(object arg1, object arg2, IList/*!*/ splattee, Proc procArg, object self, BlockParam/*!*/ blockParam) { object result; From d943ca9125638e9dc2e1f9d49a0bdb6abc35597a Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:08:08 +0100 Subject: [PATCH 116/147] Method#super_method stops at a method made public by `public :m' With obj extended by a module whose foo is private, `public :foo' in obj's singleton class and a module prepended to that class, obj.method(:foo).super_method skipped the singleton class's entry and went on to the module's private foo. `public :foo' in a class that inherits foo leaves a zsuper method there, which a super call skips because it goes on to the inherited method itself. CRuby's super_method stops at it and reports it as the method it stands for, with the class as its owner, and its own super_method is nil (test_method's test_prepended_public_zsuper). Method#super_method and UnboundMethod#super_method now resolve through RubyModule.ResolveSuperMethodForReflection, which walks the ancestors after the owner as a super call does but accepts such a forwarder and resolves it as ResolveMethod already did (the code is now shared, ResolveForwarderNoLock). A super call still skips it. Callers with refinements keep the old path. The super_method and zsuper tests of CRuby's test_method pass (17 tests); ruby/spec core/method, core/unboundmethod and language unchanged. New test SuperMethodForwarder1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/SuperTests.cs | 33 +++++++++++++ Src/Libraries/Builtins/MethodOps.cs | 6 +-- Src/Libraries/Builtins/UnboundMethod.cs | 6 +-- Src/Ruby/Builtins/RubyModule.cs | 62 +++++++++++++++++++----- 5 files changed, 86 insertions(+), 22 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index af4be866a..ebcbe98ff 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -914,6 +914,7 @@ public Tests(Driver/*!*/ driver) { SuperParameterless2B, SuperParameterless3, SuperParameterlessKeywordRest1, + SuperMethodForwarder1, SuperKeywordSplat1, SuperKeywordRestPassOn1, SuperParameterlessKeywordRest2, diff --git a/Src/IronRuby.Tests/Runtime/SuperTests.cs b/Src/IronRuby.Tests/Runtime/SuperTests.cs index f2ae7bdf4..f64075a72 100644 --- a/Src/IronRuby.Tests/Runtime/SuperTests.cs +++ b/Src/IronRuby.Tests/Runtime/SuperTests.cs @@ -1007,6 +1007,39 @@ p self.foo rescue p $! main main # +"); + } + + /// + /// Method#super_method stops at the entry `public :m' leaves in a module that inherits m (MRI's zsuper method + /// entry), whose #owner is that module, as the Method made by looking m up there says. + /// + public void SuperMethodForwarder1() { + TestOutput(@" +mod = Module.new { private def foo; [:ok] end } +obj = Object.new.extend(mod) +class << obj; public :foo; end +mod1 = Module.new { def foo; [:mod1] + super end } +obj.singleton_class.prepend(mod1) +m = obj.method(:foo) +s = m.super_method +p m.owner == mod1, s.owner == obj.singleton_class, s.super_method, s.call, obj.foo +class K; private def foo; :k; end; end +class L < K; public :foo; end +module P; def foo; super; end; end +L.prepend(P) +u = L.instance_method(:foo) +p u.owner, u.super_method.owner, u.super_method.super_method, L.new.foo +", @" +true +true +nil +[:ok] +[:mod1, :ok] +P +L +nil +:k "); } } diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 16ffd579c..169ddd5b3 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -133,11 +133,7 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* string name = self.Info.OriginalName ?? self.Name; var targetClass = context.GetImmediateClassOf(self.Target); - MethodResolutionResult result; - using (context.ClassHierarchyLocker()) { - result = targetClass.ResolveSuperMethodNoLock(name, owner); - } - + MethodResolutionResult result = targetClass.ResolveSuperMethodForReflection(name, owner); return result.Found ? new RubyMethod(self.Target, result.Info, name) : null; } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 1ba68d3f5..14fff3960 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -139,11 +139,7 @@ public static UnboundMethod GetSuperMethod(RubyContext/*!*/ context, UnboundMeth // an alias resolves super under the name the body was written with string name = self._info.OriginalName ?? self._name; - MethodResolutionResult result; - using (context.ClassHierarchyLocker()) { - result = self._targetConstraint.ResolveSuperMethodNoLock(name, owner); - } - + MethodResolutionResult result = self._targetConstraint.ResolveSuperMethodForReflection(name, owner); return result.Found ? new UnboundMethod(self._targetConstraint, name, result.Info) : null; } diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 9ebdeb9fa..8d8180ab0 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -2727,23 +2727,61 @@ public MethodResolutionResult ResolveMethodWithRefinements(string/*!*/ name, Vis var result = ResolveMethodNoLock(name, visibility, MethodLookup.ReturnForwarder, (scope != null) ? scope.GetActiveRefinements() : null).InvalidateSitesOnOverride(); - // `public :m' in a module that inherits m leaves an entry there that only forwards - // to the inherited body. MRI's Method made out of it reports that module as its - // #owner and the forwarder's visibility, so hand back a copy of the body that says so. if (result.Found && result.Info.IsSuperForwarder) { - var forwarder = (SuperForwarderInfo)result.Info; - var target = result.Owner.ResolveSuperMethodNoLock(forwarder.SuperName, result.Owner).InvalidateSitesOnOverride(); - if (!target.Found) { - return target; + return ResolveForwarderNoLock(result); + } + + return result; + } + } + + // `public :m' in a module that inherits m leaves an entry there that only forwards + // to the inherited body. MRI's Method made out of it reports that module as its + // #owner and the forwarder's visibility, so hand back a copy of the body that says so. + private static MethodResolutionResult ResolveForwarderNoLock(MethodResolutionResult forwarderResult) { + var forwarder = (SuperForwarderInfo)forwarderResult.Info; + var target = forwarderResult.Owner.ResolveSuperMethodNoLock(forwarder.SuperName, forwarderResult.Owner).InvalidateSitesOnOverride(); + if (!target.Found) { + return target; + } + + var copy = target.Info.Copy(forwarder.Flags, target.Info.DeclaringModule); + copy.AliasOwner = forwarder.AliasOwner ?? forwarderResult.Owner; + copy.OriginalName = forwarder.OriginalName ?? target.Info.OriginalName; + return new MethodResolutionResult(copy, forwarderResult.Owner, true); + } + + /// + /// Method#super_method: what `super' from reaches, except that a `public :m' + /// forwarder on the way is the method found there (MRI's zsuper method entry), made into a Method as + /// makes one: its #owner is the module the forwarder is in. + /// + public MethodResolutionResult ResolveSuperMethodForReflection(string/*!*/ name, RubyModule/*!*/ callerModule) { + using (Context.ClassHierarchyLocker()) { + if (callerModule.RefinedModule != null) { + return ResolveSuperMethodNoLock(name, callerModule); + } + + InitializeMethodsNoLock(); + + RubyMemberInfo info = null; + RubyModule owner = null; + bool foundModule = false; + bool skipHidden = false; + if (ForEachAncestor((module) => { + if (module == callerModule) { + foundModule = true; + return false; } - var copy = target.Info.Copy(forwarder.Flags, target.Info.DeclaringModule); - copy.AliasOwner = forwarder.AliasOwner ?? result.Owner; - copy.OriginalName = forwarder.OriginalName ?? target.Info.OriginalName; - return new MethodResolutionResult(copy, result.Owner, true); + owner = module; + return foundModule && module.TryGetMethod(name, ref skipHidden, out info); + }) && !info.IsUndefined) { + var result = new MethodResolutionResult(info, owner, true); + return info.IsSuperForwarder ? ResolveForwarderNoLock(result) : result; } - return result; + return MethodResolutionResult.NotFound; } } From 0b2c7e7ea70db8ad5a7cf45101dbbb9fcfa943a0 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:08:10 +0100 Subject: [PATCH 117/147] Array#[], String#[] and their []= take an object that describes a range MRI's rb_range_beg_len goes through rb_range_values, which takes any object answering #begin, #end and #exclude_end? (private ones too, as rb_check_funcall asks) for the Range they describe, refusing only an Enumerator::ArithmeticSequence. Array#[], #slice, #[]=, String#[], #slice, #[]= and Symbol#[] all ask it before they convert the index to an Integer, so "abcd"[duck] is "bc" on CRuby. IronRuby took such an object for #values_at only, asking for public methods, and every other method raised "no implicit conversion of DuckRange into Integer". RangeValuesStorage is rb_range_values as a call-site storage: it asks respond_to?(name, true) and calls the three methods as from inside the object. #values_at uses it in place of IListOps.RangeLike, and the untyped-index overloads of the methods above try it after the Integer and Float fast paths, so an Integer index costs no more than before. String#[]= gets an Integer overload of its own beside the untyped one, whose replacement is untyped too so that a Regexp index still picks its own overload. A range-like index starting before the array or string is a RangeError naming the object's #inspect, as MRI's is. test_range's test_beg_len and test_duckrange pass. ruby/spec core/array, core/string, core/range and core/symbol show no new failures, CRuby's test_array no new failures, and Array_DuckRangeIndex1 checks the methods against CRuby 4.0's output. slice!, byteslice and fill still take only a real Range. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/ArrayTests.cs | 40 ++++++++++ Src/Libraries/Builtins/MutableStringOps.cs | 47 +++++++++++- Src/Libraries/Builtins/RangeValuesStorage.cs | 63 +++++++++++++++ Src/Libraries/Builtins/SymbolOps.cs | 5 +- Src/Libraries/Extensions/IListOps.cs | 80 ++++++++------------ 6 files changed, 183 insertions(+), 53 deletions(-) create mode 100644 Src/Libraries/Builtins/RangeValuesStorage.cs diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0841f56ec..2d0d006b3 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1351,6 +1351,7 @@ public Tests(Driver/*!*/ driver) { Array_JoinRecursive1, Array_JoinNested1, Array_RangeLongEnd1, + Array_DuckRangeIndex1, Array_HashRecursiveElement1, String_DumpNonUnicode1, IO_PutsRecursiveToAry1, diff --git a/Src/IronRuby.Tests/Runtime/ArrayTests.cs b/Src/IronRuby.Tests/Runtime/ArrayTests.cs index 6a75df2d7..a6d5097f4 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -615,6 +615,46 @@ public void Array_RangeLongEnd1() { "); } + /// + /// MRI's rb_range_values: an index that is not a Range but has #begin, #end and #exclude_end? - private + /// ones too - reads and assigns as the Range it describes (Array#[], #[]=, String#[], #[]=, Symbol#[]). + /// + public void Array_DuckRangeIndex1() { + TestOutput(@" +class DuckRange + def initialize(b, e, x = false) = (@b, @e, @x = b, e, x) + def begin = @b + def end = @e + def exclude_end? = @x +end +p ""abcd""[DuckRange.new(1, 2)], ""abcd"".slice(DuckRange.new(1, 2, true)), :abcd[DuckRange.new(2, nil)] +p [1, 2, 3, 4][DuckRange.new(1, 2)], [1, 2, 3].values_at(DuckRange.new(0, 1)) +a = [1, 2, 3]; a[DuckRange.new(0, 1)] = 9; p a +s = +""abcd""; s[DuckRange.new(0, 1)] = ""X""; p s +s = +""ab""; s[1] = ""Q""; s[1.5] = ""R""; p s +p((begin; [0][DuckRange.new(-10, 0)] = 1; rescue RangeError; $!.class; end)) +o = Object.new +class << o; attr_accessor :begin, :end; end +p(([1][o] rescue $!)) +def o.exclude_end? = false +o.begin = 0; o.end = 0 +class << o; private :begin, :end; end +p [1][o] +", @" +""bc"" +""b"" +""cd"" +[2, 3] +[1, 2] +[9, 3] +""Xcd"" +""aR"" +RangeError +# +[1] +"); + } + /// /// Array#join separates the elements of nested arrays, empty ones included, and starts in US-ASCII when the /// first element is an array, taking another encoding only from a string that is not ASCII (MRI's diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 462ea99d9..5821fb97e 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1095,7 +1095,24 @@ public static MutableString RemoveSubstringInPlace(MutableString/*!*/ self, [Not [RubyMethod("[]")] [RubyMethod("slice")] - public static MutableString GetChar(MutableString/*!*/ self, [DefaultProtocol]int index) { + public static MutableString GetChar(ConversionStorage/*!*/ fixnumCast, RangeValuesStorage/*!*/ rangeValues, + MutableString/*!*/ self, object index) { + int i; + if (index is int) { + i = (int)index; + } else { + // rb_str_aref asks rb_range_beg_len before it converts the index: an object with + // #begin, #end and #exclude_end? stands for the Range it describes. + Range range = rangeValues.TryConvert(index); + if (range != null) { + return GetSubstring(fixnumCast, self, range); + } + i = Protocols.CastToFixnum(fixnumCast, index); + } + return GetChar(self, i); + } + + public static MutableString GetChar(MutableString/*!*/ self, int index) { return InExclusiveRangeNormalized(GetCharacterLength(self), ref index) ? GetCharacterSlice(self, index, 1) : null; } @@ -1401,9 +1418,33 @@ public static object SetByte(MutableString/*!*/ self, [DefaultProtocol]int index } [RubyMethod("[]=")] - public static MutableString/*!*/ ReplaceCharacter(MutableString/*!*/ self, - [DefaultProtocol]int index, [DefaultProtocol, NotNull]MutableString/*!*/ value) { + public static MutableString/*!*/ ReplaceCharacter(ConversionStorage/*!*/ fixnumCast, ConversionStorage/*!*/ stringCast, + RangeValuesStorage/*!*/ rangeValues, MutableString/*!*/ self, object index, object value) { + + // The replacement is untyped so that a Regexp index still picks its own overload; it is + // converted after the index, as rb_str_aset does. + + if (!(index is int)) { + // rb_str_aset: an object with #begin, #end and #exclude_end? assigns to the Range it + // describes, and one starting outside the string is reported by its #inspect. + Range range = rangeValues.TryConvert(index); + if (range != null) { + if (range.Begin is int) { + int length = GetCharacterLength(self); + int begin = (int)range.Begin < 0 ? (int)range.Begin + length : (int)range.Begin; + if (begin < 0 || begin > length) { + throw RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString()); + } + } + return ReplaceSubstring(fixnumCast, self, range, Protocols.CastToString(stringCast, value)); + } + } + int i = index is int ? (int)index : Protocols.CastToFixnum(fixnumCast, index); + return ReplaceCharacter(self, i, Protocols.CastToString(stringCast, value)); + } + [RubyMethod("[]=")] + public static MutableString/*!*/ ReplaceCharacter(MutableString/*!*/ self, int index, [DefaultProtocol, NotNull]MutableString/*!*/ value) { // MRI's rb_str_update checks the encodings (rb_enc_check) before the index. self.RequireCompatibleEncoding(value); diff --git a/Src/Libraries/Builtins/RangeValuesStorage.cs b/Src/Libraries/Builtins/RangeValuesStorage.cs new file mode 100644 index 000000000..5af642f50 --- /dev/null +++ b/Src/Libraries/Builtins/RangeValuesStorage.cs @@ -0,0 +1,63 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using IronRuby.Runtime; +using IronRuby.Runtime.Calls; + +namespace IronRuby.Builtins { + /// + /// MRI's rb_range_values: an index that is not a Range but has #begin, #end and #exclude_end? + /// stands for the Range they describe (Array#[], String#[], #values_at...). The methods are + /// asked for the way rb_check_funcall asks, private ones included, and an + /// Enumerator::ArithmeticSequence is refused before they are asked. + /// + public sealed class RangeValuesStorage : RubyCallSiteStorage { + private CallSite> _respondToSite; + private CallSite> _beginSite; + private CallSite> _endSite; + private CallSite> _excludeEndSite; + + public RangeValuesStorage(RubyContext/*!*/ context) : base(context) { } + + /// + /// The Range the value describes, or null when it is not range-like (its caller then + /// converts it to an Integer, as MRI's callers of rb_range_beg_len do). + /// + public Range TryConvert(object value) { + Range range = value as Range; + if (range != null) { + return range; + } + if (value == null || value is int || value is double || value is long || value is BigInteger || value is bool || + value is MutableString || value is RubySymbol || + !RespondTo(value, "begin") || !RespondTo(value, "end") || !RespondTo(value, "exclude_end?") || + IsArithmeticSequence(value)) { + return null; + } + + var beginSite = RubyUtils.GetCallSite(ref _beginSite, Context, "begin", RubyCallSignature.WithImplicitSelf(0)); + var endSite = RubyUtils.GetCallSite(ref _endSite, Context, "end", RubyCallSignature.WithImplicitSelf(0)); + var excludeEndSite = RubyUtils.GetCallSite(ref _excludeEndSite, Context, "exclude_end?", RubyCallSignature.WithImplicitSelf(0)); + object begin = beginSite.Target(beginSite, value); + object end = endSite.Target(endSite, value); + return Range.CreateValidated(begin, end, RubyOps.IsTrue(excludeEndSite.Target(excludeEndSite, value))); + } + + private bool RespondTo(object value, string/*!*/ name) { + var site = RubyUtils.GetCallSite(ref _respondToSite, Context, "respond_to?", RubyCallSignature.WithImplicitSelf(2)); + return RubyOps.IsTrue(site.Target(site, value, Context.EncodeIdentifier(name), true)); + } + + private bool IsArithmeticSequence(object value) { + if (!(value is Enumerator)) { + return false; + } + for (RubyClass cls = Context.GetClassOf(value); cls != null; cls = cls.SuperClass) { + if (cls.Name == "Enumerator::ArithmeticSequence") { + return true; + } + } + return false; + } + } +} diff --git a/Src/Libraries/Builtins/SymbolOps.cs b/Src/Libraries/Builtins/SymbolOps.cs index b89e7402d..f50efd53e 100644 --- a/Src/Libraries/Builtins/SymbolOps.cs +++ b/Src/Libraries/Builtins/SymbolOps.cs @@ -311,8 +311,9 @@ public static bool EndsWith(ConversionStorage/*!*/ stringCast, Ru [RubyMethod("[]")] [RubyMethod("slice")] - public static MutableString GetChar(RubySymbol/*!*/ self, [DefaultProtocol]int index) { - return MutableStringOps.GetChar(self.String, index); + public static MutableString GetChar(ConversionStorage/*!*/ fixnumCast, RangeValuesStorage/*!*/ rangeValues, + RubySymbol/*!*/ self, object index) { + return MutableStringOps.GetChar(fixnumCast, rangeValues, self.String, index); } [RubyMethod("[]")] diff --git a/Src/Libraries/Extensions/IListOps.cs b/Src/Libraries/Extensions/IListOps.cs index e9a5b63a7..72bb76271 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -616,7 +616,8 @@ public static int GetHashCode(UnaryOpStorage/*!*/ hashStorage, ConversionStorage [RubyMethod("[]")] [RubyMethod("slice")] - public static object GetElement(ConversionStorage/*!*/ integerConversion, IList/*!*/ self, object index) { + public static object GetElement(ConversionStorage/*!*/ integerConversion, RangeValuesStorage/*!*/ rangeValues, + ConversionStorage/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, object index) { if (index is int) { return GetElement(self, (int)index); } @@ -625,6 +626,12 @@ public static object GetElement(ConversionStorage/*!*/ integerConv if (index is double) { return GetElement(self, (double)index); } + // rb_ary_aref1 asks rb_range_beg_len first: an object with #begin, #end and + // #exclude_end? indexes as the Range it describes. + Range range = rangeValues.TryConvert(index); + if (range != null) { + return GetElements(fixnumCast, allocateStorage, self, range); + } return GetElement(self, Protocols.CastToInteger(integerConversion, index)); } @@ -695,7 +702,13 @@ public static IList GetElements(ConversionStorage/*!*/ fixnumCast, UnaryOpS [RubyMethod("at")] public static object At(ConversionStorage/*!*/ integerConversion, IList/*!*/ self, object index) { - return GetElement(integerConversion, self, index); + if (index is int) { + return GetElement(self, (int)index); + } + if (index is double) { + return GetElement(self, (double)index); + } + return GetElement(self, Protocols.CastToInteger(integerConversion, index)); } #endregion @@ -741,8 +754,22 @@ private static int CastIndex(ConversionStorage/*!*/ fixnumCast, object inde } [RubyMethod("[]=")] - public static object SetElement(ConversionStorage/*!*/ fixnumCast, IList/*!*/ self, object index, object value) { + public static object SetElement(ConversionStorage/*!*/ arrayTryCast, ConversionStorage/*!*/ fixnumCast, + RangeValuesStorage/*!*/ rangeValues, IList/*!*/ self, object index, object value) { RequireNotFrozen(self); + if (!(index is int)) { + // rb_ary_aset: an object with #begin, #end and #exclude_end? assigns to the Range it + // describes, and one reaching before the first element is reported by its #inspect. + Range range = rangeValues.TryConvert(index); + if (range != null) { + if (range.Begin is int && (int)range.Begin + self.Count < 0) { + throw RubyExceptions.CreateRangeError("{0} out of range", (object)rangeValues.Context.Inspect(index).ToString()); + } + int start, count; + RangeToStartAndCount(fixnumCast, range, self.Count, out start, out count); + return SetElement(arrayTryCast, self, start, count, value); + } + } int i = CastIndex(fixnumCast, index); RubyArray array = self as RubyArray; return array != null ? SetElement(array, i, value) : SetElement(self, i, value); @@ -2002,57 +2029,14 @@ public static object ReverseIndex(BinaryOpStorage/*!*/ equals, BlockParam predic #region values_at - /// - /// rb_range_values refuses an Enumerator::ArithmeticSequence before asking for #begin and - /// #end, so (0..2).step(2) is an index that does not convert. The class is the prelude's. - /// - private static bool IsArithmeticSequence(RubyContext/*!*/ context, object value) { - if (!(value is Enumerator)) { - return false; - } - for (RubyClass cls = context.GetClassOf(value); cls != null; cls = cls.SuperClass) { - if (cls.Name == "Enumerator::ArithmeticSequence") { - return true; - } - } - return false; - } - - /// - /// rb_range_values: an object that is not an Integer but has #begin, #end and #exclude_end? - /// stands for the Range they describe. Null for anything else. - /// - private static Range RangeLike(RespondToStorage/*!*/ respondToStorage, - CallSiteStorage>/*!*/ beginStorage, - CallSiteStorage>/*!*/ endStorage, - CallSiteStorage>/*!*/ excludeEndStorage, object value) { - - if (value == null || value is int || value is long || value is System.Numerics.BigInteger || value is bool || - !Protocols.RespondTo(respondToStorage, value, "begin") || - !Protocols.RespondTo(respondToStorage, value, "end") || - !Protocols.RespondTo(respondToStorage, value, "exclude_end?") || - IsArithmeticSequence(respondToStorage.Context, value)) { - return null; - } - var beginSite = beginStorage.GetCallSite("begin", 0); - var endSite = endStorage.GetCallSite("end", 0); - var excludeEndSite = excludeEndStorage.GetCallSite("exclude_end?", 0); - object begin = beginSite.Target(beginSite, value); - object end = endSite.Target(endSite, value); - return Range.CreateValidated(begin, end, RubyOps.IsTrue(excludeEndSite.Target(excludeEndSite, value))); - } - [RubyMethod("values_at")] public static RubyArray/*!*/ ValuesAt(ConversionStorage/*!*/ fixnumCast, - UnaryOpStorage/*!*/ allocateStorage, RespondToStorage/*!*/ respondToStorage, - CallSiteStorage>/*!*/ beginStorage, - CallSiteStorage>/*!*/ endStorage, - CallSiteStorage>/*!*/ excludeEndStorage, + UnaryOpStorage/*!*/ allocateStorage, RangeValuesStorage/*!*/ rangeValues, IList/*!*/ self, params object[]/*!*/ values) { RubyArray result = new RubyArray(); for (int i = 0; i < values.Length; i++) { - Range range = values[i] as Range ?? RangeLike(respondToStorage, beginStorage, endStorage, excludeEndStorage, values[i]); + Range range = rangeValues.TryConvert(values[i]); if (range != null) { // MRI asks for the range with errors on: a range reaching past the end of // the array is padded with nil out to its full length (values_at(0..9) on a From 812428cfde47e9908243e24456c23172f62b2a95 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:08:24 +0100 Subject: [PATCH 118/147] A local `it' that a block using `it' assigns is a variable of its own 1.then { x = it; it = 5; it += 1; [x, it] } shared one variable between the block's implicit parameter and the local `it' it assigns, so assigning the local overwrote the parameter: Binding#implicit_parameter_get(:it) then said 5, and binding.local_variables listed `it' before anything was assigned. In CRuby (prism) these are two variables: a read of the parameter is an ItLocalVariableReadNode, a read or write of the local a LocalVariable*Node, the parameter is not a local variable, and eval sees the local only (test_proc's test_implicit_parameters_for_it_complex). The parameter is now kept under the compiler name `?it?', which no local can have, and Binding#implicit_parameters and #implicit_parameter_get translate it back to `it'. test_it and test_implicit_parameters of CRuby's test_proc pass; ruby/spec language and core/binding, core/proc unchanged. New test ItParameterLocal1. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/BlockTests.cs | 23 +++++++++++++++++++ Src/Libraries/Builtins/BindingOps.cs | 12 +++++++--- Src/Prism/PrismAstBridge.cs | 16 ++++++++++--- .../Runtime/Calls/RubyParameterSignature.cs | 6 +++++ 5 files changed, 52 insertions(+), 6 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index ebcbe98ff..8fe256186 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1194,6 +1194,7 @@ public Tests(Driver/*!*/ driver) { BlockKeywordsPositional1, YieldEmptyKeywordSplat1, LibraryBlockOrphanBreak1, + ItParameterLocal1, PreludeKeywordsYielder1, SymbolProcKeywords1, ToIntToStrConversion1, diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index b3b948838..a38775df0 100644 --- a/Src/IronRuby.Tests/Runtime/BlockTests.cs +++ b/Src/IronRuby.Tests/Runtime/BlockTests.cs @@ -2388,6 +2388,29 @@ p y({x: 1}) { |a, b = 0| [a, b] } "); } + /// + /// A local variable `it' that a block using `it' assigns is a variable of its own: the parameter stays what it was + /// for Binding#implicit_parameter_get, and eval sees the local. + /// + public void ItParameterLocal1() { + TestOutput(@" +require 'ruby4' +p(1.then { it; eval('it') rescue $!.class }) +p(1.then { it; binding.local_variables }) +p(1.then { it; it = 5; [it, binding.local_variables, binding.implicit_parameters, binding.implicit_parameter_get(:it), eval('it')] }) +p(1.then { x = it; it = 5; it += 1; [x, it] }) +p(3.then { [it, 2.then { it = 7; it }, it] }) +p proc { that = it; it = nil; [that, it] }.call(1) +", @" +NameError +[] +[5, [:it], [:it], 1, 5] +[1, 6] +[3, 7, 3] +[1, nil] +"); + } + /// /// A block a library method wrote in C# is MRI's C block: called after that method has returned, its break has /// nowhere to go, which MRI calls an "unexpected break" ([ruby-dev:45041]); a Ruby block's is "from proc-closure". diff --git a/Src/Libraries/Builtins/BindingOps.cs b/Src/Libraries/Builtins/BindingOps.cs index 5014be1c0..7d7c0c306 100644 --- a/Src/Libraries/Builtins/BindingOps.cs +++ b/Src/Libraries/Builtins/BindingOps.cs @@ -15,6 +15,7 @@ using System; using IronRuby.Runtime; +using IronRuby.Runtime.Calls; namespace IronRuby.Builtins { [RubyClass("Binding", Extends = typeof(Binding))] @@ -41,7 +42,7 @@ public static RubyArray GetSourceLocation(RubyContext/*!*/ context, Binding/*!*/ var result = new RubyArray(names != null ? names.Length : 0); if (names != null) { foreach (var name in names) { - result.Add(context.EncodeIdentifier(name)); + result.Add(context.EncodeIdentifier(name == RubyParameterSignature.ItParameterName ? "it" : name)); } } return result; @@ -61,12 +62,17 @@ public static object GetImplicitParameter(ConversionStorage/*!*/ String.Format("implicit parameter '{0}' is not defined for {1}", parameterName, context.Inspect(self)) ); } - return self.FrameScope.GetImplicitParameterValue(parameterName); + return self.FrameScope.GetImplicitParameterValue(ImplicitParameterSlot(parameterName)); } private static bool IsImplicitParameter(Binding/*!*/ self, string/*!*/ name) { var names = self.FrameScope.OwnImplicitParameterNames; - return names != null && Array.IndexOf(names, name) >= 0; + return names != null && Array.IndexOf(names, ImplicitParameterSlot(name)) >= 0; + } + + // `it' is kept under a name a local variable cannot have (RubyParameterSignature.ItParameterName) + private static string/*!*/ ImplicitParameterSlot(string/*!*/ name) { + return name == "it" ? RubyParameterSignature.ItParameterName : name; } /// diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 095c94bb4..3eea636cb 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -766,7 +766,7 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.LocalVariableReadNode read: return CurrentScope.ResolveOrAddVariable(read.Name, span); case Pm.ItLocalVariableReadNode _: - return CurrentScope.ResolveOrAddVariable("it", span); + return CurrentScope.ResolveOrAddVariable(ItParameterName, span); case Pm.LocalVariableWriteNode write: return new SimpleAssignmentExpression( CurrentScope.ResolveOrAddVariable(write.Name, span), Expr(write.Value), null, span); @@ -2070,12 +2070,16 @@ private Parameters BlockParameters(Pm.PmNode parametersNode, bool autoSplat, out } case Pm.ItParametersNode it: { var span = Span(it); - var mandatory = new LeftValue[] { DefineParameter("it", span) }; + // A local the block assigns to is another variable that is also called `it' (prism tells + // the reads of the parameter from those of the local), so the parameter is kept under a + // name of its own: `it = nil' leaves Binding#implicit_parameter_get(:it) alone, and eval + // sees the local. + var mandatory = new LeftValue[] { DefineParameter(ItParameterName, span) }; // `it` is a parameter without a name as far as #parameters is concerned var declared = new[] { new RubyParameterSignature.Parameter("req", null) }; return new Parameters(mandatory, 1, null, null, null, span) { Signature = new RubyParameterSignature(declared, 1, 0, 0, false, 0, false, false) { - ImplicitParameterNames = new[] { "it" } + ImplicitParameterNames = new[] { ItParameterName } } }; } @@ -3060,6 +3064,12 @@ private Arguments ZSuperArguments(Pm.ParametersNode/*!*/ node, List // ---- pattern matching (case/in), lowered to tests + bindings ---- private const string ForwardingRestName = "?fwd?"; + + /// + /// Where a block's `it' is kept: a compiler name, like the ones below, which no local variable can have + /// (see Binding#implicit_parameter_get). + /// + public const string ItParameterName = RubyParameterSignature.ItParameterName; internal const string AnonymousKeywordRestName = "?kwrest?"; private const string ForwardingBlockName = "?fwdblk?"; diff --git a/Src/Ruby/Runtime/Calls/RubyParameterSignature.cs b/Src/Ruby/Runtime/Calls/RubyParameterSignature.cs index d6de3cbeb..4c696a89d 100644 --- a/Src/Ruby/Runtime/Calls/RubyParameterSignature.cs +++ b/Src/Ruby/Runtime/Calls/RubyParameterSignature.cs @@ -76,6 +76,12 @@ public RubyParameterSignature(Parameter[]/*!*/ parameters, int leadingCount, int /// public string[] ImplicitParameterNames { get; set; } + /// + /// The name `it' is kept under among a block's locals (and in ), which is not + /// `it': a local variable the block assigns is called that. + /// + public const string ItParameterName = "?it?"; + /// The declared parameters, in order. internal Parameter[]/*!*/ Parameters { get { return _parameters; } From 6572c8d21e24bdc75ef0a13ac203bc52fc9e3c89 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:09:41 +0100 Subject: [PATCH 119/147] IO#fcntl works on the standard streams and raises fcntl(2)'s errno STDOUT.fcntl(Fcntl::F_GETFL) let a System::NotSupportedException out: the standard streams are console streams with no descriptor of their own behind them, and RubyIO.FileControl asked the stream for one. Any fcntl that failed was reported as EBADF, whatever fcntl(2) said. CRuby 4.0.10 answers STDOUT.fcntl(F_GETFL) and STDIN.fcntl(F_GETFD) with the kernel's flags for 0/1/2, and raises the errno fcntl(2) gave (Errno::EINVAL for an unknown command). FileControl now uses KernelDescriptor, which is 0, 1 and 2 for the standard streams and the stream's own descriptor otherwise, and raises the Errno for fcntl(2)'s errno. NativeFileControl (sockets) is unchanged. Checked against CRuby 4.0.10 with those three calls. --- Src/Ruby/Builtins/RubyIO.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index 25a6ed8a7..3093bf0c1 100644 --- a/Src/Ruby/Builtins/RubyIO.cs +++ b/Src/Ruby/Builtins/RubyIO.cs @@ -1232,11 +1232,19 @@ public virtual int FileControl(int commandId, int arg) { throw new NotSupportedException(); } - int fd = NativeDescriptor; + // The standard streams are console streams with no descriptor of their own to report, + // but the kernel's 0, 1 and 2 are theirs: STDOUT.fcntl(F_GETFL) let the CLR's + // NotSupportedException out. + int fd = KernelDescriptor; if (fd < 0) { throw new NotSupportedException(); } - int result = NativeFileControl(fd, commandId, arg); + int result = LibcVariadic.Fcntl(fd, commandId, arg); + if (result < 0) { + // what fcntl(2) said - EINVAL for an unknown command, EBADF, EAGAIN for a lock - + // rather than EBADF whatever it was, as MRI's rb_sys_fail does + throw RubyExceptions.CreateErrno(_context, Marshal.GetLastPInvokeError(), null); + } // The descriptor's own O_APPEND is the answer wherever the kernel has one, but a // stream IronRuby opened in append mode without telling the kernel (the CLR // positions an appending FileStream itself) still reports the flag it holds. From 33cd296da98ba65a41b21c320b36265653159d1c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:09:52 +0100 Subject: [PATCH 120/147] A byte limit on #gets in UTF-16 or UTF-32 ends on a whole character MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit f.readline(2) on a file read as UTF-32LE answered the two bytes "a\0", half a character, and every read after it was out of step: the limit was not stretched to the end of the character as it is for UTF-8. MRI counts the limit in bytes and then reads on while the last character is incomplete (extra_limit in io.c). CRuby 4.0.10 on "aあbc\n" in UTF-32LE: readline(2) is "a", gets(1) "あ", gets(nil, 2) "b", readline(5) "aあ"; on "a\u{1F600}b\n" in UTF-16BE readline(3) is "a\u{1F600}" (the surrogate pair whole). RubyEncoding.EndsInsideCharacter, which the line reader asks, only knew UTF-8 and the multibyte encodings; it now knows that a UTF-32 character is four bytes and a UTF-16 one two, or four after a high surrogate. Checked against CRuby 4.0.10 with the cases above (test_io's test_readline_limit_nonascii). --- Src/Ruby/Builtins/RubyEncoding.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Src/Ruby/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index 77b26894b..dae93f99d 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -701,6 +701,21 @@ public bool EndsInsideCharacter(byte[]/*!*/ bytes, int start, int count) { return start + count - head < length; } + // The wide Unicode encodings go by code units: a UTF-32 character is four bytes, and + // a UTF-16 one is two, or four when the first unit is a high surrogate. Without this + // a byte limit on a UTF-32 #gets cut its characters in half. + int codePage = StrictEncoding.CodePage; + if (codePage == 12000 || codePage == 12001) { + return count % 4 != 0; + } + if (codePage == 1200 || codePage == 1201) { + if (count % 2 != 0) { + return true; + } + int high = bytes[start + count - (codePage == 1200 ? 1 : 2)]; + return high >= 0xD8 && high <= 0xDB; + } + int end = start + count; int p = start; while (p < end) { From 089701c482dd889f6784cc9b2d1511ac3920ebd2 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:09:53 +0100 Subject: [PATCH 121/147] File.open's Errno::EACCES names the path File.open("/etc/shadow") raised Errno::EACCES with the CLR's sentence: "Permission denied - Access to the path '/etc/shadow' is denied.". CRuby 4.0.10 says "Permission denied @ rb_sysopen - /etc/shadow"; IronRuby leaves out the "@ function" part throughout, as its ENOENT already does ("No such file or directory - /nonexist/x"). OpenFileStream now raises the EACCES with "Permission denied - " and the path, keeping the CLR exception as the inner one. The directory case before it (EISDIR, or a directory opened for reading) is unchanged. Checked with File.open of an unreadable file and with "w" on a file that cannot be written, and with IO#reopen of such a path. --- Src/Ruby/Builtins/RubyFile.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Src/Ruby/Builtins/RubyFile.cs b/Src/Ruby/Builtins/RubyFile.cs index 1d61215d1..ab7ec0115 100644 --- a/Src/Ruby/Builtins/RubyFile.cs +++ b/Src/Ruby/Builtins/RubyFile.cs @@ -128,7 +128,7 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO throw RubyExceptions.CreateErrno(context, e.HResult, path); } throw; - } catch (UnauthorizedAccessException) { + } catch (UnauthorizedAccessException e) { // .NET reports opening a directory as an access violation; MRI // distinguishes it, so only a genuine one stays EACCES (which is // what UnauthorizedAccessException already maps to). @@ -142,7 +142,9 @@ public RubyFile(RubyContext/*!*/ context, Stream/*!*/ stream, int descriptor, IO } throw RubyExceptions.CreateEISDIR(path); } - throw; + // Named by the path, as MRI's rb_sysopen does ("Permission denied - /etc/x"), + // rather than by the CLR's own sentence about it. + throw new UnauthorizedAccessException("Permission denied - " + path, e); } catch (ArgumentException e) { throw RubyExceptions.CreateEINVAL(e.Message, e); } From 163ed5247cf1e1b9a0e2be41c35964479a6481b1 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:10:45 +0100 Subject: [PATCH 122/147] File's instance methods work on an IO reopened to a File io.reopen(file) gives io the File's class, as MRI's io_reopen does, but the CLR object stays a RubyIO, and every File method declared on RubyFile refused it: x = STDOUT.dup; x.reopen(File.open(path)); x.size raised TypeError "no implicit conversion of IO into File", and so did x.stat, x.mtime, x.flock, File.size(x) and the rest. In CRuby 4.0.10 those all answer for the reopened file (size, stat, lstat, atime/mtime/ctime, flock, chmod; truncate says "not opened for writing" for a read-only one), since MRI's File methods only need the descriptor and the path it now holds. chmod, chown, truncate, flock, atime, ctime, mtime, birthtime, stat, lstat and size now take a RubyIO. They already worked through the descriptor; where they named the File's path (error messages, lstat) they ask FilePathOf, which is a RubyFile's Path or the path a reopened IO keeps. Checked against CRuby 4.0.10 by reopening STDOUT.dup onto a File and calling each of them. --- Src/Libraries/Builtins/FileOps.cs | 66 ++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 24 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index c562abc33..8eb4cd524 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -301,24 +301,25 @@ public static class Constants { #region chmod, chown, lchmod, lchown, umask [RubyMethod("chmod")] - public static object Chmod(RubyFile/*!*/ self, [DefaultProtocol]int permission) { + public static object Chmod(RubyIO/*!*/ self, [DefaultProtocol]int permission) { self.RequireInitialized(); if (Posix.IsAvailable) { int fd = GetNativeFileDescriptor(self); int errno; if (fd >= 0) { if (Posix.FChmod(fd, permission, out errno) != 0) { - throw Posix.Error(errno, self.Path, self.Context); + throw Posix.Error(errno, FilePathOf(self), self.Context); } return 0; } } - if (self.Path == null) { + string path = FilePathOf(self); + if (path == null) { // Without fchmod there is nothing to change a pathless File through; MRI's // rb_file_chmod answers nil then, rather than raising. return null; } - Chmod(self.Path, permission); + Chmod(path, permission); return 0; } @@ -384,7 +385,7 @@ private static int ToUidGid(RubyContext/*!*/ context, object value, bool owner) } [RubyMethod("chown")] - public static int ChangeOwner(RubyContext/*!*/ context, RubyFile/*!*/ self, object owner, object group) { + public static int ChangeOwner(RubyContext/*!*/ context, RubyIO/*!*/ self, object owner, object group) { self.RequireInitialized(); int uid = ToUidGid(context, owner, true); int gid = ToUidGid(context, group, false); @@ -394,7 +395,7 @@ public static int ChangeOwner(RubyContext/*!*/ context, RubyFile/*!*/ self, obje int errno; if (fd >= 0) { if (Posix.FChown(fd, uid, gid, out errno) != 0) { - throw Posix.Error(errno, self.Path, context); + throw Posix.Error(errno, FilePathOf(self), context); } } } @@ -521,11 +522,12 @@ public static int Delete(ConversionStorage/*!*/ toPath, RubyClass // The size is an off_t: a file of 4 GiB and more is an ordinary thing to ask for. [RubyMethod("truncate")] - public static int Truncate(ConversionStorage/*!*/ integerConversion, RubyFile/*!*/ self, object length) { + public static int Truncate(ConversionStorage/*!*/ integerConversion, RubyIO/*!*/ self, object length) { long size = Protocols.CastToInteger(integerConversion, length).ToInt64(); self.RequireWritable(); if (size < 0) { - throw self.Path != null ? RubyExceptions.CreateEINVAL("Invalid argument - {0}", self.Path) : RubyExceptions.CreateEINVAL(); + string path = FilePathOf(self); + throw path != null ? RubyExceptions.CreateEINVAL("Invalid argument - {0}", path) : RubyExceptions.CreateEINVAL(); } // ftruncate(2) leaves the file offset alone; Stream.SetLength pulls it back @@ -1217,7 +1219,7 @@ internal static int GetNativeFileDescriptor(RubyIO/*!*/ io) { } [RubyMethod("flock")] - public static object FileLock(RubyFile/*!*/ self, [DefaultProtocol]int operation) { + public static object FileLock(RubyIO/*!*/ self, [DefaultProtocol]int operation) { self.RequireInitialized(); if (OperatingSystem.IsWindows()) { return WindowsFileLock(self, operation); @@ -1243,7 +1245,7 @@ public static object FileLock(RubyFile/*!*/ self, [DefaultProtocol]int operation return 0; } if (errno != Posix.EWouldBlock) { - throw Posix.Error(errno, self.Path, self.Context); + throw Posix.Error(errno, FilePathOf(self), self.Context); } if (nonBlocking) { // LOCK_NB on a locked file reports "would block" rather than raising @@ -1380,7 +1382,7 @@ private static void WindowsSymLink(string/*!*/ strOld, string/*!*/ strNew) { /// writes, so without it `gem install` of any gem with an executable failed. /// [System.Runtime.Versioning.SupportedOSPlatform("windows")] - private static object WindowsFileLock(RubyFile/*!*/ self, int operation) { + private static object WindowsFileLock(RubyIO/*!*/ self, int operation) { var fs = self.GetStream().BaseStream as FileStream; if (fs == null) { throw RubyExceptions.CreateEBADF(); @@ -1394,7 +1396,7 @@ private static object WindowsFileLock(RubyFile/*!*/ self, int operation) { int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); // Unlocking a file that is not locked is not an error for flock(2). if (error != ERROR_NOT_LOCKED) { - throw RubyExceptions.CreateEINVAL("{0}", self.Path); + throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); } } return 0; @@ -1404,7 +1406,7 @@ private static object WindowsFileLock(RubyFile/*!*/ self, int operation) { if ((operation & Posix.LOCK_EX) != 0) { flags |= LOCKFILE_EXCLUSIVE_LOCK; } else if ((operation & Posix.LOCK_SH) == 0) { - throw RubyExceptions.CreateEINVAL("{0}", self.Path); + throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); } while (true) { @@ -1414,7 +1416,7 @@ private static object WindowsFileLock(RubyFile/*!*/ self, int operation) { } int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (error != ERROR_LOCK_VIOLATION && error != ERROR_IO_PENDING) { - throw RubyExceptions.CreateEINVAL("{0}", self.Path); + throw RubyExceptions.CreateEINVAL("{0}", FilePathOf(self)); } if ((operation & Posix.LOCK_NB) != 0) { return false; @@ -1666,7 +1668,7 @@ private static bool IsAsciiString(string/*!*/ str) { #region atime, ctime, mtime, utime [RubyMethod("atime")] - public static RubyTime AccessTime(RubyContext/*!*/ context, RubyFile/*!*/ self) { + public static RubyTime AccessTime(RubyContext/*!*/ context, RubyIO/*!*/ self) { return RubyStatOps.AccessTime(RubyStatOps.Create(self)); } @@ -1677,7 +1679,7 @@ public static RubyTime AccessTime(RespondToStorage/*!*/ respondToStorage, CallSi } [RubyMethod("ctime")] - public static RubyTime CreateTime(RubyContext/*!*/ context, RubyFile/*!*/ self) { + public static RubyTime CreateTime(RubyContext/*!*/ context, RubyIO/*!*/ self) { return RubyStatOps.CreateTime(RubyStatOps.Create(self)); } @@ -1688,7 +1690,7 @@ public static RubyTime CreateTime(RespondToStorage/*!*/ respondToStorage, CallSi } [RubyMethod("mtime")] - public static RubyTime ModifiedTime(RubyContext/*!*/ context, RubyFile/*!*/ self) { + public static RubyTime ModifiedTime(RubyContext/*!*/ context, RubyIO/*!*/ self) { return RubyStatOps.ModifiedTime(RubyStatOps.Create(self)); } @@ -1808,7 +1810,7 @@ public static MutableString FileType(ConversionStorage/*!*/ toPat } [RubyMethod("stat")] - public static FileSystemInfo Stat(RubyFile/*!*/ self) { + public static FileSystemInfo Stat(RubyIO/*!*/ self) { return RubyStatOps.Create(self); } @@ -1817,16 +1819,17 @@ public static FileSystemInfo Stat(RubyFile/*!*/ self) { /// through a symbolic link describes the link. A File with no path is fstat'd. /// [RubyMethod("lstat")] - public static FileSystemInfo LStat(RubyFile/*!*/ self) { + public static FileSystemInfo LStat(RubyIO/*!*/ self) { self.RequireOpen(); - if (self.Path == null) { + string path = FilePathOf(self); + if (path == null) { return RubyStatOps.Create(self); } - return RubyStatOps.Create(self.Context, self.Path, false); + return RubyStatOps.Create(self.Context, path, false); } [RubyMethod("birthtime")] - public static RubyTime BirthTime(RubyContext/*!*/ context, RubyFile/*!*/ self) { + public static RubyTime BirthTime(RubyContext/*!*/ context, RubyIO/*!*/ self) { return RubyStatOps.BirthTime(RubyStatOps.Create(self)); } @@ -1836,11 +1839,11 @@ public static RubyTime BirthTime(ConversionStorage/*!*/ toPath, R } [RubyMethod("size")] - public static object FileSize(RubyFile/*!*/ self) { + public static object FileSize(RubyIO/*!*/ self) { // fstat the descriptor rather than the path: the size of a file that has // since been unlinked is still readable, and a closed File raises IOError. self.RequireOpen(); - return RubyStatOps.Size(RubyStatOps.Create((RubyIO)self)); + return RubyStatOps.Size(RubyStatOps.Create(self)); } [RubyMethod("inspect")] public static MutableString/*!*/ Inspect(RubyIO/*!*/ self) { @@ -1876,6 +1879,21 @@ public static MutableString GetPath(RubyIO/*!*/ self) { return GetPath((RubyFile)self); } + /// + /// The path a File's methods name in their errors and lstat: an IO reopened to a File + /// takes that File's class without becoming a RubyFile (the CLR object cannot change + /// type), and MRI's File methods work on it all the same, through the descriptor and + /// the path it keeps. + /// + private static string FilePathOf(RubyIO/*!*/ self) { + var file = self as RubyFile; + if (file != null) { + return file.Path; + } + MutableString path = RubyIOOps.GetIOPath(self); + return (path != null) ? self.Context.DecodePath(path) : null; + } + private static MutableString GetPath(RubyFile/*!*/ self) { self.RequireInitialized(); if (self.Path == null) { From 4ad247726b5d19d3f2dd6cd9083e409af2dfb1c3 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:10:58 +0100 Subject: [PATCH 123/147] File.join reads its array as it goes and keeps fs_enc_check's encoding Two differences from MRI's rb_file_join ([ruby-core:48012], test_file_ exhaustive's test_join_ascii_incompatible): - The parts were all taken out of the array before any was converted, so a #to_path that put a UTF-16LE String into the array after itself had that String joined as the one it replaced, and nothing raised. MRI checks the Strings it is given up front, then reads each element when it comes to it, checking what a #to_path left there; CRuby 4.0.10 raises Encoding::CompatibilityError. - MRI gives the result fs_enc_check's encoding: the two must be compatible, and where that leaves US-ASCII the encoding of the part that is not US-ASCII wins. File.join("a" (US-ASCII), "b" (Windows-1251)) is Windows-1251 in CRuby 4.0.10 and was US-ASCII. The join now walks each array by index, checking its Strings first, and gives the result the encoding PathEncodingCheck (fs_enc_check) answers after each part. A nested array that was visited before is no longer mistaken for recursion when it appears twice ([a, a]); only an array inside itself is. Checked against CRuby 4.0.10 with the test's cases, UTF-16LE parts, UTF-8/EUC-JP parts and the US-ASCII/Windows-1251 join. --- Src/Libraries/Builtins/FileOps.cs | 67 ++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 8eb4cd524..583cdb305 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1126,26 +1126,43 @@ public static RubyArray Split(ConversionStorage/*!*/ toPath, Ruby [RubyMethod("join", RubyMethodAttributes.PublicSingleton)] public static MutableString Join(ConversionStorage/*!*/ toPath, RubyClass/*!*/ self, params object[]/*!*/ parts) { MutableString result = null; - Dictionary visitedLists = null; - var worklist = new Stack(); int current = 0; - MutableString str; - - Push(worklist, parts); - while (worklist.Count > 0) { - object part = worklist.Pop(); - var list = part as IList; - if (list != null) { - if (list.Count == 0) { + JoinList(toPath, parts, ref result, ref current, null); + return result ?? MutableString.CreateEmpty(); + } + + /// + /// MRI's rb_file_join over one array. The Strings in it are checked before any element + /// is converted, and each element is read when its turn comes rather than up front: a + /// #to_path may change what the array holds after it, and what it put there is joined + /// (and checked) - [ruby-core:48012]. + /// + private static void JoinList(ConversionStorage/*!*/ toPath, IList/*!*/ list, + ref MutableString result, ref int current, Dictionary visitedLists) { + + for (int i = 0; i < list.Count; i++) { + var s = list[i] as MutableString; + if (s != null) { + Protocols.CheckPath(s); + } + } + + for (int i = 0; i < list.Count; i++) { + object part = list[i]; + MutableString str; + var nested = part as IList; + if (nested != null) { + if (nested.Count == 0) { str = MutableString.FrozenEmpty; - } else if (visitedLists != null && visitedLists.ContainsKey(list)) { + } else if (ReferenceEquals(nested, list) || (visitedLists != null && visitedLists.ContainsKey(nested))) { throw RubyExceptions.CreateArgumentError("recursive array"); } else { if (visitedLists == null) { visitedLists = new Dictionary(ReferenceEqualityComparer.Instance); } - visitedLists.Add(list, true); - Push(worklist, list); + visitedLists.Add(nested, true); + JoinList(toPath, nested, ref result, ref current, visitedLists); + visitedLists.Remove(nested); continue; } } else if (part == null) { @@ -1160,22 +1177,32 @@ public static MutableString Join(ConversionStorage/*!*/ toPath, R } if (current > 0) { - // Append negotiates the encodings, so the join of two EUC-JP paths - // stays EUC-JP instead of decaying to binary. + // MRI's fs_enc_check: the encodings have to be compatible, and where that + // leaves US-ASCII the joined part's own encoding is kept, so "a" (US-ASCII) + // joined with a Windows-1251 "b" is Windows-1251. + RubyEncoding encoding = PathEncodingCheck(result, str); AppendDirectoryName(result, str); + result.ForceEncoding(encoding); } else { result = MutableString.CreateMutable(str.Encoding).Append(str); } current++; } - - return result ?? MutableString.CreateEmpty(); } - private static void Push(Stack/*!*/ stack, IList/*!*/ values) { - for (int i = values.Count - 1; i >= 0; i--) { - stack.Push(values[i]); + /// + /// MRI's fs_enc_check: rb_enc_check of the two paths, except that an answer of US-ASCII + /// gives way to the first path's encoding, or failing that the second's. + /// + private static RubyEncoding/*!*/ PathEncodingCheck(MutableString/*!*/ path1, MutableString/*!*/ path2) { + RubyEncoding encoding = path1.RequireCompatibleEncoding(path2); + if (encoding == RubyEncoding.Ascii) { + encoding = path1.Encoding; + if (encoding == RubyEncoding.Ascii) { + encoding = path2.Encoding; + } } + return encoding; } private static void AppendDirectoryName(MutableString/*!*/ result, MutableString/*!*/ name) { From 8d1294bf83086f69629bd7556df889963c9896de Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:11:25 +0100 Subject: [PATCH 124/147] File.expand_path and File.absolute_path keep a path's bytes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File.expand_path of a Windows-1251 path ("/привет") gave back the path's UTF-8 bytes still labelled Windows-1251: the path was decoded to a .NET string, expanded, and encoded again in the filesystem encoding (test_file_exhaustive's test_expand_path_encoding). The result's encoding was the argument's whatever else went into it, so File.expand_path("~") of a US-ASCII "~" was US-ASCII, and so was a US-ASCII relative path joined to the working directory (test_expand_path_encoding_filesystem); two incompatible paths were joined without complaint. MRI's rb_file_expand_path_internal works on bytes: the path's are kept as they are, and only what comes from the system - the working directory, a home directory - is the filesystem's. The result is in the path's encoding beside a root, in the filesystem encoding after a "~", and otherwise in fs_enc_check's answer for the directory and the path, which raises Encoding::CompatibilityError for incompatible ones; a working directory that is not ASCII is converted to that encoding (append_fspath). Off Windows, ExpandPathBytes now does the same: the path crosses into the .NET string byte for byte, the directory or home in front of it is encoded in the filesystem encoding, RubyUtils.ExpandPath folds the dots and separators, and the bytes come back with MRI's encoding. Windows, whose file names are Unicode, keeps the old route. Checked against CRuby 4.0.10 on the two tests' cases and on paths in Windows-1251, EUC-JP, US-ASCII, BINARY and IBM437, with and without a base directory, including the EUC-JP/Windows-31J incompatibility. --- Src/Libraries/Builtins/FileOps.cs | 77 +++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 583cdb305..6cd04a9af 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -915,6 +915,11 @@ private static string StripPathCharacters(string path) { MutableString pathStr = Protocols.CastToPath(toPath, path); RequireUsablePathEncoding(context, pathStr); + if (!IsWindows) { + MutableString basePathStr = (basePath != null) ? Protocols.CastToPath(toPath, basePath) : null; + return ExpandPathBytes(context, pathStr, basePathStr, true); + } + // The base is converted whatever the path, but it is only expanded - "~name" looked // up - when the path needs it: MRI's expand_path ignores it beside an absolute path. string expanded = ExpandTilde(context, DecodePathLike(context, pathStr)); @@ -930,6 +935,73 @@ private static string StripPathCharacters(string path) { return EncodePathLike(context, result, pathStr); } + /// + /// MRI's rb_file_expand_path_internal off Windows. A path is bytes there: what it holds + /// is kept byte for byte, whatever its encoding, and only the pieces that come from the + /// system - the working directory, a home directory - are the filesystem's. The result's + /// encoding is MRI's too: the path's beside a root, the filesystem's after a "~", and + /// fs_enc_check of the directory and the path otherwise (incompatible ones raise). + /// Decoding the path to a .NET string and encoding the result in the filesystem encoding + /// gave a Windows-1251 path back as UTF-8 bytes still labelled Windows-1251. + /// + private static MutableString/*!*/ ExpandPathBytes(RubyContext/*!*/ context, MutableString/*!*/ path, + MutableString basePath, bool expandHome) { + + string bytes = BytesAsChars(path); + RubyEncoding encoding; + if (expandHome && bytes.Length > 0 && bytes[0] == '~') { + int slash = bytes.IndexOf('/'); + string head = (slash < 0) ? bytes : bytes.Substring(0, slash); + string user = DecodePathLike(context, MutableString.CreateBinary(CharsAsBytes(head), path.Encoding)); + MutableString home = context.EncodePath(ExpandTilde(context, user)); + bytes = BytesAsChars(home) + ((slash < 0) ? "" : bytes.Substring(slash)); + encoding = home.Encoding; + } else if (bytes.Length > 0 && bytes[0] == '/') { + encoding = PathEncodingCheck(MutableString.CreateAscii("/"), path); + } else if (basePath != null) { + MutableString directory = ExpandPathBytes(context, basePath, null, expandHome); + encoding = PathEncodingCheck(directory, path); + bytes = BytesAsChars(directory) + "/" + bytes; + } else { + // MRI's append_fspath: the working directory is the filesystem's, and is converted + // to the path's encoding when that is what the two come to. + string cwd = context.Platform.CurrentDirectory; + MutableString directory = context.EncodePath(cwd); + encoding = path.Encoding; + if (encoding != directory.Encoding) { + encoding = PathEncodingCheck(path, directory); + if (encoding != directory.Encoding && !directory.IsAscii()) { + try { + directory = MutableString.Create(cwd, encoding).CheckEncoding(); + } catch (EncoderFallbackException) { + // rb_str_conv_enc gives the string back as it was when it cannot + } + } + } + bytes = BytesAsChars(directory) + "/" + bytes; + } + + string result = RubyUtils.ExpandPath(context.Platform, bytes, null, false); + return MutableString.CreateBinary(CharsAsBytes(result), encoding); + } + + private static string/*!*/ BytesAsChars(MutableString/*!*/ str) { + int count = str.GetByteCount(); + var chars = new char[count]; + for (int i = 0; i < count; i++) { + chars[i] = (char)str.GetByte(i); + } + return new String(chars); + } + + private static byte[]/*!*/ CharsAsBytes(string/*!*/ str) { + var bytes = new byte[str.Length]; + for (int i = 0; i < str.Length; i++) { + bytes[i] = (byte)str[i]; + } + return bytes; + } + /// /// "~" uses $HOME and falls back to the user database; "~name" always goes to the /// user database. A $HOME that is empty or relative is an error, as in CRuby, and @@ -1081,6 +1153,11 @@ private static void RequireUsablePathEncoding(RubyContext/*!*/ context, MutableS var context = self.Context; MutableString pathStr = Protocols.CastToPath(toPath, path); + if (!IsWindows) { + MutableString basePathStr = (basePath != null) ? Protocols.CastToPath(toPath, basePath) : null; + return ExpandPathBytes(context, pathStr, basePathStr, false); + } + string result = RubyUtils.ExpandPath( context.Platform, context.DecodePath(pathStr), From 839966003784247af9edc2eb4bdfd58ff3de9392 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:26:31 +0100 Subject: [PATCH 125/147] IO.allocate's #write, #print and encodings raise "uninitialized stream" An IO made by IO.allocate wrote an empty String without complaint (write("") answered 0, print("") nil, write() 0) and reported an external encoding of UTF-8 - test_io's test_uninitialized. MRI's io_write looks for the stream (GetWriteIO, rb_io_check_initialized) before it notices that there is nothing to write, and #external_encoding and #internal_encoding go through GetOpenFile; all of them raise IOError "uninitialized stream" in CRuby 4.0.10. A closed IO is different: there write("") is still 0 and the encodings are still answered. The write paths call RequireInitialized before the empty-String shortcut (which stays, for the closed-pipe case Open3 depends on), and the two encoding methods do the same; the internal callers of GetExternalEncoding are unchanged. Checked against CRuby 4.0.10 for IO.allocate and for a closed pipe. --- Src/Libraries/Builtins/IoOps.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index f1b1c59ea..c51b1d9cd 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -1668,7 +1668,14 @@ private static int GetStdHandleFd(ConsoleStreamType streamType) { /// nil for a write-only one - which is what a plain "w" or "r+" gets. /// [RubyMethod("external_encoding")] - public static RubyEncoding GetExternalEncoding(RubyIO/*!*/ self) { + public static RubyEncoding ExternalEncoding(RubyIO/*!*/ self) { + // MRI's GetOpenFile: an IO with no stream at all (IO.allocate) has no encoding to + // report, though a closed one still has its own. + self.RequireInitialized(); + return GetExternalEncoding(self); + } + + internal static RubyEncoding GetExternalEncoding(RubyIO/*!*/ self) { if (self.Enc2 != null) { return self.Enc2; } @@ -1684,6 +1691,7 @@ public static RubyEncoding GetExternalEncoding(RubyIO/*!*/ self) { /// [RubyMethod("internal_encoding")] public static RubyEncoding GetInternalEncoding(RubyIO/*!*/ self) { + self.RequireInitialized(); return self.Enc2 != null ? self.Enc : null; } @@ -1838,6 +1846,7 @@ public static int Write(TranscodeStorage/*!*/ encodeForWrite, RubyIO/*!*/ self, [RubyMethod("write")] public static int Write(TranscodeStorage/*!*/ encodeForWrite, ConversionStorage/*!*/ tosConversion, RubyIO/*!*/ self, params object[]/*!*/ args) { + self.RequireInitialized(); int total = 0; foreach (object arg in args) { var str = arg as MutableString; @@ -1872,6 +1881,8 @@ private static int Write(RubyIO/*!*/ self, MutableString/*!*/ val, bool signalOn // MRI's write of an empty string makes no syscall at all and answers 0, even on a // pipe whose reader is gone. Flushing here instead manufactures EPIPE - which is // what Open3.capture3 ("git --version", no stdin data) used to hit on its i.write "". + // It does look for a stream first (GetWriteIO): IO.allocate has none to write to. + self.RequireInitialized(); if (val.IsEmpty) { return 0; } From 3026035e6ec1f3193267e1d0292830154ffefc1d Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:26:32 +0100 Subject: [PATCH 126/147] File#initialize refuses to reinitialize a File Calling #initialize again on an open File reopened it on the new path (f.send(:initialize, path) answered the File), and with no arguments it complained about the arity instead - test_io's test_reinitialize. MRI's rb_file_initialize raises RuntimeError "reinitializing File" for a File that already has a stream, open or closed, before it looks at the arguments; CRuby 4.0.10 does so for all three cases. The prelude's File#initialize asks a new __ir_require_uninitialized__ first. File.new does not go through it (its constructor is C#), and a subclass's super into File#initialize starts from an allocated File, which has no stream yet. Checked against CRuby 4.0.10, and that File.new and a File subclass whose initialize calls super still open their file. --- Src/Libraries/Builtins/FileOps.cs | 9 +++++++++ Src/StdLib/ironruby/ruby4.rb | 1 + 2 files changed, 10 insertions(+) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 6cd04a9af..e6b804270 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -68,6 +68,15 @@ internal static bool Exists(RubyContext/*!*/ context, MutableString/*!*/ path) { return Reinitialize(toInt, toHash, toPath, toStr, new RubyFile(self.Context), descriptorOrPath, optionsOrMode, optionsOrPermissions, options); } + // MRI's rb_file_initialize refuses a File that already has a stream - open or closed - + // before it looks at the arguments; the prelude's File#initialize asks here first. + [RubyMethod("__ir_require_uninitialized__", RubyMethodAttributes.PrivateInstance)] + public static void RequireUninitialized(RubyIO/*!*/ self) { + if (self.Initialized) { + throw new RuntimeError("reinitializing File"); + } + } + [RubyMethod("initialize", RubyMethodAttributes.PrivateInstance)] public static RubyFile/*!*/ Reinitialize( ConversionStorage/*!*/ toInt, diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index e06ff9766..db996e12d 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -2232,6 +2232,7 @@ class File # File takes a permission argument between the mode and the options. def initialize(*args, **opts) + __ir_require_uninitialized__ if args.size > 3 ::Kernel.raise(::ArgumentError, "wrong number of arguments (given #{args.size}, expected 1..3)") From 1224db2e4629aa1938fb32e323c0d0912ad68abb Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:29:11 +0100 Subject: [PATCH 127/147] IO#gets of a long line from a pipe waits for the rest of it A line longer than the 4 KiB read buffer that reached a pipe in two writes came back as two lines: 8188 "a"s, a pause, then "\r\na\r\n" was read as "aaa...a" and "\r\n" (test_io's test_gets_chomp_default_rs, where r.gets(chomp: true) answered "" instead of "a"). The reader for the default separator grew its buffer and read again until it found "\n", but took any read that did not fill the buffer to be the end of the stream. A pipe or a socket answers with what it has so far, so a short read is not the end; only a read of nothing is. CRuby 4.0.10 gives the whole line in each case. The loop now ends the line at the end of the stream only when a read brings nothing, and grows the buffer before reading into a full one. The general reader (other separators, a limit) already did this. Io_GetsLongLineFromPipe1 covers lines of 8188 and 20000 bytes written in two parts; checked against CRuby 4.0.10, and spec/core/io as before. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/IoTests.cs | 20 ++++++++++++++++++++ Src/Ruby/Builtins/RubyBufferedStream.cs | 24 ++++++++++++------------ 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0841f56ec..7b57057f7 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1073,6 +1073,7 @@ public Tests(Driver/*!*/ driver) { Io_LineReaders2, Io_LineReaders3, Io_UngetcConverted1, + Io_GetsLongLineFromPipe1, Io_UnreadPushedBack1, Io_WideLineReaders1, Io_Timeout1, diff --git a/Src/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index d26856bb2..90dedfa6a 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -876,6 +876,26 @@ def t(label) /// buffer reaching back past the start of the file is not given back. IO.copy_stream writes through its /// destination IO the same way, and to the end of a file opened for appending. /// + /// + /// A line longer than the read buffer that reaches a pipe in two writes is one line: a + /// short read is not the end of the stream (test_io's test_gets_chomp_default_rs). + /// + public void Io_GetsLongLineFromPipe1() { + TestOutput(@" +[8188, 20000].each do |n| + r, w = IO.pipe + t = Thread.new { w.write('a' * n); sleep 0.2; w.write(""\r\na\r\n""); w.close } + first = r.gets + p [first.size, first.end_with?(""\r\n""), r.gets(chomp: true), r.gets] + t.join + r.close +end +", @" +[8190, true, ""a"", nil] +[20002, true, ""a"", nil] +"); + } + public void Io_UnreadPushedBack1() { TestOutput(@" require 'ruby4' diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index b48d337d9..148801597 100644 --- a/Src/Ruby/Builtins/RubyBufferedStream.cs +++ b/Src/Ruby/Builtins/RubyBufferedStream.cs @@ -655,23 +655,23 @@ public MutableString ReadLine(RubyEncoding/*!*/ encoding, bool preserveEndOfLine bool bufferResized = false; int lf = Array.IndexOf(_buffer, LF, _bufferStart, _bufferCount); while (lf < 0) { - int s = _bufferCount; - LoadBuffer(_buffer.Length - _bufferCount); - Debug.Assert(_bufferStart == 0); - - lf = Array.IndexOf(_buffer, LF, s, _bufferCount - s); - if (lf >= 0) { - break; + if (_bufferCount == _buffer.Length) { + Debug.Assert(_bufferStart == 0); + Array.Resize(ref _buffer, _buffer.Length << 1); + bufferResized = true; } - // end of stream: - if (_bufferCount < _buffer.Length) { + // Only a read of nothing is the end of the stream. A pipe or a socket hands over + // what it has so far, so a short read used to end the line there: a line longer + // than the buffer that arrived in two writes came back as two lines. + int s = _bufferCount; + int loaded = LoadBuffer(_buffer.Length - _bufferCount); + Debug.Assert(_bufferStart == 0); + if (loaded == 0) { return ConsumeLine(encoding, _bufferCount, _bufferCount, bufferResized); } - Array.Resize(ref _buffer, _buffer.Length << 1); - bufferResized = true; - _bufferStart = 0; + lf = Array.IndexOf(_buffer, LF, s, _bufferCount - s); } int lineLength; From a8f50bc5180a662758d6fc13683351c38ae1cc21 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:37:37 +0100 Subject: [PATCH 128/147] File.expand_path joins a relative path to its base without doubling a root slash ExpandPathBytes (8d1294bf) appended "/" and the path to the expanded base directory and expanded the result. When the base is the root, that made File.expand_path(".", "/") "//" and File.expand_path(".", "//") "///"; CRuby's rb_file_expand_path_internal only adds a separator when the base does not already end in one, giving "/" and "//". The base's bytes are now passed to RubyUtils.ExpandPath as its base directory, which already joins the two that way. Checked against CRuby 4.0.10: test_file_exhaustive's test_expand_path* and test_absolute_path* pass, and expand_path(".", "/"), (".", "//"), ("a", "/b/") and ("..", "/") print what CRuby prints. --- Src/Libraries/Builtins/FileOps.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index e6b804270..860957671 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -957,6 +957,8 @@ private static string StripPathCharacters(string path) { MutableString basePath, bool expandHome) { string bytes = BytesAsChars(path); + // the absolute directory a relative path is taken in, as bytes too + string baseBytes = null; RubyEncoding encoding; if (expandHome && bytes.Length > 0 && bytes[0] == '~') { int slash = bytes.IndexOf('/'); @@ -970,7 +972,7 @@ private static string StripPathCharacters(string path) { } else if (basePath != null) { MutableString directory = ExpandPathBytes(context, basePath, null, expandHome); encoding = PathEncodingCheck(directory, path); - bytes = BytesAsChars(directory) + "/" + bytes; + baseBytes = BytesAsChars(directory); } else { // MRI's append_fspath: the working directory is the filesystem's, and is converted // to the path's encoding when that is what the two come to. @@ -987,10 +989,10 @@ private static string StripPathCharacters(string path) { } } } - bytes = BytesAsChars(directory) + "/" + bytes; + baseBytes = BytesAsChars(directory); } - string result = RubyUtils.ExpandPath(context.Platform, bytes, null, false); + string result = RubyUtils.ExpandPath(context.Platform, bytes, baseBytes, false); return MutableString.CreateBinary(CharsAsBytes(result), encoding); } From d07288ad2815193eec1a826e54803725d96fa1bd Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:37:37 +0100 Subject: [PATCH 129/147] IO#gets with a limit counts the bytes of the converted line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an IO has an internal encoding, a byte limit on gets/readline/ each_line applies to the converted text in CRuby: a "r:iso-8859-1:utf-8" file holding "\xE9\xE9\xE9\n" gives "é" for readline(2) and "éé" for readline(3), since each é is two bytes once converted. IronRuby took the converting path only for internal encodings of more than one byte per character, so with a single-byte external encoding it cut the line at the file's bytes ("éé" for readline(2)), and a UTF-32LE internal encoding with "w+:utf-8:utf-32le" failed test_readline_limit_nonascii. A limit now sends the line through the converting reader whenever there is an internal encoding. Checked against CRuby 4.0.10: test_io's and test_io_m17n's test_readline_limit*, test_gets_limit* and test_each_line_limit* pass, and readline(2), readline(3), gets(nil, 3), each_line(2) and gets(1) on the file above print what CRuby prints. --- Src/Libraries/Builtins/IoOps.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index c51b1d9cd..c4392b3a2 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -2586,7 +2586,10 @@ private static bool EndsWith(List/*!*/ bytes, byte[]/*!*/ suffix) { /// private static MutableString ReadLineOrParagraph(TranscodeStorage/*!*/ transcode, TranscodeStorage/*!*/ universal, RubyIO/*!*/ self, bool universalNewline, MutableString separator, int limit, out bool converted) { - converted = self.HasPendingChars || (self.Enc2 != null && self.Enc2.MinBytesPerChar > 1); + // A byte limit counts the bytes of the converted text, too: "r:iso-8859-1:utf-8" with a + // limit of 2 reads one "é", which is two bytes once converted, not the two "é"s two + // bytes of the file hold; a UTF-32LE internal encoding makes every character four. + converted = self.HasPendingChars || (self.Enc2 != null && (self.Enc2.MinBytesPerChar > 1 || limit >= 0)); if (converted) { return ReadLineFromPendingChars(transcode, universal, self, separator, limit); } From 2eb180aa89ba3e2461745b506d3a70764fad2f2b Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:40:42 +0100 Subject: [PATCH 130/147] A buffered IO write delivers what handle_interrupt(:on_blocking) held back MRI's io_binwrite calls rb_thread_check_ints before it writes anything, which is a blocking interrupt check: inside Thread.handle_interrupt( RuntimeError => :on_blocking), a Thread#raise that arrived earlier is raised at the next IO#write or #puts, and the bytes are not written. IO#syswrite makes no such check, and Kernel#p writes under rb_uninterruptible, so its output still goes out. IronRuby checked only at waits, so `puts "ng"` in test_thread's test_handle_interrupt_and_io was printed before the exception came. IO#write's common path (the one #puts, #print and #<< use, not the one syswrite falls back to) now calls CheckAsyncException(true) before it writes a non-empty string, and Kernel#p marks its writes as uninterruptible with a thread-static count. Thread_HandleInterruptIoWrite1 checks write, puts, syswrite and p against CRuby 4.0's output. test_handle_interrupt_and_io still hangs: its `nil while th_waiting` loop is replaced by an OSR copy that keeps th_waiting in a CLR local, so it never sees the main thread's write (with -X:NoOSR the test prints "ok" as CRuby does). ruby/spec core/io, core/thread, kernel p/puts/print/ warn and library/stringio show no new failures; the IronRuby.Tests Thread, Fiber and IO tests pass. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/FiberTests.cs | 43 ++++++++++++++++++++++++ Src/Libraries/Builtins/IoOps.cs | 14 ++++++++ Src/Libraries/Builtins/KernelOps.cs | 22 +++++++----- 4 files changed, 72 insertions(+), 8 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 2d0d006b3..a84e3981a 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -1161,6 +1161,7 @@ public Tests(Driver/*!*/ driver) { Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, Thread_HandleInterruptInherited1, + Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, Thread_KillBehindRaise1, Thread_KillBehindRescuedRaise1, diff --git a/Src/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index daa0a3117..60351dc51 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -193,6 +193,49 @@ p q.pop "); } + /// + /// A buffered IO write is an interrupt check, as MRI's io_binwrite makes one before it writes + /// (rb_thread_check_ints): an exception Thread.handle_interrupt(... => :on_blocking) holds back + /// is raised there and nothing is written. IO#syswrite makes no check, and Kernel#p writes under + /// rb_uninterruptible (CRuby's TestThread#test_handle_interrupt_and_io and _and_p). + /// + public void Thread_HandleInterruptIoWrite1() { + TestOutput(@" +require 'ruby4' +r, w = IO.pipe +def check(label) + ready = Thread::Queue.new + $go = false + t = Thread.new { + Thread.current.report_on_exception = false + Thread.handle_interrupt(RuntimeError => :on_blocking) { + ready << true + Thread.pass until $go + yield + } + } + ready.pop + t.raise RuntimeError, label + $go = true + t.join +rescue RuntimeError => e + e.message +end +p check(""write"") { w.write ""write "" } +p check(""puts"") { w.puts ""puts"" } +p check(""syswrite"") { w.syswrite ""syswrite "" } +p check(""p"") { o = $stdout; $stdout = w; p :p; $stdout = o } +w.close +p r.read +", @" +""write"" +""puts"" +""syswrite"" +""p"" +""syswrite :p\n"" +"); + } + /// /// Thread#raise reaches the fiber the thread is running, wherever its fibers are in a switch. /// Every fiber is a CLR thread of its own; the interrupt used to be routed to the fiber that diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index 974be3e4b..5072bf517 100644 --- a/Src/Libraries/Builtins/IoOps.cs +++ b/Src/Libraries/Builtins/IoOps.cs @@ -1854,6 +1854,13 @@ public static int Write(TranscodeStorage/*!*/ encodeForWrite, ConversionStorage< return site.Target(site, self, val) as MutableString ?? val; } + /// + /// Non-zero while Kernel#p writes on this thread: MRI's rb_p writes under rb_uninterruptible, + /// so a buffered write there is no interrupt check. + /// + [ThreadStatic] + internal static int _uninterruptibleWrites; + private static int Write(RubyIO/*!*/ self, MutableString/*!*/ val, bool signalOnPipeError) { // MRI's write of an empty string makes no syscall at all and answers 0, even on a // pipe whose reader is gone. Flushing here instead manufactures EPIPE - which is @@ -1862,6 +1869,13 @@ private static int Write(RubyIO/*!*/ self, MutableString/*!*/ val, bool signalOn return 0; } + // MRI's io_binwrite checks for interrupts before it writes anything, as a blocking call + // does (rb_thread_check_ints): an exception Thread.handle_interrupt(... => :on_blocking) + // holds back is raised there, before the bytes go out. syswrite makes no such check. + if (signalOnPipeError && _uninterruptibleWrites == 0) { + RubyUtils.CheckAsyncException(true); + } + try { int bytesWritten = self.WriteBytes(val, 0, val.GetByteCount()); if (self.AutoFlush || !signalOnPipeError) { diff --git a/Src/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index fc06079da..198583575 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -3218,15 +3218,21 @@ public static object PrintInspect(BinaryOpStorage/*!*/ writeStorage, UnaryOpStor inspectedArgs[i] = Protocols.ConvertToString(tosConversion, inspect.Target(inspect, args[i])); } - // no dynamic dispatch to "puts": - foreach (var arg in inspectedArgs) { - PrintOps.Puts(writeStorage, writeStorage.Context.StandardOutput, arg); - } + // no dynamic dispatch to "puts"; and no interrupt check in the writes, which MRI makes + // under rb_uninterruptible (see RubyIOOps.Write): + RubyIOOps._uninterruptibleWrites++; + try { + foreach (var arg in inspectedArgs) { + PrintOps.Puts(writeStorage, writeStorage.Context.StandardOutput, arg); + } - // rb_f_p flushes $stdout when it is an IO, so the output is visible to a reader at once - var stdout = writeStorage.Context.StandardOutput as RubyIO; - if (args.Length > 0 && stdout != null) { - RubyIOOps.Flush(stdout); + // rb_f_p flushes $stdout when it is an IO, so the output is visible to a reader at once + var stdout = writeStorage.Context.StandardOutput as RubyIO; + if (args.Length > 0 && stdout != null) { + RubyIOOps.Flush(stdout); + } + } finally { + RubyIOOps._uninterruptibleWrites--; } if (args.Length == 0) { From 73cc182d979a8495490a16dc5de78688bb3bdb16 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:43:25 +0100 Subject: [PATCH 131/147] Regexp literals and interpolations are preprocessed as MRI does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several encoding rules of MRI's regexp preprocessing (re.c's rb_reg_preprocess and its callers in prism_compile.c) were missing: - A regexp literal's text took the file's encoding even where prism flags it FORCED_BINARY: /\x80/ in a US-ASCII file was US-ASCII, BINARY in MRI (parse_regexp_encoding). - An interpolation of a plain string literal (/a#{"b"}c/) is folded into the literal by MRI's compiler, so the regexp is built once and a pattern Onigmo rejects is a SyntaxError: /#{"\x80"}/ in a UTF-8 file was accepted. - Each piece of literal text of an interpolated regexp is checked on its own (parse_regexp_string_part): /\xc2#{ }\xa1/u is a SyntaxError in MRI. - The interpolated pieces must each be valid in their encoding and agree on the encoding they tie the regexp to (rb_reg_preprocess_dregexp): /#{s1}#{s2}/ with s1, s2 = '\xc2', '\xa1' is "ArgumentError: too short escaped multibyte character", a broken piece "invalid multibyte character", and a Windows-31J and an EUC-JP piece "RegexpError: encoding mismatch in dynamic regexp". - A \u escape above 0x7f cannot meet a character, raw or escaped, of a non UTF-8 pattern: Regexp.new("\xc2\xa1\\u{6666}".b) is "UTF-8 character in non UTF-8 regexp", and the other order "non ASCII character in UTF-8 regexp" or "escaped non ASCII character in UTF-8 regexp". The bridge now reads the binary flag, folds string-literal interpolations and checks literal pieces (RubyRegex.CheckLiteralFragment, reported as a SyntaxError); a regexp whose parts all turn out literal is created as a static one; the dynamic CreateRegex* helpers check their parts first (RubyRegex.GetFixedEncoding), and RubyRegex.Set refuses mixed \u patterns (RequireSingleEncoding). Checked against CRuby 4.0.10 with a probe of 75 literal forms in US-ASCII, UTF-8 and EUC-JP files, now all equal but /ሴ#{ }\x80/ in US-ASCII (SyntaxError here, RegexpError in MRI), and 21 Regexp.new patterns. test_m17n goes from 13 failures to 5 (test_dynamic_{utf8,eucjp,sjis}_regexp, test_regexp_usascii, test_regexp_mixed_unicode, test_regexp_embed pass). New IronRuby.Tests test Regex_LiteralEncodings1; the Regex*, MutableString*, String_* tests pass; ruby/spec language, core/regexp, core/matchdata, core/string, core/symbol, core/encoding and library/stringscanner show no failure outside Util/spec-known-failures.txt. --- Src/IronRuby.Tests/RubyTests.cs | 1 + Src/IronRuby.Tests/Runtime/RegexTests.cs | 43 ++++ Src/Prism/PrismAstBridge.cs | 71 +++++- Src/Ruby/Builtins/RubyRegex.cs | 210 ++++++++++++++++++ .../Ast/Expressions/RegularExpression.cs | 14 ++ Src/Ruby/Runtime/RubyOps.cs | 55 ++++- 6 files changed, 380 insertions(+), 14 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 0841f56ec..9f990b117 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -206,6 +206,7 @@ public Tests(Driver/*!*/ driver) { Regex_MatchStringClassAndIdentity1, Regex_SharedTranslation1, Regex_SharedTranslation2, + Regex_LiteralEncodings1, Scenario_RubyScopeParsing, Scenario_RubyScopes1, diff --git a/Src/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 62770c6a1..f2566b746 100644 --- a/Src/IronRuby.Tests/Runtime/RegexTests.cs +++ b/Src/IronRuby.Tests/Runtime/RegexTests.cs @@ -620,6 +620,49 @@ public void Regex_SharedTranslation2() { Assert(field.GetValue(d) == compiled); Assert(d.Match(input).GetGroupStart(1) == 10); // the last "tr" } + + /// + /// The encoding of a regexp literal and MRI's preprocessing of its pieces: a \x escape above + /// 0x7f makes a US-ASCII file's literal binary, a literal interpolating only string literals + /// is built once and a SyntaxError if it is invalid, each literal piece of an interpolated + /// one must be valid alone, and the interpolated pieces must be valid and agree on an + /// encoding (rb_reg_preprocess_dregexp). A \u escape cannot meet bytes of another encoding. + /// + public void Regex_LiteralEncodings1() { + TestOutput(@" +require 'ruby4' +def t(code) + eval(code).encoding +rescue SyntaxError, RegexpError, ArgumentError => e + e.class +end +p t(%Q{# encoding: US-ASCII\n/\\x80/}) +p t(%Q{/a\#{""\\x80""}/}) +p t(%Q{/\\xc2\#{ }\\xa1/u}) +p t(%Q{/\\xc2\\xa1\#{ }/u}) +s1, s2 = '\xc2', '\xa1' +p((/#{s1}#{s2}/ rescue $!)) +x = ""\x80"" +p((/#{x}/ rescue $!)) +p((Regexp.new(""\xc2\xa1\\u{6666}"".b) rescue $!)) +p((Regexp.new(""\\u{6666}\\xc2\\xa1"".b) rescue $!)) +p 2.times.map { /a#{""b""}c/ }.uniq(&:object_id).size +r = Regexp.new(""\xa4\xa2"".b.force_encoding(""EUC-JP"")) +s = ""\x82\xa0"".b.force_encoding(""Windows-31J"") +p((/#{s}#{r}/ rescue $!)) +", @" +# +SyntaxError +SyntaxError +# +# +# +# +# +1 +# +"); + } } } diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index b891a21fb..9e9c6cdf5 100644 --- a/Src/Prism/PrismAstBridge.cs +++ b/Src/Prism/PrismAstBridge.cs @@ -712,20 +712,24 @@ private int StatementLine(Pm.PmNode/*!*/ node) { case Pm.EmbeddedStatementsNode embedded: return StatementsAsExpression(embedded.Statements, span); - case Pm.RegularExpressionNode regex: + case Pm.RegularExpressionNode regex: { WarnRegexp(regex.Unescaped, span); + var encoding = RegexLiteralEncoding(regex); return new RegularExpression( - new List { new StringLiteral(LiteralValue(regex.Unescaped, _encoding), _encoding, span) }, + new List { new StringLiteral(LiteralValue(regex.Unescaped, encoding), encoding, span) }, RegexOptions(regex), false, span); - case Pm.MatchLastLineNode matchLast: + } + case Pm.MatchLastLineNode matchLast: { WarnRegexp(matchLast.Unescaped, span); + var encoding = RegexLiteralEncoding(matchLast); return new RegularExpression( - new List { new StringLiteral(LiteralValue(matchLast.Unescaped, _encoding), _encoding, span) }, + new List { new StringLiteral(LiteralValue(matchLast.Unescaped, encoding), encoding, span) }, RegexOptions(matchLast), true, span); + } case Pm.InterpolatedRegularExpressionNode interpRegex: - return new RegularExpression(StringParts(interpRegex.Parts), RegexOptions(interpRegex), span); + return new RegularExpression(RegexParts(interpRegex.Parts, RegexOptions(interpRegex)), RegexOptions(interpRegex), span); case Pm.InterpolatedMatchLastLineNode interpMatchLast: - return new RegularExpression(StringParts(interpMatchLast.Parts), RegexOptions(interpMatchLast), true, span); + return new RegularExpression(RegexParts(interpMatchLast.Parts, RegexOptions(interpMatchLast)), RegexOptions(interpMatchLast), true, span); case Pm.CallNode call: return Call(call, span); @@ -1268,6 +1272,61 @@ private static bool MayHaveNestedQuantifier(string/*!*/ pattern) { return result; } + /// + /// The parts of an interpolated regexp. An interpolation that is itself a plain string + /// literal (/a#{"b"}/) is folded into the literal text around it, as MRI's compiler does: + /// a regexp left with literal parts only is then built once, like /ab/, and a pattern + /// Onigmo rejects is a SyntaxError rather than a RegexpError. (An empty /a#{ }/ stays an + /// interpolation of nil, in MRI too.) + /// + private List/*!*/ RegexParts(Pm.PmNode/*!*/[]/*!*/ parts, RubyRegexOptions options) { + var result = new List(); + foreach (var part in parts) { + if (part is Pm.StringNode fragment) { + CheckRegexFragment(fragment, options); + } + if (part is Pm.EmbeddedStatementsNode embedded) { + var body = (embedded.Statements as Pm.StatementsNode)?.Body; + if (body != null && body.Length == 1 && body[0] is Pm.StringNode str) { + result.Add(new StringLiteral(LiteralValue(str.Unescaped, LiteralEncoding(str)), LiteralEncoding(str), Span(str))); + continue; + } + } + result.AddRange(StringParts(new[] { part })); + } + return result; + } + + /// + /// MRI's compiler checks each piece of literal text of an interpolated regexp on its own + /// (parse_regexp_string_part): /\xc2#{ }\xa1/u is a SyntaxError although /\xc2\xa1/u is + /// fine. Text without escapes or non-ASCII characters has nothing to check. + /// + private void CheckRegexFragment(Pm.StringNode/*!*/ fragment, RubyRegexOptions options) { + if (_errorSink == null) { + return; + } + byte[] bytes = fragment.Unescaped; + if (Array.IndexOf(bytes, (byte)'\\') < 0 && Array.TrueForAll(bytes, b => b < 0x80)) { + return; + } + var encoding = LiteralEncoding(fragment); + try { + RubyRegex.CheckLiteralFragment(MutableString.CreateBinary(bytes, encoding), options); + } catch (RegexpError e) { + _errorSink.Add(_sourceUnit, e.Message, Span(fragment), 0, Severity.FatalError); + } + } + + /// + /// The encoding of a regexp literal's text: binary when prism says a \x escape above 0x7f + /// forces it (/\x80/ in a US-ASCII file), the source encoding otherwise. MRI's + /// parse_regexp_encoding; a /u, /e, /s or /n option is the regexp options' business. + /// + private RubyEncoding/*!*/ RegexLiteralEncoding(Pm.PmNode/*!*/ node) { + return HasFlag(node, Pm.RegularExpressionFlags.ForcedBinaryEncoding) ? RubyEncoding.Binary : _encoding; + } + private ConstructedSymbol Symbol(Pm.PmNode/*!*/ node) { switch (node) { case Pm.SymbolNode symbol: return new ConstructedSymbol(LiteralText(symbol.Unescaped)); diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index 012c6cbe7..c34413915 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -161,9 +161,188 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _pattern = pattern.PrepareForCharacterRead().Clone().Freeze(); } + RequireSingleEncoding(); TransformPattern(false); } + /// + /// MRI's rb_reg_check_preprocess, which its compiler runs on each piece of literal text of + /// an interpolated regexp literal (/\xc2#{x}\xa1/u): the piece alone must be valid in its + /// encoding, and its escapes must decode, or the literal is a SyntaxError even though the + /// pieces would make a valid pattern together. Only escapes and encodings are checked + /// here, not the pattern's syntax: a piece may well be an unbalanced "(". + /// Throws RegexpError. + /// + public static void CheckLiteralFragment(MutableString/*!*/ fragment, RubyRegexOptions options) { + ContractUtils.RequiresNotNull(fragment, "fragment"); + var regex = new RubyRegex(); + regex._options = options & ~RubyRegexOptions.Once; + RubyEncoding encoding = RubyEncoding.GetRegexEncoding(options); + regex._pattern = (encoding != null) ? MutableString.CreateBinary(fragment.ToByteArray(), encoding) : fragment; + if (regex._pattern.Encoding != RubyEncoding.Binary && regex._pattern.ContainsInvalidCharacters()) { + throw new RegexpError("invalid multibyte character: " + regex.Inspect().ToString()); + } + regex.RequireSingleEncoding(); + regex.GetClrPatternSource(); + } + + /// + /// The encoding a piece of an interpolated regexp ties the regexp to, or null if it is + /// ASCII only and escapes nothing outside ASCII (MRI's rb_reg_preprocess fixed_enc): its own + /// encoding for a character outside ASCII, a \xHH or octal escape above 0x7f or a + /// \p{...} property, UTF-8 for a \u escape above 0x7f, whichever comes first. A piece that + /// is not valid in its encoding is an ArgumentError, as in MRI. + /// + public static RubyEncoding GetFixedEncoding(MutableString/*!*/ part) { + RubyEncoding encoding = part.Encoding; + if (encoding != RubyEncoding.Binary && part.ContainsInvalidCharacters()) { + throw RubyExceptions.CreateArgumentError("invalid multibyte character"); + } + if (!encoding.IsAsciiIdentity) { + return encoding; + } + if (!part.IsAscii()) { + return encoding; + } + string source = part.ToString(); + int i = source.IndexOf('\\'); + if (i >= 0 && encoding != RubyEncoding.Binary && encoding != RubyEncoding.Ascii) { + // its escapes must decode on their own: /#{'\xc2'}#{'\xa1'}/ is an ArgumentError + try { + CheckLiteralFragment(part, RubyRegexOptions.NONE); + } catch (RegexpError e) { + string message = e.Message; + int at = message.IndexOf(": /", StringComparison.Ordinal); + throw RubyExceptions.CreateArgumentError(at < 0 ? message : message.Substring(0, at)); + } + } + while (i >= 0 && i + 1 < source.Length) { + char c = source[i + 1]; + if (c == 'u') { + ReadUnicodeEscape(source, i + 2, out bool nonAscii); + if (nonAscii) { + return RubyEncoding.UTF8; + } + } else if (c == 'p' || c == 'P') { + if (i + 2 < source.Length && source[i + 2] == '{') { + return encoding; + } + } else { + int value = ReadByteEscape(source, i, out _); + if (value >= 0x80) { + return encoding; + } + } + // an escaped backslash is not the start of an escape + i = source.IndexOf('\\', i + 2); + } + return null; + } + + /// + /// MRI's rb_reg_preprocess: a regexp is in one encoding, so in a pattern of an encoding + /// other than UTF-8 a \u escape above 0x7f (which can only mean UTF-8) cannot meet a + /// character of the pattern's own encoding outside ASCII, raw or written as \xHH or octal + /// escapes. Which of the three errors it is depends on which came first. + /// US-ASCII is left alone: MRI reads its byte escapes differently. + /// + private void RequireSingleEncoding() { + RubyEncoding encoding = _pattern.Encoding; + if (encoding == RubyEncoding.UTF8 || encoding == RubyEncoding.Ascii || !encoding.IsAsciiIdentity) { + return; + } + string source = _pattern.ConvertToString(); + if (source.IndexOf("\\u", StringComparison.Ordinal) < 0) { + return; + } + + const int None = 0, Own = 1, Utf8 = 2; + int fixedTo = None; + bool extended = (_options & RubyRegexOptions.Extended) != 0; + var groups = new Stack(); + int classDepth = 0; + int i = 0; + while (i < source.Length) { + char c = source[i]; + if (c != '\\') { + int next = SkipNonEscape(source, i, ref extended, groups, ref classDepth); + if (next == i + 1 && c >= 0x80) { + if (fixedTo == Utf8) { + throw new RegexpError("non ASCII character in UTF-8 regexp: " + PreprocessErrorSource()); + } + fixedTo = Own; + } + i = next; + continue; + } + + int value = ReadByteEscape(source, i, out int end); + if (value >= 0) { + if (value >= 0x80) { + if (fixedTo == Utf8) { + throw new RegexpError("escaped non ASCII character in UTF-8 regexp: " + PreprocessErrorSource()); + } + fixedTo = Own; + } + i = end; + continue; + } + + if (i + 1 < source.Length && source[i + 1] == 'u') { + end = ReadUnicodeEscape(source, i + 2, out bool nonAscii); + if (nonAscii) { + if (fixedTo == Own) { + throw new RegexpError("UTF-8 character in non UTF-8 regexp: " + PreprocessErrorSource()); + } + fixedTo = Utf8; + } + i = end; + continue; + } + + // any other escape, \\ included, is two characters + i += 2; + } + } + + /// + /// Steps over the code points of a \uHHHH or \u{H ...} escape whose digits start at + /// , telling whether one of them is above 0x7f. A malformed escape + /// is left to the translation to refuse. + /// + private static int ReadUnicodeEscape(string/*!*/ source, int i, out bool nonAscii) { + nonAscii = false; + if (i < source.Length && source[i] == '{') { + int j = i + 1; + while (j < source.Length && source[j] != '}') { + int value = 0, digits = 0; + while (j < source.Length && Tokenizer.ToDigit(source[j]) < 16) { + value = value * 16 + Tokenizer.ToDigit(source[j]); + j++; + digits++; + } + if (digits > 0 && value > 0x7f) { + nonAscii = true; + } + if (digits == 0) { + if (source[j] != ' ' && source[j] != '\t') { + break; + } + j++; + } + } + return Math.Min(j + 1, source.Length); + } + + int code = 0, count = 0; + while (count < 4 && i + count < source.Length && Tokenizer.ToDigit(source[i + count]) < 16) { + code = code * 16 + Tokenizer.ToDigit(source[i + count]); + count++; + } + nonAscii = count == 4 && code > 0x7f; + return i + count; + } + /// /// Creates a copy of the proc that has the same target, context, self object as this instance. /// Doesn't copy instance data. @@ -1769,6 +1948,37 @@ public static void RequireValidPattern(MutableString/*!*/ pattern) { } // For an error message about bytes that do not decode: ASCII as is, the rest as \xHH. + /// + /// The pattern as MRI's preprocessing errors show it (rb_reg_error_desc): between slashes, + /// without options, a character outside ASCII as \xHH if it is one byte and as \x{HHHH} + /// if it is more. + /// + private string/*!*/ PreprocessErrorSource() { + var result = new StringBuilder("/"); + RubyEncoding encoding = _pattern.Encoding; + if (encoding == RubyEncoding.Binary) { + result.Append(EscapeNonAsciiBytes(_pattern)); + } else { + foreach (char c in _pattern.ConvertToString()) { + if (c < 0x80) { + result.Append(c); + continue; + } + byte[] bytes = encoding.EscapingEncoding.GetBytes(new[] { c }); + if (bytes.Length == 1) { + result.Append("\\x").Append(bytes[0].ToString("X2", System.Globalization.CultureInfo.InvariantCulture)); + } else { + result.Append("\\x{"); + foreach (byte b in bytes) { + result.Append(b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)); + } + result.Append('}'); + } + } + } + return result.Append('/').ToString(); + } + private static string/*!*/ EscapeNonAsciiBytes(MutableString/*!*/ str) { var result = new StringBuilder(); foreach (byte b in str.ToByteArray()) { diff --git a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs index fc44d7b23..998eb27eb 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs @@ -80,6 +80,20 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options } MSA.Expression/*!*/ StringConstructor.IFactory.CreateExpressionM(AstGenerator/*!*/ gen, MSAst.ExpressionCollectionBuilder/*!*/ args) { + // Literal parts only (/a#{"b"}c/, folded by the parser), merged into one constant: the regexp + // is as static as /abc/, built once and a SyntaxError if Onigmo rejects it, as MRI compiles it. + // The text gets the encoding CreateMutableStringM would give it. + if (args.Count == 1 && args.Expression0 is MSA.ConstantExpression constant && constant.Value is MutableString literal) { + var encoding = literal.Encoding; + var sourceEncoding = gen.Encoding; + if (encoding != sourceEncoding && sourceEncoding != RubyEncoding.Ascii && sourceEncoding.IsAsciiIdentity && literal.IsAscii()) { + encoding = sourceEncoding; + } + return Methods.CreateRegexB.OpCall( + Ast.Constant(literal.ToByteArray()), encoding.Expression, AstUtils.Constant(_options), AstUtils.Constant(new StrongBox(null)) + ); + } + string suffix = new String('M', args.Count); args.Add(gen.Encoding.Expression); args.Add(AstUtils.Constant(_options)); diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 9cab79818..d5dbe7510 100644 --- a/Src/Ruby/Runtime/RubyOps.cs +++ b/Src/Ruby/Runtime/RubyOps.cs @@ -3228,13 +3228,13 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc if (once) { // Note that the user is responsible for thread synchronization if (regexpCache.Value == null) { - regexpCache.Value = CreateFrozen(createRegex); + regexpCache.Value = CreateFrozen(createRegex, isLiteralWithoutSubstitutions); } return regexpCache.Value; } else { // In the future, we can consider caching the last Regexp. For some regexp literals // with substitution, the substition will be the same most of the time - return CreateFrozen(createRegex); + return CreateFrozen(createRegex, isLiteralWithoutSubstitutions); } } catch (RegexpError e) { if (isLiteralWithoutSubstitutions) { @@ -3251,9 +3251,15 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc /// MRI freezes a regexp literal, interpolated or not, but leaves Regexp.new unfrozen. /// Every literal is built through here, so this is the one place that has to do it. /// It does not intern them: /x/.equal?(/x/) is false in MRI too. + /// A literal whose bytes do not decode in its encoding (/#{"\x80"}/ in a UTF-8 file) is + /// refused when it is compiled, which comes out as a SyntaxError; the pieces of an + /// interpolated one have been checked by CheckDynamicRegexParts. /// - private static RubyRegex/*!*/ CreateFrozen(Func createRegex) { + private static RubyRegex/*!*/ CreateFrozen(Func createRegex, bool isLiteralWithoutSubstitutions) { var result = createRegex(); + if (isLiteralWithoutSubstitutions) { + RubyRegex.RequireValidPattern(result.Pattern); + } result.Freeze(); return result; } @@ -3282,33 +3288,66 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc return CreateRegexWorker(options, regexpCache, true, createRegex); } + /// + /// MRI's rb_reg_preprocess_dregexp: each piece of an interpolated regexp has to be valid in + /// its own encoding (or it is an ArgumentError, even when the pieces would make a valid + /// string together), and the pieces that tie the regexp to an encoding - by a character + /// outside ASCII, or an escape of one - have to agree on which. + /// + private static void CheckDynamicRegexParts(MutableString part1, MutableString part2) { + RubyEncoding fixedEncoding = null; + CheckDynamicRegexPart(part1, ref fixedEncoding); + CheckDynamicRegexPart(part2, ref fixedEncoding); + } + + private static void CheckDynamicRegexParts(MutableString/*!*/[]/*!*/ parts) { + RubyEncoding fixedEncoding = null; + foreach (var part in parts) { + CheckDynamicRegexPart(part, ref fixedEncoding); + } + } + + private static void CheckDynamicRegexPart(MutableString part, ref RubyEncoding fixedEncoding) { + if (part == null) { + return; + } + RubyEncoding encoding = RubyRegex.GetFixedEncoding(part); + if (encoding == null) { + return; + } + if (fixedEncoding != null && fixedEncoding != encoding) { + throw new RegexpError("encoding mismatch in dynamic regexp : " + fixedEncoding.Name + " and " + encoding.Name); + } + fixedEncoding = encoding; + } + [Emitted] public static RubyRegex/*!*/ CreateRegexM(MutableString str1, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(CreateMutableStringM(str1, encoding), options); }; + Func createRegex = delegate { CheckDynamicRegexParts(str1, null); return new RubyRegex(CreateMutableStringM(str1, encoding), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } [Emitted] public static RubyRegex/*!*/ CreateRegexLM(string/*!*/ str1, MutableString str2, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(CreateMutableStringLM(str1, str2, encoding), options); }; + Func createRegex = delegate { CheckDynamicRegexParts(MutableString.Create(str1, encoding), str2); return new RubyRegex(CreateMutableStringLM(str1, str2, encoding), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } [Emitted] public static RubyRegex/*!*/ CreateRegexML(MutableString str1, string/*!*/ str2, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(CreateMutableStringML(str1, str2, encoding), options); }; + Func createRegex = delegate { CheckDynamicRegexParts(str1, MutableString.Create(str2, encoding)); return new RubyRegex(CreateMutableStringML(str1, str2, encoding), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } [Emitted] public static RubyRegex/*!*/ CreateRegexMM(MutableString str1, MutableString str2, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(CreateMutableStringMM(str1, str2, encoding), options); }; + Func createRegex = delegate { CheckDynamicRegexParts(str1, str2); return new RubyRegex(CreateMutableStringMM(str1, str2, encoding), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } [Emitted] public static RubyRegex/*!*/ CreateRegexN(MutableString[]/*!*/ strings, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(CreateMutableStringN(strings), options); }; + Func createRegex = delegate { CheckDynamicRegexParts(strings); return new RubyRegex(CreateMutableStringN(strings), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } From 7f3a8f263f2510668d6bde31d3ddf2719f6c549c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:45:50 +0100 Subject: [PATCH 132/147] A \p{...} property fixes a regexp's encoding MRI's rb_reg_preprocess fixes the encoding of a pattern that names a character property (has_property), ASCII only as its source is: /\p{Alpha}/ in a UTF-8 file is a fixed UTF-8 regexp, Regexp.new('\p{Hiragana}' in EUC-JP) a fixed EUC-JP one, /\p{Alpha}/n a fixed BINARY one. IronRuby made them all US-ASCII and not fixed, so they matched a non-ASCII string of any encoding where MRI raises Encoding::CompatibilityError, and Regexp.union accepted them next to a string of another encoding. RubyRegex#Encoding and #IsFixedEncoding now look for a property outside comments (cached like the non-ASCII escape check), and Regexp.union asks a Regexp part whether it is fixed (rb_reg_fixed_encoding_p) instead of whether its source is ASCII only, so Regexp.union(/\p{Alpha}/, euc_jp_string) and Regexp.union(/abc/u, euc_jp_string) are "incompatible encodings: UTF-8 and EUC-JP" as in MRI. Checked against CRuby 4.0.10 with eleven property patterns (encoding and fixed_encoding?), three matches and nine unions; test_m17n's test_regexp_property passes. ruby/spec core/regexp, core/string and language show no failure outside Util/spec-known-failures.txt. --- Src/Libraries/Builtins/RubyRegexOps.cs | 5 +-- Src/Ruby/Builtins/RubyRegex.cs | 50 ++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/RubyRegexOps.cs b/Src/Libraries/Builtins/RubyRegexOps.cs index 4f9d90229..43ad75476 100644 --- a/Src/Libraries/Builtins/RubyRegexOps.cs +++ b/Src/Libraries/Builtins/RubyRegexOps.cs @@ -834,8 +834,9 @@ private static string GroupName(object groupIndex) { RubyEncoding encoding; var regex = part as RubyRegex; if (regex != null) { - encoding = IsAsciiOnly(regex.Pattern) && (regex.Options & RubyRegexOptions.FixedEncoding) == 0 - ? null : regex.Encoding; + // MRI asks rb_reg_fixed_encoding_p: /\p{Alpha}/ and /abc/u are tied to an + // encoding although their sources are ASCII only + encoding = IsAsciiOnly(regex.Pattern) && !regex.IsFixedEncoding ? null : regex.Encoding; } else { var str = (MutableString)part; encoding = IsAsciiOnly(str) ? null : str.Encoding; diff --git a/Src/Ruby/Builtins/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index c34413915..42e77993d 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -153,6 +153,7 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _cachedRegex = null; _cachedAstralRegex = null; _nonAsciiEscape = -1; + _hasProperty = -1; RubyEncoding encoding = RubyEncoding.GetRegexEncoding(options); if (encoding != null) { @@ -821,10 +822,16 @@ public RubyEncoding/*!*/ Encoding { return isUnicode ? RubyEncoding.UTF8 : _pattern.Encoding; } + // a \p{...} property means characters of the source's encoding: MRI's + // rb_reg_preprocess fixes the encoding for it (has_property) + if (PatternHasProperty()) { + return _pattern.Encoding; + } + return RubyEncoding.Ascii; } - if (encodingOptions == RubyRegexOptions.FIXED && _pattern.IsAscii() && !PatternHasNonAsciiEscape(out _)) { + if (encodingOptions == RubyRegexOptions.FIXED && _pattern.IsAscii() && !PatternHasNonAsciiEscape(out _) && !PatternHasProperty()) { return RubyEncoding.Ascii; } @@ -952,6 +959,43 @@ public static bool HasBackReference(MutableString/*!*/ pattern) { /// written with byte escapes would silently lose its encoding when unioned with a plain /// ASCII string. /// + // -1 until PatternHasProperty has looked, then 0 or 1 + private int _hasProperty = -1; + + /// + /// Whether the pattern names a character property, \p{...}, \P{...} or \p{^...}, outside a + /// comment. MRI fixes the regexp to its source's encoding for one, ASCII only as the + /// source is: /\p{Alpha}/ is a fixed UTF-8 regexp in a UTF-8 file. + /// + private bool PatternHasProperty() { + int cached = _hasProperty; + if (cached < 0) { + cached = FindProperty(_pattern.ConvertToString(), (_options & RubyRegexOptions.Extended) != 0) ? 1 : 0; + _hasProperty = cached; + } + return cached != 0; + } + + private static bool FindProperty(string/*!*/ source, bool extended) { + if (source.IndexOf("{", StringComparison.Ordinal) < 0) { + return false; + } + var groups = new Stack(); + int classDepth = 0; + int i = 0; + while (i < source.Length) { + if (source[i] != '\\') { + i = SkipNonEscape(source, i, ref extended, groups, ref classDepth); + continue; + } + if (i + 2 < source.Length && (source[i + 1] == 'p' || source[i + 1] == 'P') && source[i + 2] == '{') { + return true; + } + i += 2; + } + return false; + } + private bool PatternHasNonAsciiEscape(out bool isUnicode) { int cached = _nonAsciiEscape; if (cached < 0) { @@ -1049,11 +1093,11 @@ public bool IsFixedEncoding { // pins the encoding only once the pattern really compiles to non-ASCII bytes, // which it does for a byte escape as much as for a literal non-ASCII character. bool isUnicode; - return !_pattern.IsAscii() || PatternHasNonAsciiEscape(out isUnicode); + return !_pattern.IsAscii() || PatternHasNonAsciiEscape(out isUnicode) || PatternHasProperty(); } return (_options & (RubyRegexOptions.EUC | RubyRegexOptions.SJIS | RubyRegexOptions.UTF8 | RubyRegexOptions.FixedEncoding)) != 0 - || Encoding != RubyEncoding.Ascii; + || Encoding != RubyEncoding.Ascii || PatternHasProperty(); } } From f3310a733cf30f9883024f56d10987179b09fcc5 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:45:50 +0100 Subject: [PATCH 133/147] A UTF-16/32 string of broken length keeps its bytes, and chomps as MRI does "A" forced to UTF-16BE is one byte that is not a whole code unit. The escaping encoding carries such a byte through the character representation as U+DC00 plus the byte, but only recognized U+DC80..U+DCFF as escapes on the way back, since in an ASCII compatible encoding no ASCII byte is ever escaped. In UTF-16 and UTF-32 one is, and it came back as the three CESU-8 bytes of a surrogate: "A" in UTF-16BE chomped to "\xED\xB1\x81", and "\n\x00x" in UTF-16LE split into lines as ["\n\x00", "\xED\xB1\xB8"]. The escape range is now U+DC00..U+DCFF everywhere (EscapingEncoding, the character enumerators, #inspect, #succ): a strict UTF-16 or UTF-32 decoder never produces a lone surrogate, and an ASCII compatible one never escapes a byte below 0x80, so nothing else lives there. #chomp on a UTF-16 or UTF-32 string with $/ or "\n" (and with "", the paragraph loop) now works on the bytes as MRI's smart_chomp and chompped_length do: the newline it removes is the code unit at the head of the character the last unit's worth of bytes falls in, so "A" is left alone (test_string's test_chomp) and "\n\x00x" in UTF-16LE chomps to "", as in MRI. Checked against CRuby 4.0.10 with chomp, chomp("\n"), chop, lines, lines(chomp: true), each_line("\n") and lines("") on six broken and whole strings in each of UTF-16LE/BE and UTF-32LE/BE (168 lines, all equal); test_string's test_chomp passes. New IronRuby.Tests test MutableString_WideBrokenLength1; the MutableString*, String_*, Regex* tests pass; ruby/spec core/string, core/symbol, core/encoding, core/regexp and language show no failure outside Util/spec-known-failures.txt. --- Src/IronRuby.Tests/RubyTests.cs | 1 + .../Runtime/MutableStringTests.cs | 27 ++++++ Src/Libraries/Builtins/MutableStringOps.cs | 87 ++++++++++++++++++- Src/Ruby/Builtins/MutableString.cs | 4 +- Src/Ruby/Runtime/EscapingEncoding.cs | 11 ++- 5 files changed, 121 insertions(+), 9 deletions(-) diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index 9f990b117..f4c14a29e 100644 --- a/Src/IronRuby.Tests/RubyTests.cs +++ b/Src/IronRuby.Tests/RubyTests.cs @@ -62,6 +62,7 @@ public Tests(Driver/*!*/ driver) { MutableString_ConcatAscii2, MutableString_SliceAppend1, MutableString_SipHash1, + MutableString_WideBrokenLength1, RubyArray_Ctors, RubyArray_Basic, RubyArray_Add, diff --git a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs index 9a0d44556..5ec040eeb 100644 --- a/Src/IronRuby.Tests/Runtime/MutableStringTests.cs +++ b/Src/IronRuby.Tests/Runtime/MutableStringTests.cs @@ -2086,6 +2086,33 @@ public void MutableString_CopyOnWrite2() { ", @" 7056 0 +"); + } + + /// + /// A UTF-16 or UTF-32 string of a broken length keeps its bytes through the character + /// representation (the odd byte is escaped as U+DC00 plus the byte, even below 0x80), and + /// #chomp works on the bytes as MRI's smart_chomp does. + /// + public void MutableString_WideBrokenLength1() { + TestOutput(@" +require 'ruby4' +%w[UTF-16BE UTF-16LE UTF-32LE].each do |enc| + s = ""A"".b.force_encoding(enc) + p [s.chomp.b, s.chomp("""").b, s.chomp!, s.reverse.b] +end +s = ""\n\x00x"".b.force_encoding(""UTF-16LE"") +p s.chomp.b, s.lines.map(&:b) +p ""a\x00\r\x00\n\x00"".b.force_encoding(""UTF-16LE"").chomp.b +p ""a\x00\n\x00\n\x00\r\x00"".b.force_encoding(""UTF-16LE"").chomp("""").b +", @" +[""A"", ""A"", nil, ""A""] +[""A"", ""A"", nil, ""A""] +[""A"", ""A"", nil, ""A""] +"""" +[""\n\x00"", ""x""] +""a\x00"" +""a\x00\n\x00\n\x00\r\x00"" "); } } diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 462ea99d9..cd76828cf 100644 --- a/Src/Libraries/Builtins/MutableStringOps.cs +++ b/Src/Libraries/Builtins/MutableStringOps.cs @@ -1285,11 +1285,11 @@ public static object GetByte(MutableString/*!*/ self, [DefaultProtocol]int index /// /// /// Whether the character at the index is a byte that is not valid in the string's encoding, - /// which EscapingEncoding holds as a lone low surrogate, U+DC80 plus the byte. + /// which EscapingEncoding holds as a lone low surrogate, U+DC00 plus the byte. /// private static bool IsEscapedByte(MutableString/*!*/ str, int index) { char c = str.GetChar(index); - return c >= '\uDC80' && c <= '\uDCFF' && (index == 0 || !Char.IsHighSurrogate(str.GetChar(index - 1))); + return c >= '\uDC00' && c <= '\uDCFF' && (index == 0 || !Char.IsHighSurrogate(str.GetChar(index - 1))); } [RubyMethod("ord")] @@ -2059,6 +2059,84 @@ private static void AppendPadding(MutableString/*!*/ result, MutableString/*!*/ return result; } + private static bool IsWideUnicode(RubyEncoding/*!*/ encoding) { + switch (encoding.CodePage) { + case RubyEncoding.CodePageUTF16LE: + case RubyEncoding.CodePageUTF16BE: + case RubyEncoding.CodePageUTF32LE: + case RubyEncoding.CodePageUTF32BE: + return true; + default: + return false; + } + } + + /// + /// MRI's smart_chomp (and, with , the loop chompped_length runs + /// for an empty separator) in UTF-16 and UTF-32, done on the bytes: a string of a broken + /// length is not a whole number of characters, and the newline MRI finds is the one at the + /// head of the character the last code unit's worth of bytes falls in. So "A" in UTF-16BE + /// is left as it is, and "\n\0x" in UTF-16LE (a newline and a stray byte) chomps to "". + /// + private static MutableString/*!*/ WideChomp(MutableString/*!*/ self, bool paragraph) { + byte[] bytes = self.ToByteArray(); + RubyEncoding encoding = self.Encoding; + int unit = encoding.MinBytesPerChar; + int end = bytes.Length; + while (end >= unit) { + int head = WideLeftCharHead(bytes, end - unit, encoding); + bool newline = WideCodeAt(bytes, head, end, encoding) == '\n'; + if (newline) { + end = head; + } else if (paragraph) { + break; + } + int previous = end - unit; + if (previous >= 0) { + previous = WideLeftCharHead(bytes, previous, encoding); + if (WideCodeAt(bytes, previous, end, encoding) == '\r' && (newline || !paragraph)) { + end = previous; + } + } + if (!paragraph) { + break; + } + } + + var result = self.CreateDerived(); + result.Append(bytes, 0, end); + return result; + } + + // Onigmo's left_adjust_char_head for UTF-16 and UTF-32: back to a code unit boundary, and + // in UTF-16 back over a high surrogate the unit there is the second half of. + private static int WideLeftCharHead(byte[]/*!*/ bytes, int position, RubyEncoding/*!*/ encoding) { + int unit = encoding.MinBytesPerChar; + position -= position % unit; + if (unit == 2 && position >= 2 && WideUnitAt(bytes, position, encoding) is int low && low >= 0xDC00 && low <= 0xDFFF) { + int high = WideUnitAt(bytes, position - 2, encoding); + if (high >= 0xD800 && high <= 0xDBFF) { + position -= 2; + } + } + return position; + } + + private static int WideUnitAt(byte[]/*!*/ bytes, int position, RubyEncoding/*!*/ encoding) { + bool bigEndian = encoding.IsBigEndianUnicode; + if (encoding.MinBytesPerChar == 2) { + return bigEndian ? (bytes[position] << 8) | bytes[position + 1] : (bytes[position + 1] << 8) | bytes[position]; + } + return bigEndian + ? (bytes[position] << 24) | (bytes[position + 1] << 16) | (bytes[position + 2] << 8) | bytes[position + 3] + : (bytes[position + 3] << 24) | (bytes[position + 2] << 16) | (bytes[position + 1] << 8) | bytes[position]; + } + + // The code unit at position if a whole one fits before end, -1 if not. + private static int WideCodeAt(byte[]/*!*/ bytes, int position, int end, RubyEncoding/*!*/ encoding) { + return position + encoding.MinBytesPerChar <= end ? WideUnitAt(bytes, position, encoding) : -1; + } + private static MutableString InternalChomp(MutableString/*!*/ self, MutableString separator, bool defaultSeparator) { if (separator == null) { return self.CloneDerived(); @@ -2066,7 +2144,7 @@ private static MutableString InternalChomp(MutableString/*!*/ self, MutableStrin // Remove multiple trailing CR/LFs if (separator.IsEmpty) { - return ChompTrailingCarriageReturns(self, false); + return IsWideUnicode(self.Encoding) ? WideChomp(self, true) : ChompTrailingCarriageReturns(self, false); } // Remove single trailing CR/LFs @@ -2078,6 +2156,9 @@ private static MutableString InternalChomp(MutableString/*!*/ self, MutableStrin if (!newline) { self.RequireCompatibleEncoding(separator); } + if (newline && IsWideUnicode(self.Encoding)) { + return WideChomp(self, false); + } if (newline) { if (length > 1 && result.GetChar(length - 2) == '\r' && result.GetChar(length - 1) == '\n') { result.Remove(length - 2, 2); diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index d373aabd8..e253e57d1 100644 --- a/Src/Ruby/Builtins/MutableString.cs +++ b/Src/Ruby/Builtins/MutableString.cs @@ -3176,9 +3176,9 @@ public static int AppendUnicodeCharRepresentation(StringBuilder/*!*/ result, int return inc; } - /// A lone low surrogate in U+DC80..U+DCFF stands for one undecodable byte. + /// A lone low surrogate in U+DC00..U+DCFF stands for one undecodable byte. private static bool IsEscapedByte(int c) { - return c >= EscapingEncoding.EscapeBase + 0x80 && c <= EscapingEncoding.EscapeBase + 0xFF; + return c >= EscapingEncoding.EscapeBase && c <= EscapingEncoding.EscapeBase + 0xFF; } /// \uXXXX up to U+FFFF, \u{XXXXXX} above it - MRI writes both in upper case. diff --git a/Src/Ruby/Runtime/EscapingEncoding.cs b/Src/Ruby/Runtime/EscapingEncoding.cs index 805f972a5..d68bb6d04 100644 --- a/Src/Ruby/Runtime/EscapingEncoding.cs +++ b/Src/Ruby/Runtime/EscapingEncoding.cs @@ -41,9 +41,12 @@ namespace IronRuby.Runtime { /// One undecodable byte becomes one character, which is also how MRI counts them - "a\xFFb" is /// three characters long in UTF-8 - so character offsets agree with MRI's as well. /// - /// The range U+DC80..U+DCFF cannot occur in text decoded from any of the encodings this is - /// used with: UTF-8 and friends cannot encode an unpaired surrogate at all, and a single byte - /// encoding has no character above U+FFFF to pair one with. Validity is *not* decided here - + /// The range U+DC00..U+DCFF cannot occur in text decoded from any of the encodings this is + /// used with: UTF-8 and friends cannot encode an unpaired surrogate at all, a single byte + /// encoding has no character above U+FFFF to pair one with, and the strict UTF-16 and UTF-32 + /// decoders refuse a lone surrogate. Only those last two escape a byte below 0x80: the odd + /// byte at the end of "A" in UTF-16BE, which has to come back as "A" and not as the three + /// bytes of a surrogate. Validity is *not* decided here - /// String#valid_encoding? still asks the strict encoding, which is what makes it able to /// answer false for a string this class decoded happily. /// @@ -59,7 +62,7 @@ internal EscapingEncoding(Encoding/*!*/ inner) } internal static bool IsEscapedByte(char c) { - return c >= (char)0xDC80 && c <= (char)0xDCFF; + return c >= EscapeBase && c <= (char)0xDCFF; } /// The longest character any encoding used here produces. From 084168c290634bc416ff64346ca96862c221371e Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 19:51:57 +0100 Subject: [PATCH 134/147] File.join says "string contains null byte" for a NUL in a String argument The File.join rewrite (4ad24772) checks the Strings of each array before converting any element, and that check let Protocols.CheckPath's "path name contains null byte" through. CRuby's rb_file_join reads a String argument with StringValueCStr and says "string contains null byte", which spec/core/file/join_spec.rb's "raises errors for null bytes" expects. The message was already translated for converted elements; the up-front check now translates it the same way. Checked: CRuby 4.0.10 raises "string contains null byte" for a NUL in the first or a later part; join_spec, expand_path_spec, absolute_path_spec and spec/library/pathname pass (141 examples, 0 failures), and test_join* in test_file_exhaustive pass. --- Src/Libraries/Builtins/FileOps.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Src/Libraries/Builtins/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 860957671..f03cdfc41 100644 --- a/Src/Libraries/Builtins/FileOps.cs +++ b/Src/Libraries/Builtins/FileOps.cs @@ -1231,7 +1231,12 @@ private static void JoinList(ConversionStorage/*!*/ toPath, IList for (int i = 0; i < list.Count; i++) { var s = list[i] as MutableString; if (s != null) { - Protocols.CheckPath(s); + try { + Protocols.CheckPath(s); + } catch (ArgumentException e) when (e.Message == "path name contains null byte") { + // rb_file_join reports a NUL as a plain string problem (StringValueCStr). + throw RubyExceptions.CreateArgumentError("string contains null byte"); + } } } From 858d4a5250d63d9e837548dfd6e5d35a1e358166 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 20:44:18 +0100 Subject: [PATCH 135/147] Backtrace_AsciiLocalePaths1 compares the expanded path's bytes File.expand_path now keeps a base path's encoding as CRuby does: a BINARY base gives a BINARY result (File.expand_path('x', "/tmp/caf\xC3\xA9".b) is ASCII-8BIT on CRuby 4.0.10 too). Under a US-ASCII locale IronRuby's backtrace paths are BINARY, so the test's expand_path of File.dirname(LIB) is BINARY, and end_with? of a UTF-8 literal raised Encoding::CompatibilityError. The test checks that the bytes survive, as the line above it does, by comparing .b. --- Src/IronRuby.Tests/Runtime/BacktraceTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/Runtime/BacktraceTests.cs b/Src/IronRuby.Tests/Runtime/BacktraceTests.cs index 75fad9ee4..24a0472d3 100644 --- a/Src/IronRuby.Tests/Runtime/BacktraceTests.cs +++ b/Src/IronRuby.Tests/Runtime/BacktraceTests.cs @@ -647,7 +647,7 @@ p dc.encoding load File.join(t.b, dc, 'm.rb') p [LIB, M].map(&:encoding), [LIB, M].all?(&:valid_encoding?) p LIB.b.end_with?(""café/lib.rb"".b), M.b.include?(""café/m.rb:2"".b) - p File.expand_path('x', File.dirname(LIB)).end_with?(""café/x"") + p File.expand_path('x', File.dirname(LIB)).b.end_with?(""café/x"".b) ensure Encoding.default_external = old end From 2f61e89f6e6da5e4318479cda6b517e70c418ed6 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 21:28:29 +0100 Subject: [PATCH 136/147] cruby-test: baseline after the second round of test/ruby fixes A full sweep of CRuby 4.0.10's test/ruby on this branch, six files at a time; the six files that ran past 600 s under that load were run again alone with a 1500 s limit. 141 of 142 files now end with a summary (139 before): test_gc and test_trace no longer hang. test_iseq is still out of scope. 10,382 tests, 499 failures, 3,323 errors; 6,494 passing (6,342 before). The errors include many Timeouts of assert_separately and subprocess tests under the sweep's load. Every test that failed here and not in the last baseline sweep, other than as a Timeout, was checked: - test_m17n_comb's test_str_sub! passes alone; - test_io's test_copy_stream_no_busy_wait measures .NET's tiered JIT working in the background in the first seconds of the process (0.8 CPU-s in an idle second; copy_stream itself uses 0.01 CPU-s/s once it waits); - the rest are in test_gc, which had no summary before. --- Util/cruby-test/baseline.txt | 122 +++++++++++++++++------------------ 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/Util/cruby-test/baseline.txt b/Util/cruby-test/baseline.txt index 769d23616..506d31e8e 100644 --- a/Util/cruby-test/baseline.txt +++ b/Util/cruby-test/baseline.txt @@ -1,9 +1,9 @@ -test_alias 18 tests 1 failures 3 errors 0 skips +test_alias 18 tests 1 failures 2 errors 0 skips test_allocation 76 tests 0 failures 76 errors 0 skips -test_argf 73 tests 18 failures 2 errors 0 skips +test_argf 73 tests 19 failures 1 errors 0 skips test_arithmetic_sequence 37 tests 0 failures 0 errors 0 skips test_arity 3 tests 0 failures 0 errors 0 skips -test_array 493 tests 6 failures 20 errors 2 skips +test_array 493 tests 0 failures 16 errors 2 skips test_assignment 29 tests 0 failures 0 errors 0 skips test_ast 2666 tests 10 failures 2656 errors 0 skips test_autoload 27 tests 1 failures 3 errors 0 skips @@ -11,11 +11,11 @@ test_backtrace 31 tests 4 failures 0 errors 0 sk test_basicinstructions 26 tests 0 failures 0 errors 0 skips test_beginendblock 16 tests 4 failures 1 errors 0 skips test_bignum 73 tests 1 failures 2 errors 0 skips -test_box 65 tests 5 failures 24 errors 31 skips +test_box 65 tests 4 failures 25 errors 31 skips test_call 65 tests 2 failures 0 errors 0 skips test_case 6 tests 0 failures 0 errors 0 skips -test_class 62 tests 5 failures 3 errors 0 skips -test_clone 7 tests 0 failures 0 errors 0 skips +test_class 62 tests 2 failures 3 errors 0 skips +test_clone 7 tests 0 failures 1 errors 0 skips test_comparable 11 tests 0 failures 0 errors 0 skips test_compile_prism 182 tests 1 failures 179 errors 0 skips test_complex 57 tests 0 failures 0 errors 0 skips @@ -23,114 +23,114 @@ test_complex2 2 tests 0 failures 0 errors 0 sk test_complexrational 2 tests 0 failures 0 errors 0 skips test_condition 1 tests 0 failures 0 errors 0 skips test_const 5 tests 0 failures 0 errors 0 skips -test_continuation 7 tests 0 failures 3 errors 0 skips +test_continuation 7 tests 0 failures 5 errors 0 skips test_data 16 tests 0 failures 0 errors 0 skips test_default_gems 1 tests 0 failures 0 errors 0 skips test_defined 39 tests 4 failures 1 errors 0 skips -test_dir 39 tests 8 failures 2 errors 0 skips -test_dir_m17n 22 tests 10 failures 1 errors 0 skips +test_dir 39 tests 1 failures 1 errors 0 skips +test_dir_m17n 22 tests 7 failures 5 errors 0 skips test_dup 6 tests 0 failures 0 errors 0 skips -test_econv 85 tests 7 failures 5 errors 0 skips -test_encoding 15 tests 1 failures 0 errors 0 skips -test_enum 90 tests 2 failures 2 errors 0 skips -test_enumerator 70 tests 0 failures 0 errors 0 skips -test_env 94 tests 16 failures 1 errors 0 skips +test_econv 85 tests 4 failures 2 errors 0 skips +test_encoding 15 tests 0 failures 4 errors 0 skips +test_enum 90 tests 2 failures 3 errors 0 skips +test_enumerator 70 tests 0 failures 1 errors 0 skips +test_env 94 tests 0 failures 11 errors 0 skips test_eval 40 tests 3 failures 2 errors 0 skips -test_exception 101 tests 16 failures 4 errors 0 skips -test_fiber 35 tests 3 failures 0 errors 2 skips -test_file 80 tests 2 failures 24 errors 1 skips -test_file_exhaustive 125 tests 6 failures 2 errors 0 skips +test_exception 101 tests 13 failures 7 errors 0 skips +test_fiber 35 tests 3 failures 1 errors 2 skips +test_file 80 tests 0 failures 23 errors 1 skips +test_file_exhaustive 125 tests 0 failures 2 errors 0 skips test_fixnum 39 tests 0 failures 0 errors 0 skips test_flip 5 tests 1 failures 0 errors 0 skips test_float 63 tests 0 failures 1 errors 0 skips test_fnmatch 15 tests 3 failures 0 errors 0 skips test_frozen 6 tests 0 failures 0 errors 0 skips test_frozen_error 5 tests 1 failures 0 errors 0 skips -test_gc NO SUMMARY (exit 124, timed out) -test_gc_compact 28 tests 7 failures 6 errors 7 skips -test_hash 298 tests 5 failures 9 errors 0 skips +test_gc 53 tests 12 failures 11 errors 2 skips +test_gc_compact 28 tests 7 failures 7 errors 7 skips +test_hash 298 tests 3 failures 14 errors 0 skips test_ifunless 1 tests 0 failures 0 errors 0 skips test_inlinecache 3 tests 0 failures 0 errors 0 skips test_insns_leaf 2 tests 0 failures 0 errors 0 skips -test_integer 38 tests 0 failures 1 errors 0 skips +test_integer 38 tests 0 failures 2 errors 0 skips test_integer_comb 41 tests 0 failures 0 errors 0 skips -test_io 252 tests 30 failures 10 errors 5 skips +test_io 252 tests 11 failures 12 errors 4 skips test_io_buffer 87 tests 9 failures 13 errors 1 skips -test_io_m17n 160 tests 21 failures 1 errors 0 skips +test_io_m17n 160 tests 14 failures 3 errors 0 skips test_io_timeout 4 tests 0 failures 0 errors 4 skips test_iseq NO SUMMARY (exit 1) test_iterator 32 tests 0 failures 0 errors 0 skips test_key_error 6 tests 0 failures 0 errors 0 skips -test_keyword 115 tests 4 failures 2 errors 0 skips +test_keyword 115 tests 4 failures 5 errors 0 skips test_lambda 27 tests 1 failures 0 errors 0 skips -test_lazy_enumerator 64 tests 0 failures 0 errors 0 skips +test_lazy_enumerator 64 tests 0 failures 1 errors 0 skips test_literal 29 tests 1 failures 1 errors 0 skips -test_m17n 127 tests 13 failures 0 errors 1 skips -test_m17n_comb 82 tests 3 failures 0 errors 0 skips -test_marshal 234 tests 27 failures 8 errors 0 skips +test_m17n 127 tests 4 failures 0 errors 1 skips +test_m17n_comb 82 tests 1 failures 0 errors 0 skips +test_marshal 234 tests 8 failures 3 errors 0 skips test_math 34 tests 0 failures 0 errors 0 skips test_memory_view 0 tests 0 failures 0 errors 0 skips test_metaclass 1 tests 0 failures 0 errors 0 skips -test_method 99 tests 12 failures 5 errors 0 skips +test_method 99 tests 4 failures 5 errors 0 skips test_method_cache 4 tests 0 failures 0 errors 0 skips test_mixed_unicode_escapes 1 tests 1 failures 0 errors 0 skips -test_module 195 tests 5 failures 12 errors 0 skips +test_module 195 tests 6 failures 14 errors 0 skips test_name_error 11 tests 0 failures 1 errors 0 skips test_nomethod_error 10 tests 0 failures 0 errors 0 skips test_not 2 tests 0 failures 0 errors 0 skips test_numeric 27 tests 1 failures 0 errors 0 skips -test_object 67 tests 6 failures 2 errors 0 skips +test_object 67 tests 5 failures 1 errors 0 skips test_object_id 132 tests 0 failures 2 errors 0 skips -test_objectspace 37 tests 10 failures 10 errors 0 skips -test_optimization 90 tests 46 failures 24 errors 0 skips -test_pack 56 tests 4 failures 0 errors 0 skips -test_parse 107 tests 20 failures 1 errors 0 skips +test_objectspace 37 tests 10 failures 9 errors 0 skips +test_optimization 90 tests 47 failures 23 errors 0 skips +test_pack 56 tests 2 failures 0 errors 0 skips +test_parse 107 tests 17 failures 1 errors 0 skips test_path 6 tests 0 failures 0 errors 0 skips test_pattern_matching 30 tests 0 failures 0 errors 0 skips test_pipe 12 tests 0 failures 2 errors 0 skips test_primitive 25 tests 0 failures 0 errors 0 skips -test_proc 120 tests 8 failures 5 errors 0 skips +test_proc 120 tests 3 failures 6 errors 0 skips test_process 142 tests 28 failures 19 errors 1 skips -test_ractor 19 tests 6 failures 2 errors 0 skips -test_rand 41 tests 0 failures 0 errors 0 skips +test_ractor 19 tests 3 failures 8 errors 0 skips +test_rand 41 tests 0 failures 1 errors 0 skips test_random_formatter 26 tests 0 failures 0 errors 0 skips -test_range 67 tests 0 failures 2 errors 0 skips +test_range 67 tests 0 failures 0 errors 0 skips test_rational 52 tests 0 failures 0 errors 0 skips test_rational2 1 tests 0 failures 0 errors 0 skips test_readpartial 4 tests 1 failures 0 errors 0 skips -test_refinement 122 tests 12 failures 3 errors 0 skips -test_regexp 167 tests 34 failures 14 errors 0 skips -test_require 52 tests 9 failures 9 errors 0 skips +test_refinement 122 tests 6 failures 8 errors 0 skips +test_regexp 167 tests 32 failures 12 errors 0 skips +test_require 52 tests 9 failures 14 errors 0 skips test_require_lib 39 tests 0 failures 2 errors 0 skips test_rubyoptions 68 tests 50 failures 1 errors 0 skips test_rubyvm 3 tests 1 failures 2 errors 0 skips -test_set 63 tests 0 failures 0 errors 2 skips -test_settracefunc 102 tests 40 failures 12 errors 0 skips +test_set 63 tests 0 failures 2 errors 2 skips +test_settracefunc 102 tests 38 failures 16 errors 0 skips test_shapes 0 tests 0 failures 0 errors 0 skips -test_signal 21 tests 2 failures 2 errors 1 skips +test_signal 21 tests 2 failures 4 errors 1 skips test_sleep 2 tests 0 failures 0 errors 0 skips test_sprintf 35 tests 3 failures 0 errors 0 skips test_sprintf_comb 95 tests 0 failures 0 errors 0 skips test_stack 3 tests 2 failures 1 errors 0 skips -test_string 475 tests 17 failures 13 errors 0 skips +test_string 475 tests 14 failures 17 errors 0 skips test_string_memory 3 tests 0 failures 3 errors 0 skips test_stringchar 4 tests 0 failures 0 errors 0 skips test_struct 102 tests 0 failures 2 errors 0 skips -test_super 50 tests 2 failures 4 errors 0 skips -test_symbol 59 tests 0 failures 6 errors 0 skips -test_syntax 171 tests 6 failures 5 errors 0 skips +test_super 50 tests 2 failures 5 errors 0 skips +test_symbol 59 tests 0 failures 7 errors 0 skips +test_syntax 171 tests 8 failures 3 errors 0 skips test_system 8 tests 2 failures 1 errors 0 skips -test_thread 98 tests 12 failures 12 errors 4 skips -test_thread_cv 13 tests 2 failures 1 errors 0 skips -test_thread_queue 40 tests 4 failures 1 errors 0 skips -test_threadgroup 3 tests 1 failures 0 errors 0 skips -test_time 89 tests 8 failures 11 errors 0 skips -test_time_tz 166 tests 14 failures 1 errors 0 skips -test_trace NO SUMMARY (exit 124, timed out) -test_transcode 101 tests 16 failures 5 errors 0 skips +test_thread 98 tests 5 failures 6 errors 4 skips +test_thread_cv 13 tests 0 failures 1 errors 0 skips +test_thread_queue 40 tests 2 failures 1 errors 0 skips +test_threadgroup 3 tests 0 failures 0 errors 0 skips +test_time 89 tests 2 failures 8 errors 0 skips +test_time_tz 166 tests 12 failures 1 errors 0 skips +test_trace 4 tests 0 failures 0 errors 0 skips +test_transcode 101 tests 14 failures 5 errors 0 skips test_undef 3 tests 0 failures 0 errors 0 skips test_unicode_escape 8 tests 0 failures 0 errors 0 skips -test_variable 32 tests 2 failures 1 errors 0 skips +test_variable 32 tests 1 failures 1 errors 0 skips test_vm_dump 0 tests 0 failures 0 errors 0 skips test_warning 1 tests 0 failures 0 errors 0 skips test_weakkeymap 13 tests 0 failures 1 errors 0 skips @@ -141,5 +141,5 @@ test_yjit 0 tests 0 failures 0 errors 0 sk test_yjit_exit_locations 0 tests 0 failures 0 errors 0 skips test_zjit 0 tests 0 failures 0 errors 0 skips -142 files: 53 clean, 86 with failures, 3 without a summary -10325 tests, 2552627 assertions, 649 failures, 3269 errors, 65 skips; 6342 passing +142 files: 51 clean, 90 with failures, 1 without a summary +10382 tests, 2531843 assertions, 499 failures, 3323 errors, 66 skips; 6494 passing From f566fdc7ba99801f75f96749b56bf391ed112d7d Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 23:32:00 +0100 Subject: [PATCH 137/147] SyntaxError_MessageLocation1 writes its bad magic comment in binary On Windows File.write writes text mode, so the file the test loads had CRLF line endings and the source lines the magic-comment error quotes did not match the expected message (windows-latest net11.0 failed on it). The check is about the message, not the line endings, so the file is now written with File.binwrite. --- Src/IronRuby.Tests/Runtime/MiscTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 43d6f18a1..5fef26bc3 100644 --- a/Src/IronRuby.Tests/Runtime/MiscTests.cs +++ b/Src/IronRuby.Tests/Runtime/MiscTests.cs @@ -4072,7 +4072,7 @@ public void SyntaxError_MessageLocation1() { bad = File.join(d, 'bad.rb') File.write(bad, ""x = 1\n"" * 49 + ""x = )\n"") begin; load bad; rescue SyntaxError => e; p e.message.start_with?(""#{bad}:50: ""), e.path == bad; end - File.write(bad, ""# encoding: bogus\np 1\n"") + File.binwrite(bad, ""# encoding: bogus\np 1\n"") begin; load bad; rescue ArgumentError => e; p e.message == ""#{bad}:1: unknown or invalid encoding in the magic comment\n> 1 | # encoding: bogus\n | ^~~~~\n 2 | p 1\n"", e.backtrace.grep(/Parse/); end end begin; eval(""# coding: foo\n"", nil, 'm.rb', 3); rescue ArgumentError => e; p e.message; end From 6c42fca04d608210629bbaf590f147ec49f76343 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Sun, 22 Nov 2026 23:41:51 +0100 Subject: [PATCH 138/147] Dir.home: a user name whose #to_str gives no String is a TypeError Dir.home(obj) took whatever obj.to_str returned: an Array that was empty became the current user, and an Integer raised NoMethodError for #empty?. CRuby converts the name with StringValue, which raises TypeError ("can't convert Object to String (Object#to_str gives Array)") for anything but a String, nil included. A String now goes straight through, and a #to_str result that is not one raises that TypeError. Checked against CRuby 4.0.10 for nil, [], 123, an Integer argument and an empty String. --- Src/StdLib/ironruby/ruby4.rb | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index c7240a3a2..b2ad0fd0c 100644 --- a/Src/StdLib/ironruby/ruby4.rb +++ b/Src/StdLib/ironruby/ruby4.rb @@ -4677,8 +4677,15 @@ class << Dir def home(user = nil) # MRI converts the name with to_str, and an empty one is the current user, as nil is. unless user.nil? - raise TypeError, "no implicit conversion of #{user.class} into String" unless user.respond_to?(:to_str) - user = user.to_str + unless user.is_a?(String) + raise TypeError, "no implicit conversion of #{user.class} into String" unless user.respond_to?(:to_str) + converted = user.to_str + # StringValue: what #to_str gives has to be a String (nil included, which is not "no name") + unless converted.is_a?(String) + raise TypeError, "can't convert #{user.class} to String (#{user.class}#to_str gives #{converted.class})" + end + user = converted + end user = nil if user.empty? end if user.nil? From c46987ad0f268d20661791c7ff9a14114c4e7e90 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:08:44 +0100 Subject: [PATCH 139/147] Method#owner of a respond_to_missing? method is the class it was made on MRI's mnew_missing stores the receiver's class (its singleton class if it has one) when the Method is made. IronRuby worked it out again from the receiver on each #owner and #unbind, so a singleton class made since changed the answer, and UnboundMethod#bind of such a method gave the new receiver's class rather than the unbound method's owner. RubyMethod now keeps the owner it was made with, and bind passes the UnboundMethod's owner on. Checked against CRuby 4.0. --- Src/Libraries/Builtins/MethodOps.cs | 8 ++++---- Src/Libraries/Builtins/UnboundMethod.cs | 2 +- Src/Ruby/Builtins/RubyMethod.cs | 21 ++++++++++++++++----- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index 169ddd5b3..0e505d38b 100644 --- a/Src/Libraries/Builtins/MethodOps.cs +++ b/Src/Libraries/Builtins/MethodOps.cs @@ -72,10 +72,10 @@ public static int GetArity(RubyMethod/*!*/ self) { [RubyMethod("owner")] public static RubyModule/*!*/ GetOwner(RubyMethod/*!*/ self) { // A method only respond_to_missing? vouches for belongs to the receiver's class (its - // singleton class if it has one), as mnew_missing makes it, not to the method_missing - // that would run it. + // singleton class if it had one) as it was when the Method was made, which is what + // mnew_missing stores, not to the method_missing that would run it. if (self.IsMethodMissing) { - return self.Info.Context.GetImmediateClassOf(self.Target); + return self.MethodMissingOwner; } return self.Info.AliasOwner ?? self.Info.DeclaringModule ?? self.GetTargetClass(); } @@ -140,7 +140,7 @@ public static RubyMethod GetSuperMethod(RubyContext/*!*/ context, RubyMethod/*!* [RubyMethod("unbind")] public static UnboundMethod/*!*/ Unbind(RubyMethod/*!*/ self) { return new UnboundMethod( - self.IsMethodMissing ? self.Info.Context.GetImmediateClassOf(self.Target) : self.GetTargetClass(), + self.IsMethodMissing ? self.MethodMissingOwner : self.GetTargetClass(), self.Name, self.Info, self.IsMethodMissing ); } diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 14fff3960..6fc15d771 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -116,7 +116,7 @@ public static int GetArity(UnboundMethod/*!*/ self) { } if (self._isMethodMissing) { - return RubyMethod.CreateMethodMissing(target, self._info, self._name); + return RubyMethod.CreateMethodMissing(target, self._info, self._name, self._targetConstraint); } var result = new RubyMethod(target, self._info, self._name); if (!constraint.IsClass) { diff --git a/Src/Ruby/Builtins/RubyMethod.cs b/Src/Ruby/Builtins/RubyMethod.cs index 2342f351c..bb1ba09d3 100644 --- a/Src/Ruby/Builtins/RubyMethod.cs +++ b/Src/Ruby/Builtins/RubyMethod.cs @@ -46,6 +46,10 @@ public partial class RubyMethod : IDuplicable { /// private readonly string _methodMissingName; + // The #owner of such a method: the receiver's class (its singleton class if it had one) when the + // Method was made, which mnew_missing stores rather than works out again later. + private readonly RubyModule _methodMissingOwner; + /// /// The module the method reads as looked up on, when that is not the receiver's class: /// UnboundMethod#bind of a method a module owns makes a Method of that module, which @@ -57,6 +61,11 @@ public bool IsMethodMissing { get { return _methodMissingName != null; } } + /// The #owner of a method made by , null for any other. + public RubyModule MethodMissingOwner { + get { return _methodMissingOwner; } + } + public object Target { get { return _target; } } @@ -78,20 +87,22 @@ public RubyMethod(object target, RubyMemberInfo/*!*/ info, string/*!*/ name) { _name = name; } - private RubyMethod(object target, RubyMemberInfo/*!*/ info, string/*!*/ name, string methodMissingName) + private RubyMethod(object target, RubyMemberInfo/*!*/ info, string/*!*/ name, string methodMissingName, RubyModule methodMissingOwner) : this(target, info, name) { _methodMissingName = methodMissingName; + _methodMissingOwner = methodMissingOwner; } /// - /// A Method standing in for a name the object only answers through #method_missing. + /// A Method standing in for a name the object only answers through #method_missing, owned by + /// (an UnboundMethod's owner, bound again) or else by the receiver's class. /// - public static RubyMethod/*!*/ CreateMethodMissing(object target, RubyMemberInfo/*!*/ info, string/*!*/ name) { - return new RubyMethod(target, info, name, name); + public static RubyMethod/*!*/ CreateMethodMissing(object target, RubyMemberInfo/*!*/ info, string/*!*/ name, RubyModule owner = null) { + return new RubyMethod(target, info, name, name, owner ?? info.Context.GetImmediateClassOf(target)); } object IDuplicable.Duplicate(RubyContext/*!*/ context, bool copySingletonMembers) { - var result = new RubyMethod(_target, _info, _name, _methodMissingName); + var result = new RubyMethod(_target, _info, _name, _methodMissingName, _methodMissingOwner); result.LookupModule = LookupModule; context.CopyInstanceData(this, result, copySingletonMembers); return result; From bff4dbac76e927c988a57a06dc2fb4387ee92e3c Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:08:49 +0100 Subject: [PATCH 140/147] UnboundMethod#bind checks the receiver against the method's #owner MRI's umethod_bind checks against the owner, so an alias or a `public :m' made in a subclass binds only to instances of that subclass. IronRuby checked against the module the method body was defined in and let a superclass instance through. Checked against CRuby 4.0 ("bind argument must be an instance of C"). --- Src/Libraries/Builtins/UnboundMethod.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 6fc15d771..14fedd6d9 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -95,7 +95,7 @@ public static int GetArity(UnboundMethod/*!*/ self) { } /// - /// The receiver has to be a kind of the module the method is *defined* in, not of the one + /// The receiver has to be a kind of the method's #owner (mostly the module it is defined in), not of the one /// it was extracted from: Child.instance_method(:inherited_one) binds to any Parent, which /// constraining on Child would refuse. Since Ruby 3.0 (Feature #15608) a method whose owner /// is a module rather than a class binds to anything at all. @@ -103,7 +103,9 @@ public static int GetArity(UnboundMethod/*!*/ self) { [RubyMethod("bind")] public static RubyMethod/*!*/ Bind(UnboundMethod/*!*/ self, object target) { RubyContext context = self._targetConstraint.Context; - RubyModule constraint = self._info.DeclaringModule ?? self._targetConstraint; + // MRI checks against the method's #owner: an alias, or a `public :m' in a subclass, binds only + // to instances of the class it is in + RubyModule constraint = GetOwner(self); // a refinement's method binds to what the refinement refines (Feature #14223) if (constraint.IsRefinement && constraint.RefinedModule != null) { constraint = constraint.RefinedModule; From eea63412622f2c4f2abf48700118c0c9c3057897 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:08:54 +0100 Subject: [PATCH 141/147] Method#inspect lets an anonymous module's #inspect raise method_inspect writes modules with rb_inspect, which passes on what #inspect raises. IronRuby caught it and fell back to the module's default name. --- Src/Libraries/Builtins/UnboundMethod.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 14fedd6d9..e64480a90 100644 --- a/Src/Libraries/Builtins/UnboundMethod.cs +++ b/Src/Libraries/Builtins/UnboundMethod.cs @@ -288,12 +288,9 @@ public static object BindCall(RubyScope/*!*/ scope, BlockParam block, UnboundMet // method_inspect writes each module with rb_inspect, so an anonymous one that says what it is // (EnvUtil.labeled_class) is shown by what it says rather than as #. private static MutableString/*!*/ InspectModule(RubyContext/*!*/ context, RubyModule/*!*/ module) { + // and what its #inspect raises goes to the caller, as from rb_inspect if (module.Name == null && !module.IsSingletonClass) { - try { - return context.Inspect(module); - } catch (Exception) { - // the name it would have had - } + return context.Inspect(module); } return module.GetDisplayName(context, false); } From db5f7409e407f47e7cc60337705c9b1a75fc6ace Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:01 +0100 Subject: [PATCH 142/147] Module#using in a string module_eval inside a method is refused A string module_eval runs in the frame that called it, so MRI raises "Module#using is not permitted in methods" when that frame is a method. IronRuby took the eval's module scope for a class body and allowed it. --- Src/Libraries/Builtins/ModuleOps.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/Libraries/Builtins/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 9f00373fa..40584455a 100644 --- a/Src/Libraries/Builtins/ModuleOps.cs +++ b/Src/Libraries/Builtins/ModuleOps.cs @@ -226,12 +226,12 @@ public static void Prepended(RubyModule/*!*/ self, RubyModule/*!*/ owner) { public static RubyModule/*!*/ Using(RubyScope/*!*/ scope, RubyModule/*!*/ self, object module) { // MRI refuses it inside a method body and the blocks in it (a module_eval or Module.new // block included), but a class body opened in a method (`class << self`) is a frame of - // its own and may use it + // its own and may use it. A string module_eval is not: it runs in the frame that called it. for (RubyScope s = scope; s != null; s = s.Parent) { if (s.Kind == ScopeKind.Method || s.Kind == ScopeKind.BlockMethod) { throw RubyExceptions.CreateRuntimeError("Module#using is not permitted in methods"); } - if (s.Kind == ScopeKind.Module || s.Kind == ScopeKind.TopLevel) { + if ((s.Kind == ScopeKind.Module && !(s is RubyModuleEvalScope)) || s.Kind == ScopeKind.TopLevel) { break; } } From 11a884192b15559c55486c7864261f78ebf6054d Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:03 +0100 Subject: [PATCH 143/147] Thread sleep takes a raise parked between its check and the signal reset When the sleeper saw a pending async exception it reset the run signal and returned. A Thread#raise parked after that check, whose RunForInterrupt wake-up came before the Reset, lost its wake-up, and the sleeper waited for one that had come and gone. It now delivers the pending exception right after the Reset; one parked after the Reset sets the signal again. --- Src/Libraries/Builtins/ThreadOps.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Src/Libraries/Builtins/ThreadOps.cs b/Src/Libraries/Builtins/ThreadOps.cs index 0faffdb5f..a9c01486f 100644 --- a/Src/Libraries/Builtins/ThreadOps.cs +++ b/Src/Libraries/Builtins/ThreadOps.cs @@ -607,13 +607,17 @@ private bool WokenForMaskedInterrupt() { if (_wokenByRun) { return false; } - if (RubyUtils.HasPendingAsyncException(_thread)) { - // drop the RunForInterrupt wake-up, if it has not been taken, or the next wait ends at once - _runSignal.Reset(); - return true; + if (!RubyUtils.HasPendingAsyncException(_thread)) { + return false; } - return false; + // drop the RunForInterrupt wake-up, if it has not been taken, or the next wait ends at once + _runSignal.Reset(); } + // A raise that may be delivered and was parked since the look above has had its wake-up + // dropped by that Reset, if its RunForInterrupt came first: take it now rather than wait + // for a wake-up that has come and gone. One parked after the Reset sets the signal again. + RubyUtils.CheckAsyncException(); + return true; } /// From 8ba129e72708f82a4ab39b485a4423525c446fa6 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:12 +0100 Subject: [PATCH 144/147] A cloned module's methods keep the refinements their def saw The refinements active at a def are recorded per declaring module. A clone's copies of the methods had no record, so they saw what the defining scope had `using'd since, or nothing. InitializeMembersFrom now copies the record to the clone, as MRI's cref goes with the copied method. --- Src/Ruby/Builtins/RubyModule.cs | 4 ++++ Src/Ruby/Runtime/Calls/RubyMethodBody.cs | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Src/Ruby/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 909683383..cd754eab2 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -892,6 +892,10 @@ internal void InitializeMembersFrom(RubyModule/*!*/ module) { // the original module ([Bug #15877]). Methods written elsewhere (in a block, in another module's // body, the singleton methods of a `def self.m') keep the scope they were written in. var rubyMethod = method.Value as RubyMethodInfo; + if (rubyMethod != null) { + // the refinements active at its `def' go with it, whichever scope it gets + rubyMethod.Body.CopyDefinitionRefinements(rubyMethod.DeclaringModule, this); + } var moduleScope = (rubyMethod != null) ? rubyMethod.DeclaringScope as RubyModuleScope : null; if (moduleScope != null && moduleScope.Module == module) { rewrittenScopes ??= new Dictionary(); diff --git a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs index 438ae9126..d7c2a8a2f 100644 --- a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs +++ b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs @@ -329,6 +329,20 @@ record = GetDefinitionRefinementsNoLock(declaringModule); } } + /// + /// Gives , a clone of , the refinements the body's `def' saw + /// there: the copy's methods see what the original's did, not what the scope they were written in has + /// `using'd since (RubyModule.InitializeMembersFrom). + /// + internal void CopyDefinitionRefinements(RubyModule/*!*/ original, RubyModule/*!*/ copy) { + lock (this) { + StrongBox record; + if (_definitionRefinements != null && _definitionRefinements.TryGetValue(original, out record) && record.Value != null) { + GetDefinitionRefinementsNoLock(copy).Value = record.Value; + } + } + } + private StrongBox/*!*/ GetDefinitionRefinementsNoLock(RubyModule/*!*/ declaringModule) { if (_definitionRefinements == null) { _definitionRefinements = new ConditionalWeakTable>(); From 4af0c3584bd0d9223fc8d9a20c4199df3dfd0516 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:13 +0100 Subject: [PATCH 145/147] method_missing called directly sets the NoMethodError reason afresh vm_call_method_missing sets the reason for each call. IronRuby kept the one an earlier call left, so after a custom method_missing that never reached super had been undefined, a direct method_missing(:x) or send(:method_missing, :x) raised NameError ("undefined local variable or method") where CRuby 4.0 raises NoMethodError with private_call? true. Checked against CRuby 4.0. --- Src/Ruby/Runtime/Calls/RubyCallAction.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 22633ce2c..2574aa60f 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -936,6 +936,13 @@ internal static bool BuildMethodMissingCall(MetaObjectBuilder/*!*/ metaBuilder, if (defaultFallback && methodName == Symbols.MethodMissing && incompatibleVisibility == RubyMethodVisibility.None) { var basicMethodMissing = args.RubyContext.BasicObjectClass.GetMethod(Symbols.MethodMissing) as RubyLibraryMethodInfo; if (basicMethodMissing != null) { + // MRI sets the reason afresh for this call (vm_call_method_missing): what an earlier + // call left for a custom method_missing that never reached super is not this one's + if (!isSuperCall) { + metaBuilder.AddInitialization(Methods.SetMethodMissingReason.OpCall( + AstUtils.Constant(args.Signature.HasImplicitSelf), AstUtils.Constant(false) + )); + } basicMethodMissing.BuildCall(metaBuilder, args, Symbols.MethodMissing); return true; } From 368141f4f1eda52e41c5f3f032ab65ef16c5d5f9 Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:20 +0100 Subject: [PATCH 146/147] Kernel#clone copies the instance variables of the singleton class's singleton class rb_singleton_class_clone_and_attach clones the metaclass with its instance variables, as it does the singleton class itself. IronRuby copied only its methods. --- Src/Ruby/Runtime/RubyContext.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 18d342667..a7d4f94bc 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3120,7 +3120,10 @@ public void CopyInstanceData(object source, object target, bool copySingletonMem // rb_singleton_class_clone_and_attach clones along with it var meta = singleton.ImmediateClass; if (meta.IsSingletonClass && !meta.IsDummySingletonClass && ReferenceEquals(meta.SingletonClassOf, singleton)) { - singletonDup.GetOrCreateSingletonClass().InitializeMembersFrom(meta); + var metaDup = singletonDup.GetOrCreateSingletonClass(); + metaDup.InitializeMembersFrom(meta); + // with its instance variables, as for the singleton class above + CopyInstanceData(meta, metaDup, false); } SetInstanceSingletonOfNoLock(target, ref targetData, singletonDup); From 07d0353ee7f1efbadd5a8e4f60af4c4363f00ade Mon Sep 17 00:00:00 2001 From: Andi Idogawa Date: Mon, 23 Nov 2026 22:09:26 +0100 Subject: [PATCH 147/147] An exception's singleton #backtrace is used where MRI uses it MRI looks #backtrace up in CLASS_OF, the singleton class when there is one, so `def e.backtrace' counts. IronRuby looked only in the exception's class. --- Src/Ruby/Runtime/RubyContext.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index a7d4f94bc..e88f0f13f 100644 --- a/Src/Ruby/Runtime/RubyContext.cs +++ b/Src/Ruby/Runtime/RubyContext.cs @@ -3553,7 +3553,8 @@ internal object GetCurrentExceptionBacktrace() { return null; } - var method = GetClassOf(e).ResolveMethod("backtrace", VisibilityContext.AllVisible).Info; + // the exception's own singleton class too (`def e.backtrace'): MRI looks it up in CLASS_OF + var method = GetImmediateClassOf(e).ResolveMethod("backtrace", VisibilityContext.AllVisible).Info; if (method == null || method is RubyLibraryMethodInfo && method.DeclaringModule == ExceptionClass) { return RubyExceptionData.GetInstance(e).Backtrace; }