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.
111class Phlex::Compiler::Diagnostics
121 include Enumerable
13
141 Diagnostic = Data.define(:path, :line, :message) do
151 def to_s = "#{path}:#{line}: #{message}"
16 end
17
181 def initialize(path, strict: true)
19189 @path = path
20189 @strict = strict
21189 @diagnostics = []
22 end
23
24 # In file order, whichever pass reported them.
251 def each(&)
2633 @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.
301 def report(node, message)
3166 @diagnostics << Diagnostic.new(path: @path, line: line_of(node), message:)
32 end
33
341 def refuse(node, message)
3515 raise Phlex::Compiler::Error, Diagnostic.new(path: @path, line: line_of(node), message:).to_s if @strict
36
375 report(node, message)
38 end
39
401 private def line_of(node)
4176 (Integer === node) ? node : node&.start_linereceiver never nil
42 end
43end