Skip to content

Commit 57c58c7

Browse files
committed
implement dbg for if expressions
1 parent 47079bc commit 57c58c7

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

lib/elixir/lib/macro.ex

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2642,6 +2642,15 @@ defmodule Macro do
26422642
end
26432643
end
26442644

2645+
defp dbg_ast_to_debuggable({:if, _meta, [condition_ast, _clauses]} = ast) do
2646+
quote do
2647+
condition_result = unquote(condition_ast)
2648+
result = unquote(ast)
2649+
2650+
{:if, unquote(escape(ast)), unquote(escape(condition_ast)), condition_result, result}
2651+
end
2652+
end
2653+
26452654
# Any other AST.
26462655
defp dbg_ast_to_debuggable(ast) do
26472656
quote do: {:value, unquote(escape(ast)), unquote(ast)}
@@ -2755,6 +2764,23 @@ defmodule Macro do
27552764
{formatted, value}
27562765
end
27572766

2767+
defp dbg_format_ast_to_debug(
2768+
{:if, ast, condition_ast, condition_result, result},
2769+
options
2770+
) do
2771+
formatted = [
2772+
dbg_maybe_underline("If condition", options),
2773+
":\n",
2774+
dbg_format_ast_with_value(condition_ast, condition_result, options),
2775+
?\n,
2776+
dbg_maybe_underline("If expression", options),
2777+
" (#{if result, do: "do", else: "else"} clause executed):\n",
2778+
dbg_format_ast_with_value(ast, result, options)
2779+
]
2780+
2781+
{formatted, result}
2782+
end
2783+
27582784
defp dbg_format_ast_to_debug({:value, code_ast, value}, options) do
27592785
{dbg_format_ast_with_value(code_ast, value, options), value}
27602786
end

lib/elixir/test/elixir/macro_test.exs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,62 @@ defmodule MacroTest do
536536
"""
537537
end
538538

539+
test "if statement" do
540+
x = true
541+
map = %{a: 5, b: 1}
542+
543+
{result, formatted} =
544+
dbg_format(
545+
if true and x do
546+
map[:a] * 2
547+
else
548+
map[:b]
549+
end
550+
)
551+
552+
assert result == 10
553+
554+
assert formatted =~ "macro_test.exs"
555+
556+
assert formatted =~ """
557+
If condition:
558+
true and x #=> true
559+
560+
If expression (do clause executed):
561+
if true and x do
562+
map[:a] * 2
563+
else
564+
map[:b]
565+
end #=> 10
566+
"""
567+
end
568+
569+
test "if statement without else" do
570+
x = true
571+
map = %{a: 5, b: 1}
572+
573+
{result, formatted} =
574+
dbg_format(
575+
if false and x do
576+
map[:a] * 2
577+
end
578+
)
579+
580+
assert result == nil
581+
582+
assert formatted =~ "macro_test.exs"
583+
584+
assert formatted =~ """
585+
If condition:
586+
false and x #=> false
587+
588+
If expression (else clause executed):
589+
if false and x do
590+
map[:a] * 2
591+
end #=> nil
592+
"""
593+
end
594+
539595
test "with \"syntax_colors: []\" it doesn't print any color sequences" do
540596
{_result, formatted} = dbg_format("hello")
541597
refute formatted =~ "\e["

0 commit comments

Comments
 (0)