Module: RuboCop::Cop::Util

Extended by:
AST::Sexp
Includes:
PathUtil
Included in:
AlignmentCorrector, Cop, MultilineLiteralBraceCorrector, StringLiteralCorrector, UnusedArgCorrector
Defined in:
lib/rubocop/cop/util.rb

Overview

This module contains a collection of useful utility methods.

Constant Summary collapse

BYTE_ORDER_MARK =

The Unicode codepoint

0xfeff
EQUALS_ASGN_NODES =
%i[lvasgn ivasgn cvasgn gvasgn
casgn masgn].freeze
SHORTHAND_ASGN_NODES =
%i[op_asgn or_asgn and_asgn].freeze
ASGN_NODES =
(EQUALS_ASGN_NODES + SHORTHAND_ASGN_NODES).freeze
MODIFIER_NODES =
%i[if while until].freeze
CONDITIONAL_NODES =
(MODIFIER_NODES + [:case]).freeze
LOGICAL_OPERATOR_NODES =
%i[and or].freeze
OPERATOR_METHODS =

phrogz.net/programmingruby/language.html#table_18.4 Backtick is added last just to help editors parse this code.

%w(
  | ^ & <=> == === =~ > >= < <= << >>
  + - * / % ** ~ +@ -@ !@ ~@ [] []= ! != !~
).map(&:to_sym).push(:'`').freeze
LITERAL_REGEX =

Match literal regex characters, not including anchors, character classes, alternatives, groups, repetitions, references, etc

/[\w\s\-,"'!#%&<>=;:`~]|\\[^AbBdDgGhHkpPRwWXsSzZ0-9]/

Class Method Summary collapse

Methods included from AST::Sexp

s

Methods included from PathUtil

absolute?, find_file_upwards, match_path?, pwd, relative_path, reset_pwd, smart_path

Class Method Details

.begins_its_line?(range) ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/rubocop/cop/util.rb', line 171

def begins_its_line?(range)
  (range.source_line =~ /\S/) == range.column
end

.comment_line?(line_source) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/rubocop/cop/util.rb', line 51

def comment_line?(line_source)
  line_source =~ /^\s*#/
end

.double_quotes_required?(string) ⇒ Boolean

If converting a string to Ruby string literal source code, must double quotes be used?

Returns:

  • (Boolean)


206
207
208
209
210
211
212
213
214
# File 'lib/rubocop/cop/util.rb', line 206

def double_quotes_required?(string)
  # Double quotes are required for strings which either:
  # - Contain single quotes
  # - Contain non-printable characters, which must use an escape

  # Regex matches IF there is a ' or there is a \\ in the string that is
  # not preceded/followed by another \\ (e.g. "\\x34") but not "\\\\".
  string =~ /'|(?<! \\) \\{2}* \\ (?![\\"])/x
end

.effective_column(range) ⇒ Object

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value. This gives the column as it appears when viewing the file in an editor.



109
110
111
112
113
114
115
116
# File 'lib/rubocop/cop/util.rb', line 109

def effective_column(range)
  if range.line == 1 &&
     @processed_source.raw_source.codepoints.first == BYTE_ORDER_MARK
    range.column - 1
  else
    range.column
  end
end

.ends_its_line?(range) ⇒ Boolean

Returns:

  • (Boolean)


175
176
177
178
# File 'lib/rubocop/cop/util.rb', line 175

def ends_its_line?(range)
  line = range.source_buffer.source_line(range.last_line)
  (line =~ /\s*\z/) == range.last_column
end

.escape_string(string) ⇒ Object



220
221
222
# File 'lib/rubocop/cop/util.rb', line 220

def escape_string(string)
  string.inspect[1..-2].tap { |s| s.gsub!(/\\"/, '"') }
end

.first_part_of_call_chain(node) ⇒ Object

Returns, for example, a bare ‘if` node if the given node is an `if` with calls chained to the end of it.



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/rubocop/cop/util.rb', line 188

def first_part_of_call_chain(node)
  while node
    case node.type
    when :send
      receiver, _method_name, _args = *node
      node = receiver
    when :block
      method, _args, _body = *node
      node = method
    else
      break
    end
  end
  node
end

.interpret_string_escapes(string) ⇒ Object



261
262
263
# File 'lib/rubocop/cop/util.rb', line 261

def interpret_string_escapes(string)
  StringInterpreter.interpret(string)
end

.line_range(arg) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rubocop/cop/util.rb', line 55

def line_range(arg)
  source_range = case arg
                 when Parser::Source::Range
                   arg
                 when Parser::AST::Node
                   arg.source_range
                 else
                   raise ArgumentError, "Invalid argument #{arg}"
                 end

  source_range.begin.line..source_range.end.line
end

.needs_escaping?(string) ⇒ Boolean

Returns:

  • (Boolean)


216
217
218
# File 'lib/rubocop/cop/util.rb', line 216

def needs_escaping?(string)
  double_quotes_required?(escape_string(string))
end

.on_node(syms, sexp, excludes = []) {|sexp| ... } ⇒ Object

Yields:

  • (sexp)


77
78
79
80
81
82
83
84
# File 'lib/rubocop/cop/util.rb', line 77

def on_node(syms, sexp, excludes = [], &block)
  return to_enum(:on_node, syms, sexp, excludes) unless block_given?

  yield sexp if Array(syms).include?(sexp.type)
  return if Array(excludes).include?(sexp.type)

  sexp.each_child_node { |elem| on_node(syms, elem, excludes, &block) }
end

.operator?(symbol) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/rubocop/cop/util.rb', line 35

def operator?(symbol)
  OPERATOR_METHODS.include?(symbol)
end

.parentheses?(node) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
71
# File 'lib/rubocop/cop/util.rb', line 68

def parentheses?(node)
  node.loc.respond_to?(:end) && node.loc.end &&
    node.loc.end.is?(')'.freeze)
end

.parenthesized_call?(send) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/rubocop/cop/util.rb', line 73

def parenthesized_call?(send)
  send.loc.begin && send.loc.begin.is?('(')
end

.precede?(n1, n2) ⇒ Boolean

Returns:

  • (Boolean)


271
272
273
# File 'lib/rubocop/cop/util.rb', line 271

def precede?(n1, n2)
  line_distance(n1, n2) == 1
end

.range_between(start_pos, end_pos) ⇒ Object



118
119
120
# File 'lib/rubocop/cop/util.rb', line 118

def range_between(start_pos, end_pos)
  Parser::Source::Range.new(processed_source.buffer, start_pos, end_pos)
end

.range_by_whole_lines(range, include_final_newline: false) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/rubocop/cop/util.rb', line 155

def range_by_whole_lines(range, include_final_newline: false)
  buffer = @processed_source.buffer

  begin_pos = range.begin_pos
  begin_offset = range.column
  begin_of_first_line = begin_pos - begin_offset

  last_line = buffer.source_line(range.last_line)
  end_pos = range.end_pos
  end_offset = last_line.length - range.last_column
  end_offset += 1 if include_final_newline
  end_of_last_line = end_pos + end_offset

  Parser::Source::Range.new(buffer, begin_of_first_line, end_of_last_line)
end

.range_with_surrounding_comma(range, side = :both) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/rubocop/cop/util.rb', line 122

def range_with_surrounding_comma(range, side = :both)
  buffer = @processed_source.buffer
  src = buffer.source

  go_left, go_right = directions(side)

  begin_pos = range.begin_pos
  end_pos = range.end_pos
  begin_pos = move_pos(src, begin_pos, -1, go_left, /,/)
  end_pos = move_pos(src, end_pos, 1, go_right, /,/)

  Parser::Source::Range.new(buffer, begin_pos, end_pos)
end

.range_with_surrounding_space(range:, side: :both, newlines: true, whitespace: false) ⇒ Object



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/rubocop/cop/util.rb', line 136

def range_with_surrounding_space(range:,
                                 side: :both,
                                 newlines: true,
                                 whitespace: false)
  buffer = @processed_source.buffer
  src = buffer.source

  go_left, go_right = directions(side)

  begin_pos = range.begin_pos
  if go_left
    begin_pos =
      final_pos(src, begin_pos, -1, newlines, whitespace)
  end
  end_pos = range.end_pos
  end_pos = final_pos(src, end_pos, 1, newlines, whitespace) if go_right
  Parser::Source::Range.new(buffer, begin_pos, end_pos)
end

.same_line?(n1, n2) ⇒ Boolean

Returns:

  • (Boolean)


265
266
267
268
269
# File 'lib/rubocop/cop/util.rb', line 265

def same_line?(n1, n2)
  n1.respond_to?(:loc) &&
    n2.respond_to?(:loc) &&
    n1.loc.line == n2.loc.line
end

.source_range(source_buffer, line_number, column, length = 1) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rubocop/cop/util.rb', line 86

def source_range(source_buffer, line_number, column, length = 1)
  if column.is_a?(Range)
    column_index = column.begin
    length = column.size
  else
    column_index = column
  end

  line_begin_pos = if line_number.zero?
                     0
                   else
                     source_buffer.line_range(line_number).begin_pos
                   end
  begin_pos = line_begin_pos + column_index
  end_pos = begin_pos + length

  Parser::Source::Range.new(source_buffer, begin_pos, end_pos)
end

.strip_quotes(str) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/util.rb', line 39

def strip_quotes(str)
  if str[0] == '"' || str[0] == "'"
    str[0] = ''
  else
    # we're dealing with %q or %Q
    str[0, 3] = ''
  end
  str[-1] = ''

  str
end

.stripped_source_upto(line) ⇒ Object



275
276
277
# File 'lib/rubocop/cop/util.rb', line 275

def stripped_source_upto(line)
  processed_source[0..line].map(&:strip)
end

.symbol_without_quote?(string) ⇒ Boolean

Returns:

  • (Boolean)


240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/rubocop/cop/util.rb', line 240

def symbol_without_quote?(string)
  special_gvars = %w[
    $! $" $$ $& $' $* $+ $, $/ $; $: $. $< $= $> $? $@ $\\ $_ $` $~ $0
    $-0 $-F $-I $-K $-W $-a $-d $-i $-l $-p $-v $-w
  ]
  redefinable_operators = %w(
    | ^ & <=> == === =~ > >= < <= << >>
    + - * / % ** ~ +@ -@ [] []= ` ! != !~
  )

  # method name
  string =~ /\A[a-zA-Z_]\w*[!?]?\z/ ||
    # instance / class variable
    string =~ /\A\@\@?[a-zA-Z_]\w*\z/ ||
    # global variable
    string =~ /\A\$[1-9]\d*\z/ ||
    string =~ /\A\$[a-zA-Z_]\w*\z/ ||
    special_gvars.include?(string) ||
    redefinable_operators.include?(string)
end

.to_string_literal(string) ⇒ Object



224
225
226
227
228
229
230
# File 'lib/rubocop/cop/util.rb', line 224

def to_string_literal(string)
  if needs_escaping?(string) && compatible_external_encoding_for?(string)
    string.inspect
  else
    "'#{string.gsub('\\') { '\\\\' }}'"
  end
end

.to_supported_styles(enforced_style) ⇒ Object



279
280
281
282
283
# File 'lib/rubocop/cop/util.rb', line 279

def to_supported_styles(enforced_style)
  enforced_style
    .sub(/^Enforced/, 'Supported')
    .sub('Style', 'Styles')
end

.to_symbol_literal(string) ⇒ Object



232
233
234
235
236
237
238
# File 'lib/rubocop/cop/util.rb', line 232

def to_symbol_literal(string)
  if symbol_without_quote?(string)
    ":#{string}"
  else
    ":#{to_string_literal(string)}"
  end
end

.within_node?(inner, outer) ⇒ Boolean

Returns:

  • (Boolean)


180
181
182
183
184
# File 'lib/rubocop/cop/util.rb', line 180

def within_node?(inner, outer)
  o = outer.is_a?(AST::Node) ? outer.source_range : outer
  i = inner.is_a?(AST::Node) ? inner.source_range : inner
  i.begin_pos >= o.begin_pos && i.end_pos <= o.end_pos
end