Module: Audition::Rewriters::MagicComments

Defined in:
lib/audition/rewriters.rb

Overview

-- magic comments ----------------------------------------------

Defined Under Namespace

Classes: ConstantValues

Constant Summary collapse

SCV_LINE =
"# shareable_constant_value: literal\n"
FSL_LINE =
"# frozen_string_literal: true\n"

Class Method Summary collapse

Class Method Details

.comment_plan(file, line) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/audition/rewriters.rb', line 46

def self.comment_plan(file, line)
  offset = file.magic_insertion_offset
  {
    edit: Autofix.new(start_offset: offset,
      end_offset: offset,
      replacement: line,
      safety: :unsafe),
    covers: ["mutable-constants"]
  }
end

.constant_values(file) ⇒ Object



57
58
59
60
61
# File 'lib/audition/rewriters.rb', line 57

def self.constant_values(file)
  collector = ConstantValues.new
  collector.visit(file.root)
  collector.values
end

.plan(file, findings) ⇒ Object

shareable_constant_value: literal raises at load for non-literal constant values (verified on 4.0), so it is only planned when every constant assignment in the file classifies as a literal. Otherwise, if the flagged values are all strings, frozen_string_literal covers them.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/audition/rewriters.rb', line 22

def self.plan(file, findings)
  return nil if file.shareable_constants?
  return nil if findings.none? { |f| f.check == "mutable-constants" }

  classifier = Static::LiteralClassifier.new(
    frozen_string_literal: file.frozen_string_literal?
  )
  kinds = constant_values(file).map { |v| classifier.classify(v) }
  flagged = kinds.reject do |k|
    %i[shareable unknown].include?(k)
  end
  scv_ok = kinds.all? do |k|
    %i[shareable mutable_string mutable_container
      shallow_freeze].include?(k)
  end

  if scv_ok
    comment_plan(file, SCV_LINE)
  elsif !file.frozen_string_literal? &&
      flagged.all? { |k| k == :mutable_string }
    comment_plan(file, FSL_LINE)
  end
end