Skip to content

Commit

Permalink
fix: with replacement edge cases (#108)
Browse files Browse the repository at this point in the history
Closes #107
  • Loading branch information
novaugust committed Dec 12, 2023
1 parent ef5d1c6 commit f16b65c
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## main

### Fixes

* `with`: fix `with` replacement when it's the only child of a `do` or `->` block (Closes #107, h/t @kerryb -- turns out those edge cases _did_ exist in the wild!)

## v0.11.0

### Improvements
Expand Down
41 changes: 33 additions & 8 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -202,22 +202,47 @@ defmodule Styler.Style.Blocks do
# `a = b(); c = d(); :ok`
defp replace_with_statement(zipper, preroll) do
[[{_do, do_body} | _elses] | preroll] = Enum.reverse(preroll)
block = Enum.reverse(preroll, [do_body])

case Zipper.up(zipper) do
nil ->
Zipper.zip({:__block__, [], block})
# RedundantWithClauseResult except we rewrote the `<-` to an `=`
# with a, b, x <- y(), do: x
# =>
# a; b; y
block =
case preroll do
[{:=, _, [lhs, rhs]} | rest] ->
if nodes_equivalent?(lhs, do_body),
do: [rhs | rest],
else: [do_body | preroll]

_ ->
[do_body | preroll]
end

block = Enum.reverse(block)

case Zipper.up(zipper) do
# x = with a, b, c, do: d
# =>
# x =
# (
# a
# b
# c
# d
# )
# @TODO would be nice to changeto
# a
# b
# c
# x = d
{{:=, _, _}, _} ->
Zipper.update(zipper, fn {:with, meta, _} -> {:__block__, Keyword.take(meta, [:line]), block} end)

{{:__block__, _, _}, _} ->
_ ->
zipper
|> Style.ensure_block_parent()
|> Zipper.prepend_siblings(block)
|> Zipper.remove()

{ast, _} ->
raise "unexpected `with` parent ast: #{inspect(ast)}"
end
end

Expand Down
30 changes: 30 additions & 0 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,36 @@ defmodule Styler.Style.BlocksTest do
y()
"""
)

assert_style(
"""
def run() do
with value <- arg do
value
end
end
""",
"""
def run do
arg
end
"""
)

assert_style(
"""
fn ->
with value <- arg do
value
end
end
""",
"""
fn ->
arg
end
"""
)
end

test "doesn't false positive with vars" do
Expand Down

0 comments on commit f16b65c

Please sign in to comment.