Skip to content

Commit

Permalink
Use RegexpNode#each_capture
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre authored and mergify[bot] committed Aug 26, 2020
1 parent 7efae1c commit b5f5b5e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 54 deletions.
37 changes: 2 additions & 35 deletions lib/rubocop/cop/lint/mixed_regexp_capture_types.rb
Expand Up @@ -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
Expand Down
28 changes: 9 additions & 19 deletions lib/rubocop/cop/lint/out_of_range_regexp_ref.rb
Expand Up @@ -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
Expand Down

0 comments on commit b5f5b5e

Please sign in to comment.