Skip to content

Commit

Permalink
fix: fix unary operators in pipes (fixes #128)
Browse files Browse the repository at this point in the history
  • Loading branch information
saveman71 authored and novaugust committed Jan 26, 2024
1 parent 012bcd0 commit 7af0397
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/style/pipes.ex
Original file line number Diff line number Diff line change
Expand Up @@ -143,17 +143,24 @@ defmodule Styler.Style.Pipes do
quote do: {:|>, _, [{:|>, _, [unquote(a), unquote(b)]}, unquote(c)]}
end

# Unary operators needs to be expanded (#128)
defp maybe_wrap_unary({op, meta, []}) when op in ~w(- +)a,
do: {{:., meta, [{:__aliases__, meta, [:Kernel]}, op]}, meta, []}

defp maybe_wrap_unary(lhs), do: lhs

# a |> fun => a |> fun()
defp fix_pipe({:|>, m, [lhs, {fun, m2, nil}]}), do: {:|>, m, [lhs, {fun, m2, []}]}
# a |> then(&fun/1) |> c => a |> fun() |> c()
defp fix_pipe({:|>, m, [lhs, {:then, _, [{:&, _, [{:/, _, [{fun, m2, _}, _]}]}]}]}), do: {:|>, m, [lhs, {fun, m2, []}]}
# a |> then(&fun(&1, d)) |> c => a |> fun(d) |> c()
defp fix_pipe({:|>, m, [lhs, {:then, _, [{:&, _, [{fun, m2, [{:&, _, _} | args]}]}]}]} = pipe) do
rewrite = {fun, m2, args}

# if `&1` is referenced more than once, we have to continue using `then`
if rewrite |> Zipper.zip() |> Zipper.any?(&match?({:&, _, _}, &1)),
do: pipe,
else: {:|>, m, [lhs, rewrite]}
else: {:|>, m, [lhs, maybe_wrap_unary(rewrite)]}
end

# Credo.Check.Readability.PipeIntoAnonymousFunctions
Expand Down
4 changes: 4 additions & 0 deletions test/style/pipes_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,10 @@ defmodule Styler.Style.PipesTest do
assert_style "a |> then(&fun(&1)) |> c", "a |> fun() |> c()"
assert_style "a |> then(&fun(&1, d)) |> c", "a |> fun(d) |> c()"

# Unary operators
assert_style "a |> then(&(-&1)) |> c", "a |> Kernel.-() |> c()"
assert_style "a |> then(&(+&1)) |> c", "a |> Kernel.+() |> c()"

assert_style "a |> then(&fun(d, &1)) |> c()"
assert_style "a |> then(&fun(&1, d, %{foo: &1})) |> c()"
end
Expand Down

0 comments on commit 7af0397

Please sign in to comment.