Skip to content

raise compile error when inspect protocol options don't match struct #11801

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
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
14 changes: 14 additions & 0 deletions lib/elixir/lib/inspect.ex
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,9 @@ defimpl Inspect, for: Any do
only = Keyword.get(options, :only, fields)
except = Keyword.get(options, :except, [])

:ok = validate_option(only, fields, module)
:ok = validate_option(except, fields, module)

filtered_fields =
fields
|> Enum.reject(&(&1 in except))
Expand All @@ -478,6 +481,17 @@ defimpl Inspect, for: Any do
end
end

defp validate_option(option_list, fields, module) do
case option_list -- fields do
[] ->
:ok

unknown_fields ->
raise ArgumentError,
"unknown fields #{Kernel.inspect(unknown_fields)} given when deriving the Inspect protocol for #{Kernel.inspect(module)}. :only and :except values must match struct fields"
end
end

def inspect(%module{} = struct, opts) do
try do
module.__struct__()
Expand Down
22 changes: 22 additions & 0 deletions lib/elixir/test/elixir/inspect_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,28 @@ defmodule Inspect.MapTest do
"%Inspect.MapTest.StructWithAllFieldsInOnlyOption{\n a: 1,\n b: 2\n}"
end

test "struct missing fields in the :only option" do
assert_raise ArgumentError,
"unknown fields [:c] given when deriving the Inspect protocol for Inspect.MapTest.StructMissingFieldsInOnlyOption. :only and :except values must match struct fields",
fn ->
defmodule StructMissingFieldsInOnlyOption do
@derive {Inspect, only: [:c]}
defstruct [:a, :b]
end
end
end

test "struct missing fields in the :except option" do
assert_raise ArgumentError,
"unknown fields [:c, :d] given when deriving the Inspect protocol for Inspect.MapTest.StructMissingFieldsInExceptOption. :only and :except values must match struct fields",
fn ->
defmodule StructMissingFieldsInExceptOption do
@derive {Inspect, except: [:c, :d]}
defstruct [:a, :b]
end
end
end

defmodule StructWithExceptOption do
@derive {Inspect, except: [:b, :c]}
defstruct [:a, :b, :c, :d]
Expand Down