From ecdf9f1250433fc2a9524ad8d7563737927f2d96 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 6 Feb 2022 00:47:01 +0900 Subject: [PATCH] [Fix #10401] Fix a false positive for `Style/HashSyntax` Fixes #10401. This PR fixes a false positive for `Style/HashSyntax` when local variable hash key and hash value are the same. --- .../fix_a_false_positive_for_style_hash_syntax.md | 1 + lib/rubocop/cop/mixin/hash_shorthand_syntax.rb | 2 +- spec/rubocop/cop/style/hash_syntax_spec.rb | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_a_false_positive_for_style_hash_syntax.md diff --git a/changelog/fix_a_false_positive_for_style_hash_syntax.md b/changelog/fix_a_false_positive_for_style_hash_syntax.md new file mode 100644 index 00000000000..9ae3a240c8e --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_hash_syntax.md @@ -0,0 +1 @@ +* [#10401](https://github.com/rubocop/rubocop/issues/10401): Fix a false positive for `Style/HashSyntax` when local variable hash key and hash value are the same. ([@koic][]) diff --git a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb index 52505001715..1030d6e8488 100644 --- a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb +++ b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb @@ -41,7 +41,7 @@ def enforced_shorthand_syntax end def require_hash_value?(hash_key_source, node) - return true if require_hash_value_for_around_hash_literal?(node) + return true if !node.key.sym_type? || require_hash_value_for_around_hash_literal?(node) hash_value = node.value return true unless hash_value.send_type? || hash_value.lvar_type? diff --git a/spec/rubocop/cop/style/hash_syntax_spec.rb b/spec/rubocop/cop/style/hash_syntax_spec.rb index b05ecf94fa7..95e2fd9ad00 100644 --- a/spec/rubocop/cop/style/hash_syntax_spec.rb +++ b/spec/rubocop/cop/style/hash_syntax_spec.rb @@ -959,6 +959,19 @@ def do_something RUBY end + it 'does not register an offense when method call hash key and hash value are the same' do + expect_no_offenses(<<~RUBY) + {foo => foo} + RUBY + end + + it 'does not register an offense when lvar hash key and hash value are the same' do + expect_no_offenses(<<~RUBY) + foo = 42 + {foo => foo} + RUBY + end + it 'does not register an offense when without parentheses call expr follows' do # Prevent syntax errors shown in the URL: https://bugs.ruby-lang.org/issues/18396 expect_no_offenses(<<~RUBY)