This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
loop_keywords.rb
66 lines (60 loc) · 1.54 KB
/
loop_keywords.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
module RubyLint
module Analysis
##
# Analysis class that checks if certain keywords are used inside a
# block/loop or not. For example, the following is not valid Ruby code:
#
# next
#
# But the following is valid:
#
# [10, 20].each do |n|
# next
# end
#
# The following isn't valid either:
#
# def foo
# next
# end
#
# See {KEYWORDS} for a list of the keywords that can only be used inside a
# loop.
#
class LoopKeywords < Base
register 'loop_keywords'
##
# List of keywords that can only be used inside a loop.
#
# @return [Array]
#
KEYWORDS = [:next, :break]
##
# List of statements that do allow the use of the various keywords.
#
# @return [Array]
#
STATEMENTS = [:while, :until, :for]
KEYWORDS.each do |kw|
define_method("on_#{kw}") { |node| verify_keyword(kw, node) }
end
STATEMENTS.each do |statement|
define_method("on_#{statement}") do
@allow_keyword = true
end
define_method("after_#{statement}") do
@allow_keyword = false
end
end
##
# @param [Symbol] keyword
# @param [RubyLint::AST::Node] node
#
def verify_keyword(keyword, node)
if current_scope.type != :block and !@allow_keyword
error("#{keyword} can only be used inside a loop/block", node)
end
end
end # BlockKeywords
end # Analysis
end # RubyLint