Class: Rubocop::Cop::Style::Semicolon

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/style/semicolon.rb

Overview

This cop checks for multiple expressions placed on the same line. It also checks for lines terminated with a semicolon.

Constant Summary collapse

MSG =
'Do not use semicolons to terminate expressions.'

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #corrections, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, all, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#investigate(processed_source) ⇒ Object



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
# File 'lib/rubocop/cop/style/semicolon.rb', line 11

def investigate(processed_source)
  return unless processed_source.ast

  on_node(:begin, processed_source.ast) do |node|
    exprs = node.children

    next if exprs.size < 2

    # create a map matching lines to the number of expressions on them
    exprs_lines = exprs.map { |e| e.loc.expression.line }
    lines = exprs_lines.group_by { |i| i }

    # every line with more than 1 expression on it is an offence
    lines.each do |line, expr_on_line|
      if expr_on_line.size > 1
        # TODO: Find the correct position of the semicolon. We don't
        # know if the first semicolon on the line is a separator of
        # expressions. It's just a guess.
        column = processed_source[line - 1].index(';')
        add_offence(:convention,
                    source_range(processed_source.buffer,
                                 processed_source[0...(line - 1)],
                                 column, 1),
                    MSG)
      end
    end
  end

  tokens_for_lines = processed_source.tokens.group_by do |token|
    token.pos.line
  end

  tokens_for_lines.each do |line, tokens|
    if tokens.last.type == :tSEMI # rubocop:disable SymbolName
      column = tokens.last.pos.column
      add_offence(:convention,
                  source_range(processed_source.buffer,
                               processed_source[0...(line - 1)],
                               column, 1),
                  MSG)
    end
  end
end