From 19015ab29d0648f26f9e2b492db05797658790c1 Mon Sep 17 00:00:00 2001 From: Matt Enlow Date: Sun, 12 Nov 2023 08:11:11 -0700 Subject: [PATCH] with statement: drop singleton identity else. closes #84 --- lib/style/blocks.ex | 12 ++++++++++-- test/style/blocks_test.exs | 21 +++++++++++++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/style/blocks.ex b/lib/style/blocks.ex index 8387c818..4f3a0fc3 100644 --- a/lib/style/blocks.ex +++ b/lib/style/blocks.ex @@ -88,15 +88,23 @@ defmodule Styler.Style.Blocks do do: {rest, [rhs]}, else: {reversed_clauses, Enum.reverse(postroll, [do_body])} - do_else = [{do_block, {:__block__, do_body_meta, do_body}} | elses] + # drop singleton identity else clauses like `else foo -> foo end` + new_elses = + case elses do + [{{_, _, [:else]}, [{:->, _, [[left], right]}]}] -> if nodes_equivalent?(left, right), do: [], else: elses + _ -> elses + end + + do_else = [{do_block, {:__block__, do_body_meta, do_body}} | new_elses] children = Enum.reverse(reversed_clauses, [do_else]) # only rewrite if it needs rewriting! + # can probably stop optimizing like this once we handle comments nicely cond do Enum.any?(preroll) -> {:__block__, m, preroll ++ [{:with, m, children}]} - rewrite_body? or Enum.any?(postroll) -> + rewrite_body? or Enum.any?(postroll) or new_elses != elses -> {:with, m, children} true -> diff --git a/test/style/blocks_test.exs b/test/style/blocks_test.exs index cd9fc29e..355812c8 100644 --- a/test/style/blocks_test.exs +++ b/test/style/blocks_test.exs @@ -117,6 +117,23 @@ defmodule Styler.Style.BlocksTest do """) end + test "removes identity else clauses" do + assert_style( + """ + with :ok <- b(), :ok <- b() do + :ok + else + :what -> :what + end + """, + """ + with :ok <- b(), :ok <- b() do + :ok + end + """ + ) + end + test "Credo.Check.Readability.WithSingleClause" do assert_style( """ @@ -164,8 +181,6 @@ defmodule Styler.Style.BlocksTest do a = bop boop :horay! - else - :error -> :error end """ ) @@ -183,8 +198,6 @@ defmodule Styler.Style.BlocksTest do a = bop boop :horay! - else - :error -> :error end """ )