Skip to content

Commit 5e15f2e

Browse files
committed
Merge pull request #4072 from lexmag/non-keywords-access
Raise when Access syntax used on non-keywords
2 parents d9356c3 + f440374 commit 5e15f2e

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/elixir/lib/access.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ defmodule Access do
5353
:maps.find(key, map)
5454
end
5555

56-
def fetch(list, key) when is_list(list) do
56+
def fetch(list, key) when is_list(list) and is_atom(key) do
5757
case :lists.keyfind(key, 1, list) do
5858
{^key, value} -> {:ok, value}
5959
false -> :error

lib/elixir/test/elixir/access_test.exs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ defmodule AccessTest do
2121

2222
test "for nil" do
2323
assert nil[:foo] == nil
24+
assert Access.fetch(nil, :foo) == :error
2425
assert Access.get(nil, :foo) == nil
2526
assert_raise ArgumentError, "could not put/update key :foo on a nil value", fn ->
2627
Access.get_and_update(nil, :foo, fn nil -> {:ok, :bar} end)
@@ -32,6 +33,13 @@ defmodule AccessTest do
3233
assert [foo: [bar: :baz]][:foo][:bar] == :baz
3334
assert [foo: [bar: :baz]][:fuu][:bar] == nil
3435

36+
assert Access.fetch([foo: :bar], :foo) == {:ok, :bar}
37+
assert Access.fetch([foo: :bar], :bar) == :error
38+
39+
assert_raise FunctionClauseError, fn ->
40+
Access.fetch([{"foo", :bar}], "foo")
41+
end
42+
3543
assert Access.get([foo: :bar], :foo) == :bar
3644
assert Access.get_and_update([], :foo, fn nil -> {:ok, :baz} end) == {:ok, [foo: :baz]}
3745
assert Access.get_and_update([foo: :bar], :foo, fn :bar -> {:ok, :baz} end) == {:ok, [foo: :baz]}
@@ -43,6 +51,9 @@ defmodule AccessTest do
4351
assert %{1.0 => 1.0}[1.0] == 1.0
4452
assert %{1 => 1}[1.0] == nil
4553

54+
assert Access.fetch(%{foo: :bar}, :foo) == {:ok, :bar}
55+
assert Access.fetch(%{foo: :bar}, :bar) == :error
56+
4657
assert Access.get(%{foo: :bar}, :foo) == :bar
4758
assert Access.get_and_update(%{}, :foo, fn nil -> {:ok, :baz} end) == {:ok, %{foo: :baz}}
4859
assert Access.get_and_update(%{foo: :bar}, :foo, fn :bar -> {:ok, :baz} end) == {:ok, %{foo: :baz}}

0 commit comments

Comments
 (0)