Skip to content

unless rewrites: don't use Kernel.! in conditions in the head #13857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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