From b2f6363e79c3406a3e330748b6bf2a2cd5c66176 Mon Sep 17 00:00:00 2001 From: Matt Enlow Date: Tue, 9 May 2023 16:02:01 -0600 Subject: [PATCH] Rewrite case true/false to if else (`Credo.Check.Refactor.CaseTrivialMatches`) --- lib/style/simple.ex | 29 ++++++++++++++++ test/style/simple_test.exs | 69 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) diff --git a/lib/style/simple.ex b/lib/style/simple.ex index 7cfcc314..8618f7a2 100644 --- a/lib/style/simple.ex +++ b/lib/style/simple.ex @@ -55,8 +55,37 @@ defmodule Styler.Style.Simple do {:cont, Zipper.replace(zipper, {reverse, r_meta, [lhs, rhs]}), ctx} end + def run( + {{:case, _, + [ + head, + [{_, [{:->, _, [[{:__block__, _, [true]}], true_body]}, {:->, _, [[{:__block__, _, [false]}], false_body]}]}] + ]}, _} = zipper, + ctx + ) do + {:cont, Zipper.replace(zipper, if_ast(head, true_body, false_body)), ctx} + end + + def run( + {{:case, _, + [ + head, + [{_, [{:->, _, [[{:__block__, _, [false]}], false_body]}, {:->, _, [[{:__block__, _, [true]}], true_body]}]}] + ]}, _} = zipper, + ctx + ) do + {:cont, Zipper.replace(zipper, if_ast(head, true_body, false_body)), ctx} + end + def run(zipper, ctx), do: {:cont, zipper, ctx} + # don't write an else clause if it's `false -> nil` + defp if_ast(head, true_body, {:__block__, _, [nil]}), + do: {:if, [do: []], [head, [{{:__block__, [], [:do]}, true_body}]]} + + defp if_ast(head, true_body, false_body), + do: {:if, [do: [], end: []], [head, [{{:__block__, [], [:do]}, true_body}, {{:__block__, [], [:else]}, false_body}]]} + defp delimit(token), do: token |> String.to_charlist() |> remove_underscores([]) |> add_underscores([]) defp remove_underscores([?_ | rest], acc), do: remove_underscores(rest, acc) diff --git a/test/style/simple_test.exs b/test/style/simple_test.exs index 273551fa..4114f53e 100644 --- a/test/style/simple_test.exs +++ b/test/style/simple_test.exs @@ -38,4 +38,73 @@ defmodule Styler.Style.SimpleTest do assert_style("Enum.reverse(foo, bar) ++ bar") end end + + describe "case true false do" do + test "rewrites case true false to if else" do + assert_style( + """ + case foo do + true -> :ok + false -> :error + end + """, + """ + if foo do + :ok + else + :error + end + """ + ) + + assert_style( + """ + case foo do + false -> :error + true -> :ok + end + """, + """ + if foo do + :ok + else + :error + end + """ + ) + + assert_style( + """ + case foo do + true -> :ok + false -> nil + end + """, + """ + if foo do + :ok + end + """ + ) + + assert_style( + """ + case foo do + true -> :ok + false -> + Logger.warn("it's false") + nil + end + """, + """ + if foo do + :ok + else + Logger.warn("it's false") + nil + end + """ + ) + end + end end