Merge pull request #7928 from Homebrew/dependabot/bundler/Library/Homebrew/rubocop-performance-1.7.0

build(deps): bump rubocop-performance from 1.6.1 to 1.7.0 in /Library/Homebrew
This commit is contained in:
Mike McQuaid 2020-07-07 14:18:54 +01:00 committed by GitHub
commit 02eda2f7f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 856 additions and 104 deletions

View File

@ -91,8 +91,8 @@ GEM
unicode-display_width (>= 1.4.0, < 2.0)
rubocop-ast (0.1.0)
parser (>= 2.7.0.1)
rubocop-performance (1.6.1)
rubocop (>= 0.71.0)
rubocop-performance (1.7.0)
rubocop (>= 0.82.0)
rubocop-rspec (1.41.0)
rubocop (>= 0.68.1)
ruby-macho (2.2.0)

View File

@ -561,7 +561,7 @@ module Homebrew
return if !Utils.git_available? || !(coretap_path/".git").exist?
branch = coretap_path.git_branch
return if branch.nil? || branch =~ /master/
return if branch.blank? || branch.include?("master")
<<~EOS
#{CoreTap.instance.full_name} is not on the master branch.

View File

@ -191,7 +191,8 @@ module Homebrew
def check_xcode_license_approved
# If the user installs Xcode-only, they have to approve the
# license or no "xc*" tool will work.
return unless `/usr/bin/xcrun clang 2>&1` =~ /license/ && !$CHILD_STATUS.success?
return unless `/usr/bin/xcrun clang 2>&1`.include?("license")
return if $CHILD_STATUS.success?
<<~EOS
You have not agreed to the Xcode license.

View File

@ -268,7 +268,7 @@ module Language
t.stage { do_install Pathname.pwd }
else
t = t.lines.map(&:strip) if t.respond_to?(:lines) && t =~ /\n/
t = t.lines.map(&:strip) if t.respond_to?(:lines) && t.include?("\n")
do_install t
end
end

View File

@ -86,7 +86,7 @@ class JavaRequirement < Requirement
end
def exact_version?
@version && @version.to_s.chars.last != "+"
@version && @version.to_s[-1] != "+"
end
def fits_latest?

View File

@ -47,7 +47,7 @@ module RuboCop
# Check if command-line is wrongly used in formula's desc
if match = regex_match_group(desc, /(command ?line)/i)
c = match.to_s.chars.first
c = match.to_s[0]
problem "Description should use \"#{c}ommand-line\" instead of \"#{match}\""
end
@ -86,7 +86,7 @@ module RuboCop
correction = node.source
first_word = string_content(node).split.first
unless VALID_LOWERCASE_WORDS.include?(first_word)
first_char = first_word.to_s.chars.first
first_char = first_word.to_s[0]
correction.sub!(/^(['"]?)([a-z])/, "\\1#{first_char.upcase}") if first_char
end
correction.sub!(/^(['"]?)an?\s/i, "\\1")

View File

@ -37,7 +37,7 @@ module RuboCop
# https://wiki.freedesktop.org/project_name.
# "Software" is redirected to https://wiki.freedesktop.org/www/Software/project_name
when %r{^http://((?:www|nice|libopenraw|liboil|telepathy|xorg)\.)?freedesktop\.org/(?:wiki/)?}
if homepage =~ /Software/
if homepage.include?("Software")
problem "#{homepage} should be styled `https://wiki.freedesktop.org/www/Software/project_name`"
else
problem "#{homepage} should be styled `https://wiki.freedesktop.org/project_name`"

View File

@ -247,7 +247,7 @@ module RuboCop
# Don't use GitHub .zip files
zip_gh_pattern = %r{https://.*github.*/(archive|releases)/.*\.zip$}
audit_urls(urls, zip_gh_pattern) do |_, url|
next if url.match?(%r{releases/download})
next if url.include?("releases/download")
problem "Use GitHub tarballs rather than zipballs (url is #{url})."
end

View File

@ -73,8 +73,8 @@ describe RuboCop::Cop::FormulaAudit::Homepage do
RUBY
inspect_source(source)
if homepage.match?(%r{http://www\.freedesktop\.org})
if homepage.match?(/Software/)
if homepage.include?("http://www.freedesktop.org")
if homepage.include?("Software")
expected_offenses = [{ message: "#{homepage} should be styled " \
"`https://wiki.freedesktop.org/www/Software/project_name`",
severity: :convention,
@ -89,7 +89,7 @@ describe RuboCop::Cop::FormulaAudit::Homepage do
column: 2,
source: source }]
end
elsif homepage.match?(%r{https://code\.google\.com})
elsif homepage.include?("https://code.google.com")
expected_offenses = [{ message: "#{homepage} should end with a slash",
severity: :convention,
line: 2,

View File

@ -48,7 +48,7 @@ describe RuboCop::Cop::FormulaAudit::Patches do
EOS
inspect_source(source)
expected_offense = if patch_url.match?(%r{/raw\.github\.com/})
expected_offense = if patch_url.include?("/raw.github.com/")
[{ message:
<<~EOS.chomp,
GitHub/Gist patches should specify a revision:
@ -58,7 +58,7 @@ describe RuboCop::Cop::FormulaAudit::Patches do
line: 5,
column: 12,
source: source }]
elsif patch_url.match?(%r{macports/trunk})
elsif patch_url.include?("macports/trunk")
[{ message:
<<~EOS.chomp,
MacPorts patches should specify a revision instead of trunk:
@ -232,7 +232,7 @@ describe RuboCop::Cop::FormulaAudit::Patches do
RUBY
inspect_source(source)
expected_offense = if patch_url.match?(%r{/raw\.github\.com/})
expected_offense = if patch_url.include?("/raw.github.com/")
[{ message:
<<~EOS.chomp,
GitHub/Gist patches should specify a revision:
@ -242,7 +242,7 @@ describe RuboCop::Cop::FormulaAudit::Patches do
line: 5,
column: 16,
source: source }]
elsif patch_url.match?(%r{macports/trunk})
elsif patch_url.include?("macports/trunk")
[{ message:
<<~EOS.chomp,
MacPorts patches should specify a revision instead of trunk:

View File

@ -63,6 +63,6 @@ $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-ast-0.1.0/lib
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-progressbar-1.10.1/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unicode-display_width-1.7.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-0.87.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-performance-1.6.1/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-performance-1.7.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rspec-1.41.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-macho-2.2.0/lib"

View File

@ -1,77 +0,0 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop is used to identify usages of `count` on an
# `Array` and `Hash` and change them to `size`.
#
# @example
# # bad
# [1, 2, 3].count
#
# # bad
# {a: 1, b: 2, c: 3}.count
#
# # good
# [1, 2, 3].size
#
# # good
# {a: 1, b: 2, c: 3}.size
#
# # good
# [1, 2, 3].count { |e| e > 2 }
# TODO: Add advanced detection of variables that could
# have been assigned to an array or a hash.
class Size < Cop
MSG = 'Use `size` instead of `count`.'
def on_send(node)
return unless eligible_node?(node)
add_offense(node, location: :selector)
end
def autocorrect(node)
->(corrector) { corrector.replace(node.loc.selector, 'size') }
end
private
def eligible_node?(node)
return false unless node.method?(:count) && !node.arguments?
eligible_receiver?(node.receiver) && !allowed_parent?(node.parent)
end
def eligible_receiver?(node)
return false unless node
array?(node) || hash?(node)
end
def allowed_parent?(node)
node&.block_type?
end
def array?(node)
return true if node.array_type?
return false unless node.send_type?
_, constant = *node.receiver
constant == :Array || node.method?(:to_a)
end
def hash?(node)
return true if node.hash_type?
return false unless node.send_type?
_, constant = *node.receiver
constant == :Hash || node.method?(:to_h)
end
end
end
end
end

View File

@ -1,5 +1,16 @@
# This is the default configuration file.
Performance/AncestorsInclude:
Description: 'Use `A <= B` instead of `A.ancestors.include?(B)`.'
Reference: 'https://github.com/JuanitoFatas/fast-ruby#ancestorsinclude-vs--code'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/BigDecimalWithNumericArgument:
Description: 'Convert numeric argument to string before passing to BigDecimal.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/BindCall:
Description: 'Use `bind_call(obj, args, ...)` instead of `bind(obj).call(args, ...)`.'
Enabled: true
@ -131,6 +142,12 @@ Performance/InefficientHashSearch:
VersionAdded: '0.56'
Safe: false
Performance/IoReadlines:
Description: 'Use `IO.each_line` (`IO#each_line`) instead of `IO.readlines` (`IO#readlines`).'
Reference: 'https://docs.gitlab.com/ee/development/performance.html#reading-from-files-and-other-data-sources'
Enabled: false
VersionAdded: '1.7'
Performance/OpenStruct:
Description: 'Use `Struct` instead of `OpenStruct`.'
Enabled: false
@ -138,10 +155,11 @@ Performance/OpenStruct:
Safe: false
Performance/RangeInclude:
Description: 'Use `Range#cover?` instead of `Range#include?`.'
Description: 'Use `Range#cover?` instead of `Range#include?` (or `Range#member?`).'
Reference: 'https://github.com/JuanitoFatas/fast-ruby#cover-vs-include-code'
Enabled: true
VersionAdded: '0.36'
VersionChanged: '1.7'
Safe: false
Performance/RedundantBlockCall:
@ -165,6 +183,16 @@ Performance/RedundantMerge:
# Max number of key-value pairs to consider an offense
MaxKeyValuePairs: 2
Performance/RedundantSortBlock:
Description: 'Use `sort` instead of `sort { |a, b| a <=> b }`.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/RedundantStringChars:
Description: 'Checks for redundant `String#chars`.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/RegexpMatch:
Description: >-
Use `match?` instead of `Regexp#match`, `String#match`, `Symbol#match`,
@ -179,6 +207,11 @@ Performance/ReverseEach:
Enabled: true
VersionAdded: '0.30'
Performance/ReverseFirst:
Description: 'Use `last(n).reverse` instead of `reverse.first(n)`.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/Size:
Description: >-
Use `size` instead of `count` for counting
@ -187,6 +220,17 @@ Performance/Size:
Enabled: true
VersionAdded: '0.30'
Performance/SortReverse:
Description: 'Use `sort.reverse` instead of `sort { |a, b| b <=> a }`.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/Squeeze:
Description: "Use `squeeze('a')` instead of `gsub(/a+/, 'a')`."
Reference: 'https://github.com/JuanitoFatas/fast-ruby#remove-extra-spaces-or-other-contiguous-characters-code'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/StartWith:
Description: 'Use `start_with?` instead of a regex match anchored to the beginning of a string.'
Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringmatch-vs-stringstart_withstringend_with-code-start-code-end'
@ -200,6 +244,11 @@ Performance/StartWith:
VersionAdded: '0.36'
VersionChanged: '1.6'
Performance/StringInclude:
Description: 'Use `String#include?` instead of a regex match with literal-only pattern.'
Enabled: 'pending'
VersionAdded: '1.7'
Performance/StringReplacement:
Description: >-
Use `tr` instead of `gsub` when you are replacing the same

View File

@ -0,0 +1,28 @@
# frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for cops checking `Enumerable#sort` blocks.
module SortBlock
extend NodePattern::Macros
include RangeHelp
def_node_matcher :sort_with_block?, <<~PATTERN
(block
$(send _ :sort)
(args (arg $_a) (arg $_b))
$send)
PATTERN
def_node_matcher :replaceable_body?, <<~PATTERN
(send (lvar %1) :<=> (lvar %2))
PATTERN
private
def sort_range(send, node)
range_between(send.loc.selector.begin_pos, node.loc.end.end_pos)
end
end
end
end

View File

@ -0,0 +1,45 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop is used to identify usages of `ancestors.include?` and
# change them to use `<=` instead.
#
# @example
# # bad
# A.ancestors.include?(B)
#
# # good
# A <= B
#
class AncestorsInclude < Cop
include RangeHelp
MSG = 'Use `<=` instead of `ancestors.include?`.'
def_node_matcher :ancestors_include_candidate?, <<~PATTERN
(send (send $_subclass :ancestors) :include? $_superclass)
PATTERN
def on_send(node)
return unless ancestors_include_candidate?(node)
location_of_ancestors = node.children[0].loc.selector.begin_pos
end_location = node.loc.selector.end_pos
range = range_between(location_of_ancestors, end_location)
add_offense(node, location: range)
end
def autocorrect(node)
ancestors_include_candidate?(node) do |subclass, superclass|
lambda do |corrector|
corrector.replace(node, "#{subclass.source} <= #{superclass.source}")
end
end
end
end
end
end
end

View File

@ -0,0 +1,43 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where numeric argument to BigDecimal should be
# converted to string. Initializing from String is faster
# than from Numeric for BigDecimal.
#
# @example
#
# # bad
# BigDecimal(1, 2)
# BigDecimal(1.2, 3, exception: true)
#
# # good
# BigDecimal('1', 2)
# BigDecimal('1.2', 3, exception: true)
#
class BigDecimalWithNumericArgument < Cop
MSG = 'Convert numeric argument to string before passing to `BigDecimal`.'
def_node_matcher :big_decimal_with_numeric_argument?, <<~PATTERN
(send nil? :BigDecimal $numeric_type? ...)
PATTERN
def on_send(node)
big_decimal_with_numeric_argument?(node) do |numeric|
add_offense(node, location: numeric.source_range)
end
end
def autocorrect(node)
big_decimal_with_numeric_argument?(node) do |numeric|
lambda do |corrector|
corrector.wrap(numeric, "'", "'")
end
end
end
end
end
end
end

View File

@ -0,0 +1,127 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where inefficient `readlines` method
# can be replaced by `each_line` to avoid fully loading file content into memory.
#
# @example
#
# # bad
# File.readlines('testfile').each { |l| puts l }
# IO.readlines('testfile', chomp: true).each { |l| puts l }
#
# conn.readlines(10).map { |l| l.size }
# file.readlines.find { |l| l.start_with?('#') }
# file.readlines.each { |l| puts l }
#
# # good
# File.open('testfile', 'r').each_line { |l| puts l }
# IO.open('testfile').each_line(chomp: true) { |l| puts l }
#
# conn.each_line(10).map { |l| l.size }
# file.each_line.find { |l| l.start_with?('#') }
# file.each_line { |l| puts l }
#
class IoReadlines < Cop
include RangeHelp
MSG = 'Use `%<good>s` instead of `%<bad>s`.'
ENUMERABLE_METHODS = (Enumerable.instance_methods + [:each]).freeze
def_node_matcher :readlines_on_class?, <<~PATTERN
$(send $(send (const nil? {:IO :File}) :readlines ...) #enumerable_method?)
PATTERN
def_node_matcher :readlines_on_instance?, <<~PATTERN
$(send $(send ${nil? !const_type?} :readlines ...) #enumerable_method? ...)
PATTERN
def on_send(node)
readlines_on_class?(node) do |enumerable_call, readlines_call|
offense(node, enumerable_call, readlines_call)
end
readlines_on_instance?(node) do |enumerable_call, readlines_call, _|
offense(node, enumerable_call, readlines_call)
end
end
def autocorrect(node)
readlines_on_instance?(node) do |enumerable_call, readlines_call, receiver|
# We cannot safely correct `.readlines` method called on IO/File classes
# due to its signature and we are not sure with implicit receiver
# if it is called in the context of some instance or mentioned class.
return if receiver.nil?
lambda do |corrector|
range = correction_range(enumerable_call, readlines_call)
if readlines_call.arguments?
call_args = build_call_args(readlines_call.arguments)
replacement = "each_line(#{call_args})"
else
replacement = 'each_line'
end
corrector.replace(range, replacement)
end
end
end
private
def enumerable_method?(node)
ENUMERABLE_METHODS.include?(node.to_sym)
end
def offense(node, enumerable_call, readlines_call)
range = offense_range(enumerable_call, readlines_call)
good_method = build_good_method(enumerable_call)
bad_method = build_bad_method(enumerable_call)
add_offense(
node,
location: range,
message: format(MSG, good: good_method, bad: bad_method)
)
end
def offense_range(enumerable_call, readlines_call)
readlines_pos = readlines_call.loc.selector.begin_pos
enumerable_pos = enumerable_call.loc.selector.end_pos
range_between(readlines_pos, enumerable_pos)
end
def build_good_method(enumerable_call)
if enumerable_call.method?(:each)
'each_line'
else
"each_line.#{enumerable_call.method_name}"
end
end
def build_bad_method(enumerable_call)
"readlines.#{enumerable_call.method_name}"
end
def correction_range(enumerable_call, readlines_call)
begin_pos = readlines_call.loc.selector.begin_pos
end_pos = if enumerable_call.method?(:each)
enumerable_call.loc.expression.end_pos
else
enumerable_call.loc.dot.begin_pos
end
range_between(begin_pos, end_pos)
end
def build_call_args(call_args_node)
call_args_node.map(&:source).join(', ')
end
end
end
end
end

View File

@ -3,18 +3,19 @@
module RuboCop
module Cop
module Performance
# This cop identifies uses of `Range#include?`, which iterates over each
# This cop identifies uses of `Range#include?` and `Range#member?`, which iterates over each
# item in a `Range` to see if a specified item is there. In contrast,
# `Range#cover?` simply compares the target item with the beginning and
# end points of the `Range`. In a great majority of cases, this is what
# is wanted.
#
# This cop is `Safe: false` by default because `Range#include?` and
# This cop is `Safe: false` by default because `Range#include?` (or `Range#member?`) and
# `Range#cover?` are not equivalent behaviour.
#
# @example
# # bad
# ('a'..'z').include?('b') # => true
# ('a'..'z').member?('b') # => true
#
# # good
# ('a'..'z').cover?('b') # => true
@ -24,7 +25,7 @@ module RuboCop
#
# ('a'..'z').cover?('yellow') # => true
class RangeInclude < Cop
MSG = 'Use `Range#cover?` instead of `Range#include?`.'
MSG = 'Use `Range#cover?` instead of `Range#%<bad_method>s`.'
# TODO: If we traced out assignments of variables to their uses, we
# might pick up on a few more instances of this issue
@ -32,13 +33,14 @@ module RuboCop
# (We don't even catch it if the Range is in double parens)
def_node_matcher :range_include, <<~PATTERN
(send {irange erange (begin {irange erange})} :include? ...)
(send {irange erange (begin {irange erange})} ${:include? :member?} ...)
PATTERN
def on_send(node)
return unless range_include(node)
add_offense(node, location: :selector)
range_include(node) do |bad_method|
message = format(MSG, bad_method: bad_method)
add_offense(node, location: :selector, message: message)
end
end
def autocorrect(node)

View File

@ -0,0 +1,53 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where `sort { |a, b| a <=> b }`
# can be replaced with `sort`.
#
# @example
# # bad
# array.sort { |a, b| a <=> b }
#
# # good
# array.sort
#
class RedundantSortBlock < Cop
include SortBlock
MSG = 'Use `sort` instead of `%<bad_method>s`.'
def on_block(node)
sort_with_block?(node) do |send, var_a, var_b, body|
replaceable_body?(body, var_a, var_b) do
range = sort_range(send, node)
add_offense(
node,
location: range,
message: message(var_a, var_b)
)
end
end
end
def autocorrect(node)
sort_with_block?(node) do |send, _var_a, _var_b, _body|
lambda do |corrector|
range = sort_range(send, node)
corrector.replace(range, 'sort')
end
end
end
private
def message(var_a, var_b)
bad_method = "sort { |#{var_a}, #{var_b}| #{var_a} <=> #{var_b} }"
format(MSG, bad_method: bad_method)
end
end
end
end
end

View File

@ -0,0 +1,137 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop checks for redundant `String#chars`.
#
# @example
# # bad
# str.chars[0..2]
# str.chars.slice(0..2)
#
# # good
# str[0..2].chars
#
# # bad
# str.chars.first
# str.chars.first(2)
# str.chars.last
# str.chars.last(2)
#
# # good
# str[0]
# str[0...2].chars
# str[-1]
# str[-2..-1].chars
#
# # bad
# str.chars.take(2)
# str.chars.drop(2)
# str.chars.length
# str.chars.size
# str.chars.empty?
#
# # good
# str[0...2].chars
# str[2..-1].chars
# str.length
# str.size
# str.empty?
#
class RedundantStringChars < Cop
include RangeHelp
MSG = 'Use `%<good_method>s` instead of `%<bad_method>s`.'
REPLACEABLE_METHODS = %i[[] slice first last take drop length size empty?].freeze
def_node_matcher :redundant_chars_call?, <<~PATTERN
(send $(send _ :chars) $#replaceable_method? $...)
PATTERN
def on_send(node)
redundant_chars_call?(node) do |receiver, method, args|
range = offense_range(receiver, node)
message = build_message(method, args)
add_offense(node, location: range, message: message)
end
end
def autocorrect(node)
redundant_chars_call?(node) do |receiver, method, args|
range = correction_range(receiver, node)
replacement = build_good_method(method, args)
lambda do |corrector|
corrector.replace(range, replacement)
end
end
end
private
def replaceable_method?(method_name)
REPLACEABLE_METHODS.include?(method_name)
end
def offense_range(receiver, node)
range_between(receiver.loc.selector.begin_pos, node.loc.expression.end_pos)
end
def correction_range(receiver, node)
range_between(receiver.loc.dot.begin_pos, node.loc.expression.end_pos)
end
def build_message(method, args)
good_method = build_good_method(method, args)
bad_method = build_bad_method(method, args)
format(MSG, good_method: good_method, bad_method: bad_method)
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength
def build_good_method(method, args)
case method
when :[], :slice
"[#{build_call_args(args)}].chars"
when :first
if args.any?
"[0...#{args.first.source}].chars"
else
'[0]'
end
when :last
if args.any?
"[-#{args.first.source}..-1].chars"
else
'[-1]'
end
when :take
"[0...#{args.first.source}].chars"
when :drop
"[#{args.first.source}..-1].chars"
else
".#{method}"
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/MethodLength
def build_bad_method(method, args)
case method
when :[]
"chars[#{build_call_args(args)}]"
else
if args.any?
"chars.#{method}(#{build_call_args(args)})"
else
"chars.#{method}"
end
end
end
def build_call_args(call_args_node)
call_args_node.map(&:source).join(', ')
end
end
end
end
end

View File

@ -0,0 +1,78 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where `reverse.first(n)` and `reverse.first`
# can be replaced by `last(n).reverse` and `last`.
#
# @example
#
# # bad
# array.reverse.first(5)
# array.reverse.first
#
# # good
# array.last(5).reverse
# array.last
#
class ReverseFirst < Cop
include RangeHelp
MSG = 'Use `%<good_method>s` instead of `%<bad_method>s`.'
def_node_matcher :reverse_first_candidate?, <<~PATTERN
(send $(send _ :reverse) :first (int _)?)
PATTERN
def on_send(node)
reverse_first_candidate?(node) do |receiver|
range = correction_range(receiver, node)
message = build_message(node)
add_offense(node, location: range, message: message)
end
end
def autocorrect(node)
reverse_first_candidate?(node) do |receiver|
range = correction_range(receiver, node)
replacement = build_good_method(node)
lambda do |corrector|
corrector.replace(range, replacement)
end
end
end
private
def correction_range(receiver, node)
range_between(receiver.loc.selector.begin_pos, node.loc.expression.end_pos)
end
def build_message(node)
good_method = build_good_method(node)
bad_method = build_bad_method(node)
format(MSG, good_method: good_method, bad_method: bad_method)
end
def build_good_method(node)
if node.arguments?
"last(#{node.arguments.first.source}).reverse"
else
'last'
end
end
def build_bad_method(node)
if node.arguments?
"reverse.first(#{node.arguments.first.source})"
else
'reverse.first'
end
end
end
end
end
end

View File

@ -0,0 +1,75 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop is used to identify usages of `count` on an
# `Array` and `Hash` and change them to `size`.
#
# @example
# # bad
# [1, 2, 3].count
# (1..3).to_a.count
# Array[*1..3].count
# Array(1..3).count
#
# # bad
# {a: 1, b: 2, c: 3}.count
# [[:foo, :bar], [1, 2]].to_h.count
# Hash[*('a'..'z')].count
# Hash(key: :value).count
#
# # good
# [1, 2, 3].size
# (1..3).to_a.size
# Array[*1..3].size
# Array(1..3).size
#
# # good
# {a: 1, b: 2, c: 3}.size
# [[:foo, :bar], [1, 2]].to_h.size
# Hash[*('a'..'z')].size
# Hash(key: :value).size
#
# # good
# [1, 2, 3].count { |e| e > 2 }
# TODO: Add advanced detection of variables that could
# have been assigned to an array or a hash.
class Size < Cop
MSG = 'Use `size` instead of `count`.'
def_node_matcher :array?, <<~PATTERN
{
[!nil? array_type?]
(send _ :to_a)
(send (const nil? :Array) :[] _)
(send nil? :Array _)
}
PATTERN
def_node_matcher :hash?, <<~PATTERN
{
[!nil? hash_type?]
(send _ :to_h)
(send (const nil? :Hash) :[] _)
(send nil? :Hash _)
}
PATTERN
def_node_matcher :count?, <<~PATTERN
(send {#array? #hash?} :count)
PATTERN
def on_send(node)
return if node.parent&.block_type? || !count?(node)
add_offense(node, location: :selector)
end
def autocorrect(node)
->(corrector) { corrector.replace(node.loc.selector, 'size') }
end
end
end
end
end

View File

@ -0,0 +1,54 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where `sort { |a, b| b <=> a }`
# can be replaced by a faster `sort.reverse`.
#
# @example
# # bad
# array.sort { |a, b| b <=> a }
#
# # good
# array.sort.reverse
#
class SortReverse < Cop
include SortBlock
MSG = 'Use `sort.reverse` instead of `%<bad_method>s`.'
def on_block(node)
sort_with_block?(node) do |send, var_a, var_b, body|
replaceable_body?(body, var_b, var_a) do
range = sort_range(send, node)
add_offense(
node,
location: range,
message: message(var_a, var_b)
)
end
end
end
def autocorrect(node)
sort_with_block?(node) do |send, _var_a, _var_b, _body|
lambda do |corrector|
range = sort_range(send, node)
replacement = 'sort.reverse'
corrector.replace(range, replacement)
end
end
end
private
def message(var_a, var_b)
bad_method = "sort { |#{var_a}, #{var_b}| #{var_b} <=> #{var_a} }"
format(MSG, bad_method: bad_method)
end
end
end
end
end

View File

@ -0,0 +1,70 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies places where `gsub(/a+/, 'a')` and `gsub!(/a+/, 'a')`
# can be replaced by `squeeze('a')` and `squeeze!('a')`.
#
# The `squeeze('a')` method is faster than `gsub(/a+/, 'a')`.
#
# @example
#
# # bad
# str.gsub(/a+/, 'a')
# str.gsub!(/a+/, 'a')
#
# # good
# str.squeeze('a')
# str.squeeze!('a')
#
class Squeeze < Cop
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
PREFERRED_METHODS = {
gsub: :squeeze,
gsub!: :squeeze!
}.freeze
def_node_matcher :squeeze_candidate?, <<~PATTERN
(send
$!nil? ${:gsub :gsub!}
(regexp
(str $#repeating_literal?)
(regopt))
(str $_))
PATTERN
def on_send(node)
squeeze_candidate?(node) do |_, bad_method, regexp_str, replace_str|
regexp_str = regexp_str[0..-2] # delete '+' from the end
regexp_str = interpret_string_escapes(regexp_str)
return unless replace_str == regexp_str
good_method = PREFERRED_METHODS[bad_method]
message = format(MSG, current: bad_method, prefer: good_method)
add_offense(node, location: :selector, message: message)
end
end
def autocorrect(node)
squeeze_candidate?(node) do |receiver, bad_method, _regexp_str, replace_str|
lambda do |corrector|
good_method = PREFERRED_METHODS[bad_method]
string_literal = to_string_literal(replace_str)
new_code = "#{receiver.source}.#{good_method}(#{string_literal})"
corrector.replace(node.source_range, new_code)
end
end
end
private
def repeating_literal?(regex_str)
regex_str.match?(/\A(?:#{Util::LITERAL_REGEX})\+\z/)
end
end
end
end
end

View File

@ -0,0 +1,57 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop identifies unnecessary use of a regex where
# `String#include?` would suffice.
#
# @example
# # bad
# 'abc'.match?(/ab/)
# /ab/.match?('abc')
# 'abc' =~ /ab/
# /ab/ =~ 'abc'
# 'abc'.match(/ab/)
# /ab/.match('abc')
#
# # good
# 'abc'.include?('ab')
class StringInclude < Cop
MSG = 'Use `String#include?` instead of a regex match with literal-only pattern.'
def_node_matcher :redundant_regex?, <<~PATTERN
{(send $!nil? {:match :=~ :match?} (regexp (str $#literal?) (regopt)))
(send (regexp (str $#literal?) (regopt)) {:match :match?} $str)
(match-with-lvasgn (regexp (str $#literal?) (regopt)) $_)}
PATTERN
def on_send(node)
return unless redundant_regex?(node)
add_offense(node)
end
alias on_match_with_lvasgn on_send
def autocorrect(node)
redundant_regex?(node) do |receiver, regex_str|
receiver, regex_str = regex_str, receiver if receiver.is_a?(String)
regex_str = interpret_string_escapes(regex_str)
lambda do |corrector|
new_source = receiver.source + '.include?(' +
to_string_literal(regex_str) + ')'
corrector.replace(node.source_range, new_source)
end
end
end
private
def literal?(regex_str)
regex_str.match?(/\A#{Util::LITERAL_REGEX}+\z/)
end
end
end
end
end

View File

@ -1,7 +1,10 @@
# frozen_string_literal: true
require_relative 'mixin/regexp_metacharacter'
require_relative 'mixin/sort_block'
require_relative 'performance/ancestors_include'
require_relative 'performance/big_decimal_with_numeric_argument'
require_relative 'performance/bind_call'
require_relative 'performance/caller'
require_relative 'performance/case_when_splat'
@ -18,13 +21,20 @@ require_relative 'performance/flat_map'
require_relative 'performance/inefficient_hash_search'
require_relative 'performance/open_struct'
require_relative 'performance/range_include'
require_relative 'performance/io_readlines'
require_relative 'performance/redundant_block_call'
require_relative 'performance/redundant_match'
require_relative 'performance/redundant_merge'
require_relative 'performance/redundant_sort_block'
require_relative 'performance/redundant_string_chars'
require_relative 'performance/regexp_match'
require_relative 'performance/reverse_each'
require_relative 'performance/reverse_first'
require_relative 'performance/size'
require_relative 'performance/sort_reverse'
require_relative 'performance/squeeze'
require_relative 'performance/start_with'
require_relative 'performance/string_include'
require_relative 'performance/string_replacement'
require_relative 'performance/times_map'
require_relative 'performance/unfreeze_string'