Module: Spoom::Sorbet::Translate::Validator

Defined in:
lib/spoom/sorbet/translate/validator.rb

Overview

Checks that a translation preserved the lines of every “landmark” (e.g. classes, method defs, and so on) so line numbers in the rewritten output still line up with the original source.

Class Method Summary collapse

Class Method Details

.validate(original, rewritten) ⇒ Object

Compares the landmarks in both sources and returns a result describing what changed:

missing_from_rewritten_output - dropped: an occurrence in the original
                                that is gone from the rewrite
excess_in_rewritten_output    - added: an occurrence in the rewrite with
                                no match in the original
on_wrong_line                 - survived but moved to a different line

: (String original, String rewritten) -> ValidationResult



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
# File 'lib/spoom/sorbet/translate/validator.rb', line 25

def validate(original, rewritten)
  original_landmarks = LandmarkFinder.find_landmarks_in(original)
  rewritten_landmarks = LandmarkFinder.find_landmarks_in(rewritten)

  missing = []
  excess = []
  on_wrong_line = []

  (original_landmarks.keys | rewritten_landmarks.keys).each do |landmark_id|
    original_lines = original_landmarks.fetch(landmark_id, [])
    rewritten_lines = rewritten_landmarks.fetch(landmark_id, [])

    dropped = original_lines - rewritten_lines
    added = rewritten_lines - original_lines

    if dropped.any? && added.any?
      # Present in both but on different lines: the landmark moved.
      on_wrong_line << { landmark_id:, expected: dropped, actual: added }
    else
      dropped.each { |line| missing << { landmark_id:, line: } }
      added.each { |line| excess << { landmark_id:, line: } }
    end
  end

  if original.lines.count != rewritten.lines.count
    on_wrong_line << { landmark_id: "EOF", expected: [original.lines.count], actual: [rewritten.lines.count] }
  end

  ValidationResult.new(
    missing_from_rewritten_output: missing,
    excess_in_rewritten_output: excess,
    on_wrong_line: on_wrong_line,
  )
end