Skip to content

Commit 67c3ad5

Browse files
committed
Add brackets around keyword lists when formatting with when, closes #13503
1 parent 883e0c2 commit 67c3ad5

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/elixir/lib/code/formatter.ex

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1966,6 +1966,14 @@ defmodule Code.Formatter do
19661966
# fn a, b, c when d -> e end
19671967
defp clause_args_to_algebra([{:when, meta, args}], state) do
19681968
{args, right} = split_last(args)
1969+
1970+
# If there are any keywords, wrap them in lists
1971+
args =
1972+
Enum.map(args, fn
1973+
[_ | _] = keyword -> {:__block__, [], [keyword]}
1974+
other -> other
1975+
end)
1976+
19691977
left = {{:special, :clause_args}, meta, [args]}
19701978
binary_op_to_algebra(:when, "when", meta, left, right, :no_parens_arg, state)
19711979
end

lib/elixir/test/elixir/code_formatter/general_test.exs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,28 @@ defmodule Code.Formatter.GeneralTest do
296296
assert_same code, @short_length
297297
end
298298

299+
test "keeps parens if argument includes keyword list" do
300+
assert_same """
301+
fn [] when is_integer(x) ->
302+
x + 42
303+
end
304+
"""
305+
306+
bad = """
307+
fn (input: x) when is_integer(x) ->
308+
x + 42
309+
end
310+
"""
311+
312+
good = """
313+
fn [input: x] when is_integer(x) ->
314+
x + 42
315+
end
316+
"""
317+
318+
assert_format bad, good
319+
end
320+
299321
test "with a single clause, followed by a newline, and can fit in one line" do
300322
assert_same """
301323
fn

0 commit comments

Comments
 (0)