Skip to content

Commit 952ce9b

Browse files
committed
raise compile error when inspect protocol options don't match struct
1 parent 549a867 commit 952ce9b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/elixir/lib/inspect.ex

Lines changed: 12 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, __CALLER__)
459+
:ok = validate_option(except, fields, module, __CALLER__)
460+
458461
filtered_fields =
459462
fields
460463
|> Enum.reject(&(&1 in except))
@@ -478,6 +481,15 @@ defimpl Inspect, for: Any do
478481
end
479482
end
480483

484+
defp validate_option(option_list, fields, module, caller) do
485+
if not Enum.empty?(option_list -- fields) do
486+
description = "When deriving inspect protocol of #{module}, values must match struct fields"
487+
raise CompileError, file: caller.file, line: caller.line, description: description
488+
end
489+
490+
:ok
491+
end
492+
481493
def inspect(%module{} = struct, opts) do
482494
try do
483495
module.__struct__()

lib/elixir/test/elixir/inspect_test.exs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,30 @@ 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+
message =
699+
~r"When deriving inspect protocol of Elixir.Inspect.MapTest.StructMissingFieldsInOnlyOption, values must match struct fields"
700+
701+
assert_raise CompileError, message, fn ->
702+
defmodule StructMissingFieldsInOnlyOption do
703+
@derive {Inspect, only: [:c]}
704+
defstruct [:a, :b]
705+
end
706+
end
707+
end
708+
709+
test "struct missing fields in the :except option" do
710+
message =
711+
~r"When deriving inspect protocol of Elixir.Inspect.MapTest.StructMissingFieldsInExceptOption, values must match struct fields"
712+
713+
assert_raise CompileError, message, fn ->
714+
defmodule StructMissingFieldsInExceptOption do
715+
@derive {Inspect, except: [:c]}
716+
defstruct [:a, :b]
717+
end
718+
end
719+
end
720+
697721
defmodule StructWithExceptOption do
698722
@derive {Inspect, except: [:b, :c]}
699723
defstruct [:a, :b, :c, :d]

0 commit comments

Comments
 (0)