From 8d91e98b56293635a0d2fb1ad024f7f9424374e9 Mon Sep 17 00:00:00 2001 From: Alex Ghiculescu Date: Thu, 1 Oct 2020 14:34:35 -0500 Subject: [PATCH] Fix crash in Style/ExplicitBlockArgument --- CHANGELOG.md | 2 ++ lib/rubocop/cop/style/explicit_block_argument.rb | 8 ++++++-- spec/rubocop/cop/style/explicit_block_argument_spec.rb | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46466c7c6d7..54a7ccfe000 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#8809](https://github.com/rubocop-hq/rubocop/pull/8809): Fix multiple offense detection for `Style/For`. ([@pbernays][]) * [#8801](https://github.com/rubocop-hq/rubocop/issues/8801): Fix `Layout/SpaceAroundEqualsInParameterDefault` only registered once in a line. ([@rdunlop][]) * [#8514](https://github.com/rubocop-hq/rubocop/issues/8514): Correct multiple `Style/MethodDefParentheses` per file. ([@rdunlop][]) +* [#8825](https://github.com/rubocop-hq/rubocop/issues/8825): Fix crash in `Style/ExplicitBlockArgument` when code is called outside of a method. ([@ghiculescu][]) ### Changes @@ -4942,3 +4943,4 @@ [@tleish]: https://github.com/tleish [@pbernays]: https://github.com/pbernays [@rdunlop]: https://github.com/rdunlop +[@ghiculescu]: https://github.com/ghiculescu diff --git a/lib/rubocop/cop/style/explicit_block_argument.rb b/lib/rubocop/cop/style/explicit_block_argument.rb index 0300a675d18..426cbb9f694 100644 --- a/lib/rubocop/cop/style/explicit_block_argument.rb +++ b/lib/rubocop/cop/style/explicit_block_argument.rb @@ -57,12 +57,16 @@ def on_yield(node) yielding_block?(block_node) do |send_node, block_args, yield_args| return unless yielding_arguments?(block_args, yield_args) + def_node = block_node.each_ancestor(:def, :defs).first + # if `yield` is being called outside of a method context, ignore + # this is not a valid ruby pattern, but can happen in haml or erb, + # so this can cause crashes in haml_lint + return unless def_node + add_offense(block_node) do |corrector| corrector.remove(block_body_range(block_node, send_node)) add_block_argument(send_node, corrector) - - def_node = block_node.each_ancestor(:def, :defs).first add_block_argument(def_node, corrector) if @def_nodes.add?(def_node) end end diff --git a/spec/rubocop/cop/style/explicit_block_argument_spec.rb b/spec/rubocop/cop/style/explicit_block_argument_spec.rb index be6d3f1357e..a6f55c5f845 100644 --- a/spec/rubocop/cop/style/explicit_block_argument_spec.rb +++ b/spec/rubocop/cop/style/explicit_block_argument_spec.rb @@ -154,4 +154,12 @@ def m end RUBY end + + it 'does not register an offense when code is called outside of a method' do + expect_no_offenses(<<~RUBY) + render("partial") do + yield + end + RUBY + end end