123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Lint::MisplacedMagicComment

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/lint/misplaced_magic_comment.rb

Overview

Checks for magic comments placed where Ruby silently ignores them.

The encoding magic comment is only honored on the first line of a file, or on the second line when the first line is a shebang. Anywhere else it is silently ignored - even directly below another comment or a blank line.

Other magic comments (such as frozen_string_literal) are honored anywhere before the first token of code, but are ignored after any code, with a warning emitted only when running Ruby with -w.

A magic comment misplaced ahead of a shebang also renders the shebang ineffective, since a shebang is only recognized on the first line.

Note
An encoding comment that is only preceded by other magic comments is not flagged by this cop; that case is handled by Lint/OrderedMagicComments. shareable_constant_value is never flagged, as Ruby intentionally allows it mid-file with block scoping.

Examples:

# bad
# Documentation comment
# encoding: ascii-8bit
puts 'hello'

# good
# encoding: ascii-8bit
# Documentation comment
puts 'hello'

# bad
require 'foo'
# frozen_string_literal: true

# good
# frozen_string_literal: true
require 'foo'

# bad
# frozen_string_literal: true
#!/usr/bin/env ruby
puts 'hello'

# good
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 'hello'

Cop Safety Information:

  • This cop’s autocorrection is unsafe because moving the magic comment to its effective position activates it, which changes runtime behavior (e.g. the source encoding or string mutability).

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to #on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

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.

#final_pos

rubocop:disable-next Metrics/ParameterLists.

#move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed

 — grouped under the Commissioner heading above.

#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns a gems locked versions (i.e.

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Attribute Details

#shebang?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 109

def shebang?
  processed_source.lines.first.to_s.start_with?('#!')
end

Instance Method Details

#check_comment(comment) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 75

def check_comment(comment)
  return unless magic_comment_shaped?(comment.text)

  magic_comment = MagicComment.parse(comment.text)
  return unless magic_comment.valid?

  if magic_comment.encoding_specified?
    return unless known_encoding?(magic_comment.encoding)

    check_encoding_comment(comment)
  elsif magic_comment.frozen_string_literal_specified?
    check_top_block_comment(comment, 'frozen_string_literal')
  end
end

#check_encoding_comment(comment) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 122

def check_encoding_comment(comment)
  line = comment.source_range.line
  return if line == effective_encoding_line && comment_starts_line?(comment)
  # Leave `# frozen_string_literal: true` + `# encoding: x` runs at the
  # very top to Lint/OrderedMagicComments, which already reorders them.
  return if preceded_only_by_magic_comments?(comment)

  add_offense(comment, message: MSG_ENCODING) do |corrector|
    move_comment(corrector, comment, effective_encoding_line)
  end
end

#check_magic_comment_above_shebang (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 144

def check_magic_comment_above_shebang
  shebang_comment = processed_source.comments.find do |comment|
    comment.source_range.line > 1 && comment.text.start_with?('#!') &&
      comment.source_range.column.zero?
  end
  return unless shebang_comment
  # Only flag when what precedes the shebang is magic comments -
  # a `#!` comment deep inside a file is not an intended shebang.
  return unless preceded_only_by_magic_comments?(shebang_comment)

  add_offense(shebang_comment, message: MSG_ABOVE_SHEBANG)
end

#check_top_block_comment(comment, directive) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 134

def check_top_block_comment(comment, directive)
  return unless first_code_token
  return unless comment.source_range.begin_pos > first_code_token.begin_pos

  message = format(MSG_AFTER_CODE, directive: directive)
  add_offense(comment, message: message) do |corrector|
    move_comment(corrector, comment, effective_encoding_line)
  end
end

#comment_starts_line?(comment) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 164

def comment_starts_line?(comment)
  processed_source.lines[comment.source_range.line - 1].lstrip.start_with?('#')
end

#effective_encoding_line (private)

First line that may carry an effective encoding comment.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 114

def effective_encoding_line
  shebang? ? 2 : 1
end

#first_code_token (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 118

def first_code_token
  @first_code_token ||= processed_source.sorted_tokens.find { |token| !token.comment? }
end

#known_encoding?(name) ⇒ Boolean (private)

Prose that happens to open with Encoding: parses as an encoding comment (# Encoding: force given encoding yields force). Ruby ignores a misplaced encoding comment entirely, so a name no encoding answers to means the line is a comment, not a directive.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 102

def known_encoding?(name)
  Encoding.find(name)
  true
rescue ArgumentError
  false
end

#magic_comment_shaped?(text) ⇒ Boolean (private)

The Emacs and Vim regexps in ::RuboCop::MagicComment match anywhere inside a comment, which would flag documentation that merely quotes a magic comment (e.g. # # -- coding: UTF-8 --). Require the magic comment to start right after the #.

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 94

def magic_comment_shaped?(text)
  /\A#(?![^#]*#)/.match?(text)
end

#move_comment(corrector, comment, target_line) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 168

def move_comment(corrector, comment, target_line)
  removal_range = if comment_starts_line?(comment)
                    range_by_whole_lines(comment.source_range, include_final_newline: true)
                  else
                    range_with_surrounding_space(comment.source_range, side: :left)
                  end
  corrector.remove(removal_range)
  target_range = processed_source.buffer.line_range(target_line)
  if comment.source_range.line < target_line
    corrector.insert_after(target_range, "\n#{comment.text}")
  else
    corrector.insert_before(target_range, "#{comment.text}\n")
  end
end

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 66

def on_new_investigation
  return if processed_source.buffer.source.empty?

  check_magic_comment_above_shebang
  processed_source.comments.each { |comment| check_comment(comment) }
end

#preceded_only_by_magic_comments?(comment) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/lint/misplaced_magic_comment.rb', line 157

def preceded_only_by_magic_comments?(comment)
  (1...comment.source_range.line).all? do |line_number|
    text = processed_source.lines[line_number - 1]
    (line_number == 1 && text.start_with?('#!')) || MagicComment.parse(text).valid?
  end
end