Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jez committed Jan 9, 2024
1 parent d77ee4f commit 5b01a53
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/rubocop/cop/sorbet/signatures/void_checked_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ class VoidCheckedTests < ::RuboCop::Cop::Base

# @!method checked_tests(node)
def_node_search(:checked_tests, <<~PATTERN)
(send _ :checked (sym :tests))
({csend send} _ :checked (sym :tests))
PATTERN

MESSAGE =
"Returning `.void` from a sig marked `.checked(:tests)` means that the" \
"method will return a different value in non-test environments (possibly" \
"with different truthiness). Either use `.returns(T.anything).checked(:tests)`" \
"Returning `.void` from a sig marked `.checked(:tests)` means that the " \
"method will return a different value in non-test environments (possibly " \
"with different truthiness). Either use `.returns(T.anything).checked(:tests)` " \
"to keep checking in tests, or `.void.checked(:never)` to leave it untouched."
private_constant(:MESSAGE)

Expand All @@ -50,15 +50,26 @@ class VoidCheckedTests < ::RuboCop::Cop::Base

if node.method?(:void)
node
elsif (recv = node.receiver)
top_level_void(recv)
else
top_level_void(node.receiver)
nil
end
end

def on_signature(node)
checked_send = checked_tests(node).first
return unless checked_send

if (parent = node.parent) && (sibling_index = node.sibling_index)
later_siblings = parent.children[(sibling_index + 1)..]
if (def_node = later_siblings.find { |sibling| sibling.is_a?(RuboCop::AST::DefNode) })
# Sorbet requires that `initialize` methods return `.void`
# (A stylistic convention which happens to be enforced by Sorbet)
return if def_node.method_name == :initialize
end
end

void_send = top_level_void(node.body)

return unless void_send
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/sorbet/signatures/void_checked_tests_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,22 @@ def foo(x); end
def foo(&blk); end
RUBY
end

it("allows .void in initialize methods") do
expect_no_offenses(<<~RUBY)
sig { void.checked(:tests) }
def initialize; end
RUBY
end

it("handles weird nodes between sig and def") do
# Happened in real test case in wild, where an initial version of this
# cop raised an uncaught exception.
expect_no_offenses(<<~RUBY)
sig { void.checked(:tests) }
X = 1
def initialize; end
RUBY
end
end
end

0 comments on commit 5b01a53

Please sign in to comment.