diff --git a/Src/IronRuby.Tests/RubyTests.cs b/Src/IronRuby.Tests/RubyTests.cs index b81db8f85..d21771a36 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, @@ -206,6 +207,7 @@ public Tests(Driver/*!*/ driver) { Regex_MatchStringClassAndIdentity1, Regex_SharedTranslation1, Regex_SharedTranslation2, + Regex_LiteralEncodings1, Regex_PropertyEncoding1, Regex_BinaryCtype1, Regex_InspectResultEncoding1, @@ -333,6 +335,7 @@ public Tests(Driver/*!*/ driver) { Scenario_RubyProcYieldArgs2, Scenario_RubyProcYieldArgs3, Scenario_RubyProcYieldArgs4, + Scenario_RubyProcYieldArgs5, Scenario_RubyProcCallArgs1, Scenario_RubyProcCallArgs2A, Scenario_RubyProcCallArgs2B, @@ -343,6 +346,7 @@ public Tests(Driver/*!*/ driver) { Scenario_RubyBlockArgs4B, Scenario_RubyBlockArgs5, Scenario_RubyBlockArgs6, + Scenario_RubyBlockArgs7, Proc_RhsAndBlockArguments1, Block_ProcParams1, @@ -552,6 +556,7 @@ public Tests(Driver/*!*/ driver) { Hooks3, MethodLookupCacheFull1, Hooks4, + TraceVar_AssignInHandler1, ClrFields1, ClrFields2, @@ -763,6 +768,7 @@ public Tests(Driver/*!*/ driver) { ClrClosedInterfaceExtensions2, HostingDefaultOptions1, HostingEncodingOption1, + HostingTimeSitesPerRuntime1, Interactive1, Interactive2, @@ -850,6 +856,7 @@ public Tests(Driver/*!*/ driver) { UndefMethodLookup3, UndefMethodLookup4, UndefMethodLookup6, + UndefMethodMissing1, UndefCoreMethodWarnings1, RemoveBasicObjectInitialize1, MethodAdded1, @@ -862,6 +869,7 @@ public Tests(Driver/*!*/ driver) { Visibility4, Visibility5, Visibility6, + Visibility7, VisibilityCaching1, VisibilityCaching2, DefineMethodVisibility1, @@ -915,6 +923,7 @@ public Tests(Driver/*!*/ driver) { SuperParameterless2B, SuperParameterless3, SuperParameterlessKeywordRest1, + SuperMethodForwarder1, SuperKeywordSplat1, SuperKeywordRestPassOn1, SuperParameterlessKeywordRest2, @@ -1031,6 +1040,7 @@ public Tests(Driver/*!*/ driver) { Marshal_LoadFloat1, Marshal_SetIVars1, Marshal_NameError1, + Marshal_LoadChecks1, Integer_SqrtPowDigits1, Prelude_DataStructErrors1, Prelude_AliasNames1, @@ -1075,6 +1085,8 @@ public Tests(Driver/*!*/ driver) { Io_LineReaders2, Io_LineReaders3, Io_UngetcConverted1, + Io_GetsLongLineFromPipe1, + Io_UnreadPushedBack1, Io_WideLineReaders1, Io_Timeout1, Io_Timeout2, @@ -1161,6 +1173,8 @@ public Tests(Driver/*!*/ driver) { WeakMap_NoBlock1, Fiber_ThreadRaiseReachesRunningFiber1, Thread_HandleInterruptOtherRuntime1, + Thread_HandleInterruptInherited1, + Thread_HandleInterruptIoWrite1, Thread_RaiseBetweenBlockCallsMeetsRescue1, Thread_KillBehindRaise1, Thread_KillBehindRescuedRaise1, @@ -1190,6 +1204,9 @@ public Tests(Driver/*!*/ driver) { PreludeKeywordsArity1, LibraryKeywordsStored1, BlockKeywordsPositional1, + YieldEmptyKeywordSplat1, + LibraryBlockOrphanBreak1, + ItParameterLocal1, PreludeKeywordsYielder1, SymbolProcKeywords1, ToIntToStrConversion1, @@ -1215,6 +1232,7 @@ public Tests(Driver/*!*/ driver) { ClassDuplication7, Clone1, Dup1, + CloneConstantLookup1, Structs1, MetaModules1, MetaModulesDuplication1, @@ -1349,6 +1367,10 @@ public Tests(Driver/*!*/ driver) { Array_Cycle1, Range_Recursive1, Array_JoinRecursive1, + Array_JoinNested1, + Array_RangeLongEnd1, + Array_DuckRangeIndex1, + 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 9007000db..a6d5097f4 100644 --- a/Src/IronRuby.Tests/Runtime/ArrayTests.cs +++ b/Src/IronRuby.Tests/Runtime/ArrayTests.cs @@ -566,6 +566,118 @@ public void Array_JoinRecursive1() { # # ""12335"" +"); + } + + /// + /// 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. + /// + 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] +# +# +# +"); + } + + /// + /// 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 + /// 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/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 diff --git a/Src/IronRuby.Tests/Runtime/BlockTests.cs b/Src/IronRuby.Tests/Runtime/BlockTests.cs index 3628d12ef..a38775df0 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. /// @@ -1574,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(@" @@ -2298,6 +2356,82 @@ def i(x, &b) 3 10 2 +"); + } + + /// + /// `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 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". + /// + 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/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/IronRuby.Tests/Runtime/FiberTests.cs b/Src/IronRuby.Tests/Runtime/FiberTests.cs index 6dbadd78a..60351dc51 100644 --- a/Src/IronRuby.Tests/Runtime/FiberTests.cs +++ b/Src/IronRuby.Tests/Runtime/FiberTests.cs @@ -156,6 +156,86 @@ 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 +"); + } + + /// + /// 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/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/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/IronRuby.Tests/Runtime/IoTests.cs b/Src/IronRuby.Tests/Runtime/IoTests.cs index 468b9d377..90dedfa6a 100644 --- a/Src/IronRuby.Tests/Runtime/IoTests.cs +++ b/Src/IronRuby.Tests/Runtime/IoTests.cs @@ -870,6 +870,67 @@ 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. + /// + /// + /// 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' +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/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/IronRuby.Tests/Runtime/MiscTests.cs b/Src/IronRuby.Tests/Runtime/MiscTests.cs index 72dd82d8d..5fef26bc3 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) @@ -1856,13 +1858,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 +1870,7 @@ p e.message ""XST"" ""XST"" ZoneFailure -""marshaled time format differ"" +2001-04-01 00:00:00 UTC "); } @@ -3621,6 +3619,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. @@ -3671,7 +3710,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] } @@ -3686,7 +3725,7 @@ p Kernel.instance_method(:then) == Kernel.instance_method(:yield_self), Kernel.i [] # # -# +# 9 # # @@ -4033,9 +4072,10 @@ 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"") - begin; load bad; rescue ArgumentError => e; p e.message == ""#{bad}:1: unknown or invalid encoding in the magic comment"", e.backtrace.grep(/Parse/); end + 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 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 ", @" @@ -4043,6 +4083,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/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/IronRuby.Tests/Runtime/RegexTests.cs b/Src/IronRuby.Tests/Runtime/RegexTests.cs index 663e6052c..328a22ee8 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]"); @@ -621,6 +621,49 @@ public void Regex_SharedTranslation2() { 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 +# +"); + } + /// /// A character property pins a regexp to the encoding of its source, as MRI's /// rb_reg_preprocess does (Regexp::FIXEDENCODING, and no match against a string of another 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/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/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__ 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/Libraries/Builtins/Dir.cs b/Src/Libraries/Builtins/Dir.cs index 0d716acce..57a37db14 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] @@ -127,7 +135,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 +143,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 +294,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 +322,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); @@ -385,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; } @@ -497,7 +605,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 diff --git a/Src/Libraries/Builtins/EncodingConverter.cs b/Src/Libraries/Builtins/EncodingConverter.cs index e21cbc4cb..48baf722e 100644 --- a/Src/Libraries/Builtins/EncodingConverter.cs +++ b/Src/Libraries/Builtins/EncodingConverter.cs @@ -48,12 +48,18 @@ 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; 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; @@ -84,6 +90,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; @@ -148,6 +157,12 @@ public class RubyConverter { // 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 @@ -234,6 +249,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"); } @@ -313,7 +329,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); } @@ -352,29 +368,33 @@ 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() { + if (_explicitConvPath != null) { + return new RubyArray(_explicitConvPath); + } return MakeConvPath(_noConversion ? null : _path, _flags); } @@ -851,6 +871,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)) { @@ -901,6 +942,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) { @@ -1143,7 +1251,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; } } @@ -1270,7 +1378,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) { @@ -1284,14 +1392,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'); @@ -1479,12 +1586,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)); @@ -1507,7 +1620,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); } @@ -1533,10 +1646,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); @@ -1547,6 +1683,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, @@ -1619,8 +1822,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("#")); } @@ -1645,12 +1848,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; 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/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/FileOps.cs b/Src/Libraries/Builtins/FileOps.cs index 133bfb4fc..f03cdfc41 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, @@ -117,6 +126,7 @@ internal static bool Exists(RubyContext/*!*/ context, MutableString/*!*/ path) { permissions = p.Value; } } + info.RequireBinmodeForAsciiIncompatible(); self.ConversionOptions = RubyIOOps.AddTextModeDecorator(context, info, options); // descriptor or path: @@ -300,24 +310,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; } @@ -383,7 +394,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); @@ -393,7 +404,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); } } } @@ -520,11 +531,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 @@ -620,7 +632,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) { @@ -905,18 +924,95 @@ 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 - ); + 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)); + 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); } + /// + /// 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); + // 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('/'); + 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); + 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. + 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 + } + } + } + baseBytes = BytesAsChars(directory); + } + + string result = RubyUtils.ExpandPath(context.Platform, bytes, baseBytes, 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 @@ -1068,6 +1164,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), @@ -1113,26 +1214,48 @@ 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) { + 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"); + } + } + } + + 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) { @@ -1147,22 +1270,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) { @@ -1206,7 +1339,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); @@ -1232,7 +1365,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 @@ -1369,7 +1502,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(); @@ -1383,7 +1516,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; @@ -1393,7 +1526,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) { @@ -1403,7 +1536,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; @@ -1655,7 +1788,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)); } @@ -1666,7 +1799,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)); } @@ -1677,7 +1810,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)); } @@ -1796,14 +1929,27 @@ 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) { + public static FileSystemInfo Stat(RubyIO/*!*/ 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(RubyIO/*!*/ self) { + self.RequireOpen(); + string path = FilePathOf(self); + if (path == null) { + return RubyStatOps.Create(self); + } + 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)); } @@ -1813,14 +1959,20 @@ 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(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)). @@ -1838,7 +1990,31 @@ 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); + } + + /// + /// 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) { return null; @@ -1860,18 +2036,37 @@ public 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; @@ -2076,13 +2271,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] @@ -2090,6 +2293,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); @@ -2500,6 +2731,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)), diff --git a/Src/Libraries/Builtins/IoOps.cs b/Src/Libraries/Builtins/IoOps.cs index c1484bbd8..1c4b17d7f 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); @@ -205,6 +206,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 +229,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) { @@ -241,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); @@ -362,29 +397,88 @@ 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. + // 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; if (file != null && sourceFile != null) { file.Path = sourceFile.Path; file.PathEncoding = sourceFile.PathEncoding; + } else if (file == null) { + SetIOPath(self, GetIOPath(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,21 +496,13 @@ 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); + // 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. @@ -1490,28 +1576,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)); @@ -1591,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; } @@ -1607,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; } @@ -1761,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; @@ -1791,14 +1877,30 @@ 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 // 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; } + // 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) { @@ -2356,6 +2458,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: @@ -2497,13 +2600,46 @@ 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); } + 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 @@ -2658,6 +2794,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; } @@ -2972,6 +3130,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) { @@ -3132,9 +3291,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. @@ -3162,7 +3333,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); } } @@ -3297,6 +3469,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; @@ -3376,21 +3549,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 +3578,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 +3649,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 +3683,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/Libraries/Builtins/KernelOps.cs b/Src/Libraries/Builtins/KernelOps.cs index f75a73ffc..d3945f4fe 100644 --- a/Src/Libraries/Builtins/KernelOps.cs +++ b/Src/Libraries/Builtins/KernelOps.cs @@ -1348,22 +1348,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) { @@ -3218,15 +3235,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) { diff --git a/Src/Libraries/Builtins/Marshal.cs b/Src/Libraries/Builtins/Marshal.cs index 0d693e1d9..465b705eb 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; + } } @@ -119,6 +264,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"; @@ -348,9 +494,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 +521,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); @@ -422,6 +583,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); @@ -682,13 +856,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 @@ -701,14 +895,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]); } } @@ -747,6 +946,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 @@ -919,7 +1135,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'); @@ -956,6 +1172,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) { @@ -1132,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; } } @@ -1194,6 +1426,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]; @@ -1433,18 +1668,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); } @@ -1488,8 +1729,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(); @@ -1624,6 +1868,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; @@ -1632,6 +1887,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; @@ -1730,11 +1988,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 @@ -1774,7 +2037,20 @@ private RubyClass ReadLoadableType() { 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; } @@ -1787,11 +2063,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') { @@ -1804,13 +2091,24 @@ private RubyClass ReadLoadableType() { } 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); } @@ -1823,14 +2121,16 @@ private RubyClass ReadLoadableType() { 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]) { - RubyClass theClass = Context.GetClassOf(obj); 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; } @@ -1846,13 +2146,16 @@ private RubyClass ReadLoadableType() { 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; } @@ -1881,6 +2184,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 @@ -1925,6 +2231,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); @@ -1936,6 +2257,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); } @@ -1943,21 +2272,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) { @@ -2237,8 +2593,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; } @@ -2247,12 +2606,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() { @@ -2266,6 +2620,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); } @@ -2407,18 +2764,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(); } diff --git a/Src/Libraries/Builtins/MethodOps.cs b/Src/Libraries/Builtins/MethodOps.cs index a1fef7c91..0e505d38b 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); @@ -66,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 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.MethodMissingOwner; + } return self.Info.AliasOwner ?? self.Info.DeclaringModule ?? self.GetTargetClass(); } @@ -96,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); } @@ -122,17 +133,16 @@ 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; } [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.MethodMissingOwner : 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/ModuleOps.cs b/Src/Libraries/Builtins/ModuleOps.cs index 56a74f219..40584455a 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. 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 is RubyModuleEvalScope)) || 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; diff --git a/Src/Libraries/Builtins/MutableStringOps.cs b/Src/Libraries/Builtins/MutableStringOps.cs index 9452116af..bfa9fb494 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; @@ -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; } @@ -1224,10 +1241,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; @@ -1289,11 +1302,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")] @@ -1405,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); @@ -1469,7 +1506,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; @@ -1477,7 +1514,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; @@ -1780,7 +1817,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()); } @@ -2063,6 +2105,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(); @@ -2070,7 +2190,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 @@ -2082,6 +2202,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); @@ -2879,6 +3002,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. @@ -2923,13 +3052,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; } @@ -3017,7 +3147,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)); @@ -3035,6 +3165,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; } } @@ -3295,6 +3431,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]; @@ -3367,6 +3507,83 @@ private static void TranscodeByCharacter( return from.FinishTranscodingDecode(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. 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/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; diff --git a/Src/Libraries/Builtins/ProcOps.cs b/Src/Libraries/Builtins/ProcOps.cs index acf6041a3..2150e1126 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 @@ -319,6 +323,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); }); } @@ -333,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); }); @@ -350,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/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/RubyTime.cs b/Src/Libraries/Builtins/RubyTime.cs index 8fadb4308..441169029 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) @@ -265,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; @@ -429,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 31c0329bc..a05c65113 100644 --- a/Src/Libraries/Builtins/RubyTimeOps.cs +++ b/Src/Libraries/Builtins/RubyTimeOps.cs @@ -38,33 +38,37 @@ 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); } private static bool RespondTo(RubyContext/*!*/ context, object obj, string/*!*/ name) { - return context.ResolveMethod(obj, name, VisibilityContext.AllVisible).Found; + if (context.ResolveMethod(obj, name, VisibilityContext.AllVisible).Found) { + return true; + } + // 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 = context.GetOrCreateSendSite>( + "respond_to?", RubyCallSignature.WithImplicitSelf(2)); + return Protocols.IsTrue(site.Target(site, obj, context.EncodeIdentifier(name), true)); + } + + /// + /// 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, "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 @@ -132,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)); } @@ -151,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; } @@ -159,13 +163,13 @@ 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; } } - throw RubyExceptions.CreateTypeError("can't convert {0} into an exact number", context.GetClassName(value)); + throw MakeExactNumberError(context, value); } /// @@ -204,6 +208,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")); @@ -216,7 +224,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 @@ -231,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; } @@ -340,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; @@ -369,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)); } @@ -384,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) @@ -396,7 +406,20 @@ 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; + } + + /// + /// 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, "dst?", zoneObject, wallClock)); } #endregion @@ -507,14 +530,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; } @@ -586,12 +619,8 @@ private static object GetInOption(IDictionary options, bool allo 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); @@ -605,6 +634,12 @@ private static object GetInOption(IDictionary options, bool allo } } + 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) { @@ -653,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] == '.') { @@ -692,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])) { @@ -720,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"); + } } /// @@ -749,7 +793,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) { @@ -857,7 +901,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) { @@ -866,6 +910,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; } @@ -929,6 +974,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) { @@ -991,7 +1037,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"); @@ -999,6 +1047,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); } @@ -1078,7 +1129,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. @@ -1122,12 +1173,14 @@ 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; } 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; @@ -1177,6 +1230,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(); @@ -1204,6 +1286,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) { @@ -1219,6 +1303,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); @@ -1256,6 +1346,7 @@ private static uint GetUint(byte[] data, int start) { 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; } @@ -1295,17 +1386,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); } @@ -1576,6 +1667,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; } @@ -1769,7 +1861,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(); } @@ -1784,6 +1876,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; 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; 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); } 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/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 267689287..a9c01486f 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; @@ -542,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(); @@ -550,13 +556,26 @@ 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; + bool woken; + try { + woken = _runSignal.WaitOne(milliseconds); + if (!woken) { + return false; + } + } catch (ThreadInterruptedException) { + _inManagedWait = wasWaiting; + RubyUtils.TranslateThreadInterrupt(); + woken = false; + } + if (!WokenForMaskedInterrupt()) { + return woken; + } + if (milliseconds != Timeout.Infinite) { + milliseconds = (int)Math.Max(0, deadline - Environment.TickCount64); + } } } finally { EndSleep(wasSleeping); @@ -574,6 +593,33 @@ 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)) { + 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; + } + /// /// 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 +633,7 @@ private void EndSleep(bool wasSleeping) { _isSleeping = wasSleeping; if (!wasSleeping) { _runSignal.Reset(); + _wokenByRun = false; } } } @@ -594,6 +641,7 @@ private void EndSleep(bool wasSleeping) { internal void Run() { using (new RubyUtils.UninterruptedLock(_sleepLock)) { if (_isSleeping) { + _wokenByRun = true; _runSignal.Set(); } } @@ -619,6 +667,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 +678,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(); } } @@ -786,7 +840,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)); @@ -881,21 +937,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 +978,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; @@ -932,9 +996,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); @@ -1017,8 +1093,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. @@ -1059,7 +1133,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; }); } @@ -1092,9 +1166,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); @@ -1318,6 +1399,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; } /// @@ -1369,12 +1452,17 @@ 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); } 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); @@ -1456,11 +1544,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. @@ -1774,14 +1864,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); } /// 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/Libraries/Builtins/UnboundMethod.cs b/Src/Libraries/Builtins/UnboundMethod.cs index 52234a9c6..e64480a90 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,17 +103,28 @@ 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; + } 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) ); } - 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, self._targetConstraint); + } + var result = new RubyMethod(target, self._info, self._name); + if (!constraint.IsClass) { + result.LookupModule = constraint; + } + return result; } /// @@ -130,11 +141,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; } @@ -165,6 +172,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; } @@ -222,13 +232,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('.'); @@ -239,10 +249,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('#'); @@ -275,6 +285,16 @@ 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) { + // and what its #inspect raises goes to the caller, as from rb_inspect + if (module.Name == null && !module.IsSingletonClass) { + return context.Inspect(module); + } + 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/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; 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 bca2a32b3..72bb76271 100644 --- a/Src/Libraries/Extensions/IListOps.cs +++ b/Src/Libraries/Extensions/IListOps.cs @@ -78,12 +78,45 @@ internal static bool NormalizeRange(int listCount, ref int start, ref int count) return true; } + /// + /// String and MatchData read a range's ends the same way, but clamp one past the int range to + /// Int32.MaxValue - 1, since their callers add one to an inclusive end in an int. + /// + internal static int CastToRangeComponent(ConversionStorage/*!*/ fixnumCast, object value) { + long l = CastToLongRangeEndpoint(fixnumCast, value); + return l > Int32.MaxValue - 1 ? Int32.MaxValue - 1 : l < Int32.MinValue ? Int32.MinValue : (int)l; + } + + /// + /// 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 +129,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 +143,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 +162,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) { @@ -577,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); } @@ -586,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)); } @@ -656,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 @@ -702,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); @@ -813,9 +879,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 +897,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 +1586,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 +1619,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 +1629,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) { @@ -1962,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 @@ -2043,22 +2067,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 +2109,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 +2143,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; - } - } + length += binary ? parts[i].GetByteCount() : parts[i].GetCharCount(); } - any ??= separator; - - if (any == null) { - return MutableString.CreateEmpty(RubyEncoding.Ascii); - } - - 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; @@ -2211,24 +2234,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(']'); 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. diff --git a/Src/Prism/PrismAstBridge.cs b/Src/Prism/PrismAstBridge.cs index 12644c563..9fad07618 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 @@ -639,8 +673,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: @@ -708,27 +746,31 @@ 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); 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); @@ -1264,6 +1306,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)); @@ -1829,7 +1926,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: @@ -2026,12 +2129,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 } } }; } @@ -3016,6 +3123,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/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(); } diff --git a/Src/Ruby/Builtins/IOMode.cs b/Src/Ruby/Builtins/IOMode.cs index a2dc6cf2b..362460dd2 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()); @@ -102,10 +115,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; diff --git a/Src/Ruby/Builtins/MutableString.cs b/Src/Ruby/Builtins/MutableString.cs index 697b01796..d35427371 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); @@ -3176,9 +3194,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/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; } diff --git a/Src/Ruby/Builtins/RegexpTransformer.cs b/Src/Ruby/Builtins/RegexpTransformer.cs index ee6e7951d..f379491cb 100644 --- a/Src/Ruby/Builtins/RegexpTransformer.cs +++ b/Src/Ruby/Builtins/RegexpTransformer.cs @@ -1898,8 +1898,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; } @@ -2006,7 +2012,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('>'); } /// @@ -2969,7 +2976,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}-]. - set = CharacterSet.MakeRange(low, high, (high < 0x10000) ? set.Text + "-" + rangeEnd.Text : null); + // 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) ? 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); diff --git a/Src/Ruby/Builtins/RubyBufferedStream.cs b/Src/Ruby/Builtins/RubyBufferedStream.cs index c3240f536..148801597 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; @@ -223,7 +246,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 +277,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); } @@ -624,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; @@ -707,24 +738,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 +778,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 +799,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 +831,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 +850,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/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/Builtins/RubyEncoding.cs b/Src/Ruby/Builtins/RubyEncoding.cs index 6ec0ed1a1..95de2e987 100644 --- a/Src/Ruby/Builtins/RubyEncoding.cs +++ b/Src/Ruby/Builtins/RubyEncoding.cs @@ -676,6 +676,112 @@ 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; + } + + // 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) { + 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; + } + + /// + /// 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 + /// 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/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); } diff --git a/Src/Ruby/Builtins/RubyIO.cs b/Src/Ruby/Builtins/RubyIO.cs index e4dd3890c..3093bf0c1 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(); @@ -955,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; @@ -1162,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. @@ -1281,6 +1359,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/Ruby/Builtins/RubyMethod.cs b/Src/Ruby/Builtins/RubyMethod.cs index 10e4375d7..bb1ba09d3 100644 --- a/Src/Ruby/Builtins/RubyMethod.cs +++ b/Src/Ruby/Builtins/RubyMethod.cs @@ -46,10 +46,26 @@ 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 + /// #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; } } + /// The #owner of a method made by , null for any other. + public RubyModule MethodMissingOwner { + get { return _methodMissingOwner; } + } + public object Target { get { return _target; } } @@ -71,20 +87,23 @@ 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; } @@ -147,6 +166,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/Builtins/RubyModule.cs b/Src/Ruby/Builtins/RubyModule.cs index 356371987..cd754eab2 100644 --- a/Src/Ruby/Builtins/RubyModule.cs +++ b/Src/Ruby/Builtins/RubyModule.cs @@ -879,10 +879,34 @@ 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; + 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(); + 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; @@ -2707,23 +2731,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; } } @@ -4172,12 +4234,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/RubyRegex.cs b/Src/Ruby/Builtins/RubyRegex.cs index e543439b1..5fb33a75b 100644 --- a/Src/Ruby/Builtins/RubyRegex.cs +++ b/Src/Ruby/Builtins/RubyRegex.cs @@ -185,10 +185,189 @@ public void Set(MutableString/*!*/ pattern, RubyRegexOptions options) { _pattern = pattern.PrepareForCharacterRead().Clone().Freeze(); } + RequireSingleEncoding(); TransformPattern(false); RequireKnownProperties(); } + /// + /// 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. @@ -1822,6 +2001,10 @@ 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 InRegexEncoding(AppendTo(MutableString.CreateMutable(RubyEncoding.Binary))); } @@ -2451,6 +2634,37 @@ private static bool IsPrintableAscii(byte b) { } // 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/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/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/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/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; } diff --git a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs index a8a6313cc..57a31237d 100644 --- a/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs +++ b/Src/Ruby/Compiler/Ast/Expressions/RegularExpression.cs @@ -84,6 +84,20 @@ public RegularExpression(List/*!*/ pattern, RubyRegexOptions options MSA.Expression/*!*/ StringConstructor.IFactory.CreateExpressionM(AstGenerator/*!*/ gen, MSAst.ExpressionCollectionBuilder/*!*/ args) { gen.HasLiteralState = true; + // 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/Compiler/ReflectionCache.Generated.cs b/Src/Ruby/Compiler/ReflectionCache.Generated.cs index 481a146fe..0ff2ed538 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)); } } @@ -752,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/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); 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: 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 /// . diff --git a/Src/Ruby/Runtime/Calls/RubyCallAction.cs b/Src/Ruby/Runtime/Calls/RubyCallAction.cs index 286a80d04..dfb628e51 100644 --- a/Src/Ruby/Runtime/Calls/RubyCallAction.cs +++ b/Src/Ruby/Runtime/Calls/RubyCallAction.cs @@ -930,6 +930,24 @@ 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) { + // 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; + } + } + // method_missing is defined in Kernel: if (defaultFallback && args.Signature.IsVariableCall) { metaBuilder.SetError(Methods.MakeUndefinedLocalOrMethodError.OpCall( diff --git a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs index 68224c42b..11a1ef4c5 100644 --- a/Src/Ruby/Runtime/Calls/RubyMethodBody.cs +++ b/Src/Ruby/Runtime/Calls/RubyMethodBody.cs @@ -332,6 +332,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>(); 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; } 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; diff --git a/Src/Ruby/Runtime/EscapingEncoding.cs b/Src/Ruby/Runtime/EscapingEncoding.cs index 5e399d506..c03b91c1b 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. /// @@ -60,7 +63,7 @@ internal EscapingEncoding(Encoding/*!*/ inner) } internal static bool IsEscapedByte(char c) { - return c >= (char)0xDC80 && c <= (char)0xDCFF; + return c >= EscapeBase && c <= (char)0xDCFF; } /// 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(); diff --git a/Src/Ruby/Runtime/RubyContext.cs b/Src/Ruby/Runtime/RubyContext.cs index 5927481ab..890605a9e 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 @@ -2626,6 +2636,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 +2666,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; @@ -3093,6 +3115,17 @@ 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)) { + 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); } } @@ -3430,17 +3463,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) @@ -3484,13 +3542,43 @@ 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; + } + + // 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; + } + + 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; @@ -5168,6 +5256,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); @@ -5193,9 +5286,18 @@ 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)); + 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; } diff --git a/Src/Ruby/Runtime/RubyExceptions.cs b/Src/Ruby/Runtime/RubyExceptions.cs index 812fcc991..3d1ff230f 100644 --- a/Src/Ruby/Runtime/RubyExceptions.cs +++ b/Src/Ruby/Runtime/RubyExceptions.cs @@ -685,8 +685,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 @@ -708,7 +706,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/RubyOnlyEncodings.cs b/Src/Ruby/Runtime/RubyOnlyEncodings.cs index 21aedfc50..cccf5baf9 100644 --- a/Src/Ruby/Runtime/RubyOnlyEncodings.cs +++ b/Src/Ruby/Runtime/RubyOnlyEncodings.cs @@ -207,6 +207,27 @@ 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); + } + if (encoding is CesuEncoding) { + return CesuEncoding.Scan(bytes, index, end); + } + if (encoding is EmacsMuleEncoding) { + return EmacsMuleEncoding.Scan(bytes, index, end); + } + return Int32.MinValue; + } + private static int Precise(MultiByteEncoding multiByte, Encoding/*!*/ encoding, byte[]/*!*/ bytes, int index, int end) { if (multiByte != null) { return multiByte.PreciseLength(bytes, index, end); diff --git a/Src/Ruby/Runtime/RubyOps.cs b/Src/Ruby/Runtime/RubyOps.cs index 486b25333..850720561 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); @@ -1220,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; @@ -1724,6 +1748,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 @@ -3212,13 +3246,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) { @@ -3235,9 +3269,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 DynamicRegexEncoding. /// - 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; } @@ -3268,27 +3308,27 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc [Emitted] public static RubyRegex/*!*/ CreateRegexM(MutableString str1, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringM(str1, encoding), options, str1), options); }; + Func createRegex = delegate { var fixedEncoding = DynamicRegexEncoding(options, str1); return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringM(str1, encoding), options, fixedEncoding, str1), 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(InDynamicRegexEncoding(CreateMutableStringLM(str1, str2, encoding), options, + Func createRegex = delegate { var fixedEncoding = DynamicRegexEncoding(options, MutableString.Create(str1, encoding), str2); return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringLM(str1, str2, encoding), options, fixedEncoding, MutableString.Create(str1, encoding), str2), 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(InDynamicRegexEncoding(CreateMutableStringML(str1, str2, encoding), options, + Func createRegex = delegate { var fixedEncoding = DynamicRegexEncoding(options, str1, MutableString.Create(str2, encoding)); return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringML(str1, str2, encoding), options, fixedEncoding, str1, MutableString.Create(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(InDynamicRegexEncoding(CreateMutableStringMM(str1, str2, encoding), options, str1, str2), options); }; + Func createRegex = delegate { var fixedEncoding = DynamicRegexEncoding(options, str1, str2); return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringMM(str1, str2, encoding), options, fixedEncoding, str1, str2), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } @@ -3301,7 +3341,39 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc /// the option decides. /// private static MutableString/*!*/ InDynamicRegexEncoding(MutableString/*!*/ pattern, RubyRegexOptions options, - params MutableString[]/*!*/ fragments) { + RubyEncoding fixedEncoding, params MutableString[]/*!*/ fragments) { + if ((options & RubyRegexOptions.EncodingMask) != 0) { + // the option decides + return pattern; + } + if (fixedEncoding != null && pattern.Encoding != fixedEncoding && pattern.IsAscii()) { + // the concatenation may be one of the interpolated strings itself + pattern = pattern.Clone(); + pattern.ForceEncoding(fixedEncoding); + } else if (fixedEncoding == null && !pattern.IsAscii()) { + // MRI appends the fragments to the first (rb_str_buf_append), so bytes outside ASCII + // that pin nothing - after a backslash, in a comment - keep the encoding of the + // fragment they came from: /#{"(?x)a # \xFF".encode("US-ASCII")}b/ is US-ASCII. + foreach (var fragment in fragments) { + if (fragment != null && !fragment.IsAscii()) { + if (fragment.Encoding != pattern.Encoding && fragment.Encoding.IsAsciiIdentity) { + pattern = pattern.Clone(); + pattern.ForceEncoding(fragment.Encoding); + } + break; + } + } + } + return pattern; + } + + /// + /// The encoding the fragments of an interpolated regexp fix it to, null for none; it raises + /// what is wrong with a fragment. It is asked before the fragments are joined, as MRI asks: + /// fragments in two encodings are an "encoding mismatch in dynamic regexp", not the + /// concatenation's Encoding::CompatibilityError. + /// + private static RubyEncoding DynamicRegexEncoding(RubyRegexOptions options, params MutableString[]/*!*/ fragments) { bool extended = (options & RubyRegexOptions.Extended) != 0; bool binary = (options & RubyRegexOptions.EncodingMask) == RubyRegexOptions.FIXED; RubyEncoding fixedEncoding = null; @@ -3351,34 +3423,12 @@ public static object MatchString(MutableString str, RubyRegex/*!*/ regex, RubySc } fixedEncoding = encoding; } - if ((options & RubyRegexOptions.EncodingMask) != 0) { - // the option decides - return pattern; - } - if (fixedEncoding != null && pattern.Encoding != fixedEncoding && pattern.IsAscii()) { - // the concatenation may be one of the interpolated strings itself - pattern = pattern.Clone(); - pattern.ForceEncoding(fixedEncoding); - } else if (fixedEncoding == null && !pattern.IsAscii()) { - // MRI appends the fragments to the first (rb_str_buf_append), so bytes outside ASCII - // that pin nothing - after a backslash, in a comment - keep the encoding of the - // fragment they came from: /#{"(?x)a # \xFF".encode("US-ASCII")}b/ is US-ASCII. - foreach (var fragment in fragments) { - if (fragment != null && !fragment.IsAscii()) { - if (fragment.Encoding != pattern.Encoding && fragment.Encoding.IsAsciiIdentity) { - pattern = pattern.Clone(); - pattern.ForceEncoding(fragment.Encoding); - } - break; - } - } - } - return pattern; + return fixedEncoding; } [Emitted] public static RubyRegex/*!*/ CreateRegexN(MutableString[]/*!*/ strings, RubyRegexOptions options, StrongBox regexpCache) { - Func createRegex = delegate { return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringN(strings), options, strings), options); }; + Func createRegex = delegate { var fixedEncoding = DynamicRegexEncoding(options, strings); return new RubyRegex(InDynamicRegexEncoding(CreateMutableStringN(strings), options, fixedEncoding, strings), options); }; return CreateRegexWorker(options, regexpCache, false, createRegex); } @@ -3434,7 +3484,7 @@ public int GetHashCode(MutableString str) { } private static MutableString/*!*/ InternFrozenStringLiteral(MutableString/*!*/ str) { - return _frozenStringLiterals.GetOrAdd(str.Freeze(), str); + return _frozenStringLiterals.GetOrAdd(str.FreezeInterned(), str); } /// @@ -4464,15 +4514,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) { @@ -4522,7 +4563,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))); } } 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); + } } /// diff --git a/Src/Ruby/Runtime/RubyUtils.cs b/Src/Ruby/Runtime/RubyUtils.cs index 5d9c8dbbe..96be54dc5 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) { @@ -195,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 @@ -225,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; @@ -1355,7 +1358,12 @@ public static object SetHashElement(RubyContext/*!*/ context, IDictionary= 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); @@ -1484,7 +1497,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); @@ -2364,6 +2379,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) { 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) diff --git a/Src/StdLib/ironruby/ruby4.rb b/Src/StdLib/ironruby/ruby4.rb index 4c3cdb504..3793b75b4 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) @@ -1699,12 +1699,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 @@ -2231,6 +2233,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)") @@ -3925,9 +3928,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") @@ -3941,14 +3953,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 @@ -3956,7 +3964,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] @@ -4666,6 +4676,19 @@ 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? + 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? dir = ENV['HOME'] if dir.nil? && File::ALT_SEPARATOR @@ -4691,7 +4714,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 @@ -5029,8 +5051,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 @@ -5045,6 +5070,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)" @@ -5100,32 +5139,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 @@ -7959,6 +8013,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) @@ -7976,13 +8046,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 @@ -7992,14 +8062,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 @@ -8013,7 +8093,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 @@ -8033,6 +8113,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) @@ -8112,8 +8197,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 @@ -8152,7 +8237,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 @@ -8165,7 +8250,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 @@ -8927,6 +9012,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 @@ -11427,6 +11523,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. @@ -11488,6 +11593,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) @@ -11611,7 +11728,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) @@ -11697,16 +11814,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 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 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") 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