Skip to content
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