Skip to content
Open
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
7 changes: 7 additions & 0 deletions lib/rubocop/cop/type_toolkit/prefer_not_nil.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def requires_parentheses?(argument)
return false if argument.begin_type?

if argument.is_a?(RuboCop::AST::SendNode)
return bracket_call_requires_parentheses?(argument) if argument.method?(:[])
return true if argument.operator_method?
return true if argument.arguments? && !argument.parenthesized_call?
end
Expand All @@ -90,6 +91,12 @@ def requires_parentheses?(argument)

KEYWORD_EXPRESSION_TYPES.include?(argument.type)
end

# `foo[bar]` and `foo.[](bar)` can be chained directly, but command-style `foo.[] bar` cannot.
#: (RuboCop::AST::SendNode) -> bool
def bracket_call_requires_parentheses?(argument)
argument.dot? && !argument.parenthesized_call?
end
end
end
end
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/type_toolkit/prefer_not_nil_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,23 @@ def explicit_super
RUBY
end

it "parenthesizes bracket method calls only when required" do
assert_offense(<<~RUBY)
bracketed = T.must(foo[bar]).foo
^^^^^^^^^^^^^^^^ #{MSG}
explicit = T.must(foo.[](bar)).foo
^^^^^^^^^^^^^^^^^^^ #{MSG}
command = T.must(foo.[] bar).foo
^^^^^^^^^^^^^^^^^^ #{MSG}
RUBY

assert_correction(<<~RUBY)
bracketed = foo[bar].not_nil!.foo
explicit = foo.[](bar).not_nil!.foo
command = (foo.[] bar).not_nil!.foo
RUBY
end

it "preserves comments in multiline calls" do
assert_offense(<<~RUBY)
value = T.must(
Expand Down
Loading