-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfixed_size.rb
98 lines (84 loc) · 2.22 KB
/
fixed_size.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# Do not compute the size of statically sized objects.
#
# @example
# # String methods
# # bad
# 'foo'.size
# %q[bar].count
# %(qux).length
#
# # Symbol methods
# # bad
# :fred.size
# :'baz'.length
#
# # Array methods
# # bad
# [1, 2, thud].count
# %W(1, 2, bar).size
#
# # Hash methods
# # bad
# { a: corge, b: grault }.length
#
# # good
# foo.size
# bar.count
# qux.length
#
# # good
# :"#{fred}".size
# CONST = :baz.length
#
# # good
# [1, 2, *thud].count
# garply = [1, 2, 3]
# garply.size
#
# # good
# { a: corge, **grault }.length
# waldo = { a: corge, b: grault }
# waldo.size
#
class FixedSize < Base
MSG = 'Do not compute the size of statically sized objects.'
RESTRICT_ON_SEND = %i[count length size].freeze
def_node_matcher :counter, <<~MATCHER
(send ${array hash str sym} {:count :length :size} $...)
MATCHER
def on_send(node)
return if node.ancestors.any? { |ancestor| allowed_parent?(ancestor) }
counter(node) do |var, arg|
return if allowed_variable?(var) || allowed_argument?(arg)
add_offense(node)
end
end
private
def allowed_variable?(var)
contains_splat?(var) || contains_double_splat?(var)
end
def allowed_argument?(arg)
arg && non_string_argument?(arg.first)
end
def allowed_parent?(node)
node && (node.casgn_type? || node.block_type?)
end
def contains_splat?(node)
return false unless node.array_type?
node.each_child_node(:splat).any?
end
def contains_double_splat?(node)
return false unless node.hash_type?
node.each_child_node(:kwsplat).any?
end
def non_string_argument?(node)
node && !node.str_type?
end
end
end
end
end