Skip to content

Commit

Permalink
migrate_unless: don't use |> Kernel.!() in conditions in the head (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust authored Sep 24, 2024
1 parent dcf31be commit 2a25d4e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/elixir/lib/code/formatter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,22 @@ defmodule Code.Formatter do
quoted_to_algebra({:if, meta, [negate_condition(condition), block]}, context, state)
end

# a |> b() |> unless(...) => a |> b() |> Kernel.!() |> unless(...)
defp quoted_to_algebra(
{:|>, meta1, [{:|>, _, _} = condition, {:unless, meta2, [block]}]},
context,
%{migrate_unless: true} = state
) do
negated_condition = {:|>, [], [condition, {{:., [], [Kernel, :!]}, [closing: []], []}]}

quoted_to_algebra(
{:|>, meta1, [negated_condition, {:if, meta2, [block]}]},
context,
state
)
end

# condition |> unless(...) => negated(condition) |> unless(...)
defp quoted_to_algebra(
{:|>, meta1, [condition, {:unless, meta2, [block]}]},
context,
Expand Down Expand Up @@ -2516,7 +2532,6 @@ defmodule Code.Formatter do
defp negate_condition(condition) do
case condition do
{neg, _, [condition]} when neg in [:!, :not] -> condition
{:|>, _, _} -> {:|>, [], [condition, {{:., [], [Kernel, :!]}, [closing: []], []}]}
{op, _, [_, _]} when op in @bool_operators -> {:not, [], [condition]}
{guard, _, [_ | _]} when guard in @guards -> {:not, [], [condition]}
{:==, meta, [left, right]} -> {:!=, meta, [left, right]}
Expand Down
5 changes: 5 additions & 0 deletions lib/elixir/test/elixir/code_formatter/migration_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,11 @@ defmodule Code.Formatter.MigrationTest do
good = "x |> foo() |> Kernel.!() |> if(do: y)"

assert_format bad, good, @opts

bad = "unless x |> foo(), do: y"
good = "if !(x |> foo()), do: y"

assert_format bad, good, @opts
end

test "rewrites in as not in" do
Expand Down

0 comments on commit 2a25d4e

Please sign in to comment.