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 1 commit
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
17 changes: 15 additions & 2 deletions lib/elixir/lib/exception.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1342,8 +1342,21 @@ 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
{module, _distance} =
Enum.map(:code.all_available(), fn {name, _, _} ->
{name, String.jaro_distance(to_string(module), to_string(name))}
end)
|> Enum.sort_by(&elem(&1, 1), :desc)
|> Enum.take(3)
|> Enum.find(fn {module, _distance} ->
module
|> to_string()
|> String.to_atom()
|> function_exported?(function, arity)
end)

". Did you mean:\n\n * #{Exception.format_mfa(String.to_existing_atom(to_string(module)), function, arity)}\n"
end

@doc false
Expand Down
8 changes: 8 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,14 @@ defmodule ExceptionTest do
assert message =~ "* set_cookie/2"
end

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

* Enum.map/2
"""
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