Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor LetOrUseBinding formatting. #1058

Merged
merged 11 commits into from
Aug 31, 2020
17 changes: 17 additions & 0 deletions docs/FormattingConventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,23 @@ Avoid extraneous whitespace in the following situations:
- Method definitions inside a class are separated by a single blank line.
- Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
- Use blank lines in functions, sparingly, to indicate logical sections.

#### 2020 Revision

Blank lines are introduces around any multiline code constructs:
```fsharp
let a = 9

if someCondition then
printfn "meh"
()

let b = 10
let c = 10
```

The `SynExpr.IfThenElse` expression is multiline so a blank line between `let a` and `if someCondition` and between `if someCondition` and `let b` is fitting.
Single line statements are combined without any additional blank lines, see `let b` and `let c`.

### Comments

Expand Down
1 change: 1 addition & 0 deletions src/Fantomas.Tests/ActivePatternTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ let (|Integer|_|) (str: string) =

let (|ParseRegex|_|) regex str =
let m = Regex(regex).Match(str)

if m.Success
then Some(List.tail [ for x in m.Groups -> x.Value ])
else None
Expand Down
7 changes: 7 additions & 0 deletions src/Fantomas.Tests/AppTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ module Caching =
currency
address
sessionCachedNetworkData

())

()
"""

Expand Down Expand Up @@ -143,7 +145,9 @@ module Caching =
if compoundBalance < 0.0m then
ReportProblem
looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong

())

()
"""

Expand Down Expand Up @@ -173,7 +177,9 @@ module Caching =
| Cached (balance, time) ->
if compoundBalance < 0.0m
then ReportProblem compoundBalance None currency address sessionCachedNetworkData

())

()
"""

Expand Down Expand Up @@ -203,5 +209,6 @@ module Caching =
| Cached (balance, time) ->
if compoundBalance < 0.0m then ReportProblem compoundBalance
())

()
"""
18 changes: 17 additions & 1 deletion src/Fantomas.Tests/AttributeTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ let main argv =
printfn "Nice command-line arguments! Here's what JSON.NET has to say about them:" argv
|> Array.map getJsonNetJson
|> Array.iter(printfn "%s")

0 // return an integer exit code
"""

Expand Down Expand Up @@ -484,6 +485,22 @@ open System.Runtime.InteropServices
()
"""

[<Test>]
let ``line comment between attributes and do expression`` () =
formatSourceString false """
[<Foo>]
[<Bar>]
// barry
printfn "meh"
""" config
|> prepend newline
|> should equal """
[<Foo>]
[<Bar>]
// barry
printfn "meh"
"""

[<Test>]
let ``multiple attributes inside SynAttributes that exceeds max line length, 629`` () =
formatSourceString false """
Expand Down Expand Up @@ -570,7 +587,6 @@ type RoleAdminImportController(akkaService: AkkaService) =
DryRun = args.DryRun }

importer.ApiMaster <! StartImportCmd job

return Ok job
}
"""
Expand Down
23 changes: 21 additions & 2 deletions src/Fantomas.Tests/CompilerDirectivesTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -330,12 +330,14 @@ let start (args: IArgs) =
try
try
let giraffeApp = configureGiraffeApp args

WebHost.CreateDefaultBuilder().UseWebRoot(args.ClientPath)
#if DEBUG
.UseContentRoot(args.ContentRoot).UseUrls(args.Host + ":" + string args.Port)
#endif
.UseSerilog().Configure(Action<IApplicationBuilder>(configureApp giraffeApp))
.ConfigureServices(configureServices args).Build().Run()

0
with ex ->
Log.Fatal(ex, "Host terminated unexpectedly")
Expand Down Expand Up @@ -856,7 +858,7 @@ let foo = ()
"""

[<Test>]
let ``hash directive between attributes`` () =
let ``hash directive between attributes, no defines`` () =
formatSourceStringWithDefines [] """[<assembly:Foo()>]
#if BAR
[<assembly:Bar()>]
Expand All @@ -871,7 +873,6 @@ do ()

#endif
[<assembly:Meh>]

do ()
"""

Expand All @@ -891,7 +892,25 @@ do ()
[<assembly:Bar>]
#endif
[<assembly:Meh>]
do ()
"""

[<Test>]
let ``hash directive between attributes`` () =
formatSourceString false """[<assembly:Foo()>]
#if BAR
[<assembly:Bar()>]
#endif
[<assembly:Meh()>]
do ()
""" config
|> prepend newline
|> should equal """
[<assembly:Foo>]
#if BAR
[<assembly:Bar>]
#endif
[<assembly:Meh>]
do ()
"""

Expand Down
3 changes: 3 additions & 0 deletions src/Fantomas.Tests/ComputationExpressionTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1403,7 +1403,9 @@ let initDb () =
if not (File.Exists(dbFileName)) then
let dbFile = File.Create(dbFileName)
dbFile.Dispose() |> ignore

let createSql = readSqlFile "create"

using (connection ()) (fun conn ->
task {
do! conn.OpenAsync()
Expand Down Expand Up @@ -1442,6 +1444,7 @@ let private removeSubscription (log : ILogger) (req : HttpRequest) =
|> should equal """
let private removeSubscription (log : ILogger) (req : HttpRequest) =
log.LogInformation("Start remove-subscription")

task {
let origin = req.Headers.["Origin"].ToString()
let user = Authentication.getUser log req
Expand Down
6 changes: 6 additions & 0 deletions src/Fantomas.Tests/ControlStructureTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,13 @@ let ``for loops``() =
let function1 () =
for i = 1 to 10 do
printf "%d " i

printfn ""

let function2 () =
for i = 10 downto 1 do
printf "%d " i

printfn ""
"""

Expand All @@ -85,9 +87,11 @@ open System
let lookForValue value maxValue =
let mutable continueLooping = true
let randomNumberGenerator = new Random()

while continueLooping do
let rand = randomNumberGenerator.Next(maxValue)
printf "%d " rand

if rand = value then
printfn "\nFound a %d!" value
continueLooping <- false
Expand Down Expand Up @@ -151,13 +155,15 @@ let ``range expressions``() =
let function2() =
for i in 1 .. 2 .. 10 do
printf "%d " i

printfn ""
function2()""" config
|> prepend newline
|> should equal """
let function2 () =
for i in 1 .. 2 .. 10 do
printf "%d " i

printfn ""

function2 ()
Expand Down
1 change: 1 addition & 0 deletions src/Fantomas.Tests/ElmishTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,7 @@ open Feliz
let counter =
React.functionComponent (fun () ->
let (count, setCount) = React.useState (0)

Html.div [
Html.button [
prop.style [ style.marginRight 5 ]
Expand Down
1 change: 1 addition & 0 deletions src/Fantomas.Tests/FSharpScriptTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ let ``number in the filename should not end up in the module name`` () =
|> String.normalizeNewLine
|> should equal """let simplePatternMatch =
let x = "a"

match x with
| "a" -> printfn "x is a"
| "b" -> printfn "x is b"
Expand Down
4 changes: 4 additions & 0 deletions src/Fantomas.Tests/FunctionDefinitionTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ let ``let bindings with return types``() =
let divide x y =
let stream: System.IO.FileStream = System.IO.File.Create("test.txt")
let writer: System.IO.StreamWriter = new System.IO.StreamWriter(stream)

try
writer.WriteLine("test1")
Some(x / y)
Expand Down Expand Up @@ -393,13 +394,15 @@ let fold (funcs : ResultFunc<'Input, 'Output, 'TError> seq)

let runValidator (validator : ResultFunc<'Input, 'Output, 'TError>) input =
let validatorResult = validator input

match validatorResult with
| Error error ->
anyErrors <- true
collectedErrors <- error :: collectedErrors
| Ok output -> collectedOutputs <- output :: collectedOutputs

funcs |> Seq.iter (fun validator -> runValidator validator input)

match anyErrors with
| true -> Error collectedErrors
| false -> Ok collectedOutputs
Expand Down Expand Up @@ -646,6 +649,7 @@ let rec run
: HttpResponse
=
logAnalyticsForRequest log req

Http.main
CodeFormatter.GetVersion
format
Expand Down
14 changes: 14 additions & 0 deletions src/Fantomas.Tests/InterfaceTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,17 @@ type Test =
?waitForOrderDate: bool) =
""
"""

[<Test>]
let ``interface with get/set members`` () =
formatSourceString false """
type IMyInterface =
abstract MyProp : bool with get, set
abstract MyMethod : unit -> unit
""" config
|> prepend newline
|> should equal """
type IMyInterface =
abstract MyProp: bool with get, set
abstract MyMethod: unit -> unit
"""
2 changes: 2 additions & 0 deletions src/Fantomas.Tests/KeepIfThenInSameLineTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type TransferAmount(valueToSend: decimal, balanceAtTheMomentOfSending: decimal)
do
if balanceAtTheMomentOfSending < valueToSend then
invalidArg "balanceAtTheMomentOfSending" "some very very long error message"

if valueToSend <= 0m then
invalidArg "valueToSend" "Amount has to be above zero"
"""
Expand All @@ -49,6 +50,7 @@ type TransferAmount(valueToSend: decimal, balanceAtTheMomentOfSending: decimal)
invalidArg
"balanceAtTheMomentOfSending" // comment
"some very very long error message" // comment

if valueToSend <= 0m then // comment
invalidArg "valueToSend" "Amount has to be above zero" // comment
"""
Expand Down
Loading