Skip to content

Commit

Permalink
Do not write a | if it's a single case DU with a visibility modifie…
Browse files Browse the repository at this point in the history
…r. (#948)

Refactor testing for trivia before union fields. Add test to check single DU case.
  • Loading branch information
deviousasti authored Jul 7, 2020
1 parent 07fb56b commit 28ed449
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
9 changes: 8 additions & 1 deletion src/Fantomas.Tests/UnionTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ type CustomerId =
""" config
|> prepend newline
|> should equal """
type CustomerId = private | CustomerId of int
type CustomerId = private CustomerId of int
"""

[<Test>]
Expand Down Expand Up @@ -306,6 +306,13 @@ let ``single case DU with fields should not have a pipe after formatting`` () =
type DU = Record of string
"""

[<Test>]
let ``single case DU with private fields should not have a pipe after formatting`` () =
formatSourceString false """type String50 = private String50 of string""" config
|> prepend newline
|> should equal """
type String50 = private String50 of string
"""

[<Test>]
let ``single case DU, no UnionCaseFields in signature file`` () =
Expand Down
21 changes: 15 additions & 6 deletions src/Fantomas/CodePrinter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2066,32 +2066,41 @@ and genTypeDefn astContext (TypeDef(ats, px, ao, tds, tcs, tdr, ms, s, preferPos
+> unindent)

| Simple(TDSRUnion(ao', xs) as unionNode) ->
let hasLeadingTrivia (t : TriviaNode) =
t.Range = unionNode.Range && not (List.isEmpty t.ContentBefore)

let sepNlnBasedOnTrivia =
fun (ctx: Context) ->
let trivia =
ctx.Trivia
|> List.tryFind (fun t -> t.Range = unionNode.Range && not (List.isEmpty t.ContentBefore))
ctx.Trivia |> List.tryFind hasLeadingTrivia

match trivia with
| Some _ -> sepNln
| None -> sepNone
<| ctx

let unionCases =
let unionCases ctx =
match xs with
| [] -> id
| [UnionCase(attrs, _,_,_,(UnionCaseType fs)) as x] when List.isEmpty ms ->
let hasVerticalBar = Option.isSome ao' || not (List.isEmpty attrs) || List.isEmpty fs
| [] -> ctx
| [UnionCase(attrs, _,_,_,(UnionCaseType fields)) as x] when List.isEmpty ms ->

let hasVerticalBar =
(Option.isSome ao' && List.length fields <> 1) ||
ctx.Trivia |> List.exists hasLeadingTrivia ||
not (List.isEmpty attrs) ||
List.isEmpty fields

indent +> sepSpace +> sepNlnBasedOnTrivia
+> genTrivia tdr.Range
(opt sepSpace ao' genAccess
+> genUnionCase { astContext with HasVerticalBar = hasVerticalBar } x)
<| ctx
| xs ->
indent +> sepNln
+> genTrivia tdr.Range
(opt sepNln ao' genAccess
+> col sepNln xs (genUnionCase { astContext with HasVerticalBar = true }))
<| ctx

typeName +> sepEq
+> unionCases
Expand Down

0 comments on commit 28ed449

Please sign in to comment.