lib/phlex/compiler/diagnostics.rb
Lines
100%17 of 17 covered
Branches
83%5 of 6 covered
Methods
100%6 of 6 covered
| 1 | # frozen_string_literal: true | |
| 2 | ||
| 3 | # Why parts of a file were left to the runtime: a method that couldn't be | |
| 4 | # matched to the live one, or a call whose arguments or block the compiler | |
| 5 | # doesn't handle. Collected while a file is compiled and returned by | |
| 6 | # `Phlex::Compiler.explain`. | |
| 7 | # | |
| 8 | # Code the compiler refuses to compile, because it couldn't do so faithfully, | |
| 9 | # raises instead when compiling, so the problem is seen rather than worked | |
| 10 | # around silently. `explain` collects refusals like any other diagnostic. | |
| 11 | 1 | class Phlex::Compiler::Diagnostics |
| 12 | 1 | include Enumerable |
| 13 | ||
| 14 | 1 | Diagnostic = Data.define(:path, :line, :message) do |
| 15 | 1 | def to_s = "#{path}:#{line}: #{message}" |
| 16 | end | |
| 17 | ||
| 18 | 1 | def initialize(path, strict: true) |
| 19 | 189 | @path = path |
| 20 | 189 | @strict = strict |
| 21 | 189 | @diagnostics = [] |
| 22 | end | |
| 23 | ||
| 24 | # In file order, whichever pass reported them. | |
| 25 | 1 | def each(&) |
| 26 | 33 | @diagnostics.each_with_index.sort_by { |diagnostic, index| [diagnostic.line || 0, index] }.map(&:first).each(&) |
| 27 | end | |
| 28 | ||
| 29 | # The node, or the line, the diagnostic is about. | |
| 30 | 1 | def report(node, message) |
| 31 | 66 | @diagnostics << Diagnostic.new(path: @path, line: line_of(node), message:) |
| 32 | end | |
| 33 | ||
| 34 | 1 | def refuse(node, message) |
| 35 | 15 | raise Phlex::Compiler::Error, Diagnostic.new(path: @path, line: line_of(node), message:).to_s if @strict |
| 36 | ||
| 37 | 5 | report(node, message) |
| 38 | end | |
| 39 | ||
| 40 | 1 | private def line_of(node) |
| 41 | 76 | (Integer === node) ? node : node&.start_linereceiver never nil |
| 42 | end | |
| 43 | end |