Skip to content

Commit 4d6c433

Browse files
authored
Raise ArgumentError when inspect protocol options don't match struct (#11801)
1 parent 60e7e09 commit 4d6c433

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/elixir/lib/inspect.ex

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,9 @@ defimpl Inspect, for: Any do
455455
only = Keyword.get(options, :only, fields)
456456
except = Keyword.get(options, :except, [])
457457

458+
:ok = validate_option(only, fields, module)
459+
:ok = validate_option(except, fields, module)
460+
458461
filtered_fields =
459462
fields
460463
|> Enum.reject(&(&1 in except))
@@ -478,6 +481,17 @@ defimpl Inspect, for: Any do
478481
end
479482
end
480483

484+
defp validate_option(option_list, fields, module) do
485+
case option_list -- fields do
486+
[] ->
487+
:ok
488+
489+
unknown_fields ->
490+
raise ArgumentError,
491+
"unknown fields #{Kernel.inspect(unknown_fields)} given when deriving the Inspect protocol for #{Kernel.inspect(module)}. :only and :except values must match struct fields"
492+
end
493+
end
494+
481495
def inspect(%module{} = struct, opts) do
482496
try do
483497
module.__struct__()

lib/elixir/test/elixir/inspect_test.exs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,28 @@ defmodule Inspect.MapTest do
694694
"%Inspect.MapTest.StructWithAllFieldsInOnlyOption{\n a: 1,\n b: 2\n}"
695695
end
696696

697+
test "struct missing fields in the :only option" do
698+
assert_raise ArgumentError,
699+
"unknown fields [:c] given when deriving the Inspect protocol for Inspect.MapTest.StructMissingFieldsInOnlyOption. :only and :except values must match struct fields",
700+
fn ->
701+
defmodule StructMissingFieldsInOnlyOption do
702+
@derive {Inspect, only: [:c]}
703+
defstruct [:a, :b]
704+
end
705+
end
706+
end
707+
708+
test "struct missing fields in the :except option" do
709+
assert_raise ArgumentError,
710+
"unknown fields [:c, :d] given when deriving the Inspect protocol for Inspect.MapTest.StructMissingFieldsInExceptOption. :only and :except values must match struct fields",
711+
fn ->
712+
defmodule StructMissingFieldsInExceptOption do
713+
@derive {Inspect, except: [:c, :d]}
714+
defstruct [:a, :b]
715+
end
716+
end
717+
end
718+
697719
defmodule StructWithExceptOption do
698720
@derive {Inspect, except: [:b, :c]}
699721
defstruct [:a, :b, :c, :d]

0 commit comments

Comments
 (0)