diff --git a/lib/elixir/lib/kernel.ex b/lib/elixir/lib/kernel.ex index 44bad71893..184d2a2572 100644 --- a/lib/elixir/lib/kernel.ex +++ b/lib/elixir/lib/kernel.ex @@ -4128,6 +4128,9 @@ defmodule Kernel do and right lists don't match, destructuring simply stops instead of raising an error. + An explicit tail in the left-hand list, such as `[head | tail]`, raises + an `ArgumentError` at compile time. + ## Examples iex> destructure([x, y, z], [1, 2, 3, 4, 5]) @@ -4142,8 +4145,7 @@ defmodule Kernel do iex> {x, y, z} {1, nil, nil} - The left-hand side supports any expression you would use - on the left-hand side of a match: + Each element of the left-hand list can be any pattern: iex> x = 1 iex> destructure([^x, y, z], [1, 2, 3]) @@ -4155,6 +4157,14 @@ defmodule Kernel do do). """ defmacro destructure(left, right) when is_list(left) do + case :lists.reverse(left) do + [{:|, _, [_, _]} | _] -> + raise ArgumentError, "destructure/2 does not support a tail in the left-hand list" + + _ -> + :ok + end + quote do unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left))) end diff --git a/lib/elixir/test/elixir/kernel_test.exs b/lib/elixir/test/elixir/kernel_test.exs index 4470e29e9f..273c97436a 100644 --- a/lib/elixir/test/elixir/kernel_test.exs +++ b/lib/elixir/test/elixir/kernel_test.exs @@ -1238,6 +1238,14 @@ defmodule KernelTest do end describe "destructure" do + test "rejects a top-level cons pattern" do + assert_raise ArgumentError, + "destructure/2 does not support a tail in the left-hand list", + fn -> + Macro.expand_once(quote(do: destructure([a, b | tail], [1, 2, 3])), __ENV__) + end + end + test "less args" do destructure [x, y, z], [1, 2, 3, 4, 5] assert x == 1