Skip to content

Commit c3b9344

Browse files
committed
Code.get_docs/2: check for valid doc kind in public function, not in private
This was giving me a long cryptic message because we were checking for a valid kind way to far. I have renamed the attribute to @doc_kinds instead of @doc_sections Corrected kinds for :all option Mention that no valid module returns nil, and created a doctest example.
1 parent 912c461 commit c3b9344

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

lib/elixir/lib/code.ex

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,10 @@ defmodule Code do
588588
* `:type_docs` - list of all docstrings attached to
589589
`@type` callbacks using the `@typedoc` attribute
590590
591-
* `:all` - a keyword list with both `:docs` and `:moduledoc`
591+
* `:all` - a keyword list with `:docs` and `:moduledoc`, `:callback_docs`,
592+
and `:type_docs`.
593+
594+
If the module cannot be found, it returns `nil`.
592595
593596
## Examples
594597
@@ -598,8 +601,14 @@ defmodule Code do
598601
iex> String.split(text, "\n") |> Enum.at(0)
599602
"Converts an atom to a char list."
600603
604+
# Module doesn't exist
605+
iex> docs = Code.get_docs(ModuleNotGood, :all)
606+
nil
607+
601608
"""
602-
def get_docs(module, kind) when is_atom(module) do
609+
@doc_kinds [:docs, :moduledoc, :callback_docs, :type_docs, :all]
610+
611+
def get_docs(module, kind) when is_atom(module) and kind in @doc_kinds do
603612
case :code.get_object_code(module) do
604613
{_module, bin, _beam_path} ->
605614
do_get_docs(bin, kind)
@@ -608,7 +617,7 @@ defmodule Code do
608617
end
609618
end
610619

611-
def get_docs(binpath, kind) when is_binary(binpath) do
620+
def get_docs(binpath, kind) when is_binary(binpath) and kind in @doc_kinds do
612621
do_get_docs(String.to_char_list(binpath), kind)
613622
end
614623

@@ -629,10 +638,8 @@ defmodule Code do
629638
# unsupported chunk version
630639
defp lookup_docs(_, _), do: nil
631640

632-
@doc_sections [:docs, :moduledoc, :callback_docs, :type_docs]
633-
634641
defp do_lookup_docs(docs, :all), do: docs
635-
defp do_lookup_docs(docs, kind) when kind in @doc_sections,
642+
defp do_lookup_docs(docs, kind),
636643
do: Keyword.get(docs, kind)
637644

638645
## Helpers

0 commit comments

Comments
 (0)