Skip to content

Commit

Permalink
Fix an error when using regexp with non-encoding option
Browse files Browse the repository at this point in the history
This PR fixes the following error when using regexp with non-encoding option.

```console
% cat /tmp/example.rb
/\x82/n =~ 'a'

% rubocop -d /tmp/example.rb
(snip)

For /tmp: An error occurred while VariableForce cop was inspecting /tmp/example.rb.
invalid multibyte escape: /\x82/
/Users/koic/.rbenv/versions/3.1.0/lib/ruby/gems/3.1.0/gems/rubocop-1.25.1/lib/rubocop/cop/variable_force.rb:193:in
`initialize'
/Users/koic/.rbenv/versions/3.1.0/lib/ruby/gems/3.1.0/gems/rubocop-1.25.1/lib/rubocop/cop/variable_force.rb:193:in `new'
```

This error is due to `VariableForce#regexp_captured_names` not processing the regexp option.
This PR uses `RegexpNode#to_regexp` to prevent the regexp option from being cut.

In addition, the test code replaces the Parser gem (plain) AST with `ProcessedSource#ast`
so that it can call `RegexpNode#to_regexp` defined in the RuboCop AST.
  • Loading branch information
koic committed Feb 22, 2022
1 parent ec581bb commit eaf40f8
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
@@ -0,0 +1 @@
* [#10432](https://github.com/rubocop/rubocop/pull/10432): Fix an error when using regexp with non-encoding option. ([@koic][])
6 changes: 1 addition & 5 deletions lib/rubocop/cop/variable_force.rb
Expand Up @@ -186,11 +186,7 @@ def process_regexp_named_captures(node)
end

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

regexp = Regexp.new(regexp_string) # FIXME: Need to be handle `Regexp.new(/\x82/n)`.
regexp = node.to_regexp

regexp.named_captures.keys
end
Expand Down
24 changes: 16 additions & 8 deletions spec/rubocop/cop/variable_force_spec.rb
Expand Up @@ -21,7 +21,17 @@
end

context 'when processing an empty regex' do
let(:node) { s(:match_with_lvasgn, s(:regexp, s(:regopt)), s(:str)) }
let(:node) { parse_source('// =~ ""').ast }

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

# FIXME: Remove `broken_on: jruby` when JRuby incompatible is resolved:
# https://github.com/jruby/jruby/issues/7113
context 'when processing a regex with regopt', broken_on: :jruby do
let(:node) { parse_source('/\x82/n =~ "a"').ast }

it 'does not raise an error' do
expect { force.process_node(node) }.not_to raise_error
Expand All @@ -30,13 +40,11 @@

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))
parse_source(<<~REGEXP).ast
/(
pattern
)/ =~ string
REGEXP
end

it 'does not raise an error' do
Expand Down

0 comments on commit eaf40f8

Please sign in to comment.