Skip to content

Commit

Permalink
special case preserving new lines in guards to specs only
Browse files Browse the repository at this point in the history
  • Loading branch information
awalterschulze committed Aug 25, 2020
1 parent 42c0aa4 commit 0d20b39
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/erlfmt_format.erl
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ clause_to_algebra({spec_clause, _Meta, Head, [Body], empty}) ->
);
clause_to_algebra({spec_clause, _Meta, Head, [Body], Guards}) ->
HeadD = expr_to_algebra(Head),
GuardsD = expr_to_algebra(Guards),
GuardsD = spec_clause_gaurds_to_algebra(Guards),
BodyD = expr_to_algebra(Body),

Nested = fun(Doc) -> nest(concat(break(<<" ">>), Doc), ?INDENT) end,
Expand All @@ -652,10 +652,24 @@ clause_to_algebra({spec_clause, _Meta, Head, [Body], Guards}) ->
Nested(GuardsD)
).

spec_clause_gaurds_to_algebra(Expr) ->
Meta = element(2, Expr),
Doc = case Expr of
{guard_or, _Meta, Guards} -> spec_guard_to_algebra(Guards, <<";">>);
{guard_and, _Meta, Guards} -> spec_guard_to_algebra(Guards, <<",">>);
Other -> do_expr_to_algebra(Other)
end,
combine_comments(Meta, maybe_wrap_in_parens(Meta, Doc)).

spec_guard_to_algebra(Guards, Separator) ->
GuardsD = lists:map(fun spec_clause_gaurds_to_algebra/1, Guards),
Doc = fold_doc(fun(GuardD, Acc) -> break(concat(GuardD, Separator), Acc) end, GuardsD),
group(concat(maybe_force_breaks(has_any_break_between(Guards)), Doc)).

guard_to_algebra(Guards, Separator) ->
GuardsD = lists:map(fun expr_to_algebra/1, Guards),
Doc = fold_doc(fun(GuardD, Acc) -> break(concat(GuardD, Separator), Acc) end, GuardsD),
group(concat(maybe_force_breaks(has_any_break_between(Guards)), Doc)).
group(Doc).

% %% Because the spec syntax is different from regular function syntax,
% %% in the general case we have to indent them differently, but with just
Expand Down
11 changes: 11 additions & 0 deletions test/erlfmt_format_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,17 @@ fun_expression(Config) when is_list(Config) ->
" ok\n"
"%% comment 5\n"
"end.\n"
),
?assertFormat(
"fun(X) when\n"
" is_integer(X);\n"
" is_string(X)\n"
"->\n"
" X\n"
"end\n",
"fun(X) when is_integer(X); is_string(X) ->\n"
" X\n"
"end\n"
).

case_expression(Config) when is_list(Config) ->
Expand Down

0 comments on commit 0d20b39

Please sign in to comment.