Skip to content

Improve UndefinedFunctionError for mis-cased module #12839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions lib/elixir/lib/exception.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1342,8 +1342,33 @@ defmodule UndefinedFunctionError do
hint_for_loaded_module(module, function, arity, nil)
end

defp hint(_module, _function, _arity, _loaded?) do
""
defp hint(module, function, arity, _loaded?) do
downcased_module = downcase_module_name(module)

candidate =
Enum.find(:code.all_available(), fn {name, _, _} ->
downcase_module_name(name) == downcased_module
end)

with {_, _, _} <- candidate,
{:module, module} <- load_module(candidate),
true <- function_exported?(module, function, arity) do
". Did you mean:\n\n * #{Exception.format_mfa(module, function, arity)}\n"
else
_ -> ""
end
end

defp load_module({name, _path, _loaded?}) do
name
|> List.to_atom()
|> Code.ensure_loaded()
end

defp downcase_module_name(module) do
module
|> to_string()
|> String.downcase(:ascii)
end

@doc false
Expand Down
11 changes: 11 additions & 0 deletions lib/elixir/test/elixir/exception_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,17 @@ defmodule ExceptionTest do
assert message =~ "* set_cookie/2"
end

test "annotates undefined function error with module suggestions" do
assert blame_message(ENUM, & &1.map(&1, 1)) == """
function ENUM.map/2 is undefined (module ENUM is not available). Did you mean:

* Enum.map/2
"""

assert blame_message(ENUM, & &1.not_a_function(&1, 1)) ==
"function ENUM.not_a_function/2 is undefined (module ENUM is not available)"
end

test "annotates undefined function clause error with macro hints" do
assert blame_message(Integer, & &1.is_odd(1)) ==
"function Integer.is_odd/1 is undefined or private. However, there is " <>
Expand Down