Skip to content

Commit

Permalink
extract max line
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Apr 16, 2024
1 parent 5caeab9 commit 47c0c2e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
9 changes: 9 additions & 0 deletions lib/style.ex
Original file line number Diff line number Diff line change
Expand Up @@ -234,4 +234,13 @@ defmodule Styler.Style do
do: do_fix_lines(nodes, max, [shift_line(node, max - line - 2) | acc]),
else: do_fix_lines(nodes, line, [node | acc])
end

def max_line(ast) do
{_, max_line} = Macro.prewalk(ast, 0, fn
{_, meta, _} = ast, max -> {ast, max(meta[:line] || max, max)}
ast, max -> {ast, max}
end)

max_line
end
end
20 changes: 4 additions & 16 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ defmodule Styler.Style.Blocks do
# disable keyword `, do:` since there will be multiple statements in the body
with_meta =
if Enum.any?(postroll),
do: Keyword.merge(with_meta, do: [line: with_meta[:line]], end: [line: max_line(children) + 1]),
do: Keyword.merge(with_meta, do: [line: with_meta[:line]], end: [line: Style.max_line(children) + 1]),
else: with_meta

with_children = Enum.reverse(reversed_clauses, [[{do_block, do_body} | elses]])
Expand Down Expand Up @@ -186,7 +186,7 @@ defmodule Styler.Style.Blocks do
{:cont, Zipper.replace(zipper, {:if, m, [head, [do_block]]}), ctx}

[head, [do_, else_]] ->
if max_line(do_) > max_line(else_) do
if Style.max_line(do_) > Style.max_line(else_) do
# we inverted the if/else blocks of this `if` statement in a previous pass (due to negators or unless)
# shift comments etc to make it happy now
if_ast(zipper, head, do_, else_, ctx)
Expand Down Expand Up @@ -268,8 +268,8 @@ defmodule Styler.Style.Blocks do
do_body = Macro.update_meta(do_body, &Keyword.delete(&1, :end_of_expression))
else_body = Macro.update_meta(else_body, &Keyword.delete(&1, :end_of_expression))

max_do_line = max_line(do_body)
max_else_line = max_line(else_body)
max_do_line = Style.max_line(do_body)
max_else_line = Style.max_line(else_body)
end_line = max(max_do_line, max_else_line)

# Change ast meta and comment lines to fit the `if` ast
Expand Down Expand Up @@ -303,18 +303,6 @@ defmodule Styler.Style.Blocks do
|> run(%{ctx | comments: comments})
end

defp max_line(ast) do
{_, max_line} =
ast
|> Zipper.zip()
|> Zipper.traverse(0, fn
{{_, meta, _}, _} = z, max -> {z, max(meta[:line] || max, max)}
z, max -> {z, max}
end)

max_line
end

defp invert({:!=, m, [a, b]}), do: {:==, m, [a, b]}
defp invert({:!==, m, [a, b]}), do: {:===, m, [a, b]}
defp invert({_, _, [expr]}), do: expr
Expand Down

0 comments on commit 47c0c2e

Please sign in to comment.