forked from rubocop/rubocop
/
literal_as_condition.rb
135 lines (114 loc) · 3.06 KB
/
literal_as_condition.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for literals used as the conditions or as
# operands in and/or expressions serving as the conditions of
# if/while/until.
#
# @example
#
# # bad
# if 20
# do_something
# end
#
# # bad
# if some_var && true
# do_something
# end
#
# # good
# if some_var && some_condition
# do_something
# end
#
# # good
# # When using a boolean value for an infinite loop.
# while true
# break if condition
# end
class LiteralAsCondition < Cop
MSG = 'Literal `%<literal>s` appeared as a condition.'
def on_if(node)
check_for_literal(node)
end
def on_while(node)
return if condition(node).true_type?
check_for_literal(node)
end
alias on_while_post on_while
def on_until(node)
return if condition(node).false_type?
check_for_literal(node)
end
alias on_until_post on_until
def on_case(case_node)
if case_node.condition
check_case(case_node)
else
case_node.each_when do |when_node|
next unless when_node.conditions.all?(&:literal?)
add_offense(when_node)
end
end
end
def on_send(node)
return unless node.negation_method?
check_for_literal(node)
end
def message(node)
format(MSG, literal: node.source)
end
private
def check_for_literal(node)
cond = condition(node)
if cond.literal?
add_offense(cond)
else
check_node(cond)
end
end
def basic_literal?(node)
if node.array_type?
primitive_array?(node)
else
node.basic_literal?
end
end
def primitive_array?(node)
node.children.all? { |n| basic_literal?(n) }
end
def check_node(node)
if node.send_type? && node.prefix_bang?
handle_node(node.receiver)
elsif node.operator_keyword?
node.each_child_node { |op| handle_node(op) }
elsif node.begin_type? && node.children.one?
handle_node(node.children.first)
end
end
def handle_node(node)
if node.literal?
add_offense(node)
elsif %i[send and or begin].include?(node.type)
check_node(node)
end
end
def check_case(case_node)
condition = case_node.condition
return if condition.array_type? && !primitive_array?(condition)
return if condition.dstr_type?
handle_node(condition)
end
def condition(node)
if node.send_type?
node.receiver
else
node.condition
end
end
end
end
end
end