Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions ext/psych/psych_to_ruby.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ static VALUE path2class(VALUE self, VALUE path)
return rb_path_to_class(path);
}

static VALUE init_struct(VALUE self, VALUE data, VALUE attrs)
{
VALUE args = rb_ary_new2(1);
rb_ary_push(args, attrs);
rb_struct_initialize(data, args);
Comment on lines +29 to +31
Copy link
Member

@eregon eregon Nov 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is very brittle, and probably only works on CRuby due to this bug or similar: https://bugs.ruby-lang.org/issues/18632
i.e. this is passing [{ ... }] to rb_struct_initialize(), i.e. a positional Hash, not keyword arguments.
Normal behavior would be to treat that Hash as the value of the first member, and don't assign other members. But it seems to accidentally work.

It would be a lot safer to pass the values as a simple Array instead, and query the members from the class by calling struct_or_data_class.members.
From truffleruby/truffleruby#4012 (comment)

Copy link
Member

@eregon eregon Nov 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to repro this in new C API specs but I actually can't, they fail on CRuby too:

      it "accepts a single Hash in an Array" do
        @klass = @s.rb_data_define(nil, "a", "b", "c")
        data = @klass.allocate
        @s.rb_struct_initialize(data, [{ a: 1, b: 2, c: 3 }]).should == nil
        data.a.should == 1
        data.b.should == 2
        data.c.should == 3
      end

gives

ruby 3.3.5 (2024-09-03 revision ef084cc8f4) [x86_64-linux]
2)
C-API Data function rb_struct_initialize accepts a single Hash in an Array FAILED
Expected {:a=>1, :b=>2, :c=>3} == 1
to be truthy but was false

From experimenting by tweaking those specs it only works when using keyword_init: true explicitly (like Struct.new(:a, :b, :c, keyword_init: true)) , and just never works for Data.

Maybe it "works" due to init_struct getting kwargs and accidentally propagating that flag to other C calls or so (just a guess).
Looks like it in https://github.com/ruby/ruby/blob/48c7f349f68846e10d60ae77ad299a38ee014479/struct.c#L766

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In marshal.c https://github.com/ruby/ruby/blob/48c7f349f68846e10d60ae77ad299a38ee014479/marshal.c#L2150-L2176
CRuby uses a Hash only if rb_struct_s_keyword_init(), in all other cases it uses an Array of values.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since for this use case in Psych we only care about Data, not Struct, we should pass an Array of values (same as what Marshal does for Data, as far as I can tell rb_struct_s_keyword_init() is always false for Data classes).
@nevans Would you have time to fix this?

Copy link
Member

@eregon eregon Nov 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One last thought is it would really be good to ask for rb_data_initialize() upstream at https://bugs.ruby-lang.org/, because reusing rb_struct_initialize() for Data feels like a pretty huge hack, given it doesn't run any function related to Data, only rb_struct_initialize_m() which is not meant to be used with Data.
Of course that can't be used now, but would enable a cleaner way in the future.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix in #749


return data;
}

void Init_psych_to_ruby(void)
{
VALUE psych = rb_define_module("Psych");
Expand All @@ -33,6 +42,7 @@ void Init_psych_to_ruby(void)
VALUE visitor = rb_define_class_under(visitors, "Visitor", rb_cObject);
cPsychVisitorsToRuby = rb_define_class_under(visitors, "ToRuby", visitor);

rb_define_private_method(cPsychVisitorsToRuby, "init_struct", init_struct, 2);
rb_define_private_method(cPsychVisitorsToRuby, "build_exception", build_exception, 2);
rb_define_private_method(class_loader, "path2class", path2class, 1);
}
1 change: 1 addition & 0 deletions lib/psych/class_loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module Psych
class ClassLoader # :nodoc:
BIG_DECIMAL = 'BigDecimal'
COMPLEX = 'Complex'
DATA = 'Data' unless RUBY_VERSION < "3.2"
DATE = 'Date'
DATE_TIME = 'DateTime'
EXCEPTION = 'Exception'
Expand Down
40 changes: 40 additions & 0 deletions lib/psych/visitors/to_ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,32 @@ def visit_Psych_Nodes_Mapping o
s
end

when /^!ruby\/data(-with-ivars)?(?::(.*))?$/
data = register(o, resolve_class($2).allocate) if $2
members = {}

if $1 # data-with-ivars
ivars = {}
o.children.each_slice(2) do |type, vars|
case accept(type)
when 'members'
revive_data_members(members, vars)
data ||= allocate_anon_data(o, members)
when 'ivars'
revive_hash(ivars, vars)
end
end
ivars.each do |ivar, v|
data.instance_variable_set ivar, v
end
else
revive_data_members(members, o)
end
data ||= allocate_anon_data(o, members)
init_struct(data, **members)
data.freeze
data

when /^!ruby\/object:?(.*)?$/
name = $1 || 'Object'

Expand Down Expand Up @@ -340,6 +366,20 @@ def register_empty object
list
end

def allocate_anon_data node, members
klass = class_loader.data.define(*members.keys)
register(node, klass.allocate)
end

def revive_data_members hash, o
o.children.each_slice(2) do |k,v|
name = accept(k)
value = accept(v)
hash[class_loader.symbolize(name)] = value
end
hash
end

def revive_hash hash, o, tagged= false
o.children.each_slice(2) { |k,v|
key = accept(k)
Expand Down
38 changes: 38 additions & 0 deletions lib/psych/visitors/yaml_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,44 @@ def visit_Object o

alias :visit_Delegator :visit_Object

def visit_Data o
ivars = o.instance_variables
if ivars.empty?
tag = ['!ruby/data', o.class.name].compact.join(':')
register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
o.members.each do |member|
@emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
accept o.send member
end
@emitter.end_mapping

else
tag = ['!ruby/data-with-ivars', o.class.name].compact.join(':')
node = @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK)
register(o, node)

# Dump the members
accept 'members'
@emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
o.members.each do |member|
@emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
accept o.send member
end
@emitter.end_mapping

# Dump the ivars
accept 'ivars'
@emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
ivars.each do |ivar|
accept ivar.to_s
accept o.instance_variable_get ivar
end
@emitter.end_mapping

@emitter.end_mapping
end
end

def visit_Struct o
tag = ['!ruby/struct', o.class.name].compact.join(':')

Expand Down
69 changes: 69 additions & 0 deletions test/psych/test_data.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# frozen_string_literal: true
require_relative 'helper'

class PsychDataWithIvar < Data.define(:foo)
attr_reader :bar
def initialize(**)
@bar = 'hello'
super
end
end unless RUBY_VERSION < "3.2"

module Psych
class TestData < TestCase
class SelfReferentialData < Data.define(:foo)
attr_accessor :ref
def initialize(foo:)
@ref = self
super
end
end unless RUBY_VERSION < "3.2"

def setup
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
end

# TODO: move to another test?
def test_dump_data
assert_equal <<~eoyml, Psych.dump(PsychDataWithIvar["bar"])
--- !ruby/data-with-ivars:PsychDataWithIvar
members:
foo: bar
ivars:
"@bar": hello
eoyml
end

def test_self_referential_data
circular = SelfReferentialData.new("foo")

loaded = Psych.unsafe_load(Psych.dump(circular))
assert_instance_of(SelfReferentialData, loaded.ref)

assert_equal(circular, loaded)
assert_same(loaded, loaded.ref)
end

def test_roundtrip
thing = PsychDataWithIvar.new("bar")
data = Psych.unsafe_load(Psych.dump(thing))

assert_equal "hello", data.bar
assert_equal "bar", data.foo
end

def test_load
obj = Psych.unsafe_load(<<~eoyml)
--- !ruby/data-with-ivars:PsychDataWithIvar
members:
foo: bar
ivars:
"@bar": hello
eoyml

assert_equal "hello", obj.bar
assert_equal "bar", obj.foo
end
end
end

5 changes: 5 additions & 0 deletions test/psych/test_object_references.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ def test_struct_has_references
assert_reference_trip Struct.new(:foo).new(1)
end

def test_data_has_references
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
assert_reference_trip Data.define(:foo).new(1)
end

def assert_reference_trip obj
yml = Psych.dump([obj, obj])
assert_match(/\*-?\d+/, yml)
Expand Down
32 changes: 32 additions & 0 deletions test/psych/test_safe_load.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,38 @@ def test_anon_struct
end
end

D = Data.define(:d) unless RUBY_VERSION < "3.2"

def test_data_depends_on_sym
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
assert_safe_cycle(D.new(nil), permitted_classes: [D, Symbol])
assert_raise(Psych::DisallowedClass) do
cycle D.new(nil), permitted_classes: [D]
end
end

def test_anon_data
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
assert Psych.safe_load(<<-eoyml, permitted_classes: [Data, Symbol])
--- !ruby/data
foo: bar
eoyml

assert_raise(Psych::DisallowedClass) do
Psych.safe_load(<<-eoyml, permitted_classes: [Data])
--- !ruby/data
foo: bar
eoyml
end

assert_raise(Psych::DisallowedClass) do
Psych.safe_load(<<-eoyml, permitted_classes: [Symbol])
--- !ruby/data
foo: bar
eoyml
end
end

def test_safe_load_default_fallback
assert_nil Psych.safe_load("")
end
Expand Down
18 changes: 18 additions & 0 deletions test/psych/test_serialize_subclasses.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,23 @@ def test_struct_subclass
so = StructSubclass.new('foo', [1,2,3])
assert_equal so, Psych.unsafe_load(Psych.dump(so))
end

class DataSubclass < Data.define(:foo)
def initialize(foo:)
@bar = "hello #{foo}"
super(foo: foo)
end

def == other
super(other) && @bar == other.instance_eval{ @bar }
end
end unless RUBY_VERSION < "3.2"

def test_data_subclass
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
so = DataSubclass.new('foo')
assert_equal so, Psych.unsafe_load(Psych.dump(so))
end

end
end
39 changes: 39 additions & 0 deletions test/psych/test_yaml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# [ruby-core:01946]
module Psych_Tests
StructTest = Struct::new( :c )
DataTest = Data.define( :c ) unless RUBY_VERSION < "3.2"
end

class Psych_Unit_Tests < Psych::TestCase
Expand Down Expand Up @@ -1071,6 +1072,44 @@ def test_ruby_struct

end

def test_ruby_data
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
Object.remove_const :MyBookData if Object.const_defined?(:MyBookData)
# Ruby Data value objects
book_class = Data.define(:author, :title, :year, :isbn)
Object.const_set(:MyBookData, book_class)
assert_to_yaml(
[ book_class.new( "Yukihiro Matsumoto", "Ruby in a Nutshell", 2002, "0-596-00214-9" ),
book_class.new( [ 'Dave Thomas', 'Andy Hunt' ], "The Pickaxe", 2002,
book_class.new( "This should be the ISBN", "but I have more data here", 2002, "None" )
)
], <<EOY
- !ruby/data:MyBookData
author: Yukihiro Matsumoto
title: Ruby in a Nutshell
year: 2002
isbn: 0-596-00214-9
- !ruby/data:MyBookData
author:
- Dave Thomas
- Andy Hunt
title: The Pickaxe
year: 2002
isbn: !ruby/data:MyBookData
author: This should be the ISBN
title: but I have more data here
year: 2002
isbn: None
EOY
)

assert_to_yaml( Psych_Tests::DataTest.new( 123 ), <<EOY )
--- !ruby/data:Psych_Tests::DataTest
c: 123
EOY

end

def test_ruby_rational
assert_to_yaml( Rational(1, 2), <<EOY )
--- !ruby/object:Rational
Expand Down
21 changes: 21 additions & 0 deletions test/psych/visitors/test_yaml_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,27 @@ def test_override_method
assert_equal s.method, obj.method
end

D = Data.define(:foo) unless RUBY_VERSION < "3.2"

def test_data
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
assert_cycle D.new('bar')
end

def test_data_anon
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
d = Data.define(:foo).new('bar')
obj = Psych.unsafe_load(Psych.dump(d))
assert_equal d.foo, obj.foo
end

def test_data_override_method
omit "Data requires ruby >= 3.2" if RUBY_VERSION < "3.2"
d = Data.define(:method).new('override')
obj = Psych.unsafe_load(Psych.dump(d))
assert_equal d.method, obj.method
end

def test_exception
ex = Exception.new 'foo'
loaded = Psych.unsafe_load(Psych.dump(ex))
Expand Down
Loading