Skip to content

Commit

Permalink
[Fix #7655] Fix an error when processing a line break regexp
Browse files Browse the repository at this point in the history
Fixes #7655.

This PR fixes the following error when processing a regexp with a line
break at the start of capture parenthesis.

```console
% cat examle.rb
/(
  pattern
)/ =~ string

% bundle exec rubocop -d
(snip)

An error occurred while VariableForce cop was inspecting
/Users/koic/src/github.com/koic/rubocop-issues/7655/examle.rb.
end pattern with unmatched parenthesis: /(
/
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:194:in
`initialize'
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:194:in
`new'
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:194:in
`regexp_captured_names'
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:174:in
`process_regexp_named_captures'
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:86:in
`process_node'
/Users/koic/src/github.com/rubocop-hq/rubocop/lib/rubocop/cop/variable_force.rb:80:in `investigate'
```
  • Loading branch information
koic authored and bbatsov committed Jan 25, 2020
1 parent c675fa9 commit d0ccb1e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -6,6 +6,7 @@

* [#7639](https://github.com/rubocop-hq/rubocop/pull/7639): Fix logical operator edge case in `omit_parentheses` style of `Style/MethodCallWithArgsParentheses`. ([@gsamokovarov][])
* [#7661](https://github.com/rubocop-hq/rubocop/pull/7661): Fix to return correct info from multi-line regexp. ([@Tietew][])
* [#7655](https://github.com/rubocop-hq/rubocop/issues/7655): Fix an error when processing a regexp with a line break at the start of capture parenthesis. ([@koic][])

### Changes

Expand Down
5 changes: 4 additions & 1 deletion lib/rubocop/cop/variable_force.rb
Expand Up @@ -190,7 +190,10 @@ def process_regexp_named_captures(node)
end

def regexp_captured_names(node)
regexp_string = node.children[0].children[0] || ''
regexp_string = node.children.select(&:str_type?).map do |child|
child.children.first
end.join || ''

regexp = Regexp.new(regexp_string)

regexp.named_captures.keys
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/variable_force_spec.rb
Expand Up @@ -29,5 +29,22 @@
expect { force.process_node(node) }.not_to raise_error
end
end

context 'when processing a regexp with a line break at ' \
'the start of capture parenthesis' do
let(:node) do
s(:match_with_lvasgn,
s(:regexp,
s(:str, "(\n"),
s(:str, " pattern\n"),
s(:str, ')'),
s(:regopt)),
s(:send, nil?, :string))
end

it 'does not raise an error' do
expect { force.process_node(node) }.not_to raise_error
end
end
end
end

0 comments on commit d0ccb1e

Please sign in to comment.