Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not rely on return type for attr_writer RBS signatures #368

Merged
merged 1 commit into from
Oct 3, 2024
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
17 changes: 14 additions & 3 deletions lib/rbi/rbs_printer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ def visit_attr(node)
print(" #{name}")
first_sig, *_rest = node.sigs # discard remaining signatures
if first_sig
type = parse_type(first_sig.return_type)
print(": #{type.rbs_string}")
print(": ")
print_attr_sig(node, first_sig)
else
print(": untyped")
end
Expand All @@ -273,7 +273,18 @@ def visit_attr(node)

sig { params(node: RBI::Attr, sig: Sig).void }
def print_attr_sig(node, sig)
type = parse_type(sig.return_type)
type = case node
when AttrAccessor, AttrReader
parse_type(sig.return_type)
else
first_arg = sig.params.first
if first_arg
parse_type(first_arg.type)
else
Type.untyped
end
end

print(type.rbs_string)
end

Expand Down
17 changes: 15 additions & 2 deletions test/rbi/rbs_printer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -230,15 +230,28 @@ def test_print_attributes_with_signatures
attr_accessor :foo

sig { returns(String) }
attr_accessor :bar
sig { returns(Integer) }
attr_reader :bar

sig { params(baz: String).returns(String) }
attr_writer :baz

sig { params(qux: String).void }
attr_writer :qux

sig { returns(Integer) }
attr_writer :quux
RBI

# With RBS, attributes can only have one and only one return type
# if we have multiple signatures we just use the return type of the first one
# and ignore the rest
assert_equal(<<~RBI, rbi.rbs_string)
attr_accessor foo: Integer
attr_accessor bar: String
attr_reader bar: String
attr_writer baz: String
attr_writer qux: String
attr_writer quux: untyped
RBI
end

Expand Down
Loading