Skip to content
Open
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
73 changes: 45 additions & 28 deletions lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2485,12 +2485,12 @@ defmodule Kernel do
Creates and updates a struct.

The `struct` argument may be an atom (which defines `defstruct`)
or a `struct` itself. The second argument is any `Enumerable` that
emits two-element tuples (key-value pairs) during enumeration.
or a `struct` itself. The second argument is a keyword list of
fields. Passing any other enumerable is deprecated.

Keys in the `Enumerable` that don't exist in the struct are automatically
Keys in the list that don't exist in the struct are automatically
discarded. Note that keys must be atoms, as only atoms are allowed when
defining a struct. If there are duplicate keys in the `Enumerable`, the last
defining a struct. If there are duplicate keys in the list, the last
entry will be taken (same behavior as `Map.new/1`).

This function is useful for dynamically creating and updating structs, as
Expand All @@ -2514,17 +2514,27 @@ defmodule Kernel do
struct(user, unknown: "value")
#=> %User{name: "meg"}

struct(User, %{name: "meg"})
struct(User, Map.to_list(%{name: "meg"}))
#=> %User{name: "meg"}

# String keys are ignored
struct(User, %{"name" => "meg"})
#=> %User{name: "john"}

"""
@spec struct(module | struct, Enumerable.t()) :: struct
def struct(struct, fields \\ []) do
struct(struct, fields, fn
@spec struct(module | struct, keyword()) :: struct
def struct(struct, fields \\ [])

def struct(struct, []) when is_atom(struct) do
validate_struct!(struct.__struct__(), struct, 0)
end

def struct(struct, fields) when is_atom(struct) do
struct(validate_struct!(struct.__struct__(), struct, 0), fields)
end

def struct(%_{} = struct, fields) do
with false <- is_list(fields) do
warn_on_non_list_fields(:struct)
end

Enum.reduce(fields, struct, fn
{:__struct__, _val}, acc ->
acc

Expand Down Expand Up @@ -2553,15 +2563,24 @@ defmodule Kernel do
function will check if every given key-value belongs to the struct.

"""
@spec struct!(module | struct, Enumerable.t()) :: struct
@spec struct!(module | struct, keyword()) :: struct
def struct!(struct, fields \\ [])

def struct!(struct, fields) when is_atom(struct) do
def struct!(struct, fields) when is_atom(struct) and is_list(fields) do
validate_struct!(struct.__struct__(fields), struct, 1)
end

def struct!(struct, fields) when is_atom(struct) do
warn_on_non_list_fields(:struct!)
validate_struct!(struct.__struct__(Enum.to_list(fields)), struct, 1)
end

def struct!(struct, fields) when is_map(struct) do
struct(struct, fields, fn
with false <- is_list(fields) do
warn_on_non_list_fields(:struct!)
end

Enum.reduce(fields, struct, fn
{:__struct__, _}, acc ->
acc

Expand All @@ -2570,20 +2589,18 @@ defmodule Kernel do
end)
end

defp struct(struct, [], _fun) when is_atom(struct) do
validate_struct!(struct.__struct__(), struct, 0)
end

defp struct(struct, fields, fun) when is_atom(struct) do
struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun)
end

defp struct(%_{} = struct, [], _fun) do
struct
end
# TODO: Remove me on v2.0
defp warn_on_non_list_fields(fun) do
IO.warn_once(
{__MODULE__, fun},
fn ->
"passing a non-list as fields to #{fun}/2 is deprecated, " <>
"please pass a keyword list instead (for example, using Enum.to_list/1)"
end,
_stacktrace_drop_levels = 4
)

defp struct(%_{} = struct, fields, fun) do
Enum.reduce(fields, struct, fun)
:ok
end

defp validate_struct!(%{__struct__: module} = struct, module, _arity) do
Expand Down
47 changes: 20 additions & 27 deletions lib/elixir/lib/kernel/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -167,34 +167,27 @@ defmodule Kernel.Utils do
escaped_struct = :elixir_quote.escape(struct, {:struct, module}, false)

body =
case bootstrapped? do
case bootstrapped? and enforce_keys != [] do
true ->
case enforce_keys do
[] ->
quote line: 0, generated: true do
Enum.reduce(kv, unquote(escaped_struct), fn {key, val}, map ->
%{map | key => val}
end)
end

_ ->
quote line: 0, generated: true do
{map, keys} =
Enum.reduce(kv, {unquote(escaped_struct), unquote(enforce_keys)}, fn
{key, val}, {map, keys} ->
{%{map | key => val}, List.delete(keys, key)}
end)

case keys do
[] ->
map

_ ->
raise ArgumentError,
"the following keys must also be given when building " <>
"struct #{inspect(__MODULE__)}: #{inspect(keys)}"
end
end
quote line: 0, generated: true do
{map, keys} =
:lists.foldl(
fn {key, val}, {map, keys} ->
{%{map | key => val}, :lists.delete(key, keys)}
end,
{unquote(escaped_struct), unquote(enforce_keys)},
kv
)

case keys do
[] ->
map

_ ->
raise ArgumentError,
"the following keys must also be given when building " <>
"struct #{inspect(__MODULE__)}: #{inspect(keys)}"
end
end

false ->
Expand Down
26 changes: 23 additions & 3 deletions lib/elixir/test/elixir/kernel_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,10 @@ defmodule KernelTest do

user = struct(User, name: "meg")
assert user == %User{name: "meg"}
assert struct(user, %{name: "meg"}) == user
assert struct(user, name: "meg") == user

assert struct(user, unknown: "key") == user
assert struct(user, %{name: "john"}) == %User{name: "john"}
assert struct(user, name: "john") == %User{name: "john"}
assert struct(user, name: "other", __struct__: Post) == %User{name: "other"}
end

Expand All @@ -201,10 +201,30 @@ defmodule KernelTest do
struct!(user, unknown: "key")
end

assert struct!(user, %{name: "john"}) == %User{name: "john"}
assert struct!(user, name: "john") == %User{name: "john"}
assert struct!(user, name: "other", __struct__: Post) == %User{name: "other"}
end

test "struct/2 and struct!/2 with non-list fields (deprecated)" do
user = %User{name: "meg"}

assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
assert struct(User, %{name: "meg"}) == user
end) =~ "passing a non-list as fields to struct/2 is deprecated"

assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
assert struct(user, %{name: "john"}) == %User{name: "john"}
end) =~ "passing a non-list as fields to struct/2 is deprecated"

assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
assert struct!(User, %{name: "meg"}) == user
end) =~ "passing a non-list as fields to struct!/2 is deprecated"

assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
assert struct!(user, %{name: "john"}) == %User{name: "john"}
end) =~ "passing a non-list as fields to struct!/2 is deprecated"
end

test "if/2 with invalid keys" do
error_message =
"invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted"
Expand Down
Loading