diff --git a/internal/vm/marshal.go b/internal/vm/marshal.go index 3d47fb1c..1129e788 100644 --- a/internal/vm/marshal.go +++ b/internal/vm/marshal.go @@ -29,9 +29,20 @@ func (vm *VM) registerMarshal() { if len(args) == 0 { raise("ArgumentError", "wrong number of arguments (given 0, expected 1..3)") } - data := vm.marshalDump(args[0]) + io := marshalDumpIO(vm, args) + // A non-nil second argument that is neither the depth-limit Integer nor a + // writable IO is a TypeError (mirroring MRI's "instance of IO needed"). + if io == nil && len(args) >= 2 && !object.IsNil(args[1]) { + if _, isInt := args[1].(object.Integer); !isInt { + raise("TypeError", "instance of IO needed") + } + } + data := vm.marshalDump(args[0], marshalDumpLimit(args)) // Marshal.dump always returns an ASCII-8BIT (BINARY) string. - if io := marshalDumpIO(vm, args); io != nil { + if io != nil { + if vm.respondsToDynamic(io, "binmode") { + vm.send(io, "binmode", nil, nil) + } vm.send(io, "write", []object.Value{object.NewStringBytesEnc(data, "ASCII-8BIT")}, nil) return io } @@ -66,6 +77,23 @@ func (vm *VM) registerMarshal() { def("restore", load) // Marshal.restore is an alias for load } +// marshalDumpLimit reads Marshal.dump's depth limit from its arguments: the +// Integer second argument of the two-argument dump(obj, limit) form, or the +// third argument of dump(obj, io, limit). Absent, the limit is -1 (unbounded). +func marshalDumpLimit(args []object.Value) int { + if len(args) >= 2 { + if n, ok := args[1].(object.Integer); ok { + return int(n) + } + if len(args) >= 3 { + if n, ok := args[2].(object.Integer); ok { + return int(n) + } + } + } + return -1 +} + // marshalDumpIO returns the IO destination for Marshal.dump, or nil when the // call has no IO argument. The second argument is an IO when it is non-nil and // responds to #write; a bare Integer there is the depth limit, not an IO. @@ -91,6 +119,11 @@ func marshalLoadSource(vm *VM, src object.Value) []byte { if vm.respondsToDynamic(src, "read") { r := vm.send(src, "read", nil, nil) if s, ok := r.(*object.String); ok { + // An IO that yields no bytes is at end of file; MRI reports this as + // EOFError (distinct from the ArgumentError a truncated String raises). + if len(s.Bytes()) == 0 { + raise("EOFError", "end of file reached") + } return s.Bytes() } } diff --git a/internal/vm/marshal_codec.go b/internal/vm/marshal_codec.go index 812d07ea..7f865c00 100644 --- a/internal/vm/marshal_codec.go +++ b/internal/vm/marshal_codec.go @@ -40,11 +40,17 @@ type mDumper struct { syms map[string]int // symbol name -> symbol-table index objs map[object.Value]int // composite/object identity -> object-link index nextID int + // limit is the remaining recursion budget (Marshal.dump's third argument). + // It counts down one level per nested value; a negative limit (the default + // -1) never reaches zero and so imposes no bound. Reaching zero at the entry + // of any value raises, matching MRI's "exceed depth limit". + limit int } -// marshalDump returns the Ruby Marshal encoding of v. -func (vm *VM) marshalDump(v object.Value) []byte { - d := &mDumper{vm: vm, syms: map[string]int{}, objs: map[object.Value]int{}} +// marshalDump returns the Ruby Marshal encoding of v, honouring the given +// recursion limit (-1 for unlimited). +func (vm *VM) marshalDump(v object.Value, limit int) []byte { + d := &mDumper{vm: vm, syms: map[string]int{}, objs: map[object.Value]int{}, limit: limit} d.buf = []byte{marshalMajor, marshalMinor} d.writeValue(v) return d.buf @@ -68,6 +74,14 @@ func (d *mDumper) link(v object.Value) bool { } func (d *mDumper) writeValue(v object.Value) { + // Enforce Marshal.dump's recursion limit: a zero budget at the entry of any + // value is an error, and each nested value is written with one less. A + // negative budget (the -1 default) never hits zero, so it is unbounded. + if d.limit == 0 { + raise("ArgumentError", "exceed depth limit") + } + d.limit-- + defer func() { d.limit++ }() switch x := v.(type) { case object.Nil: d.buf = append(d.buf, '0') @@ -82,7 +96,12 @@ func (d *mDumper) writeValue(v object.Value) { case object.Integer: d.writeInt(big.NewInt(int64(x))) case *object.Bignum: - d.writeInt(x.I) + // A Bignum is a heap object, so repeated references link like any other + // composite (unlike a Fixnum-range Integer, which is immediate). + if d.link(x) { + return + } + d.writeBignumBody(x.I) case object.Float: d.newID() d.buf = append(d.buf, 'f') @@ -158,7 +177,16 @@ func (d *mDumper) writeInt(b *big.Int) { return } } + // An Integer outside the marshal Fixnum range dumps in the Bignum 'l' form + // and consumes an object-link id, but is immediate so it is never linked. d.newID() + d.writeBignumBody(b) +} + +// writeBignumBody emits the 'l' Bignum payload (sign, 16-bit-short count, +// little-endian magnitude). It does not allocate an object-link id; the caller +// does that (writeInt via newID, or writeValue via link for a *Bignum object). +func (d *mDumper) writeBignumBody(b *big.Int) { d.buf = append(d.buf, 'l') if b.Sign() < 0 { d.buf = append(d.buf, '-') @@ -202,6 +230,13 @@ func (d *mDumper) writeHash(h *object.Hash) { if !object.IsNil(h.DefaultProc) { raise("TypeError", "can't dump hash with default proc") } + // A Hash put into compare_by_identity mode carries no inline flag in the + // stream, so MRI wraps it in a 'C' container naming the Hash class; loading + // that container re-applies compare_by_identity. + if h.Identity { + d.buf = append(d.buf, 'C') + d.writeSymbol("Hash") + } if h.Default != nil { d.buf = append(d.buf, '}') } else { @@ -247,6 +282,9 @@ func (d *mDumper) writeRegexp(r *Regexp) { func (d *mDumper) writeClassRef(c *RClass) { if c.name == "" { + if c.isModule { + raise("TypeError", "can't dump anonymous module %s", c.ToS()) + } raise("TypeError", "can't dump anonymous class %s", c.ToS()) } if c.isModule { @@ -304,6 +342,12 @@ func (d *mDumper) writeObject(o *RObject) { if d.link(o) { return } + // Every path below names o.class; an instance of an anonymous class cannot be + // dumped, whatever hook (marshal_dump / _dump / Struct / builtin subclass / + // plain object) it would otherwise take. + if o.class.name == "" { + raise("TypeError", "can't dump anonymous class %s", o.class.ToS()) + } // An object singleton-extended by one or more modules is prefixed with an 'e' // container per module (last-extended first, matching MRI's ancestry order). if o.singleton != nil { @@ -363,8 +407,16 @@ func (d *mDumper) writeObject(o *RObject) { } return } - if o.class.name == "" { - raise("TypeError", "can't dump anonymous class %s", o.class.ToS()) + // A plain object (no marshal_dump / _dump / Struct / builtin payload) whose + // singleton class carries per-object methods (def obj.foo) or its own ivars + // (class << obj; @v = …) cannot be marshaled. A singleton that only holds + // extend-ed modules has no own methods or ivars and is emitted via 'e' above. + if o.singleton != nil && (len(o.singleton.methods) > 0 || len(o.singleton.ivars) > 0) { + raise("TypeError", "singleton can't be dumped") + } + if d.vm.marshalIsException(o.class) { + d.writeException(o) + return } d.buf = append(d.buf, 'o') d.writeSymbol(o.class.name) @@ -376,6 +428,41 @@ func (d *mDumper) writeObject(o *RObject) { } } +// writeException emits an Exception (or subclass) instance. MRI leads with the +// :mesg and :bt pseudo-ivars (the message and backtrace, or nil), which rbgo +// keeps in @message and @__backtrace__, and then the object's remaining ivars in +// assignment order. +func (d *mDumper) writeException(o *RObject) { + var others []string + for _, n := range o.liveIvarNames() { + if n == "@message" || n == "@__backtrace__" { + continue + } + others = append(others, n) + } + d.buf = append(d.buf, 'o') + d.writeSymbol(o.class.name) + d.writeLong(2 + len(others)) + d.writeSymbol("mesg") + d.writeExceptionField(o.ivars["@message"]) + d.writeSymbol("bt") + d.writeExceptionField(o.ivars["@__backtrace__"]) + for _, n := range others { + d.writeSymbol(n) + d.writeValue(o.ivars[n]) + } +} + +// writeExceptionField writes a :mesg / :bt value, emitting nil when the backing +// ivar is unset or nil. +func (d *mDumper) writeExceptionField(v object.Value) { + if v == nil || object.IsNil(v) { + d.buf = append(d.buf, '0') + return + } + d.writeValue(v) +} + // liveIvarNames returns the object's instance-variable names in first-assignment // order, dropping any that have since been removed. func (o *RObject) liveIvarNames() []string { @@ -400,6 +487,21 @@ func (d *mDumper) writeSymbol(name string) { d.writeLong(id) return } + // A symbol carrying non-ASCII bytes is, by rbgo's UTF-8 default, a UTF-8 + // symbol; MRI wraps such a symbol in an 'I' container with the :E => true + // encoding ivar (a pure-ASCII symbol stays a bare ':' with no wrapper). The + // symbol itself is interned before the E ivar so their table indices match + // MRI's first-appearance order and a repeated encoded symbol links back. + if !marshalIsASCII(name) { + d.buf = append(d.buf, 'I') + d.syms[name] = len(d.syms) + d.buf = append(d.buf, ':') + d.writeBytes(name) + d.writeLong(1) + d.writeSymbol("E") + d.buf = append(d.buf, 'T') + return + } d.syms[name] = len(d.syms) d.buf = append(d.buf, ':') d.writeBytes(name) @@ -523,11 +625,14 @@ func (r *mReader) register(v object.Value) object.Value { } // readValue reads one value and, unless it is a bare symbol or an object link, -// hands it to the load proc (whose return value MRI ignores). +// hands it to the load proc. MRI uses the proc's return value in place of the +// loaded object (so a proc can transform each object, and the top-level result +// is the proc's return for the outermost object); freezing, when requested, has +// already been applied to the object the proc receives. func (r *mReader) readValue() object.Value { v, eligible := r.readObject() if eligible && r.proc != nil { - r.vm.callBlock(r.proc, []object.Value{v}) + return r.vm.callBlock(r.proc, []object.Value{v}) } return v } @@ -573,6 +678,8 @@ func (r *mReader) readObject() (object.Value, bool) { return r.readClassRef(false), true case 'm': return r.readClassRef(true), true + case 'M': + return r.readOldModule(), true case 'U': return r.freezeValue(r.readUserMarshal()), true case 'u': @@ -608,6 +715,12 @@ func (r *mReader) readBignum() object.Value { func (r *mReader) readFloat() object.Value { s := string(r.bytes(r.long())) + // Older MRI dumps append a NUL followed by extra mantissa bytes for full + // precision (e.g. "1.3\0\314\315"); the human-readable decimal before the + // NUL already round-trips, so parse only that prefix. + if i := strings.IndexByte(s, 0); i >= 0 { + s = s[:i] + } var f float64 switch s { case "inf": @@ -693,14 +806,44 @@ func (r *mReader) readObj() object.Value { cls := r.vm.marshalClass(className) o := &RObject{class: cls, ivars: map[string]object.Value{}} r.register(o) + isExc := r.vm.marshalIsException(cls) n := r.long() for i := 0; i < n; i++ { name := r.readSymbol() - setIvar(o, name, r.readValue()) + val := r.readValue() + // MRI serialises an Exception's message and backtrace as the special + // pseudo-ivars :mesg and :bt; rbgo keeps them in @message and + // @__backtrace__. A nil value means "unset", so it is left off entirely. + if isExc { + switch name { + case "mesg": + if !object.IsNil(val) { + setIvar(o, "@message", val) + } + continue + case "bt": + if !object.IsNil(val) { + setIvar(o, "@__backtrace__", val) + } + continue + } + } + setIvar(o, name, val) } return o } +// marshalIsException reports whether cls is Exception or one of its subclasses, +// so the :mesg / :bt pseudo-ivars are mapped onto rbgo's message/backtrace. +func (vm *VM) marshalIsException(cls *RClass) bool { + for _, a := range vm.ancestors(cls) { + if a == vm.cException { + return true + } + } + return false +} + // readExtended reads the 'e' container: a module name followed by the object // that was singleton-extended with it. The base is re-extended on load. 'e' // carries no link id of its own — the wrapped object is what gets registered. @@ -718,6 +861,16 @@ func (r *mReader) readExtended() object.Value { func (r *mReader) readSubclass() object.Value { className := r.readSymbol() cls := r.vm.marshalClass(className) + // 'C:Hash' wrapping a Hash payload is MRI's carrier for a compare_by_identity + // Hash of the plain Hash class (not a user subclass): rebuild the Hash itself + // and re-apply compare_by_identity, sharing the container's single object id. + if cls == r.vm.cHash { + inner := r.readValue() + if ih, ok := inner.(*object.Hash); ok { + ih.CompareByIdentity() + } + return inner + } o := &RObject{class: cls, ivars: map[string]object.Value{}} r.register(o) o.builtin = r.readValue() @@ -765,13 +918,28 @@ func (r *mReader) readStruct() object.Value { return o } +// readClassRef reads a 'c' (class), 'm' (module), or — via readOldModule — an 'M' +// (old class-or-module) reference. 'c' insists the name resolve to a real Class +// and 'm' to a Module; 'M' accepts either, matching MRI's legacy reader. func (r *mReader) readClassRef(module bool) object.Value { name := string(r.bytes(r.long())) cls := r.vm.marshalClass(name) - _ = module + if module && !cls.isModule { + raise("ArgumentError", "%s does not refer to module", name) + } + if !module && cls.isModule { + raise("ArgumentError", "%s does not refer to class", name) + } return r.register(cls) } +// readOldModule reads the legacy 'M' reference, which names either a class or a +// module without distinguishing them. +func (r *mReader) readOldModule() object.Value { + name := string(r.bytes(r.long())) + return r.register(r.vm.marshalClass(name)) +} + func (r *mReader) readUserMarshal() object.Value { className := r.readSymbol() // The value carries the same object identity as its marshal_dump payload's @@ -827,7 +995,10 @@ func (r *mReader) readRegexp(_ bool) object.Value { return r.register(re) } -// readSymbol reads a ':' new symbol (interning it) or a ';' back-reference. +// readSymbol reads a ':' new symbol (interning it), a ';' back-reference, or an +// 'I'-wrapped encoded symbol. rbgo symbols carry no per-symbol encoding, so the +// wrapper's encoding ivars (:E / :encoding) are read past and discarded; the +// symbol name (UTF-8 bytes) is returned unchanged. func (r *mReader) readSymbol() string { tag := r.byte() switch tag { @@ -841,6 +1012,14 @@ func (r *mReader) readSymbol() string { raise("ArgumentError", "dump format error (bad symbol)") } return r.syms[idx] + case 'I': + name := r.readSymbol() + n := r.long() + for i := 0; i < n; i++ { + r.readSymbol() + r.readValue() + } + return name default: raise("ArgumentError", "dump format error(0x%x)", tag) return "" // unreachable diff --git a/internal/vm/marshal_codec_internal_test.go b/internal/vm/marshal_codec_internal_test.go index 62006edf..45bd9f36 100644 --- a/internal/vm/marshal_codec_internal_test.go +++ b/internal/vm/marshal_codec_internal_test.go @@ -128,7 +128,7 @@ func TestMarshalTimeNonUTC(t *testing.T) { vm := New(io.Discard) loc := stdtime.FixedZone("X", 2*3600) tm := &Time{t: stdtime.Date(1970, 1, 1, 2, 0, 0, 0, loc)} - b := vm.marshalDump(tm) + b := vm.marshalDump(tm, -1) // The UTC bit (0x40) must be clear: byte index 15 is the high byte of the // packed "p" word (2 header + I u :Time + 3 low payload bytes). if b[15]&0x40 != 0 { diff --git a/internal/vm/marshal_conformance_test.go b/internal/vm/marshal_conformance_test.go new file mode 100644 index 00000000..d12df8ea --- /dev/null +++ b/internal/vm/marshal_conformance_test.go @@ -0,0 +1,156 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestMarshalConformance pins the MRI-4.0.x Marshal behaviours added to the VM's +// codec (internal/vm/marshal.go and marshal_codec.go). Every expected value in +// this file was checked byte-for-byte against the reference `ruby` interpreter. +func TestMarshalConformance(t *testing.T) { + cases := []struct{ name, src, want string }{ + // --- encoded symbols: a non-ASCII symbol is 'I'-wrapped with :E=>true, + // and the E symbol is shared across the stream ----------------------- + {"sym_encoded_pair", + `p Marshal.dump(["€a".to_sym, "€b".to_sym]).bytes`, + "[4, 8, 91, 7, 73, 58, 9, 226, 130, 172, 97, 6, 58, 6, 69, 84, 73, 58, 9, 226, 130, 172, 98, 6, 59, 6, 84]\n"}, + {"sym_encoded_roundtrip", + `p Marshal.load(Marshal.dump(:€x))`, ":\"€x\"\n"}, + {"sym_ascii_unwrapped", + `p Marshal.dump(:sym).bytes`, "[4, 8, 58, 8, 115, 121, 109]\n"}, + // A non-ASCII ivar name is likewise wrapped on dump and unwrapped on load. + {"sym_encoded_ivar_dump", + `o = Object.new; o.instance_variable_set("@é", 1); p Marshal.dump(o).bytes`, + "[4, 8, 111, 58, 11, 79, 98, 106, 101, 99, 116, 6, 73, 58, 8, 64, 195, 169, 6, 58, 6, 69, 84, 105, 6]\n"}, + {"sym_encoded_ivar_load", + `o = Marshal.load("\x04\bo:\vObject\x06I:\b@\xC3\xA9\x06:\x06ETi\x06"); p o.instance_variable_get(:@é)`, + "1\n"}, + + // --- Bignum object links: a repeated Bignum links; a repeated large + // (immediate) Integer does not ------------------------------------ + {"bignum_links", + `x = 2**64; p Marshal.dump([x, x]).bytes`, + "[4, 8, 91, 7, 108, 43, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 64, 6]\n"}, + {"bignum_roundtrip", + `x = 2**64; c = Marshal.load(Marshal.dump([x, x])); p [c[0] == x, c[0].equal?(c[1])]`, + "[true, true]\n"}, + {"integer_large_not_linked", + `x = 2**40; p Marshal.dump([x, x]).bytes`, + "[4, 8, 91, 7, 108, 43, 8, 0, 0, 0, 0, 0, 1, 108, 43, 8, 0, 0, 0, 0, 0, 1]\n"}, + + // --- compare_by_identity Hash: dumped in a 'C':Hash carrier and the flag + // restored on load -------------------------------------------------- + {"cbi_hash_dump", + `h = {}; h.compare_by_identity; p Marshal.dump(h).bytes`, + "[4, 8, 67, 58, 9, 72, 97, 115, 104, 123, 0]\n"}, + {"cbi_hash_roundtrip", + `h = {}; h.compare_by_identity; p Marshal.load(Marshal.dump(h)).compare_by_identity?`, + "true\n"}, + + // --- recursion limit (Marshal.dump's 3rd argument) -------------------- + {"limit_ok", + `p Marshal.dump([1, [2]], 5).class`, "String\n"}, + {"limit_three_arg_form", + `p Marshal.dump(1, nil, 5).bytes`, "[4, 8, 105, 6]\n"}, + + // --- Exception dump/load: :mesg / :bt pseudo-ivars -------------------- + {"exc_empty_dump", + `p Marshal.dump(Exception.new).bytes`, + "[4, 8, 111, 58, 14, 69, 120, 99, 101, 112, 116, 105, 111, 110, 7, 58, 9, 109, 101, 115, 103, 48, 58, 7, 98, 116, 48]\n"}, + {"exc_message_dump", + `p Marshal.dump(Exception.new("foo")).bytes`, + "[4, 8, 111, 58, 14, 69, 120, 99, 101, 112, 116, 105, 111, 110, 7, 58, 9, 109, 101, 115, 103, 73, 34, 8, 102, 111, 111, 6, 58, 6, 69, 84, 58, 7, 98, 116, 48]\n"}, + {"exc_message_load", + `p Marshal.load("\x04\bo:\x0EException\a:\tmesg\"\bfoo:\abt0").message`, "\"foo\"\n"}, + {"exc_no_message_load", + `p Marshal.load("\x04\bo:\x0EException\a:\tmesg0:\abt0").message`, "\"Exception\"\n"}, + {"exc_backtrace_load", + `p Marshal.load("\x04\bo:\016Exception\a:\abt[\006\"\022foo/bar.rb:10:\tmesg\"\bfoo").backtrace`, + "[\"foo/bar.rb:10\"]\n"}, + {"exc_message_roundtrip", + `p Marshal.load(Marshal.dump(RuntimeError.new("boom"))).message`, "\"boom\"\n"}, + {"exc_ivar_roundtrip", + `e = RuntimeError.new("x"); e.instance_variable_set(:@k, 5); p Marshal.load(Marshal.dump(e)).instance_variable_get(:@k)`, + "5\n"}, + + // --- Float load: an old-format NUL + mantissa suffix is trimmed ------- + {"float_load_with_mantissa", + `p Marshal.load("\x04\bf\v1.3\x00\xcc\xcd")`, "1.3\n"}, + + // --- class / module references --------------------------------------- + {"old_module_load", + `p Marshal.load("\x04\bM\vKernel") == Kernel`, "true\n"}, + {"named_module_dump", + `p Marshal.dump(Comparable).bytes`, + "[4, 8, 109, 15, 67, 111, 109, 112, 97, 114, 97, 98, 108, 101]\n"}, + {"named_module_roundtrip", + `p Marshal.load(Marshal.dump(Comparable)) == Comparable`, "true\n"}, + + // --- load proc: its return value replaces the loaded object ----------- + {"proc_return_replaces", + `p Marshal.load(Marshal.dump([1, 2]), proc { [3, 4] })`, "[3, 4]\n"}, + {"proc_visits_each", + `seen = []; Marshal.load(Marshal.dump([1, 2]), proc { |o| seen << o; o }); p seen`, + "[1, 2, [1, 2]]\n"}, + + // --- dump to an IO: #binmode is called when defined; a writer without + // #binmode still works ---------------------------------------------- + {"io_binmode_called", + `class WBM; def binmode; print "BM "; end; def write(x); end; end; Marshal.dump("x", WBM.new); puts`, + "BM \n"}, + {"io_without_binmode", + `class WNB; def write(x); end; end; p Marshal.dump("x", WNB.new).class.name`, "\"WNB\"\n"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + }) + } +} + +// TestMarshalConformanceErrors pins the error conditions added to the codec. +func TestMarshalConformanceErrors(t *testing.T) { + cases := []struct{ name, src, want string }{ + // Recursion limit exceeded -> ArgumentError at the offending depth. + {"limit_zero_any_value", `Marshal.dump([], 0)`, "exceed depth limit"}, + {"limit_bare_value", `Marshal.dump(1, 0)`, "exceed depth limit"}, + {"limit_nested", `Marshal.dump([[[]]], 1)`, "exceed depth limit"}, + {"limit_three_arg", `Marshal.dump([[[]]], nil, 1)`, "exceed depth limit"}, + + // A non-writable, non-Integer second argument is not a valid IO. + {"io_not_writable", `Marshal.dump("x", Object.new)`, "IO needed"}, + + // Singleton objects cannot be dumped. + {"singleton_method", `o = Object.new; def o.foo; end; Marshal.dump(o)`, "singleton can't be dumped"}, + {"singleton_ivar", `o = Object.new; class << o; @v = 1; end; Marshal.dump(o)`, "singleton can't be dumped"}, + + // Anonymous classes/modules cannot be dumped. + {"anon_module", `Marshal.dump(Module.new)`, "anonymous module"}, + {"anon_struct", `Marshal.dump(Struct.new(:a).new(1))`, "anonymous class"}, + {"anon_range_subclass", `Marshal.dump(Class.new(Range).new(1, 2))`, "anonymous class"}, + {"anon_marshal_dump", + `class UMx; def marshal_dump; 0; end; def marshal_load(v); end; end; Marshal.dump(Class.new(UMx).new)`, + "anonymous class"}, + {"anon_dump", + `class UDx; def _dump(l); "x"; end; end; Marshal.dump(Class.new(UDx).new)`, + "anonymous class"}, + + // 'c'/'m' references insist on the right kind of constant. + {"class_ref_needs_class", `Marshal.load("\x04\bc\vKernel")`, "does not refer to class"}, + {"module_ref_needs_module", `Marshal.load("\x04\bm\vString")`, "does not refer to module"}, + + // An empty IO is at end of file. + {"eof_empty_io", `require "stringio"; Marshal.load(StringIO.new(""))`, "end of file reached"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := runErr(t, c.src) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("src=%q got=%v want error containing %q", c.src, err, c.want) + } + }) + } +} diff --git a/internal/vm/marshal_test.go b/internal/vm/marshal_test.go index 673073ae..81841e68 100644 --- a/internal/vm/marshal_test.go +++ b/internal/vm/marshal_test.go @@ -97,7 +97,7 @@ func TestMarshal(t *testing.T) { // --- freeze: kwarg + load proc ------------------------------------- {`p Marshal.load(Marshal.dump("x"), freeze: true).frozen?`, "true\n"}, {`class MFrz; end; p Marshal.load(Marshal.dump(MFrz.new), freeze: true).frozen?`, "true\n"}, - {`seen = []; Marshal.load(Marshal.dump([1, 2]), proc { |o| seen << o }); p seen`, "[1, 2, [1, 2]]\n"}, + {`seen = []; Marshal.load(Marshal.dump([1, 2]), proc { |o| seen << o; o }); p seen`, "[1, 2, [1, 2]]\n"}, {`seen = []; Marshal.load(Marshal.dump([7])) { |o| seen << o.class }; p seen`, "[Integer, Array]\n"}, // --- IO source / destination --------------------------------------- @@ -135,7 +135,6 @@ func TestMarshal(t *testing.T) { // --- Marshal.dump arity: limit / nil / non-IO second argument ----- {`p Marshal.dump(5, 3).bytes`, "[4, 8, 105, 10]\n"}, {`p Marshal.dump(5, nil).bytes`, "[4, 8, 105, 10]\n"}, - {`p Marshal.dump(5, Object.new).bytes`, "[4, 8, 105, 10]\n"}, // --- Marshal.dump always returns an ASCII-8BIT (BINARY) string ----- {`p Marshal.dump(42).encoding.name`, "\"ASCII-8BIT\"\n"}, @@ -186,6 +185,7 @@ func TestMarshal(t *testing.T) { {"Marshal.load(\"\\x04\\bS:\\vStringi\\x06\")", "is not a Struct"}, // Struct class isn't a Struct {`class BadD; def _dump(l); 5; end; end; Marshal.dump(BadD.new)`, "_dump() must return String"}, {`Marshal.dump(Class.new.new)`, "anonymous class"}, + {`Marshal.dump(5, Object.new)`, "IO needed"}, // non-writable second arg is not a valid IO } for _, c := range errs { if err := runErr(t, c.src); err == nil || !strings.Contains(err.Error(), c.want) {