diff --git a/src/Fantomas.Tests/AppTests.fs b/src/Fantomas.Tests/AppTests.fs index 9a5d70f827..2b73d845aa 100644 --- a/src/Fantomas.Tests/AppTests.fs +++ b/src/Fantomas.Tests/AppTests.fs @@ -6,7 +6,7 @@ open Fantomas.Tests.TestHelper // the current behavior results in a compile error since the |> is merged to the last line [] -let ``no nln before lambda #503`` () = +let ``no nln before lambda, #503`` () = formatSourceString false """ @@ -22,11 +22,10 @@ let a = """ let a = b - |> List.exists - (fun p -> - p.a - && p.b - |> List.exists (fun o -> o.a = "lorem ipsum dolor sit amet")) + |> List.exists (fun p -> + p.a + && p.b + |> List.exists (fun o -> o.a = "lorem ipsum dolor sit amet")) """ // compile error due to expression starting before the beginning of the function expression @@ -127,21 +126,19 @@ module Caching = (address: PublicAddress) (currency: Currency) : NotFresh = - lock - cacheFiles.CachedNetworkData - (fun _ -> - match balance with - | NotAvailable -> NotAvailable - | Cached (balance, time) -> - if compoundBalance < 0.0m then - ReportProblem - compoundBalance - None - currency - address - sessionCachedNetworkData - - ()) + lock cacheFiles.CachedNetworkData (fun _ -> + match balance with + | NotAvailable -> NotAvailable + | Cached (balance, time) -> + if compoundBalance < 0.0m then + ReportProblem + compoundBalance + None + currency + address + sessionCachedNetworkData + + ()) () """ @@ -174,17 +171,15 @@ module Caching = (address: PublicAddress) (currency: Currency) : NotFresh = - lock - cacheFiles.CachedNetworkData - (fun _ -> - match balance with - | NotAvailable -> NotAvailable - | Cached (balance, time) -> - if compoundBalance < 0.0m then - ReportProblem - looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong - - ()) + lock cacheFiles.CachedNetworkData (fun _ -> + match balance with + | NotAvailable -> NotAvailable + | Cached (balance, time) -> + if compoundBalance < 0.0m then + ReportProblem + looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong + + ()) () """ @@ -214,16 +209,14 @@ let ``should not split parameters over multiple lines when they do not exceed pa module Caching = type MainCache() = member __.RetrieveLastCompoundBalance (address: PublicAddress) (currency: Currency) : NotFresh = - lock - cacheFiles.CachedNetworkData - (fun _ -> - match balance with - | NotAvailable -> NotAvailable - | Cached (balance, time) -> - if compoundBalance < 0.0m then - ReportProblem compoundBalance None currency address sessionCachedNetworkData + lock cacheFiles.CachedNetworkData (fun _ -> + match balance with + | NotAvailable -> NotAvailable + | Cached (balance, time) -> + if compoundBalance < 0.0m then + ReportProblem compoundBalance None currency address sessionCachedNetworkData - ()) + ()) () """ @@ -253,16 +246,14 @@ let ``should not split single parameter over multiple lines when it does not exc module Caching = type MainCache() = member __.RetrieveLastCompoundBalance (address: PublicAddress) (currency: Currency) : NotFresh = - lock - cacheFiles.CachedNetworkData - (fun _ -> - match balance with - | NotAvailable -> NotAvailable - | Cached (balance, time) -> - if compoundBalance < 0.0m then - ReportProblem compoundBalance + lock cacheFiles.CachedNetworkData (fun _ -> + match balance with + | NotAvailable -> NotAvailable + | Cached (balance, time) -> + if compoundBalance < 0.0m then + ReportProblem compoundBalance - ()) + ()) () """ @@ -737,16 +728,14 @@ module Foo = let blah = it - |> List.iter - (fun (_, output) -> - thing - |> Map.iter - (fun key value -> - match value with - | Ok (TestResult.Failure f) -> failwith "" - | Error e -> failwith "" - | _ -> () // hi! - )) + |> List.iter (fun (_, output) -> + thing + |> Map.iter (fun key value -> + match value with + | Ok (TestResult.Failure f) -> failwith "" + | Error e -> failwith "" + | _ -> () // hi! + )) """ [] diff --git a/src/Fantomas.Tests/CommentTests.fs b/src/Fantomas.Tests/CommentTests.fs index af44a7cf2a..e61d4b8fd3 100644 --- a/src/Fantomas.Tests/CommentTests.fs +++ b/src/Fantomas.Tests/CommentTests.fs @@ -52,11 +52,9 @@ let print_30_permut () = /// declare and initialize let permutation: int array = - Array.init - n - (fun i -> - Console.Write(i + 1) - i) + Array.init n (fun i -> + Console.Write(i + 1) + i) permutation """ @@ -81,11 +79,9 @@ let print_30_permut () = /// declare and initialize let permutation: int array = - Array.init - n - (fun (i, j) -> - Console.Write(i + 1) - i) + Array.init n (fun (i, j) -> + Console.Write(i + 1) + i) permutation """ diff --git a/src/Fantomas.Tests/CompilerDirectivesTests.fs b/src/Fantomas.Tests/CompilerDirectivesTests.fs index b53fd06cea..75aceae412 100644 --- a/src/Fantomas.Tests/CompilerDirectivesTests.fs +++ b/src/Fantomas.Tests/CompilerDirectivesTests.fs @@ -671,11 +671,10 @@ type FunctionComponent = static member inline Lazy(f: 'Props -> ReactElement, fallback: ReactElement) : LazyFunctionComponent<'Props> = #if FABLE_COMPILER let elemType = - ReactBindings.React.``lazy`` - (fun () -> - // React.lazy requires a default export - (importValueDynamic f) - .``then`` (fun x -> createObj [ "default" ==> x ])) + ReactBindings.React.``lazy`` (fun () -> + // React.lazy requires a default export + (importValueDynamic f) + .``then`` (fun x -> createObj [ "default" ==> x ])) fun props -> ReactElementType.create @@ -892,11 +891,10 @@ type FunctionComponent = static member inline Lazy(f: 'Props -> ReactElement, fallback: ReactElement) : LazyFunctionComponent<'Props> = #if FABLE_COMPILER let elemType = - ReactBindings.React.``lazy`` - (fun () -> - // React.lazy requires a default export - (importValueDynamic f) - .``then`` (fun x -> createObj [ "default" ==> x ])) + ReactBindings.React.``lazy`` (fun () -> + // React.lazy requires a default export + (importValueDynamic f) + .``then`` (fun x -> createObj [ "default" ==> x ])) fun props -> ReactElementType.create @@ -1255,13 +1253,12 @@ let ``endif in lambda`` () = |> should equal """ -foo - (fun x -> - () +foo (fun x -> + () #if DEF - () + () #endif - ) +) """ [] @@ -2216,41 +2213,40 @@ let getDefaultProxyFor = equal """ let getDefaultProxyFor = - memoize - (fun (url: string) -> - let uri = Uri url + memoize (fun (url: string) -> + let uri = Uri url - let getDefault () = + let getDefault () = #if CUSTOM_WEBPROXY - let result = - { new IWebProxy with - member __.Credentials = null + let result = + { new IWebProxy with + member __.Credentials = null - member __.Credentials - with set _value = () + member __.Credentials + with set _value = () - member __.GetProxy _ = null - member __.IsBypassed(_host: Uri) = true } + member __.GetProxy _ = null + member __.IsBypassed(_host: Uri) = true } #else - let result = WebRequest.GetSystemWebProxy() + let result = WebRequest.GetSystemWebProxy() #endif #if CUSTOM_WEBPROXY - let proxy = result + let proxy = result #else - let address = result.GetProxy uri + let address = result.GetProxy uri - if address = uri then - null - else - let proxy = WebProxy address - proxy.BypassProxyOnLocal <- true + if address = uri then + null + else + let proxy = WebProxy address + proxy.BypassProxyOnLocal <- true #endif - proxy.Credentials <- CredentialCache.DefaultCredentials - proxy + proxy.Credentials <- CredentialCache.DefaultCredentials + proxy - match calcEnvProxies.Force().TryFind uri.Scheme with - | Some p -> if p.GetProxy uri <> uri then p else getDefault () - | None -> getDefault ()) + match calcEnvProxies.Force().TryFind uri.Scheme with + | Some p -> if p.GetProxy uri <> uri then p else getDefault () + | None -> getDefault ()) """ [] diff --git a/src/Fantomas.Tests/ComputationExpressionTests.fs b/src/Fantomas.Tests/ComputationExpressionTests.fs index 038a587930..8776952142 100644 --- a/src/Fantomas.Tests/ComputationExpressionTests.fs +++ b/src/Fantomas.Tests/ComputationExpressionTests.fs @@ -1668,23 +1668,21 @@ let initDb () = let createSql = readSqlFile "create" - using - (connection ()) - (fun conn -> - task { - do! conn.OpenAsync() - let! _ = conn.ExecuteAsync(createSql) + using (connection ()) (fun conn -> + task { + do! conn.OpenAsync() + let! _ = conn.ExecuteAsync(createSql) #if DEBUG - let! hasClients = hasClients () + let! hasClients = hasClients () - if not (hasClients) then - let seedSql = readSqlFile "seed" - let! _ = conn.ExecuteAsync(seedSql) - () -#else + if not (hasClients) then + let seedSql = readSqlFile "seed" + let! _ = conn.ExecuteAsync(seedSql) () +#else + () #endif - }) + }) """ [] @@ -1763,32 +1761,23 @@ let ``don't add extra newline before do bang`` () = """ let sendPushNotifications = allSubscriptions - |> List.map - (fun (user, subscriptions) -> - subscriptions - |> List.filter (fun s -> s.Origin = origin) - |> List.map - (fun s -> - task { - try - let ps = - PushSubscription(s.Endpoint, s.P256DH, s.Auth) - - do! webPushClient.SendNotificationAsync(ps, payload, vapidDetails) - with - | :? WebPushException as wpex -> - log.LogError(sprintf "Couldn't send notification to %s, %A" user.UserId wpex) - - do! - filterSubscriptionsAndPersist - managementToken - user.UserId - subscriptions - s.Origin - s.Endpoint - } - :> Task) - |> Task.WhenAll) + |> List.map (fun (user, subscriptions) -> + subscriptions + |> List.filter (fun s -> s.Origin = origin) + |> List.map (fun s -> + task { + try + let ps = + PushSubscription(s.Endpoint, s.P256DH, s.Auth) + + do! webPushClient.SendNotificationAsync(ps, payload, vapidDetails) + with + | :? WebPushException as wpex -> + log.LogError(sprintf "Couldn't send notification to %s, %A" user.UserId wpex) + do! filterSubscriptionsAndPersist managementToken user.UserId subscriptions s.Origin s.Endpoint + } + :> Task) + |> Task.WhenAll) """ [] diff --git a/src/Fantomas.Tests/ControlStructureTests.fs b/src/Fantomas.Tests/ControlStructureTests.fs index 13b352f09c..01c9669764 100644 --- a/src/Fantomas.Tests/ControlStructureTests.fs +++ b/src/Fantomas.Tests/ControlStructureTests.fs @@ -866,13 +866,12 @@ things equal """ things -|> Seq.map - (fun a -> - try - Some i - with - | :? Foo - | :? Bar as e when true -> None) +|> Seq.map (fun a -> + try + Some i + with + | :? Foo + | :? Bar as e when true -> None) """ [] @@ -896,13 +895,12 @@ things equal """ things -|> Seq.map - (fun a -> - try - Some i - with - | Foo _ - | Bar _ as e when true -> None) +|> Seq.map (fun a -> + try + Some i + with + | Foo _ + | Bar _ as e when true -> None) """ [] diff --git a/src/Fantomas.Tests/DisableElmishTests.fs b/src/Fantomas.Tests/DisableElmishTests.fs index 98ece6f393..c73b1f5ced 100644 --- a/src/Fantomas.Tests/DisableElmishTests.fs +++ b/src/Fantomas.Tests/DisableElmishTests.fs @@ -201,18 +201,17 @@ let counter = React.functionComponent(fun () -> equal """ let counter = - React.functionComponent - (fun () -> - let (count, setCount) = React.useState (0) - - Html.div - [ Html.button - [ prop.style [ style.marginRight 5 ] - prop.onClick (fun _ -> setCount (count + 1)) - prop.text "Increment" ] - Html.button - [ prop.style [ style.marginLeft 5 ] - prop.onClick (fun _ -> setCount (count - 1)) - prop.text "Decrement" ] - Html.h1 count ]) + React.functionComponent (fun () -> + let (count, setCount) = React.useState (0) + + Html.div + [ Html.button + [ prop.style [ style.marginRight 5 ] + prop.onClick (fun _ -> setCount (count + 1)) + prop.text "Increment" ] + Html.button + [ prop.style [ style.marginLeft 5 ] + prop.onClick (fun _ -> setCount (count - 1)) + prop.text "Decrement" ] + Html.h1 count ]) """ diff --git a/src/Fantomas.Tests/DotGetTests.fs b/src/Fantomas.Tests/DotGetTests.fs index 451db87a40..664a7d653a 100644 --- a/src/Fantomas.Tests/DotGetTests.fs +++ b/src/Fantomas.Tests/DotGetTests.fs @@ -443,17 +443,15 @@ let getColl2 = .ToString() let getColl3 = - GetCollection - (fun _ parser -> - let x = 3 - x) + GetCollection (fun _ parser -> + let x = 3 + x) .Foo let getColl4 = - GetCollection - (fun parser -> - let x = 4 - x) + GetCollection (fun parser -> + let x = 4 + x) .Foo """ diff --git a/src/Fantomas.Tests/ElmishTests.fs b/src/Fantomas.Tests/ElmishTests.fs index 7b9ba3a112..602819ab37 100644 --- a/src/Fantomas.Tests/ElmishTests.fs +++ b/src/Fantomas.Tests/ElmishTests.fs @@ -495,10 +495,9 @@ let viewEntry todo dispatch = valueOrDefault todo.description Name "title" Id("todo-" + (string todo.id)) - OnInput - (fun ev -> - UpdateEntry(todo.id, !!ev.target?value) - |> dispatch) + OnInput (fun ev -> + UpdateEntry(todo.id, !!ev.target?value) + |> dispatch) OnBlur(fun _ -> EditingEntry(todo.id, false) |> dispatch) onEnter (EditingEntry(todo.id, false)) dispatch ] ] @@ -829,25 +828,24 @@ module App open Feliz let counter = - React.functionComponent - (fun () -> - let (count, setCount) = React.useState (0) + React.functionComponent (fun () -> + let (count, setCount) = React.useState (0) - Html.div [ - Html.button [ - prop.style [ style.marginRight 5 ] - prop.onClick (fun _ -> setCount (count + 1)) - prop.text "Increment" - ] + Html.div [ + Html.button [ + prop.style [ style.marginRight 5 ] + prop.onClick (fun _ -> setCount (count + 1)) + prop.text "Increment" + ] - Html.button [ - prop.style [ style.marginLeft 5 ] - prop.onClick (fun _ -> setCount (count - 1)) - prop.text "Decrement" - ] + Html.button [ + prop.style [ style.marginLeft 5 ] + prop.onClick (fun _ -> setCount (count - 1)) + prop.text "Decrement" + ] - Html.h1 count - ]) + Html.h1 count + ]) open Browser.Dom @@ -935,16 +933,15 @@ let drawer = prop.className classes.toolbar ] props.Items - |> List.map - (fun s -> - Mui.listItem [ - listItem.button true - match state with - | Some t when t = s -> listItem.selected true - | _ -> listItem.selected false - prop.text s - prop.onClick (fun _ -> s |> MenuItemClick |> dispatch) - ]) + |> List.map (fun s -> + Mui.listItem [ + listItem.button true + match state with + | Some t when t = s -> listItem.selected true + | _ -> listItem.selected false + prop.text s + prop.onClick (fun _ -> s |> MenuItemClick |> dispatch) + ]) |> Mui.list ] ] @@ -1009,24 +1006,22 @@ let private useLocationDetail (auth0 : Auth0Hook) (roles : RolesHook) id = && not (String.IsNullOrWhiteSpace(location.Creator)) then auth0.getAccessTokenSilently () - |> Promise.bind - (fun authToken -> - let url = - sprintf "%s/users/%s" Common.backendUrl (location.Creator) - - fetch - url - [ requestHeaders [ HttpRequestHeaders.ContentType "application/json" - Common.authHeader authToken - Common.subscriptionHeader ] ]) + |> Promise.bind (fun authToken -> + let url = + sprintf "%s/users/%s" Common.backendUrl (location.Creator) + + fetch + url + [ requestHeaders [ HttpRequestHeaders.ContentType "application/json" + Common.authHeader authToken + Common.subscriptionHeader ] ]) |> Promise.bind (fun res -> res.text ()) - |> Promise.iter - (fun json -> - let usersResult = Decode.fromString nameDecoder json + |> Promise.iter (fun json -> + let usersResult = Decode.fromString nameDecoder json - match usersResult with - | Ok name -> setCreatorName (Some name) - | Error err -> JS.console.log err)), + match usersResult with + | Ok name -> setCreatorName (Some name) + | Error err -> JS.console.log err)), [| box roles.Roles box location.Creator |] ) diff --git a/src/Fantomas.Tests/IfThenElseTests.fs b/src/Fantomas.Tests/IfThenElseTests.fs index 9d80d5f75e..3126e35f44 100644 --- a/src/Fantomas.Tests/IfThenElseTests.fs +++ b/src/Fantomas.Tests/IfThenElseTests.fs @@ -1437,29 +1437,28 @@ let ``nested if/then/else in short mode, 1243`` () = """ let funcs = fse.MembersFunctionsAndValues - |> Seq.sortWith - (fun n1 n2 -> - let modifierScore (f: FSharpMemberOrFunctionOrValue) = - if f.IsProperty then - if f.IsInstanceMember then - if f.IsDispatchSlot then 9 else 1 - else - 8 - elif f.IsMember then - if f.IsInstanceMember then - if f.IsDispatchSlot then 11 else 2 - else - 10 + |> Seq.sortWith (fun n1 n2 -> + let modifierScore (f: FSharpMemberOrFunctionOrValue) = + if f.IsProperty then + if f.IsInstanceMember then + if f.IsDispatchSlot then 9 else 1 + else + 8 + elif f.IsMember then + if f.IsInstanceMember then + if f.IsDispatchSlot then 11 else 2 else - 3 + 10 + else + 3 - let n1Score = modifierScore n1 - let n2Score = modifierScore n2 + let n1Score = modifierScore n1 + let n2Score = modifierScore n2 - if n1Score = n2Score then - n1.DisplayName.CompareTo n2.DisplayName - else - n1Score.CompareTo n2Score) + if n1Score = n2Score then + n1.DisplayName.CompareTo n2.DisplayName + else + n1Score.CompareTo n2Score) """ [] @@ -2054,8 +2053,8 @@ let lessonsForm (f: ValidatedForm) dispatch = yield! [ button.isLoading prop.disabled true ] - prop.onClick - (fun _ -> CreateLessons |> dispatch) ] ] ] ] + prop.onClick (fun _ -> + CreateLessons |> dispatch) ] ] ] ] """ [] @@ -2265,8 +2264,7 @@ if result.LaunchSuccess && result.ExitCode = 0 then else if result.ExitCode = 1 then let stdout, stderr = output - |> List.map - (function + |> List.map (function | StdErr e -> Error e | StdOut l -> Ok l) |> Result.partition @@ -2326,8 +2324,7 @@ if result.LaunchSuccess && result.ExitCode = 0 then elif result.ExitCode = 1 then let stdout, stderr = output - |> List.map - (function + |> List.map (function | StdErr e -> Error e | StdOut l -> Ok l) |> Result.partition diff --git a/src/Fantomas.Tests/KeepIndentInBranchTests.fs b/src/Fantomas.Tests/KeepIndentInBranchTests.fs index f5c8d5d62a..314451181d 100644 --- a/src/Fantomas.Tests/KeepIndentInBranchTests.fs +++ b/src/Fantomas.Tests/KeepIndentInBranchTests.fs @@ -602,14 +602,13 @@ let foo = """ let foo = bar - |> List.filter - (fun i -> - if false then - false - else + |> List.filter (fun i -> + if false then + false + else - let m = quux - quux.Success && somethingElse) + let m = quux + quux.Success && somethingElse) """ [] @@ -635,14 +634,13 @@ let foo = """ let foo = bar - |> List.filter - (fun { Index = i } -> - if false then - false - else + |> List.filter (fun { Index = i } -> + if false then + false + else - let m = quux - quux.Success && somethingElse) + let m = quux + quux.Success && somethingElse) """ [] @@ -679,29 +677,27 @@ lock lockingObj (fun () -> |> should equal """ -lock - lockingObj - (fun () -> - if not thing then printfn "" +lock lockingObj (fun () -> + if not thing then printfn "" - match error with - | Some error -> - if foo then () - thing () - false - | None -> + match error with + | Some error -> + if foo then () + thing () + false + | None -> - match list1, list2, list3 with - | [], [], [] -> - stuff () - true - | [], [], _ -> - moreStuff () - true - | _ -> + match list1, list2, list3 with + | [], [], [] -> + stuff () + true + | [], [], _ -> + moreStuff () + true + | _ -> - doMoreThings () - false) + doMoreThings () + false) """ [] diff --git a/src/Fantomas.Tests/LambdaTests.fs b/src/Fantomas.Tests/LambdaTests.fs index 17a181ec1e..f83158d177 100644 --- a/src/Fantomas.Tests/LambdaTests.fs +++ b/src/Fantomas.Tests/LambdaTests.fs @@ -18,10 +18,8 @@ let ``keep comment after arrow`` () = |> should equal """ -_Target - "FSharpTypesDotNet" - (fun _ -> // obsolete - ()) +_Target "FSharpTypesDotNet" (fun _ -> // obsolete + ()) """ let ``indent multiline lambda in parenthesis, 523`` () = @@ -118,10 +116,9 @@ let a = """ let a = b - |> List.exists - (fun p -> - x - && someVeryLongIdentifierrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrzzzz___________) + |> List.exists (fun p -> + x + && someVeryLongIdentifierrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrzzzz___________) """ [] @@ -143,15 +140,13 @@ Target.create "Clean" (fun _ -> |> should equal """ -Target.create - "Clean" - (fun _ -> - [ "bin" - "src/Fantomas/bin" - "src/Fantomas/obj" - "src/Fantomas.CoreGlobalTool/bin" - "src/Fantomas.CoreGlobalTool/obj" ] - |> List.iter Shell.cleanDir) +Target.create "Clean" (fun _ -> + [ "bin" + "src/Fantomas/bin" + "src/Fantomas/obj" + "src/Fantomas.CoreGlobalTool/bin" + "src/Fantomas.CoreGlobalTool/obj" ] + |> List.iter Shell.cleanDir) """ [] @@ -170,12 +165,11 @@ List.filter (fun ({ ContentBefore = contentBefore }) -> |> should equal """ -List.filter - (fun ({ ContentBefore = contentBefore }) -> - // some comment - let a = 8 - let b = List.length contentBefore - a + b) +List.filter (fun ({ ContentBefore = contentBefore }) -> + // some comment + let a = 8 + let b = List.length contentBefore + a + b) """ [] @@ -218,10 +212,9 @@ foo (fun a -> |> should equal """ -foo - (fun a -> - let b = 8 - b) +foo (fun a -> + let b = 8 + b) """ [] @@ -239,10 +232,9 @@ let ``short ident in nested let binding`` () = equal """ let a = - foo - (fun a -> - let b = 8 - b) + foo (fun a -> + let b = 8 + b) """ [] @@ -260,10 +252,9 @@ let ``longer ident in nested let binding`` () = equal """ let a = - foobar - (fun a -> - let b = 8 - b) + foobar (fun a -> + let b = 8 + b) """ [] @@ -326,17 +317,16 @@ CloudStorageAccount.SetConfigurationSettingPublisher(fun configName configSettin |> should equal """ -CloudStorageAccount.SetConfigurationSettingPublisher - (fun configName configSettingPublisher -> - let connectionString = - if hostedService then - RoleEnvironment.GetConfigurationSettingValue(configName) - else - ConfigurationManager.ConnectionStrings.[configName] - .ConnectionString +CloudStorageAccount.SetConfigurationSettingPublisher (fun configName configSettingPublisher -> + let connectionString = + if hostedService then + RoleEnvironment.GetConfigurationSettingValue(configName) + else + ConfigurationManager.ConnectionStrings.[configName] + .ConnectionString - configSettingPublisher.Invoke(connectionString) - |> ignore) + configSettingPublisher.Invoke(connectionString) + |> ignore) """ [] @@ -374,15 +364,14 @@ let genMemberFlagsForMemberBinding astContext (mf: MemberFlags) (rangeOfBindingA (fun (ctx: Context) -> // trying to get AST trivia ctx.Trivia - |> List.tryFind - (fun { Type = t; Range = r } -> // trying to get token trivia + |> List.tryFind (fun { Type = t; Range = r } -> // trying to get token trivia - match t with - | MainNode "SynMemberDefn.Member" -> RangeHelpers.``range contains`` r rangeOfBindingAndRhs + match t with + | MainNode "SynMemberDefn.Member" -> RangeHelpers.``range contains`` r rangeOfBindingAndRhs - | Token { TokenInfo = { TokenName = "MEMBER" } } -> r.StartLine = rangeOfBindingAndRhs.StartLine + | Token { TokenInfo = { TokenName = "MEMBER" } } -> r.StartLine = rangeOfBindingAndRhs.StartLine - | _ -> false) + | _ -> false) |> Option.defaultValue (!- "override ") <| ctx) <| ctx @@ -402,10 +391,9 @@ List.tryFind (fun { Type = t; Range = r } -> // foo |> should equal """ -List.tryFind - (fun { Type = t; Range = r } -> // foo - let a = 8 - a + 9) +List.tryFind (fun { Type = t; Range = r } -> // foo + let a = 8 + a + 9) """ [] @@ -493,15 +481,14 @@ let ``don't duplicate new line before LongIdentSet`` () = equal """ let options = - jsOptions - (fun o -> - let layout = - match opts.Layout with - | Graph.Free -> createObj [] - | Graph.HierarchicalLeftRight -> createObj [ "hierarchical" ==> hierOpts "LR" ] - | Graph.HierarchicalUpDown -> createObj [ "hierarchical" ==> hierOpts "UD" ] + jsOptions (fun o -> + let layout = + match opts.Layout with + | Graph.Free -> createObj [] + | Graph.HierarchicalLeftRight -> createObj [ "hierarchical" ==> hierOpts "LR" ] + | Graph.HierarchicalUpDown -> createObj [ "hierarchical" ==> hierOpts "UD" ] - o.layout <- Some layout) + o.layout <- Some layout) """ [] @@ -561,12 +548,9 @@ Target.create "Install" (fun _ -> |> should equal """ -Target.create - "Install" - (fun _ -> - Yarn.install (fun o -> { o with WorkingDirectory = clientDir }) - // Paket restore will already happen when the build.fsx dependencies are restored - ) +Target.create "Install" (fun _ -> Yarn.install (fun o -> { o with WorkingDirectory = clientDir }) +// Paket restore will already happen when the build.fsx dependencies are restored +) """ [] @@ -584,12 +568,9 @@ Target.create "Install" (fun x -> |> should equal """ -Target.create - "Install" - (fun x -> - Yarn.install (fun o -> { o with WorkingDirectory = clientDir }) - // Paket restore will already happen when the build.fsx dependencies are restored - ) +Target.create "Install" (fun x -> Yarn.install (fun o -> { o with WorkingDirectory = clientDir }) +// Paket restore will already happen when the build.fsx dependencies are restored +) """ [] @@ -760,10 +741,9 @@ services.AddHttpsRedirection(Action(fun options -> equal """ services.AddHttpsRedirection( - Action - (fun options -> - // meh - options.HttpsPort <- Nullable(7002)) + Action (fun options -> + // meh + options.HttpsPort <- Nullable(7002)) ) |> ignore """ @@ -956,3 +936,136 @@ module Foo = blah |> Struct.map (fun _ (a, _, _) -> filterBackings a) } """ + +[] +let ``multiline SynExpr.MatchLambda`` () = + formatSourceString + false + """ +module Foo = + let bar = + [] + |> List.choose + (function + | _ -> "") +""" + config + |> prepend newline + |> should + equal + """ +module Foo = + let bar = + [] + |> List.choose (function + | _ -> "") +""" + +[] +let ``long function application ending in with lambda argument`` () = + formatSourceString + false + """ +let foobar = + someFunctionName aFirstLongArgument aSecondLongArgument aThirdLongArgument aFourthLongArgument (fun finallyThatLambdaArgument -> + aFirstLongArgument + aSecondLongArgument - aThirdLongArgument - aFourthLongArgument + finallyThatLambdaArgument) + +let somethingElse = () +""" + config + |> prepend newline + |> should + equal + """ +let foobar = + someFunctionName + aFirstLongArgument + aSecondLongArgument + aThirdLongArgument + aFourthLongArgument + (fun finallyThatLambdaArgument -> + aFirstLongArgument + aSecondLongArgument + - aThirdLongArgument + - aFourthLongArgument + + finallyThatLambdaArgument) + +let somethingElse = () +""" + +[] +let ``multiline non lambda argument`` () = + formatSourceString + false + """ +let argExpr = + col sepNln es (fun e -> + let genLambda + (pats: Context -> Context) + (bodyExpr: SynExpr) + (lpr: Range) + (rpr: Range option) + (arrowRange: Range) + (pr: Range) + : Context -> Context = + leadingExpressionIsMultiline (sepOpenTFor lpr -- "fun " + +> pats + +> genArrowWithTrivia + (genExprKeepIndentInBranch astContext bodyExpr) + arrowRange) (fun isMultiline -> + onlyIf isMultiline sepNln + +> sepCloseTFor rpr e.Range) + |> genTriviaFor SynExpr_Paren pr + () + ) +""" + config + |> prepend newline + |> should + equal + """ +let argExpr = + col sepNln es (fun e -> + let genLambda + (pats: Context -> Context) + (bodyExpr: SynExpr) + (lpr: Range) + (rpr: Range option) + (arrowRange: Range) + (pr: Range) + : Context -> Context = + leadingExpressionIsMultiline + (sepOpenTFor lpr -- "fun " + +> pats + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext bodyExpr) arrowRange) + (fun isMultiline -> + onlyIf isMultiline sepNln + +> sepCloseTFor rpr e.Range) + |> genTriviaFor SynExpr_Paren pr + + ()) +""" + +[] +let ``multiline non lambda argument, match lambda`` () = + formatSourceString + false + """ +leadingExpressionIsMultiline (sepOpenTFor lpr -- "fun " + +> pats + +> genArrowWithTrivia + (genExprKeepIndentInBranch astContext bodyExpr) + arrowRange) (function | Ok _ -> true | Error _ -> false) +""" + config + |> prepend newline + |> should + equal + """ +leadingExpressionIsMultiline + (sepOpenTFor lpr -- "fun " + +> pats + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext bodyExpr) arrowRange) + (function + | Ok _ -> true + | Error _ -> false) +""" diff --git a/src/Fantomas.Tests/LetBindingTests.fs b/src/Fantomas.Tests/LetBindingTests.fs index da53e1ef79..af8566d75e 100644 --- a/src/Fantomas.Tests/LetBindingTests.fs +++ b/src/Fantomas.Tests/LetBindingTests.fs @@ -141,10 +141,9 @@ let x = """ let x = [| 1 .. 2 |] - |> Array.mapi - (fun _ _ -> - let num = "".PadLeft(9) - num) + |> Array.mapi (fun _ _ -> + let num = "".PadLeft(9) + num) """ [] @@ -237,16 +236,14 @@ module Card = let card (props: CardProps seq) (elems: ReactElement seq) : ReactElement = let customProps = props - |> Seq.collect - (function + |> Seq.collect (function | Custom props -> props | _ -> List.empty) |> keyValueList CaseRules.LowerFirst let typeProps = props - |> Seq.choose - (function + |> Seq.choose (function | Custom _ -> None | prop -> Some prop) |> keyValueList CaseRules.LowerFirst @@ -804,25 +801,22 @@ let useEntries month year = let sortMapAndToArray (input: Transaction seq) = input |> Seq.sortBy (fun ai -> ai.Created) - |> Seq.map - (fun ai -> - {| id = ai.Id - name = ai.Name - amount = ai.Amount |}) + |> Seq.map (fun ai -> + {| id = ai.Id + name = ai.Name + amount = ai.Amount |}) |> Seq.toArray let income = events - |> Seq.choose - (function + |> Seq.choose (function | Event.AddIncome (ai) when (filter ai.Created && isNotCancelled ai.Id) -> Some ai | _ -> None) |> sortMapAndToArray let expenses = events - |> Seq.choose - (function + |> Seq.choose (function | Event.AddExpense (ae) when (filter ae.Created && isNotCancelled ae.Id) -> Some ae | _ -> None) |> sortMapAndToArray @@ -967,32 +961,29 @@ let useOverviewPerMonth () = let months = events - |> List.choose - (fun msg -> - match msg with - | Event.AddIncome ({ Created = created }) - | Event.AddExpense ({ Created = created }) -> Some(created.Month, created.Year) - | _ -> None) + |> List.choose (fun msg -> + match msg with + | Event.AddIncome ({ Created = created }) + | Event.AddExpense ({ Created = created }) -> Some(created.Month, created.Year) + | _ -> None) |> List.distinct |> List.sort |> List.groupBy snd - |> List.map - (fun (year, months) -> - let rows = - months - |> List.map - (fun (m, y) -> - {| name = getMonthName m - month = m - balance = Projections.calculateBalance m y events |}) - |> List.toArray - - let balance = - rows |> Array.sumBy (fun mth -> mth.balance) - - {| name = year - months = rows - balance = balance |}) + |> List.map (fun (year, months) -> + let rows = + months + |> List.map (fun (m, y) -> + {| name = getMonthName m + month = m + balance = Projections.calculateBalance m y events |}) + |> List.toArray + + let balance = + rows |> Array.sumBy (fun mth -> mth.balance) + + {| name = year + months = rows + balance = balance |}) |> List.toArray months @@ -1135,17 +1126,16 @@ let merge a b = There is a problem with merging all the code back togheter. Please raise an issue at https://github.com/fsprojects/fantomas/issues.\"\"\" List.zip aChunks bChunks - |> List.map - (fun (a', b') -> - let la = lengthWithoutSpaces a' - let lb = lengthWithoutSpaces b' - - if la <> lb then - if la > lb then a' else b' - else if String.length a' < String.length b' then - a' - else - b') + |> List.map (fun (a', b') -> + let la = lengthWithoutSpaces a' + let lb = lengthWithoutSpaces b' + + if la <> lb then + if la > lb then a' else b' + else if String.length a' < String.length b' then + a' + else + b') |> String.concat Environment.NewLine " @@ -1253,10 +1243,9 @@ let x = | _ -> if tcref.IsILTycon then tcref.ILTyconRawMetadata.CustomAttrs.AsArray - |> Array.exists - (fun attr -> - attr.Method.DeclaringType.TypeSpec.Name = typeof - .FullName) + |> Array.exists (fun attr -> + attr.Method.DeclaringType.TypeSpec.Name = typeof + .FullName) else false """ @@ -1316,10 +1305,9 @@ let x = | _ -> if tcref.IsILTycon then tcref.ILTyconRawMetadata.CustomAttrs.AsArray - |> Array.exists - (fun attr -> - attr.Method.DeclaringType.TypeSpec.Name = typeof - .FullName) + |> Array.exists (fun attr -> + attr.Method.DeclaringType.TypeSpec.Name = typeof + .FullName) else false """ diff --git a/src/Fantomas.Tests/ListTests.fs b/src/Fantomas.Tests/ListTests.fs index bef627f81b..274b622894 100644 --- a/src/Fantomas.Tests/ListTests.fs +++ b/src/Fantomas.Tests/ListTests.fs @@ -2085,18 +2085,16 @@ type FSharpCompilerServiceChecker(backgroundServiceEnabled) = |> Seq.tryFind (fun (k, _) -> k.ToUpperInvariant() = file.ToUpperInvariant()) project - |> Option.map - (fun (_, option) -> - option, - [ yield! - options - |> Seq.map snd - |> Seq.distinctBy (fun o -> o.ProjectFileName) - |> Seq.filter - (fun o -> - o.ReferencedProjects - |> Array.map (fun (_, v) -> Path.GetFullPath v.ProjectFileName) - |> Array.contains option.ProjectFileName) ]) + |> Option.map (fun (_, option) -> + option, + [ yield! + options + |> Seq.map snd + |> Seq.distinctBy (fun o -> o.ProjectFileName) + |> Seq.filter (fun o -> + o.ReferencedProjects + |> Array.map (fun (_, v) -> Path.GetFullPath v.ProjectFileName) + |> Array.contains option.ProjectFileName) ]) """ [] diff --git a/src/Fantomas.Tests/MultiLineLambdaClosingNewlineTests.fs b/src/Fantomas.Tests/MultiLineLambdaClosingNewlineTests.fs index 6d59d93e5d..627b95cebe 100644 --- a/src/Fantomas.Tests/MultiLineLambdaClosingNewlineTests.fs +++ b/src/Fantomas.Tests/MultiLineLambdaClosingNewlineTests.fs @@ -1011,3 +1011,29 @@ configuration .Debug() .WriteTo.Logger(fun x -> x * x) """ + +[] +let ``match lambda with other arguments`` () = + formatSourceString + false + """ +let a = + Something.foo + bar + meh + (function | Ok x -> true | Error err -> false) +""" + config + |> prepend newline + |> should + equal + """ +let a = + Something.foo + bar + meh + (function + | Ok x -> true + | Error err -> false + ) +""" diff --git a/src/Fantomas.Tests/OperatorTests.fs b/src/Fantomas.Tests/OperatorTests.fs index 3cf25489c0..7295a0be31 100644 --- a/src/Fantomas.Tests/OperatorTests.fs +++ b/src/Fantomas.Tests/OperatorTests.fs @@ -345,12 +345,10 @@ let watchFiles = use _ = !!(serverPath "*.fs") ++ (serverPath "*.fsproj") // combines fs and fsproj - |> ChangeWatcher.run - (fun changes -> - printfn "FILE CHANGE %A" changes - // stopFunc() - //Async.Start (startFunc()) - ) + |> ChangeWatcher.run (fun changes -> printfn "FILE CHANGE %A" changes + // stopFunc() + //Async.Start (startFunc()) + ) () } @@ -386,12 +384,10 @@ let watchFiles = use _ = !!(serverPath "*.fs") ++ "*.fsproj" // combines fs and fsproj - |> ChangeWatcher.run - (fun changes -> - printfn "FILE CHANGE %A" changes - // stopFunc() - //Async.Start (startFunc()) - ) + |> ChangeWatcher.run (fun changes -> printfn "FILE CHANGE %A" changes + // stopFunc() + //Async.Start (startFunc()) + ) () } @@ -889,10 +885,9 @@ let shouldIncludeRelationship relName = """ let shouldIncludeRelationship relName = req.Includes - |> List.exists - (fun path -> - path.Length >= currentIncludePath.Length + 1 - && path |> List.take (currentIncludePath.Length + 1) = currentIncludePath @ [ relName ]) + |> List.exists (fun path -> + path.Length >= currentIncludePath.Length + 1 + && path |> List.take (currentIncludePath.Length + 1) = currentIncludePath @ [ relName ]) """ [] @@ -959,8 +954,7 @@ let isCustomOperationProjectionParameter i (nm: Ident) = | Some argInfosForOverloads -> let vs = argInfosForOverloads - |> List.map - (function + |> List.map (function | None -> false | Some argInfos -> i < argInfos.Length diff --git a/src/Fantomas.Tests/PatternMatchingTests.fs b/src/Fantomas.Tests/PatternMatchingTests.fs index 8d6f3760bc..ec92b0072d 100644 --- a/src/Fantomas.Tests/PatternMatchingTests.fs +++ b/src/Fantomas.Tests/PatternMatchingTests.fs @@ -902,17 +902,16 @@ List.tryFind(fun { Type = t; Range = r } -> |> should equal """ -List.tryFind - (fun { Type = t; Range = r } -> - match t with - | MainNode SynMemberDefn_Member - | MainNode SynMemberSig_Member -> // trying to get AST trivia - RangeHelpers.``range contains`` r rangeOfBindingAndRhs +List.tryFind (fun { Type = t; Range = r } -> + match t with + | MainNode SynMemberDefn_Member + | MainNode SynMemberSig_Member -> // trying to get AST trivia + RangeHelpers.``range contains`` r rangeOfBindingAndRhs - | Token (MEMBER, _) -> // trying to get token trivia - r.StartLine = rangeOfBindingAndRhs.StartLine + | Token (MEMBER, _) -> // trying to get token trivia + r.StartLine = rangeOfBindingAndRhs.StartLine - | _ -> false) + | _ -> false) """ [] @@ -938,8 +937,7 @@ Seq.takeWhile |> should equal """ -Seq.takeWhile - (function +Seq.takeWhile (function | Write "" // for example: // type Foo = diff --git a/src/Fantomas.Tests/RecordTests.fs b/src/Fantomas.Tests/RecordTests.fs index 3fa57bb720..a21cbb52db 100644 --- a/src/Fantomas.Tests/RecordTests.fs +++ b/src/Fantomas.Tests/RecordTests.fs @@ -427,11 +427,10 @@ let ``meaningful space should be preserved, 353`` () = |> should equal """ -to'.WithCommon - (fun o' -> - { dotnetOptions o' with - WorkingDirectory = Path.getFullName "RegressionTesting/issue29" - Verbosity = Some DotNet.Verbosity.Minimal }) +to'.WithCommon (fun o' -> + { dotnetOptions o' with + WorkingDirectory = Path.getFullName "RegressionTesting/issue29" + Verbosity = Some DotNet.Verbosity.Minimal }) .WithParameters """ diff --git a/src/Fantomas.Tests/StringTests.fs b/src/Fantomas.Tests/StringTests.fs index 018142452f..19392cce7c 100644 --- a/src/Fantomas.Tests/StringTests.fs +++ b/src/Fantomas.Tests/StringTests.fs @@ -285,11 +285,10 @@ let ``newline in string`` () = let triviaNodes = tokenize [] source |> getTriviaFromTokens - |> List.filter - (fun { Item = item } -> - match item with - | StringContent ("\"\n\"") -> true - | _ -> false) + |> List.filter (fun { Item = item } -> + match item with + | StringContent ("\"\n\"") -> true + | _ -> false) List.length triviaNodes == 1 """ diff --git a/src/Fantomas.Tests/SynConstTests.fs b/src/Fantomas.Tests/SynConstTests.fs index 2512f5ffad..bb236fdc5c 100644 --- a/src/Fantomas.Tests/SynConstTests.fs +++ b/src/Fantomas.Tests/SynConstTests.fs @@ -648,25 +648,23 @@ a:hover {color: #ecc;} let kill = body.Elements() - |> Seq.map - (fun x -> - match x.Name.LocalName with - | \"h2\" -> - keep - := (List.tryFind (fun e -> e = String.Concat(x.Nodes())) eliminate) - |> Option.isNone - | \"footer\" -> keep := true - | _ -> () - - if !keep then None else Some x) + |> Seq.map (fun x -> + match x.Name.LocalName with + | \"h2\" -> + keep + := (List.tryFind (fun e -> e = String.Concat(x.Nodes())) eliminate) + |> Option.isNone + | \"footer\" -> keep := true + | _ -> () + + if !keep then None else Some x) |> Seq.toList kill - |> Seq.iter - (fun q -> - match q with - | Some x -> x.Remove() - | _ -> ()) + |> Seq.iter (fun q -> + match q with + | Some x -> x.Remove() + | _ -> ()) let packable = Path.getFullName \"./_Binaries/README.html\" diff --git a/src/Fantomas.Tests/SynExprSetTests.fs b/src/Fantomas.Tests/SynExprSetTests.fs index cf44ac1f55..37caf98aff 100644 --- a/src/Fantomas.Tests/SynExprSetTests.fs +++ b/src/Fantomas.Tests/SynExprSetTests.fs @@ -97,34 +97,33 @@ let ``don't add additional new line after SynExpr.LongIndentSet, 1111`` () = equal """ let options = - jsOptions - (fun o -> - o.autoResize <- Some true - o.edges <- Some(jsOptions (fun e -> e.arrows <- Some <| U2.Case1 "to")) - - o.interaction <- - Some( - createObj [ "hover" ==> true - "zoomView" ==> true - "hoverConnectedEdges" ==> false ] - ) - - o.layout <- Some(createObj [ "randomSeed" ==> 0 ]) - - let hierOpts dir = - createObj [ "enabled" ==> true - "levelSeparation" ==> 170 - "nodeSpacing" ==> 100 - "treeSpacing" ==> 100 - "direction" ==> dir ] - - let layout = - match opts.Layout with - | Graph.Free -> createObj [] - | Graph.HierarchicalLeftRight -> createObj [ "hierarchical" ==> hierOpts "LR" ] - | Graph.HierarchicalUpDown -> createObj [ "hierarchical" ==> hierOpts "UD" ] - - o.layout <- Some layout) + jsOptions (fun o -> + o.autoResize <- Some true + o.edges <- Some(jsOptions (fun e -> e.arrows <- Some <| U2.Case1 "to")) + + o.interaction <- + Some( + createObj [ "hover" ==> true + "zoomView" ==> true + "hoverConnectedEdges" ==> false ] + ) + + o.layout <- Some(createObj [ "randomSeed" ==> 0 ]) + + let hierOpts dir = + createObj [ "enabled" ==> true + "levelSeparation" ==> 170 + "nodeSpacing" ==> 100 + "treeSpacing" ==> 100 + "direction" ==> dir ] + + let layout = + match opts.Layout with + | Graph.Free -> createObj [] + | Graph.HierarchicalLeftRight -> createObj [ "hierarchical" ==> hierOpts "LR" ] + | Graph.HierarchicalUpDown -> createObj [ "hierarchical" ==> hierOpts "UD" ] + + o.layout <- Some layout) """ [] @@ -214,16 +213,15 @@ let ``keep new line before SynExpr.DotIndexedSet, 1314`` () = let fs = warnings - |> List.choose - (fun w -> - w.Warning.Details.SuggestedFix - |> Option.bind - (fun f -> - let f = f.Force() - let range = fcsRangeToLsp w.Warning.Details.Range + |> List.choose (fun w -> + w.Warning.Details.SuggestedFix + |> Option.bind + (fun f -> + let f = f.Force() + let range = fcsRangeToLsp w.Warning.Details.Range - f - |> Option.map (fun f -> range, { Range = range; NewText = f.ToText }))) + f + |> Option.map (fun f -> range, { Range = range; NewText = f.ToText }))) lintFixes.[uri] <- fs """ @@ -241,16 +239,14 @@ match x with let fs = warnings - |> List.choose - (fun w -> - w.Warning.Details.SuggestedFix - |> Option.bind - (fun f -> - let f = f.Force() - let range = fcsRangeToLsp w.Warning.Details.Range - - f - |> Option.map (fun f -> range, { Range = range; NewText = f.ToText }))) + |> List.choose (fun w -> + w.Warning.Details.SuggestedFix + |> Option.bind (fun f -> + let f = f.Force() + let range = fcsRangeToLsp w.Warning.Details.Range + + f + |> Option.map (fun f -> range, { Range = range; NewText = f.ToText }))) lintFixes.[uri] <- fs """ diff --git a/src/Fantomas.Tests/TypeDeclarationTests.fs b/src/Fantomas.Tests/TypeDeclarationTests.fs index 8c7c8f790f..8f941cce01 100644 --- a/src/Fantomas.Tests/TypeDeclarationTests.fs +++ b/src/Fantomas.Tests/TypeDeclarationTests.fs @@ -748,17 +748,16 @@ type BlobHelper(Account : CloudStorageAccount) = """ type BlobHelper(Account: CloudStorageAccount) = new(configurationSettingName, hostedService) = - CloudStorageAccount.SetConfigurationSettingPublisher - (fun configName configSettingPublisher -> - let connectionString = - if hostedService then - RoleEnvironment.GetConfigurationSettingValue(configName) - else - ConfigurationManager.ConnectionStrings.[configName] - .ConnectionString - - configSettingPublisher.Invoke(connectionString) - |> ignore) + CloudStorageAccount.SetConfigurationSettingPublisher (fun configName configSettingPublisher -> + let connectionString = + if hostedService then + RoleEnvironment.GetConfigurationSettingValue(configName) + else + ConfigurationManager.ConnectionStrings.[configName] + .ConnectionString + + configSettingPublisher.Invoke(connectionString) + |> ignore) BlobHelper(CloudStorageAccount.FromConfigurationSetting(configurationSettingName)) """ @@ -2228,17 +2227,16 @@ type Auth0User = AppMetaData : AppMetaData } static member Decoder : Decoder = - Decode.object - (fun get -> - let userId = - get.Required.Field "user_id" Decode.string + Decode.object (fun get -> + let userId = + get.Required.Field "user_id" Decode.string - let metaData = - get.Optional.Field "app_metadata" AppMetaData.Decoder - |> Option.defaultValue ({ PushNotificationSubscriptions = [] }) + let metaData = + get.Optional.Field "app_metadata" AppMetaData.Decoder + |> Option.defaultValue ({ PushNotificationSubscriptions = [] }) - { UserId = userId - AppMetaData = metaData }) + { UserId = userId + AppMetaData = metaData }) """ [] diff --git a/src/Fantomas/CodePrinter.fs b/src/Fantomas/CodePrinter.fs index df806bc9d0..0af9a99625 100644 --- a/src/Fantomas/CodePrinter.fs +++ b/src/Fantomas/CodePrinter.fs @@ -1599,10 +1599,6 @@ and genExpr astContext synExpr ctx = List.last pats |> fun lastPat -> ctx.MkRange lastPat.Range.End expr.Range.Start - let hasLineCommentAfterArrow = - findTriviaTokenFromName RARROW arrowRange ctx - |> Option.isSome - let body = genExprKeepIndentInBranch astContext expr @@ -1617,31 +1613,23 @@ and genExpr astContext synExpr ctx = +> triviaOfLambda printContentBefore -- "fun " +> col sepSpace pats (genPat astContext) - +> indent - +> triviaAfterArrow arrowRange +> (fun ctx -> - if ctx.Config.MultiLineLambdaClosingNewline then - (leadingExpressionIsMultiline - (ifElse hasLineCommentAfterArrow body (sepSpaceOrNlnIfExpressionExceedsPageWidth body) - +> triviaOfLambda printContentAfter - +> unindent) - (fun isMultiline -> onlyIf isMultiline sepNln) - +> sepCloseTFor rpr pr) - ctx - else - (ifElse - hasLineCommentAfterArrow + if not ctx.Config.MultiLineLambdaClosingNewline then + genArrowWithTrivia (body +> triviaOfLambda printContentAfter +> sepNlnWhenWriteBeforeNewlineNotEmpty id +> sepCloseTFor rpr pr) - (autoNlnIfExpressionExceedsPageWidth ( - body - +> triviaOfLambda printContentAfter - +> sepNlnWhenWriteBeforeNewlineNotEmpty id - +> sepCloseTFor rpr pr - )) - +> unindent) + arrowRange + ctx + else + leadingExpressionIsMultiline + (genArrowWithTrivia + (body + +> triviaOfLambda printContentAfter + +> sepNlnWhenWriteBeforeNewlineNotEmpty id) + arrowRange) + (fun isMultiline -> onlyIf isMultiline sepNln +> sepCloseTFor rpr pr) ctx) expr ctx @@ -2065,6 +2053,8 @@ and genExpr astContext synExpr ctx = fun ctx -> isShortExpression ctx.Config.MaxDotGetExpressionWidth short long ctx + // (*) (60. * 1.1515 * 1.609344) + // function is wrapped in parenthesis | AppParenArg (Choice1Of2 (Paren _, _, _, _, _, _) as app) | AppParenArg (Choice2Of2 (Paren _, _, _, _, _) as app) -> let short = genAppWithParenthesis app astContext @@ -2093,6 +2083,203 @@ and genExpr astContext synExpr ctx = expressionFitsOnRestOfLine short long + // functionName arg1 arg2 (fun x y z -> ...) + | AppWithLambda (e, es, lpr, lambda, rpr, pr) -> + let sepSpaceAfterFunctionName ctx = + match List.tryHead es with + | Some (SimpleExpr _) -> sepSpace ctx + | _ -> + match e with + | UppercaseSynExpr -> onlyIf ctx.Config.SpaceBeforeUppercaseInvocation sepSpace ctx + | LowercaseSynExpr -> onlyIf ctx.Config.SpaceBeforeLowercaseInvocation sepSpace ctx + + let arrowRange pats (bodyExpr: SynExpr) = + List.last pats + |> fun (lastPat: SynPat) -> ctx.MkRange lastPat.Range.End bodyExpr.Range.Start + + let short = + genExpr astContext e + +> sepSpaceAfterFunctionName + +> col sepSpace es (genExpr astContext) + +> onlyIf (List.isNotEmpty es) sepSpace + +> (sepOpenTFor lpr + +> (match lambda with + | Choice1Of2 (pats, body, lambdaRange) -> + !- "fun " + +> col sepSpace pats (genPat astContext) + +> tokN (arrowRange pats body) RARROW sepArrow + +> genExprKeepIndentInBranch astContext body + |> genTriviaFor SynExpr_Lambda lambdaRange + | Choice2Of2 (keywordRange, cs, range) -> + (!- "function " + |> genTriviaFor SynExpr_MatchLambda_Function keywordRange) + +> indent + +> sepNln + +> genClauses astContext cs + +> unindent + |> genTriviaFor SynExpr_MatchLambda range) + +> sepNlnWhenWriteBeforeNewlineNotEmpty sepNone + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr) + + let long (ctx: Context) : Context = + if ctx.Config.MultiLineLambdaClosingNewline then + let genArguments = + match es with + | [] -> + match lambda with + | Choice1Of2 (pats, bodyExpr, range) -> + sepOpenTFor lpr + +> (!- "fun " + +> col sepSpace pats (genPat astContext) + +> genArrowWithTrivia + (genExprKeepIndentInBranch astContext bodyExpr) + (arrowRange pats bodyExpr) + |> genTriviaFor SynExpr_Lambda range) + +> sepNln + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr + | Choice2Of2 (keywordRange, cs, matchLambdaRange) -> + sepOpenTFor lpr + +> indent + +> sepNln + +> ((!- "function " + |> genTriviaFor SynExpr_MatchLambda_Function keywordRange) + +> sepNln + +> genClauses astContext cs + |> genTriviaFor SynExpr_MatchLambda matchLambdaRange) + +> unindent + +> sepNln + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr + + | es -> + col sepNln es (genExpr astContext) + +> sepNln + +> (match lambda with + | Choice1Of2 (pats, bodyExpr, range) -> + genLambdaMultiLineClosingNewline astContext lpr pats bodyExpr range rpr pr + | Choice2Of2 (keywordRange, cs, matchLambdaRange) -> + (sepOpenTFor lpr + +> ((!- "function " + |> genTriviaFor SynExpr_MatchLambda_Function keywordRange) + +> sepNln + +> genClauses astContext cs + |> genTriviaFor SynExpr_MatchLambda matchLambdaRange) + +> sepNln + +> sepCloseTFor rpr pr) + |> genTriviaFor SynExpr_Paren pr) + +> unindent + + (genExpr astContext e + +> ifElse (List.isEmpty es) sepSpaceAfterFunctionName (indent +> sepNln) + +> genArguments) + ctx + else + match lambda with + | Choice1Of2 (pats, body, lambdaRange) -> + let arrowRange = arrowRange pats body + + let singleLineTestExpr = + genExpr astContext e + +> sepSpaceAfterFunctionName + +> col sepSpace es (genExpr astContext) + +> sepSpace + +> enterNodeFor SynExpr_Paren pr + +> sepOpenTFor lpr + +> enterNodeFor SynExpr_Lambda lambdaRange + +> !- "fun " + +> col sepSpace pats (genPat astContext) + +> tokN arrowRange RARROW sepArrow + + let singleLine = + genExpr astContext e + +> sepSpaceAfterFunctionName + +> col sepSpace es (genExpr astContext) + +> sepSpace + +> (sepOpenTFor lpr + +> (!- "fun " + +> col sepSpace pats (genPat astContext) + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext body) arrowRange + |> genTriviaFor SynExpr_Lambda lambdaRange) + +> sepNlnWhenWriteBeforeNewlineNotEmpty sepNone + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr) + + let multiLine = + genExpr astContext e + +> indent + +> sepNln + +> col sepNln es (genExpr astContext) + +> sepNln + +> (sepOpenTFor lpr + +> (!- "fun " + +> col sepSpace pats (genPat astContext) + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext body) arrowRange + |> genTriviaFor SynExpr_Lambda lambdaRange) + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr) + +> unindent + + if futureNlnCheck singleLineTestExpr ctx then + multiLine ctx + else + singleLine ctx + + | Choice2Of2 (keywordRange, cs, matchLambdaRange) -> + let singleLineTestExpr = + genExpr astContext e + +> sepSpaceAfterFunctionName + +> col sepSpace es (genExpr astContext) + +> enterNodeFor SynExpr_Paren pr + +> sepOpenTFor lpr + +> enterNodeFor SynExpr_MatchLambda matchLambdaRange + +> enterNodeFor SynExpr_MatchLambda_Function keywordRange + +> !- "function " + + let singleLine = + genExpr astContext e + +> sepSpaceAfterFunctionName + +> col sepSpace es (genExpr astContext) + +> sepSpace + +> (sepOpenTFor lpr + +> ((!- "function " + |> genTriviaFor SynExpr_MatchLambda_Function keywordRange) + +> indent + +> sepNln + +> genClauses astContext cs + +> unindent + |> genTriviaFor SynExpr_MatchLambda matchLambdaRange) + +> sepNlnWhenWriteBeforeNewlineNotEmpty id + +> unindent + +> sepCloseTFor rpr pr) + |> genTriviaFor SynExpr_Paren pr + + let multiLine = + genExpr astContext e + +> indent + +> sepNln + +> col sepNln es (genExpr astContext) + +> sepNln + +> (sepOpenTFor lpr + +> atCurrentColumn ( + (!- "function " + |> genTriviaFor SynExpr_MatchLambda_Function keywordRange) + +> sepNln + +> genClauses astContext cs + |> genTriviaFor SynExpr_MatchLambda matchLambdaRange + ) + +> sepCloseTFor rpr pr + |> genTriviaFor SynExpr_Paren pr) + +> unindent + + if futureNlnCheck singleLineTestExpr ctx then + multiLine ctx + else + singleLine ctx + + expressionFitsOnRestOfLine short long + // Always spacing in multiple arguments | App (e, es) -> genApp astContext e es | TypeApp (e, lt, ts, gt) -> @@ -2807,11 +2994,7 @@ and genMultilineFunctionApplicationArguments astContext argExpr = (sepOpenTFor lpr +> (!- "fun " +> col sepSpace pats (genPat astContext) - +> triviaAfterArrow arrowRange - +> indent - +> sepNln - +> genExprKeepIndentInBranch astContext body - +> unindent + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext body) arrowRange |> genTriviaFor SynExpr_Lambda range) +> sepNln +> sepCloseTFor rpr pr) @@ -3196,14 +3379,14 @@ and genApp astContext e es ctx = let longExpression = if shouldHaveAlternativeLambdaStyle then - let hasMultipleArguments = (List.length es) > 1 - - let sepSpaceAfterFunctionName ctx = - match e with - | UppercaseSynExpr -> onlyIf ctx.Config.SpaceBeforeUppercaseInvocation sepSpace ctx - | LowercaseSynExpr -> onlyIf ctx.Config.SpaceBeforeLowercaseInvocation sepSpace ctx - - let multipleArguments = + // sample: + // myFunction + // argumentOne + // (fun x -> + // // foo + // x = 12 + // ) + let argExpr = col sepNln es @@ -3219,10 +3402,7 @@ and genApp astContext e es ctx = leadingExpressionIsMultiline (sepOpenTFor lpr -- "fun " +> pats - +> indent - +> triviaAfterArrow arrowRange - +> autoNlnIfExpressionExceedsPageWidth (genExprKeepIndentInBranch astContext bodyExpr) - +> unindent) + +> genArrowWithTrivia (genExprKeepIndentInBranch astContext bodyExpr) arrowRange) (fun isMultiline -> onlyIf isMultiline sepNln +> sepCloseTFor rpr e.Range) @@ -3237,51 +3417,11 @@ and genApp astContext e es ctx = genLambda (col sepSpace pats (genPat astContext)) expr lpr rpr arrowRange pr | _ -> genExpr astContext e) - let singleLambdaArgument = - col - sepSpace - es - (fun e -> - let genLambda pats (bodyExpr: SynExpr) lpr rpr arrowRange lambdaRange = - sepOpenTFor lpr - +> (!- "fun " - +> pats - +> indent - +> triviaAfterArrow arrowRange - +> autoNlnIfExpressionExceedsPageWidth (genExprKeepIndentInBranch astContext bodyExpr) - |> genTriviaFor SynExpr_Lambda lambdaRange) - +> unindent - +> sepNln - +> sepCloseTFor rpr e.Range - - match e with - | Paren (lpr, Lambda (pats, expr, range), rpr, _) -> - let arrowRange = - List.last pats - |> fun lastPat -> ctx.MkRange lastPat.Range.End expr.Range.Start - - genLambda (col sepSpace pats (genPat astContext)) expr lpr rpr arrowRange range - | Paren (lpr, (MatchLambda _ as me), rpr, pr) -> - sepOpenTFor lpr - +> indent - +> sepNln - +> genExpr astContext me - +> unindent - +> sepNln - +> sepCloseTFor rpr e.Range - |> genTriviaFor SynExpr_Paren pr - | _ -> genExpr astContext e) - - let argExpr = - if hasMultipleArguments then - multipleArguments - else - singleLambdaArgument - genExpr astContext e - +> ifElse (not hasMultipleArguments) sepSpaceAfterFunctionName (indent +> sepNln) + +> indent + +> sepNln +> argExpr - +> onlyIf hasMultipleArguments unindent + +> unindent else atCurrentColumn ( genExpr astContext e @@ -3300,6 +3440,27 @@ and genApp astContext e es ctx = else expressionFitsOnRestOfLine shortExpression longExpression ctx +and genLambdaMultiLineClosingNewline + (astContext: ASTContext) + (lpr: Range) + (pats: SynPat list) + (bodyExpr: SynExpr) + (lambdaRange: Range) + (rpr: Range option) + (pr: Range) + : Context -> Context = + let arrowRange (ctx: Context) = + List.last pats + |> fun lastPat -> ctx.MkRange lastPat.Range.End bodyExpr.Range.Start + + leadingExpressionIsMultiline + (sepOpenTFor lpr -- "fun " + +> col sepSpace pats (genPat astContext) + +> (fun ctx -> genArrowWithTrivia (genExprKeepIndentInBranch astContext bodyExpr) (arrowRange ctx) ctx) + |> genTriviaFor SynExpr_Lambda lambdaRange) + (fun isMultiline -> onlyIf isMultiline sepNln +> sepCloseTFor rpr pr) + |> genTriviaFor SynExpr_Paren pr + and genAppWithTupledArgument (e, lpr, ts, tr, rpr, pr) astContext = genExpr astContext e +> sepSpace diff --git a/src/Fantomas/SourceParser.fs b/src/Fantomas/SourceParser.fs index 4bf644575e..0eeab1c7d3 100644 --- a/src/Fantomas/SourceParser.fs +++ b/src/Fantomas/SourceParser.fs @@ -1278,6 +1278,25 @@ let (|Lambda|_|) = Some(pats, getLambdaBodyExpr body, range) | _ -> None +let (|AppWithLambda|_|) (e: SynExpr) = + match e with + | App (e, es) -> + let rec visit (es: SynExpr list) (finalContinuation: SynExpr list -> SynExpr list) = + match es with + | [] -> None + | [ Paren (lpr, Lambda (pats, body, range), rpr, pr) ] -> + Some(e, finalContinuation [], lpr, (Choice1Of2(pats, body, range)), rpr, pr) + | [ Paren (lpr, (MatchLambda (keywordRange, pats) as me), rpr, pr) ] -> + Some(e, finalContinuation [], lpr, (Choice2Of2(keywordRange, pats, me.Range)), rpr, pr) + | h :: tail -> + match h with + | Paren (_, Lambda _, _, _) + | Paren (_, MatchLambda _, _, _) -> None + | _ -> visit tail (fun leadingArguments -> h :: leadingArguments |> finalContinuation) + + visit es id + | _ -> None + // Type definitions let (|TDSREnum|TDSRUnion|TDSRRecord|TDSRNone|TDSRTypeAbbrev|TDSRException|) = diff --git a/src/Fantomas/TriviaContext.fs b/src/Fantomas/TriviaContext.fs index 264bb8fa87..d05d526a9c 100644 --- a/src/Fantomas/TriviaContext.fs +++ b/src/Fantomas/TriviaContext.fs @@ -15,21 +15,13 @@ let sepOpenTFor r = tokN r LPAREN sepOpenT let sepCloseTFor rpr pr = tokN (Option.defaultValue pr rpr) RPAREN sepCloseT -let triviaAfterArrow (range: Range) (ctx: Context) = - let hasCommentAfterArrow = - findTriviaTokenFromName RARROW range ctx - |> Option.bind - (fun t -> - t.ContentAfter - |> List.tryFind - (function - | Comment (LineCommentAfterSourceCode _) -> true - | _ -> false)) - |> Option.isSome - - ((tokN range RARROW sepArrow) - +> ifElse hasCommentAfterArrow sepNln sepNone) - ctx +let genArrowWithTrivia (bodyExpr: Context -> Context) (range: Range) = + (tokN range RARROW sepArrow) + +> (fun ctx -> + if String.isNotNullOrEmpty ctx.WriterModel.WriteBeforeNewline then + (indent +> sepNln +> bodyExpr +> unindent) ctx + else + (autoIndentAndNlnIfExpressionExceedsPageWidth bodyExpr) ctx) let ``else if / elif`` (rangeOfIfThenElse: Range) (ctx: Context) = let keywords =