/
frozen_string_literal.rb
75 lines (62 loc) · 2.6 KB
/
frozen_string_literal.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
# frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for dealing with frozen string literals.
module FrozenStringLiteral
module_function
FROZEN_STRING_LITERAL = '# frozen_string_literal:'
FROZEN_STRING_LITERAL_ENABLED = '# frozen_string_literal: true'
FROZEN_STRING_LITERAL_TYPES_RUBY27 = %i[str dstr].freeze
FROZEN_STRING_LITERAL_TYPES_RUBY30 = %i[str].freeze
private_constant :FROZEN_STRING_LITERAL_TYPES_RUBY27, :FROZEN_STRING_LITERAL_TYPES_RUBY30
def frozen_string_literal_comment_exists?
leading_comment_lines.any? { |line| MagicComment.parse(line).valid_literal_value? }
end
private
def frozen_string_literal?(node)
literal_types = if target_ruby_version >= 3.0
FROZEN_STRING_LITERAL_TYPES_RUBY30
else
FROZEN_STRING_LITERAL_TYPES_RUBY27
end
literal_types.include?(node.type) && frozen_string_literals_enabled?
end
def frozen_string_literals_enabled?
ruby_version = processed_source.ruby_version
return false unless ruby_version
# TODO: Ruby officially abandon making frozen string literals default
# for Ruby 3.0.
# https://bugs.ruby-lang.org/issues/11473#note-53
# Whether frozen string literals will be the default after Ruby 3.0
# or not is still unclear as of January 2019.
# It may be necessary to add this code in the future.
#
# return true if ruby_version >= 3.1
#
# And the above `ruby_version >= 3.1` is undecided whether it will be
# Ruby 3.1, 3.2, 4.0 or others.
# See https://bugs.ruby-lang.org/issues/8976#note-41 for details.
leading_comment_lines.any? { |line| MagicComment.parse(line).frozen_string_literal? }
end
def frozen_string_literals_disabled?
leading_comment_lines.any? do |line|
MagicComment.parse(line).frozen_string_literal == false
end
end
def frozen_string_literal_specified?
leading_comment_lines.any? do |line|
MagicComment.parse(line).frozen_string_literal_specified?
end
end
def leading_comment_lines
first_non_comment_token = processed_source.tokens.find { |token| !token.comment? }
if first_non_comment_token
# `line` is 1-indexed so we need to subtract 1 to get the array index
processed_source.lines[0...first_non_comment_token.line - 1]
else
processed_source.lines
end
end
end
end
end