Skip to content

Commit 04c5c80

Browse files
author
José Valim
committed
Merge pull request #1733 from meh/inspect-raise
Add validity checking for Inspect.Algebra documents
2 parents 1cb8f3a + 7b025dd commit 04c5c80

File tree

1 file changed

+51
-5
lines changed

1 file changed

+51
-5
lines changed

lib/elixir/lib/inspect/algebra.ex

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,22 @@ defmodule Inspect.Algebra do
107107
108108
"""
109109
@spec concat(t, t) :: doc_cons_t
110-
def concat(x, y), do: doc_cons(left: x, right: y)
110+
def concat(x, y) do
111+
verify!(x)
112+
verify!(y)
113+
114+
doc_cons(left: x, right: y)
115+
end
111116

112117
@doc """
113118
Concatenates a list of documents.
114119
"""
115120
@spec concat([t]) :: doc_cons_t
116-
def concat(docs), do: folddoc(docs, &concat(&1, &2))
121+
def concat(docs) do
122+
Enum.each docs, &verify!(&1)
123+
124+
folddoc(docs, &concat(&1, &2))
125+
end
117126
118127
@doc """
119128
Nests document entity `x` positions deep. Nesting will be
@@ -127,8 +136,17 @@ defmodule Inspect.Algebra do
127136
128137
"""
129138
@spec nest(t, non_neg_integer) :: doc_nest_t
130-
def nest(x, 0), do: x
131-
def nest(x, i) when is_integer(i), do: doc_nest(indent: i, doc: x)
139+
def nest(x, 0) do
140+
verify!(x)
141+
142+
x
143+
end
144+
145+
def nest(x, i) when is_integer(i) do
146+
verify!(x)
147+
148+
doc_nest(indent: i, doc: x)
149+
end
132150
133151
@doc %S"""
134152
Document entity representing a break. This break can
@@ -198,7 +216,11 @@ defmodule Inspect.Algebra do
198216

199217
"""
200218
@spec group(t) :: doc_group_t
201-
def group(d), do: doc_group(doc: d)
219+
def group(d) do
220+
verify!(d)
221+
222+
doc_group(doc: d)
223+
end
202224

203225
@doc """
204226
Inserts a mandatory single space between two document entities.
@@ -387,4 +409,28 @@ defmodule Inspect.Algebra do
387409
prefix = repeat " ", i
388410
[@newline | [prefix | do_render d]]
389411
end
412+
413+
defp verify!(doc) do
414+
case verify(doc) do
415+
:ok ->
416+
:ok
417+
418+
_ ->
419+
raise ArgumentError, message: "invalid document type"
420+
end
421+
end
422+
423+
defp verify(doc) when doc |> is_binary or
424+
doc |> is_integer or
425+
doc == :doc_nil or
426+
doc |> is_record(:doc_cons) or
427+
doc |> is_record(:doc_nest) or
428+
doc |> is_record(:doc_break) or
429+
doc |> is_record(:doc_group) do
430+
:ok
431+
end
432+
433+
defp verify(v) do
434+
{ :error, { :invalid_doc, v } }
435+
end
390436
end

0 commit comments

Comments
 (0)