Skip to content

Fix infinite loop when dispatching protocols for %{__struct__: nil} #14313

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

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 2 additions & 0 deletions lib/elixir/lib/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,8 @@ defmodule Protocol do
end

# Internal handler for Structs
Kernel.defp(struct_impl_for(nil), do: unquote(any_impl_for))

Kernel.defp struct_impl_for(struct) do
case Code.ensure_compiled(Module.concat(__MODULE__, struct)) do
{:module, module} -> module
Expand Down
6 changes: 6 additions & 0 deletions lib/elixir/test/elixir/inspect_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,12 @@ defmodule Inspect.MapTest do
"%{__struct__: Inspect.MapTest.Private, key: 1}"
end

test "invalid struct" do
assert inspect(%{__struct__: nil}) == "%{__struct__: nil}"
assert inspect(%{__struct__: false}) == "%{__struct__: false}"
assert inspect(%{__struct__: "foo"}) == "%{__struct__: \"foo\"}"
end

defmodule Failing do
@enforce_keys [:name]
defstruct @enforce_keys
Expand Down
2 changes: 2 additions & 0 deletions lib/elixir/test/elixir/protocol_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ defmodule ProtocolTest do
assert is_nil(Sample.impl_for(self()))
assert is_nil(Sample.impl_for(hd(:erlang.ports())))
assert is_nil(Sample.impl_for(make_ref()))
assert is_nil(Sample.impl_for(%{__struct__: nil}))

assert Sample.impl_for(%ImplStruct{}) == Sample.ProtocolTest.ImplStruct
assert Sample.impl_for(%ImplStructExplicitFor{}) == Sample.ProtocolTest.ImplStructExplicitFor
Expand All @@ -117,6 +118,7 @@ defmodule ProtocolTest do
# Derived
assert WithAny.impl_for(%ImplStruct{}) == ProtocolTest.WithAny.ProtocolTest.ImplStruct
assert WithAny.impl_for(%{__struct__: "foo"}) == WithAny.Map
assert WithAny.impl_for(%{__struct__: nil}) == WithAny.Any
assert WithAny.impl_for(%{}) == WithAny.Map
assert WithAny.impl_for(self()) == WithAny.Any
end
Expand Down
Loading