Skip to content

Commit 2a25d4e

Browse files
authored
migrate_unless: don't use |> Kernel.!() in conditions in the head (#13857)
1 parent dcf31be commit 2a25d4e

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/elixir/lib/code/formatter.ex

+16-1
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,22 @@ defmodule Code.Formatter do
506506
quoted_to_algebra({:if, meta, [negate_condition(condition), block]}, context, state)
507507
end
508508

509+
# a |> b() |> unless(...) => a |> b() |> Kernel.!() |> unless(...)
510+
defp quoted_to_algebra(
511+
{:|>, meta1, [{:|>, _, _} = condition, {:unless, meta2, [block]}]},
512+
context,
513+
%{migrate_unless: true} = state
514+
) do
515+
negated_condition = {:|>, [], [condition, {{:., [], [Kernel, :!]}, [closing: []], []}]}
516+
517+
quoted_to_algebra(
518+
{:|>, meta1, [negated_condition, {:if, meta2, [block]}]},
519+
context,
520+
state
521+
)
522+
end
523+
524+
# condition |> unless(...) => negated(condition) |> unless(...)
509525
defp quoted_to_algebra(
510526
{:|>, meta1, [condition, {:unless, meta2, [block]}]},
511527
context,
@@ -2516,7 +2532,6 @@ defmodule Code.Formatter do
25162532
defp negate_condition(condition) do
25172533
case condition do
25182534
{neg, _, [condition]} when neg in [:!, :not] -> condition
2519-
{:|>, _, _} -> {:|>, [], [condition, {{:., [], [Kernel, :!]}, [closing: []], []}]}
25202535
{op, _, [_, _]} when op in @bool_operators -> {:not, [], [condition]}
25212536
{guard, _, [_ | _]} when guard in @guards -> {:not, [], [condition]}
25222537
{:==, meta, [left, right]} -> {:!=, meta, [left, right]}

lib/elixir/test/elixir/code_formatter/migration_test.exs

+5
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,11 @@ defmodule Code.Formatter.MigrationTest do
242242
good = "x |> foo() |> Kernel.!() |> if(do: y)"
243243

244244
assert_format bad, good, @opts
245+
246+
bad = "unless x |> foo(), do: y"
247+
good = "if !(x |> foo()), do: y"
248+
249+
assert_format bad, good, @opts
245250
end
246251

247252
test "rewrites in as not in" do

0 commit comments

Comments
 (0)