Current section

Files

Jump to
minipeg lib minipeg formatter.ex
Raw

lib/minipeg/formatter.ex

defmodule Minipeg.Formatter do
use Minipeg.Types
alias Minipeg.{Failure, Input, Success}
@moduledoc ~S"""
Utility for using with the function form of the `debug` combinator.
"""
@typep format_t :: :short | :medium | :long
@typep subject_t :: result_t() | Input.t | {Input.t, result_t()}
@spec fmt(format_t(), subject_t(), name_t?()) :: binary()
def fmt(type, subject, label \\ nil)
def fmt(type, {input, result}, label) do
prefix = if label, do: [label], else: []
prefix ++ [
fmt(type, input, nil), fmt(type, result, nil)
] |> Enum.join("\n")
end
def fmt(type, %Failure{} = failure, label), do: _fmt_failure(type, failure, label)
def fmt(type, %Input{} = input, label), do: _fmt_input(type, input, label)
def fmt(type, %Success{} = success, label), do: _fmt_success(type, success, label)
def format(type, label \\ nil) do
&fmt(type, {&1, &2}, label)
end
@spec _fmt_failure(format_t(), Failure.t, name_t?()) :: binary()
defp _fmt_failure(type, failure, label)
defp _fmt_failure(:short, %Failure{reason: reason}, label) do
[_labelled("Failure", label), reason] |> Enum.join
end
# defp _fmt_failure(:medium, failure, label) do
# raise "Not yet implemented"
# end
# defp _fmt_failure(:long, failure, label) do
# raise "Not yet implemented"
# end
@spec _fmt_input(format_t(), Input.t, name_t?()) :: binary()
defp _fmt_input(type, input, label)
defp _fmt_input(:short, %Input{} = input, label) do
[_labelled("Input", label), input.col, ",", input.lnb, ">", input.input] |> Enum.join
end
# defp _fmt_input(:medium, input, label) do
# raise "Not yet implemented"
# end
# defp _fmt_input(:long, input, label) do
# raise "Not yet implemented"
# end
@spec _fmt_success(format_t(), Success.t, name_t?()) :: binary()
defp _fmt_success(type, success, label)
defp _fmt_success(:short, %Success{ast: ast}, label) do
[_labelled("Success", label), inspect(ast)] |> Enum.join
end
# defp _fmt_success(:medium, success, label) do
# raise "Not yet implemented"
# end
# defp _fmt_success(:long, success, label) do
# raise "Not yet implemented"
# end
@spec _labelled(binary(), name_t?()) :: binary()
defp _labelled(origin, label)
defp _labelled(origin, nil), do: "#{origin}: "
defp _labelled(origin, label), do: "#{origin}(#{label}): "
end
# SPDX-License-Identifier: Apache-2.0