Skip to content

Commit

Permalink
rewrite pipechains ending in blocks with one or two pipes
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jan 25, 2025
1 parent fc71aee commit baf02ab
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/style/pipes.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,15 @@ defmodule Styler.Style.Pipes do
case fix_pipe_start(zipper) do
{{:|>, _, _}, _} = zipper ->
case Zipper.traverse(zipper, fn {node, meta} -> {fix_pipe(node), meta} end) do
{{:|>, _, [{:|>, _, _}, _]}, _} = chain_zipper ->
# a |> f(...args) |> block(do ... end)
# =>
# block f(a, ...args) do ... end
{{:|>, _, [{:|>, _, [a, {f, fm, args}]}, {b, bm, [[{{:__block__, dm, [:do]}, _} | _]] = ba}]}, _} = blockz ->
{:cont, Zipper.replace(blockz, {b, bm, [Style.set_line({f, fm, [a | args]}, dm[:line]) | ba]}), ctx}

{{:|>, _, [{:|>,_, x}, _]}, _} = chain_zipper ->
IO.puts "chaining it up"
dbg(x)
{:cont, find_pipe_start(chain_zipper), ctx}

# don't un-pipe into unquotes, as some expressions are only valid as pipes
Expand Down
66 changes: 66 additions & 0 deletions test/style/pipes_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,72 @@ defmodule Styler.Style.PipesTest do
)
end

test "block extraction: optimize the pipe!" do
assert_style("""
foo
|> case do
nil -> nil
end
""",
"""
case foo do
nil -> nil
end
""")

assert_style("""
foo
|> bar(baz)
|> case do
nil -> nil
end
""",
"""
case bar(foo, baz) do
nil -> nil
end
""")

assert_style("""
foo
|> bar(baz)
|> if do
:horay
else
:boo
end
""",
"""
if bar(foo, baz) do
:horay
else
:boo
end
""")
end

test "do block in the middle of a chain" do

Check failure on line 215 in test/style/pipes_test.exs

View workflow job for this annotation

GitHub Actions / Ex1.15.8/OTP25.3.2

test block pipe starts do block in the middle of a chain (Styler.Style.PipesTest)

Check failure on line 215 in test/style/pipes_test.exs

View workflow job for this annotation

GitHub Actions / Ex1.16.3/OTP25.3.2

test block pipe starts do block in the middle of a chain (Styler.Style.PipesTest)

Check failure on line 215 in test/style/pipes_test.exs

View workflow job for this annotation

GitHub Actions / Ex1.17.3/OTP25.3.2

test block pipe starts do block in the middle of a chain (Styler.Style.PipesTest)
assert_style("""
foo
|> bar(baz)
|> case(do
nil -> nil
end)
|> bop()
|> nooo()
""",
"""
case_result =
case bar(foo, baz) do
nil -> nil
end
case_result
|> bop()
|> nooo()
""")
end

test "macro with arg and do block" do
assert_style("""
"baz"
Expand Down

0 comments on commit baf02ab

Please sign in to comment.