Skip to content

Commit

Permalink
fix infinite loop rewriting negated if with empty do body. closes #196
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Sep 23, 2024
1 parent f2b269e commit d6c90cd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ they can and will change without that change being reflected in Styler's semanti
### Fixes

* `pipes`: optimizations reducing 2 pipes to 1 no longer squeeze all pipes onto one line (#180)
* `if`: fix infinite loop rewriting negated if with empty do body `if x != y, do: (), else: :ok` (#196, h/t @itamm15)

## 1.0.0

Expand Down
4 changes: 4 additions & 0 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@ defmodule Styler.Style.Blocks do
[negator, [do_block]] when is_negator(negator) ->
zipper |> Zipper.replace({:unless, m, [invert(negator), [do_block]]}) |> run(ctx)

# drop `else end`
[head, [do_block, {_, {:__block__, _, []}}]] ->
{:cont, Zipper.replace(zipper, {:if, m, [head, [do_block]]}), ctx}

# drop `else: nil`
[head, [do_block, {_, {:__block__, _, [nil]}}]] ->
{:cont, Zipper.replace(zipper, {:if, m, [head, [do_block]]}), ctx}
Expand Down
18 changes: 18 additions & 0 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,24 @@ defmodule Styler.Style.BlocksTest do
assert_style("if !!x, do: y", "if x, do: y")
end

test "regression: negation with empty do body" do
assert_style(
"""
if a != b do
# comment
else
:ok
end
""",
"""
if a == b do
# comment
:ok
end
"""
)
end

test "Credo.Check.Refactor.UnlessWithElse" do
for negator <- ["!", "not "] do
assert_style(
Expand Down

0 comments on commit d6c90cd

Please sign in to comment.