diff --git a/internal/vm/data.go b/internal/vm/data.go index 2932ba2a..3deaae6c 100644 --- a/internal/vm/data.go +++ b/internal/vm/data.go @@ -1,11 +1,22 @@ package vm import ( + "fmt" + "reflect" "strings" "github.com/go-embedded-ruby/ruby/internal/object" ) +// anonClassRepr renders an anonymous Data subclass the way MRI does inside a +// recursive Data #inspect sentinel — "#" with the class's identity +// address — so a self-referential anonymous Data prints "#:...>" +// (matching MRI's rb_class_name fallback). It is only ever called for a Data +// class, which is always a Class (never a module). +func anonClassRepr(c *RClass) string { + return fmt.Sprintf("#", reflect.ValueOf(c).Pointer()) +} + // dataDef records the member layout of a Data subclass minted by Data.define. // Unlike structDef there is no keyword-init tri-state: a Data class always // accepts both positional and keyword construction. It is stored on the RClass @@ -413,7 +424,7 @@ func dataToHPair(vm *VM, res object.Value) (object.Value, object.Value) { } } if !ok { - raise("TypeError", "wrong element type %s (expected array)", classNameOf(res)) + raise("TypeError", "wrong element type %s (expected array)", vm.classOf(res).name) } } if len(arr.Elems) != 2 { @@ -430,15 +441,15 @@ func (vm *VM) dataInspect(o *RObject) string { names := dataDefOf(o.class).names if !object.ReprEnter(o) { nm := o.class.name - if nm == "" { - nm = o.class.ToS() // anonymous: # + if !namedThroughNesting(o.class) { + nm = anonClassRepr(o.class) // anonymous / non-permanent path: # } return "#" } defer object.ReprLeave(o) var b strings.Builder b.WriteString("# 0 { + if h, ok := a[0].(*object.Hash); ok && structHashAllMembers(h, names) { + for i, nm := range names { + if v, present := h.Get(object.Symbol(nm)); present { + o.structVals[i] = v + } else { + o.structVals[i] = object.NilV + } + } + return object.NilV + } + } if len(a) > len(names) { raise("ArgumentError", "struct size differs") } @@ -209,6 +227,9 @@ func setupStruct(vm *VM) { } return object.NilV }) + // MRI keeps Struct#initialize private (Car.private_instance_methods includes + // :initialize). + vm.setInstanceVisibility(cStruct, "initialize", visPrivate) cStruct.define("members", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return structMemberSyms(structDefOf(self.(*RObject).class).names) @@ -231,7 +252,11 @@ func setupStruct(vm *VM) { names := structDefOf(self.(*RObject).class).names vals := structValues(self) for i, nm := range names { - vm.callBlock(blk, []object.Value{object.Symbol(nm), vals[i]}) + // MRI yields ONE two-element Array per pair (like Hash#each): a `|k, v|` + // block auto-splats it, while a single-parameter block (or an Enumerator + // consumer, e.g. each_pair.map { |var| var }) receives the [name, value] + // Array whole. + vm.callBlock(blk, []object.Value{object.NewArrayFromSlice([]object.Value{object.Symbol(nm), vals[i]})}) } return self }) @@ -293,14 +318,10 @@ func setupStruct(vm *VM) { for i, nm := range names { if blk != nil { res := vm.callBlock(blk, []object.Value{object.Symbol(nm), vals[i]}) - pair, ok := res.(*object.Array) - if !ok { - raise("TypeError", "wrong element type %s (expected array)", classNameOf(res)) - } - if len(pair.Elems) != 2 { - raise("ArgumentError", "element has wrong array length (expected 2, was %d)", len(pair.Elems)) - } - h.Set(pair.Elems[0], pair.Elems[1]) + // MRI coerces the returned pair with #to_ary (never #to_a); a non-Array, + // non-to_ary object is a TypeError naming the object's real class. + key, val := dataToHPair(vm, res) + h.Set(key, val) } else { h.Set(object.Symbol(nm), vals[i]) } @@ -323,7 +344,7 @@ func setupStruct(vm *VM) { } keys, ok := a[0].(*object.Array) if !ok { - raise("TypeError", "wrong argument type %s (expected Array)", classNameOf(a[0])) + raise("TypeError", "wrong argument type %s (expected Array or nil)", classNameOf(a[0])) } if len(keys.Elems) > len(names) { return h // more keys than members: MRI returns {} without inspecting them @@ -373,9 +394,19 @@ func setupStruct(vm *VM) { } v = vals[idx] case object.Symbol: - v = vals[structNameIndex(string(k), names)] + // Unlike #[], #dig with a name that is not a member returns nil (treating + // the missing member as nil) rather than raising NameError. + if i, found := structFind(string(k), names); found { + v = vals[i] + } else { + v = object.NilV + } case *object.String: - v = vals[structNameIndex(k.Str(), names)] + if i, found := structFind(k.Str(), names); found { + v = vals[i] + } else { + v = object.NilV + } default: raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(a[0])) } @@ -413,7 +444,7 @@ func setupStruct(vm *VM) { vals := o.structVals var b strings.Builder b.WriteString("# 1}).a`, "{0 => 1}\n"}, + {`S = Struct.new(:a); p S.new({}).a`, "{}\n"}, + + // #to_h block coerces the returned pair with #to_ary (never #to_a). + {`S = Struct.new(:a); class Ary1; def to_ary; [:k, 9]; end; end; p S.new(1).to_h { |k, v| Ary1.new }`, "{k: 9}\n"}, + + // #to_s / #inspect: name shown only for a permanent classpath — omitted for + // an anonymous class or one nested in an anonymous namespace. + {`puts Struct.new(:a).new("").to_s`, "#\n"}, + {`S = Struct.new(:a); puts S.new("x").to_s`, "#\n"}, + {`module NS1; B = Struct.new(:a); end; puts NS1::B.new("z").to_s`, "#\n"}, + {`m = Module.new; m.module_eval "Foo = Struct.new(:a)"; puts m::Foo.new("").to_s`, "#\n"}, + + // Recursive struct hashes collapse to a class-only value (so #eql? recursive + // structs hash alike); non-recursive nested structs still fold member hashes. + {`R = Struct.new(:a, :b); x = R.new(1, 2); y = R.new(1, 2); x[:a] = x; y[:a] = x; p x.hash == y.hash`, "true\n"}, + {`R = Struct.new(:a); o1 = R.new(R.new(1)); o2 = R.new(R.new(2)); p o1.hash == o2.hash`, "false\n"}, + + // Data#to_s naming and recursive sentinel. + {`M = Data.define(:x); puts M.new(x: 1).to_s`, "#\n"}, + {`M = Data.define(:x); k = Class.new(M); puts k.new(x: 1).to_s`, "#\n"}, + {`M = Data.define(:x); a = M.allocate; a.send(:initialize, x: a); puts a.to_s`, "#>\n"}, + // Recursive anonymous Data renders the member class as #. + {`M = Data.define(:x); k = Class.new(M); b = k.allocate; b.send(:initialize, x: b); p !!(b.to_s =~ /\A#:\.\.\.>>\z/)`, "true\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got %q\nwant %q", c.src, got, c.want) + } + } +} + +// TestStructDataResidualErrors covers the TypeError paths whose message wording or +// class-naming this change corrected. +func TestStructDataResidualErrors(t *testing.T) { + cases := []struct{ src, want string }{ + // deconstruct_keys of a non-Array, non-nil argument names "Array or nil". + {`Struct.new(:a).new(1).deconstruct_keys("x")`, "wrong argument type String (expected Array or nil)"}, + // A #to_int that returns a non-Integer names the key's real class. + {`class KK2; def to_int; "x"; end; end; Struct.new(:a, :b).new(1, 2).deconstruct_keys([KK2.new])`, "can't convert KK2 into Integer"}, + // #to_h block pair that is neither Array nor #to_ary-able names the real class. + {`Struct.new(:a).new(1).to_h { |k, v| Object.new }`, "wrong element type Object (expected array)"}, + {`Data.define(:a).new(a: 1).to_h { |k, v| Object.new }`, "wrong element type Object (expected array)"}, + } + for _, c := range cases { + err := runErr(t, c.src) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("src=%q: got err=%v, want containing %q", c.src, err, c.want) + } + } +}