From 9ceb446f41c47e28201d9b601fd2ff572d20c1cb Mon Sep 17 00:00:00 2001 From: fatkodima Date: Wed, 28 Oct 2020 03:11:51 +0200 Subject: [PATCH] Support arguments forwarding in `Lint/ToEnumArguments` cop (#8961) --- lib/rubocop/cop/lint/to_enum_arguments.rb | 3 ++- lib/rubocop/rspec/shared_contexts.rb | 4 ++++ .../cop/lint/to_enum_arguments_spec.rb | 23 ++++++++++++++++--- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/rubocop/cop/lint/to_enum_arguments.rb b/lib/rubocop/cop/lint/to_enum_arguments.rb index 4fc8df8a7358..fd6135cfb4af 100644 --- a/lib/rubocop/cop/lint/to_enum_arguments.rb +++ b/lib/rubocop/cop/lint/to_enum_arguments.rb @@ -44,7 +44,6 @@ class ToEnumArguments < Base (pair (sym %1) (lvar %1)) PATTERN - # TODO: add support for argument forwarding (`...`) when ruby 3.0 is released def on_send(node) def_node = node.each_ancestor(:def, :defs).first return unless def_node @@ -85,6 +84,8 @@ def argument_match?(send_arg, def_arg) send_arg.pairs.any? { |pair| passing_keyword_arg?(pair, def_arg_name) } when :kwrestarg send_arg.each_child_node(:kwsplat).any? { |child| child.source == def_arg.source } + when :forward_arg + send_arg.forwarded_args_type? end end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity diff --git a/lib/rubocop/rspec/shared_contexts.rb b/lib/rubocop/rspec/shared_contexts.rb index e7367814c473..1e250a01e8a7 100644 --- a/lib/rubocop/rspec/shared_contexts.rb +++ b/lib/rubocop/rspec/shared_contexts.rb @@ -138,3 +138,7 @@ def source_range(range, buffer: source_buffer) RSpec.shared_context 'ruby 2.7', :ruby27 do let(:ruby_version) { 2.7 } end + +RSpec.shared_context 'ruby 3.0', :ruby30 do + let(:ruby_version) { 3.0 } +end diff --git a/spec/rubocop/cop/lint/to_enum_arguments_spec.rb b/spec/rubocop/cop/lint/to_enum_arguments_spec.rb index 39a3ac0b5cc8..adc452270662 100644 --- a/spec/rubocop/cop/lint/to_enum_arguments_spec.rb +++ b/spec/rubocop/cop/lint/to_enum_arguments_spec.rb @@ -1,8 +1,6 @@ # frozen_string_literal: true -RSpec.describe RuboCop::Cop::Lint::ToEnumArguments do - subject(:cop) { described_class.new } - +RSpec.describe RuboCop::Cop::Lint::ToEnumArguments, :config do it 'registers an offense when required arg is missing' do expect_offense(<<~RUBY) def m(x) @@ -131,4 +129,23 @@ def m(x, y = 1, *args, required:, optional: true, **kwargs, &block) end RUBY end + + context 'arguments forwarding', :ruby30 do + it 'registers an offense when enumerator is created with non matching arguments' do + expect_offense(<<~RUBY) + def m(...) + return to_enum(:m, x, ...) unless block_given? + ^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. + end + RUBY + end + + it 'does not register an offense when enumerator is created with the correct arguments' do + expect_no_offenses(<<~RUBY) + def m(...) + return to_enum(:m, ...) unless block_given? + end + RUBY + end + end end