From b5f5b5e0f69da9f96128111563941e42a3dda0b4 Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Mon, 10 Aug 2020 12:34:55 -0400 Subject: [PATCH] Use `RegexpNode#each_capture` --- .../cop/lint/mixed_regexp_capture_types.rb | 37 +------------------ .../cop/lint/out_of_range_regexp_ref.rb | 28 +++++--------- 2 files changed, 11 insertions(+), 54 deletions(-) diff --git a/lib/rubocop/cop/lint/mixed_regexp_capture_types.rb b/lib/rubocop/cop/lint/mixed_regexp_capture_types.rb index 2ea3f47bb50..d645b1a7c65 100644 --- a/lib/rubocop/cop/lint/mixed_regexp_capture_types.rb +++ b/lib/rubocop/cop/lint/mixed_regexp_capture_types.rb @@ -25,44 +25,11 @@ class MixedRegexpCaptureTypes < Base 'in a Regexp literal.' def on_regexp(node) - return if contain_non_literal?(node) - - begin - tree = Regexp::Parser.parse(node.content) - # Returns if a regular expression that cannot be processed by regexp_parser gem. - # https://github.com/rubocop-hq/rubocop/issues/8083 - rescue Regexp::Scanner::ScannerError - return - end - - return unless named_capture?(tree) - return unless numbered_capture?(tree) + return if node.each_capture(named: false).none? + return if node.each_capture(named: true).none? add_offense(node) end - - private - - def contain_non_literal?(node) - if node.respond_to?(:type) && (node.variable? || node.send_type? || node.const_type?) - return true - end - return false unless node.respond_to?(:children) - - node.children.any? { |child| contain_non_literal?(child) } - end - - def named_capture?(tree) - tree.each_expression.any? do |e| - e.instance_of?(Regexp::Expression::Group::Capture) - end - end - - def numbered_capture?(tree) - tree.each_expression.any? do |e| - e.instance_of?(Regexp::Expression::Group::Named) - end - end end end end diff --git a/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb b/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb index a5f87ae2c0c..3843da78f2b 100644 --- a/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb +++ b/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb @@ -64,25 +64,15 @@ def on_nth_ref(node) private - def check_regexp(regexp) - return if contain_non_literal?(regexp) - - tree = Regexp::Parser.parse(regexp.content) - @valid_ref = regexp_captures(tree) - end - - def contain_non_literal?(node) - node.children.size != 2 || !node.children.first.str_type? - end - - def regexp_captures(tree) - named_capture = numbered_capture = 0 - tree.each_expression do |e| - if e.type?(:group) - e.respond_to?(:name) ? named_capture += 1 : numbered_capture += 1 - end - end - named_capture.positive? ? named_capture : numbered_capture + def check_regexp(node) + return if node.interpolation? + + named_capture = node.each_capture(named: true).count + @valid_ref = if named_capture.positive? + named_capture + else + node.each_capture(named: false).count + end end end end