forked from fsprojects/fantomas
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
CodePrinter.fs
2812 lines (2449 loc) · 123 KB
/
CodePrinter.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module internal Fantomas.CodePrinter
open System
open System.Text.RegularExpressions
open FSharp.Compiler.Range
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.SyntaxTree
open Fantomas
open Fantomas.FormatConfig
open Fantomas.SourceParser
open Fantomas.SourceTransformer
open Fantomas.Context
open Fantomas.TriviaTypes
open Fantomas.TriviaContext
/// This type consists of contextual information which is important for formatting
type ASTContext =
{
/// Original file name without extension of the parsed AST
TopLevelModuleName: string
/// Current node is the first child of its parent
IsFirstChild: bool
/// Current node is a subnode deep down in an interface
InterfaceRange: range option
/// This pattern matters for formatting extern declarations
IsCStylePattern: bool
/// Range operators are naked in 'for..in..do' constructs
IsNakedRange: bool
/// The optional `|` in pattern matching and union type definitions
HasVerticalBar: bool
/// A field is rendered as union field or not
IsUnionField: bool
/// First type param might need extra spaces to avoid parsing errors on `<^`, `<'`, etc.
IsFirstTypeParam: bool
/// Check whether the context is inside DotGet to suppress whitespaces
IsInsideDotGet: bool
/// Check whether the context is inside a SynMemberDefn.Member(memberDefn,range)
/// This is required to correctly detect the setting SpaceBeforeMember
IsMemberDefinition: bool
}
static member Default =
{ TopLevelModuleName = ""
IsFirstChild = false; InterfaceRange = None
IsCStylePattern = false; IsNakedRange = false
HasVerticalBar = false; IsUnionField = false
IsFirstTypeParam = false; IsInsideDotGet = false
IsMemberDefinition = false }
let rec addSpaceBeforeParensInFunCall functionOrMethod arg (ctx:Context) =
match functionOrMethod, arg with
| SynExpr.TypeApp(e, _, _, _, _, _, _), _ ->
addSpaceBeforeParensInFunCall e arg ctx
| SynExpr.Paren _, _ ->
true
| UppercaseSynExpr, ConstExpr(Const "()", _) ->
ctx.Config.SpaceBeforeUppercaseInvocation
| LowercaseSynExpr, ConstExpr(Const "()", _) ->
ctx.Config.SpaceBeforeLowercaseInvocation
| SynExpr.Ident(_), SynExpr.Ident(_) ->
true
| UppercaseSynExpr, Paren(_) ->
ctx.Config.SpaceBeforeUppercaseInvocation
| LowercaseSynExpr, Paren(_) ->
ctx.Config.SpaceBeforeLowercaseInvocation
| _ -> true
let addSpaceBeforeParensInFunDef (astContext: ASTContext) (functionOrMethod:string) args (ctx:Context) =
let isLastPartUppercase =
let parts = functionOrMethod.Split '.'
Char.IsUpper parts.[parts.Length - 1].[0]
match functionOrMethod, args with
| "new", _ -> false
| _, PatParen(_) ->
if astContext.IsMemberDefinition
then ctx.Config.SpaceBeforeMember
else ctx.Config.SpaceBeforeParameter
| (_:string), _ -> not isLastPartUppercase
| _ -> true
let rec genParsedInput astContext = function
| ImplFile im -> genImpFile astContext im
| SigFile si -> genSigFile astContext si
(*
See https://github.com/fsharp/FSharp.Compiler.Service/blob/master/src/fsharp/ast.fs#L1518
hs = hashDirectives : ParsedHashDirective list
mns = modules : SynModuleOrNamespace list
*)
and genImpFile astContext (ParsedImplFileInput(hs, mns)) =
col sepNone hs genParsedHashDirective +> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns (genModuleOrNamespace astContext)
and genSigFile astContext (ParsedSigFileInput(hs, mns)) =
col sepNone hs genParsedHashDirective +> (if hs.IsEmpty then sepNone else sepNln)
+> col sepNln mns (genSigModuleOrNamespace astContext)
and genParsedHashDirective (ParsedHashDirective(h, s, r)) =
let printArgument arg =
match arg with
| "" -> sepNone
// Use verbatim string to escape '\' correctly
| _ when arg.Contains("\\") -> !- (sprintf "@\"%O\"" arg)
| _ -> !- (sprintf "\"%O\"" arg)
let printIdent (ctx:Context) =
ctx.Trivia
|> List.tryFind (fun t -> t.Range = r)
|> Option.bind(fun t -> t.ContentBefore
|> List.choose (fun tc ->
match tc with
| Keyword({ TokenInfo = {TokenName = "KEYWORD_STRING"}; Content = c }) -> Some c
| _ -> None)
|> List.tryHead)
|> function
| Some kw -> !- kw
| None -> col sepSpace s printArgument
<| ctx
!- "#" -- h +> sepSpace +> printIdent
|> genTrivia r
and genModuleOrNamespace astContext (ModuleOrNamespace(ats, px, ao, s, mds, isRecursive, moduleKind) as node) =
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> rep 2 sepNln
| Some mdl ->
let attrRanges = getRangesFromAttributesFromModuleDeclaration mdl
sepNlnConsideringTriviaContentBeforeWithAttributes mdl.Range attrRanges +> sepNln
let genTriviaForLongIdent (f: Context -> Context) =
match node with
| SynModuleOrNamespace.SynModuleOrNamespace(lid,_, SynModuleOrNamespaceKind.DeclaredNamespace,_,_,_,_,_) ->
lid
|> List.fold (fun (acc: Context -> Context) (ident:Ident) -> acc |> (genTrivia ident.idRange)) f
| _ -> f
let moduleOrNamespace = ifElse moduleKind.IsModule (!- "module ") (!- "namespace ")
let recursive = ifElse isRecursive (!- "rec ") sepNone
let namespaceFn = ifElse (s = "") (!- "global") (!- s)
let namespaceIsGlobal = not moduleKind.IsModule && s = ""
let sep =
if namespaceIsGlobal
then sepNln +> sepNlnConsideringTriviaContentBefore node.Range
else sepModuleAndFirstDecl
let expr =
genPreXmlDoc px
+> genAttributes astContext ats
+> ifElse (moduleKind = AnonModule)
sepNone
(genTriviaForLongIdent (moduleOrNamespace +> opt sepSpace ao genAccess +> recursive +> namespaceFn +> sep))
if namespaceIsGlobal then
expr +> genTrivia node.Range (genModuleDeclList astContext mds)
else
expr +> genModuleDeclList astContext mds
|> genTrivia node.Range
and genSigModuleOrNamespace astContext (SigModuleOrNamespace(ats, px, ao, s, mds, _, moduleKind) as node) =
let range = match node with | SynModuleOrNamespaceSig(_,_,_,_,_,_,_,range) -> range
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None -> rep 2 sepNln
| Some mdl ->
sepNlnConsideringTriviaContentBefore mdl.Range +> sepNln
let genTriviaForLongIdent (f: Context -> Context) =
match node with
| SynModuleOrNamespaceSig(lid,_, SynModuleOrNamespaceKind.DeclaredNamespace,_,_,_,_,_) ->
lid
|> List.fold (fun (acc: Context -> Context) (ident:Ident) -> acc |> (genTrivia ident.idRange)) f
| _ -> f
let moduleOrNamespace = ifElse moduleKind.IsModule (!- "module ") (!- "namespace ")
// Don't generate trivia before in case the SynModuleOrNamespaceKind is a DeclaredNamespace
// The range of the namespace is not correct, see https://github.com/dotnet/fsharp/issues/7680
ifElse moduleKind.IsModule (enterNode range) sepNone +>
genPreXmlDoc px
+> genAttributes astContext ats
+> ifElse (moduleKind = AnonModule)
sepNone
(genTriviaForLongIdent (moduleOrNamespace +> opt sepSpace ao genAccess -- s +> sepModuleAndFirstDecl))
+> genSigModuleDeclList astContext mds
+> leaveNode range
and genModuleDeclList astContext e =
match e with
| OpenL(xs, ys) ->
match ys with
| [] -> col sepNln xs (genModuleDecl astContext)
| _ ->
let sepModuleDecl =
match List.tryHead ys with
| Some ysh ->
let attrs = getRangesFromAttributesFromModuleDeclaration ysh
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes ysh.Range attrs
| None -> rep 2 sepNln
(col sepNln xs (genModuleDecl astContext) +> sepModuleDecl +> genModuleDeclList astContext ys)
| m::rest ->
let attrs = getRangesFromAttributesFromModuleDeclaration m
let newlineAfterMultiline ctx =
let expr =
match List.tryHead rest with
| Some rm ->
let attrs = getRangesFromAttributesFromModuleDeclaration rm
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes rm.Range attrs
| None -> sepNone
expr ctx
// Call trivia manually before genLetBinding
// Otherwise the expression might become multiline because of comments or defines above the let binding
enterNode m.Range
+> leadingExpressionIsMultiline
(expressionFitsOnRestOfLine
(genModuleDecl astContext m)
(sepNlnBeforeMultilineConstruct m.Range attrs +> genModuleDecl astContext m +> newlineAfterMultiline))
(fun multiline -> onlyIf (not multiline && List.isNotEmpty rest) sepNln)
+> genModuleDeclList astContext rest
| [] -> sepNone
and genSigModuleDeclList astContext node =
match node with
| [x] -> genSigModuleDecl astContext x
| SigOpenL(xs, ys) ->
let sepXsAndYs =
match List.tryHead ys with
| Some hs ->
let attrs = getRangesFromAttributesFromSynModuleSigDeclaration hs
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes hs.Range attrs +> dumpAndContinue
| None ->
rep 2 sepNln
fun ctx ->
match ys with
| [] -> col sepNln xs (genSigModuleDecl astContext) ctx
| _ -> (col sepNln xs (genSigModuleDecl astContext) +> sepXsAndYs +> genSigModuleDeclList astContext ys) ctx
| SigHashDirectiveL(xs, ys) ->
match ys with
| [] -> col sepNone xs (genSigModuleDecl astContext)
| _ -> col sepNone xs (genSigModuleDecl astContext) +> sepNln +> genSigModuleDeclList astContext ys
| SigModuleAbbrevL(xs, ys)
| SigValL(xs, ys) ->
match ys with
| [] -> col sepNln xs (genSigModuleDecl astContext)
| _ ->
let sepXsYs =
match List.tryHead ys with
| Some ysh ->
let attributeRanges = getRangesFromAttributesFromSynModuleSigDeclaration ysh
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes ysh.Range attributeRanges
| None -> rep 2 sepNln
col sepNln xs (genSigModuleDecl astContext) +> sepXsYs +> genSigModuleDeclList astContext ys
| SigMultilineModuleDeclL(xs, ys) ->
match ys with
| [] ->
colEx (fun (smd: SynModuleSigDecl) ->
let ranges = getRangesFromAttributesFromSynModuleSigDeclaration smd
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes smd.Range ranges
) xs (genSigModuleDecl astContext)
| _ -> col (rep 2 sepNln) xs (genSigModuleDecl astContext) +> rep 2 sepNln +> genSigModuleDeclList astContext ys
| _ -> sepNone
// |> genTrivia node, see genModuleDeclList
and genModuleDecl astContext (node: SynModuleDecl) =
match node with
| Attributes(ats) ->
fun ctx ->
let attributesExpr =
// attributes can have trivia content before or after
// we do extra detection to ensure no additional newline is introduced
// first attribute should not have a newline anyway
List.fold (fun (prevContentAfterPresent, prevExpr) (a: SynAttributeList) ->
let expr =
ifElse prevContentAfterPresent sepNone (sepNlnConsideringTriviaContentBefore a.Range)
+> ((col sepNln a.Attributes (genAttribute astContext)) |> genTrivia a.Range)
let hasContentAfter =
TriviaHelpers.``has content after after that matches``
(fun tn -> tn.Range = a.Range)
(function | Directive(_) -> true | _ -> false)
ctx.Trivia
(hasContentAfter, prevExpr +> expr)
) (true, sepNone) ats
|> snd
(attributesExpr +> dumpAndContinue) ctx
| DoExpr(e) ->
genExpr astContext e
| Exception(ex) ->
genException astContext ex
| HashDirective(p) ->
genParsedHashDirective p
| Extern(ats, px, ao, t, s, ps) ->
genPreXmlDoc px
+> genAttributes astContext ats
-- "extern " +> genType { astContext with IsCStylePattern = true } false t +> sepSpace +> opt sepSpace ao genAccess
-- s +> sepOpenT +> col sepComma ps (genPat { astContext with IsCStylePattern = true }) +> sepCloseT
// Add a new line after module-level let bindings
| Let(b) ->
genLetBinding { astContext with IsFirstChild = true } "let " b
| LetRec(b::bs) ->
let sepBAndBs =
match List.tryHead bs with
| Some b' ->
let r = b'.RangeOfBindingSansRhs
sepNln +> sepNlnConsideringTriviaContentBefore r
| None -> id
genLetBinding { astContext with IsFirstChild = true } "let rec " b
+> sepBAndBs
+> colEx (fun (b': SynBinding) ->
let r = b'.RangeOfBindingSansRhs
sepNln +> sepNlnConsideringTriviaContentBefore r
) bs (genLetBinding { astContext with IsFirstChild = false } "and ")
| ModuleAbbrev(s1, s2) ->
!- "module " -- s1 +> sepEq +> sepSpace -- s2
| NamespaceFragment(m) ->
failwithf "NamespaceFragment hasn't been implemented yet: %O" m
| NestedModule(ats, px, ao, s, isRecursive, mds) ->
genPreXmlDoc px
+> genAttributes astContext ats
+> (!- "module ")
+> opt sepSpace ao genAccess
+> ifElse isRecursive (!- "rec ") sepNone -- s +> sepEq
+> indent +> sepNln
+> genModuleDeclList astContext mds +> unindent
| Open(s) ->
!- (sprintf "open %s" s)
// There is no nested types and they are recursive if there are more than one definition
| Types(t::ts) ->
let sepTs =
match List.tryHead ts with
| Some tsh -> sepNln +> sepNlnConsideringTriviaContentBefore tsh.Range
| None -> rep 2 sepNln
genTypeDefn { astContext with IsFirstChild = true } t
+> colPreEx sepTs (fun (ty: SynTypeDefn) -> sepNln +> sepNlnConsideringTriviaContentBefore ty.Range) ts (genTypeDefn { astContext with IsFirstChild = false })
| md ->
failwithf "Unexpected module declaration: %O" md
|> genTrivia node.Range
and genSigModuleDecl astContext node =
match node with
| SigException(ex) ->
genSigException astContext ex
| SigHashDirective(p) ->
genParsedHashDirective p
| SigVal(v) ->
genVal astContext v
| SigModuleAbbrev(s1, s2) ->
!- "module " -- s1 +> sepEq +> sepSpace -- s2
| SigNamespaceFragment(m) ->
failwithf "NamespaceFragment is not supported yet: %O" m
| SigNestedModule(ats, px, ao, s, mds) ->
genPreXmlDoc px
+> genAttributes astContext ats -- "module " +> opt sepSpace ao genAccess -- s +> sepEq
+> indent +> sepNln +> genSigModuleDeclList astContext mds +> unindent
| SigOpen(s) ->
!- (sprintf "open %s" s)
| SigTypes(t::ts) ->
genSigTypeDefn { astContext with IsFirstChild = true } t
+> colPre (rep 2 sepNln) (rep 2 sepNln) ts (genSigTypeDefn { astContext with IsFirstChild = false })
| md ->
failwithf "Unexpected module signature declaration: %O" md
|> genTrivia node.Range
and genAccess (Access s) = !- s
and genAttribute astContext (Attribute(s, e, target)) =
match e with
// Special treatment for function application on attributes
| ConstExpr(Const "()", _) ->
!- "[<" +> opt sepColonFixed target (!-) -- s -- ">]"
| e ->
let argSpacing =
if SourceTransformer.hasParenthesis e then id else sepSpace
!- "[<" +> opt sepColonFixed target (!-) -- s +> argSpacing +> genExpr astContext e -- ">]"
|> genTrivia e.Range
and genAttributesCore astContext (ats: SynAttribute seq) =
let genAttributeExpr astContext (Attribute(s, e, target) as attr) =
match e with
| ConstExpr(Const "()", _) ->
opt sepColonFixed target (!-) -- s
| e ->
let argSpacing =
if SourceTransformer.hasParenthesis e then id else sepSpace
opt sepColonFixed target (!-) -- s +> argSpacing +> genExpr astContext e
|> genTrivia attr.Range
ifElse (Seq.isEmpty ats) sepNone (!- "[<" +> col sepSemi ats (genAttributeExpr astContext) -- ">]")
and genOnelinerAttributes astContext ats =
let ats = List.collect (fun a -> a.Attributes) ats
ifElse (Seq.isEmpty ats) sepNone (genAttributesCore astContext ats +> sepSpace)
/// Try to group attributes if they are on the same line
/// Separate same-line attributes by ';'
/// Each bucket is printed in a different line
and genAttributes astContext (ats: SynAttributes) =
ats
|> List.fold (fun acc a ->
fun (ctx:Context) ->
let dontAddNewline =
TriviaHelpers.``has content after that ends with``
(fun t -> t.Range = a.Range)
(function | Directive(_) | Newline -> true | _ -> false)
ctx.Trivia
let chain =
acc +>
(genAttributesCore astContext a.Attributes |> genTrivia a.Range)
+> ifElse dontAddNewline sepNone sepNln
chain ctx
) sepNone
and genPreXmlDoc (PreXmlDoc lines) ctx =
if ctx.Config.StrictMode then
colPost sepNln sepNln lines (sprintf "///%s" >> (!-)) ctx
else ctx
and addSpaceAfterGenericConstructBeforeColon ctx =
if not ctx.Config.SpaceBeforeColon then
match Context.lastWriteEventOnLastLine ctx |> Option.bind Seq.tryLast with
| Some('>') -> sepSpace
| _ -> sepNone
else
sepNone
<| ctx
and genExprSepEqPrependType astContext (pat:SynPat) (e: SynExpr) (isPrefixMultiline: bool) ctx =
let hasTriviaContentAfterEqual =
ctx.Trivia
|> List.exists (fun tn ->
match tn.Type with
| TriviaTypes.Token(tok) ->
tok.TokenInfo.TokenName = "EQUALS" && tn.Range.StartLine = pat.Range.StartLine
| _ -> false
)
let sepEqual predicate = ifElse predicate (indent +> sepNln +> !- "=" +> unindent) (sepEq +> sepSpace)
match e with
| TypedExpr(Typed, e, t) ->
let addExtraSpaceBeforeGenericType =
match pat with
| SynPat.LongIdent(_, _, Some(SynValTyparDecls(_)), _, _, _) ->
addSpaceAfterGenericConstructBeforeColon
| _ -> sepNone
let hasLineCommentBeforeColon = TriviaHelpers.``has line comment before`` t.Range ctx.Trivia
let genCommentBeforeColon ctx =
(ifElse hasLineCommentBeforeColon indent sepNone
+> enterNode t.Range
+> ifElse hasLineCommentBeforeColon unindent sepNone) ctx
(addExtraSpaceBeforeGenericType
+> genCommentBeforeColon
+> sepColon
+> genType astContext false t
+> sepEqual (isPrefixMultiline || hasLineCommentBeforeColon)
+> ifElse (isPrefixMultiline || hasTriviaContentAfterEqual || hasLineCommentBeforeColon)
(indent +> sepNln +> genExpr astContext e +> unindent)
(isShortExpressionOrAddIndentAndNewline ctx.Config.MaxLetBindingWidth (genExpr astContext e))) ctx
| e ->
let genE =
match e with
| MultilineString(_)
| _ when (TriviaHelpers.``has content itself that is multiline string`` e.Range ctx.Trivia) ->
genExpr astContext e
| _ -> isShortExpressionOrAddIndentAndNewline ctx.Config.MaxLetBindingWidth (genExpr astContext e)
(sepEqual isPrefixMultiline
+> leaveEqualsToken pat.Range
+> ifElse (isPrefixMultiline || hasTriviaContentAfterEqual)
(indent +> sepNln +> genExpr astContext e +> unindent)
genE) ctx
and genTyparList astContext tps =
ifElse (List.atMostOne tps) (col wordOr tps (genTypar astContext)) (sepOpenT +> col wordOr tps (genTypar astContext) +> sepCloseT)
and genTypeAndParam astContext typeName tds tcs preferPostfix =
let types openSep closeSep =
(!- openSep +> coli sepComma tds (fun i decl -> genTyparDecl { astContext with IsFirstTypeParam = i = 0 } decl)
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext) -- closeSep)
if List.isEmpty tds then !- typeName
elif preferPostfix then !- typeName +> types "<" ">"
elif List.atMostOne tds then types "" "" -- " " -- typeName
else types "(" ")" -- " " -- typeName
and genTypeParamPostfix astContext tds tcs = genTypeAndParam astContext "" tds tcs true
and genLetBinding astContext pref b =
match b with
| LetBinding(ats, px, ao, isInline, isMutable, p, e) ->
let genPat =
match e, p with
| TypedExpr(Typed, _, t), PatLongIdent(ao, s, ps, tpso) when (List.length ps > 1)->
genPatWithReturnType ao s ps tpso (Some t) astContext
| _, PatLongIdent(ao, s, ps, tpso) when (List.length ps > 1)->
genPatWithReturnType ao s ps tpso None astContext
| _ ->
genPat astContext p
let genAttr =
ifElse astContext.IsFirstChild
(genAttributes astContext ats -- pref)
(!- pref +> genOnelinerAttributes astContext ats)
let afterLetKeyword =
opt sepSpace ao genAccess
+> ifElse isMutable (!- "mutable ") sepNone
+> ifElse isInline (!- "inline ") sepNone
genPreXmlDoc px
+> genAttr // this already contains the `let` or `and` keyword
+> leadingExpressionIsMultiline (afterLetKeyword +> genPat) (genExprSepEqPrependType astContext p e)
| DoBinding(ats, px, e) ->
let prefix = if pref.Contains("let") then pref.Replace("let", "do") else "do "
genPreXmlDoc px
+> genAttributes astContext ats -- prefix
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| b ->
failwithf "%O isn't a let binding" b
|> genTrivia b.RangeOfBindingSansRhs
and genShortGetProperty astContext (pat:SynPat) e =
genExprSepEqPrependType astContext pat e false
and genProperty astContext prefix ao propertyKind ps e =
let tuplerize ps =
let rec loop acc = function
| [p] -> (List.rev acc, p)
| p1::ps -> loop (p1::acc) ps
| [] -> invalidArg "p" "Patterns should not be empty"
loop [] ps
match ps with
| [PatTuple ps] ->
let (ps, p) = tuplerize ps
!- prefix +> opt sepSpace ao genAccess -- propertyKind
+> ifElse (List.atMostOne ps) (col sepComma ps (genPat astContext) +> sepSpace)
(sepOpenT +> col sepComma ps (genPat astContext) +> sepCloseT +> sepSpace)
+> genPat astContext p +> genExprSepEqPrependType astContext p e false
| ps ->
let (_,p) = tuplerize ps
!- prefix +> opt sepSpace ao genAccess -- propertyKind +> col sepSpace ps (genPat astContext)
+> genExprSepEqPrependType astContext p e false
|> genTrivia e.Range
and genPropertyWithGetSet astContext (b1, b2) =
match b1, b2 with
| PropertyBinding(ats, px, ao, isInline, mf1, PatLongIdent(ao1, s1, ps1, _), e1),
PropertyBinding(_, _, _, _, _, PatLongIdent(ao2, _, ps2, _), e2) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats +> genMemberFlags astContext mf1
+> ifElse isInline (!- "inline ") sepNone +> opt sepSpace ao genAccess
assert(ps1 |> Seq.map fst |> Seq.forall Option.isNone)
assert(ps2 |> Seq.map fst |> Seq.forall Option.isNone)
let ps1 = List.map snd ps1
let ps2 = List.map snd ps2
prefix
+> genTrivia b1.RangeOfBindingAndRhs
(!- s1 +> indent +> sepNln
+> genProperty astContext "with " ao1 "get " ps1 e1 +> sepNln)
+> genTrivia b2.RangeOfBindingAndRhs
(genProperty astContext "and " ao2 "set " ps2 e2 +> unindent)
| _ -> sepNone
/// Each member is separated by a new line.
and genMemberBindingList astContext node =
let newlineAfterMultiline rest ctx =
let expr =
match List.tryHead rest with
| Some rm ->
let attrs = getRangesFromAttributesFromSynBinding rm
sepNln +> sepNlnConsideringTriviaContentBeforeWithAttributes rm.RangeOfBindingSansRhs attrs
| None -> sepNone
expr ctx
match node with
| PropertyWithGetSet(gs, rest) ->
leadingExpressionIsMultiline
(expressionFitsOnRestOfLine
(genPropertyWithGetSet astContext gs)
(sepNln +> genPropertyWithGetSet astContext gs +> newlineAfterMultiline rest))
(fun multiline -> onlyIf (not multiline && List.isNotEmpty rest) sepNln)
+> genMemberBindingList astContext rest
| mb::rest ->
leadingExpressionIsMultiline
(expressionFitsOnRestOfLine
(genMemberBinding astContext mb)
(genMemberBinding astContext mb +> newlineAfterMultiline rest))
(fun multiline -> onlyIf (not multiline && List.isNotEmpty rest) sepNln)
+> genMemberBindingList astContext rest
| _ -> sepNone
and genMemberBinding astContext b =
match b with
| PropertyBinding(ats, px, ao, isInline, mf, p, e) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats +> genMemberFlags astContext mf
+> ifElse isInline (!- "inline ") sepNone +> opt sepSpace ao genAccess
let propertyKind =
match mf with
| MFProperty PropertyGet -> "get "
| MFProperty PropertySet -> "set "
| mf -> failwithf "Unexpected member flags: %O" mf
match p with
| PatLongIdent(ao, s, ps, _) ->
assert (ps |> Seq.map fst |> Seq.forall Option.isNone)
match ao, propertyKind, ps with
| None, "get ", [_, PatParen(PatConst(Const "()", _))] ->
// Provide short-hand notation `x.Member = ...` for `x.Member with get()` getters
prefix -- s +> genShortGetProperty astContext p e
| _ ->
let ps = List.map snd ps
prefix -- s +> indent +> sepNln +>
genProperty astContext "with " ao propertyKind ps e
+> unindent
| p -> failwithf "Unexpected pattern: %O" p
| MemberBinding(ats, px, ao, isInline, mf, p, e) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats +> genMemberFlagsForMemberBinding astContext mf b.RangeOfBindingAndRhs
+> ifElse isInline (!- "inline ") sepNone +> opt sepSpace ao genAccess +> genPat ({ astContext with IsMemberDefinition = true }) p
match e with
| TypedExpr(Typed, e, t) -> prefix +> sepColon +> genType astContext false t +> sepEq +> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| e -> prefix +> sepEq +> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| ExplicitCtor(ats, px, ao, p, e, so) ->
let prefix =
genPreXmlDoc px
+> genAttributes astContext ats
+> opt sepSpace ao genAccess +> genPat astContext p
+> opt sepNone so (sprintf " as %s" >> (!-))
match e with
// Handle special "then" block i.e. fake sequential expressions in constructors
| Sequential(e1, e2, false) ->
prefix +> sepEq +> indent +> sepNln
+> genExpr astContext e1 ++ "then "
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e2)
+> unindent
| e -> prefix +> sepEq +> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| b -> failwithf "%O isn't a member binding" b
|> genTrivia b.RangeOfBindingSansRhs
and genMemberFlags astContext node =
match node with
| MFMember _ -> !- "member "
| MFStaticMember _ -> !- "static member "
| MFConstructor _ -> sepNone
| MFOverride _ -> ifElse astContext.InterfaceRange.IsSome (!- "member ") (!- "override ")
// |> genTrivia node check each case
and genMemberFlagsForMemberBinding astContext (mf:MemberFlags) (rangeOfBindingAndRhs: range) =
fun ctx ->
match mf with
| MFMember _
| MFStaticMember _
| MFConstructor _ ->
genMemberFlags astContext mf
| MFOverride _ ->
(fun (ctx: Context) ->
ctx.Trivia
|> List.tryFind(fun { Type = t; Range = r } ->
match t with
| MainNode "SynMemberDefn.Member" -> // trying to get AST trivia
RangeHelpers.``range contains`` r rangeOfBindingAndRhs
| Token { TokenInfo = { TokenName = "MEMBER" } } -> // trying to get token trivia
r.StartLine = rangeOfBindingAndRhs.StartLine
| _ -> false
)
|> Option.bind(fun tn ->
tn.ContentItself
|> Option.bind (fun tc ->
match tc with
| Keyword({ Content = ("override" | "default" | "member") as kw }) -> Some (!- (kw + " "))
| _ -> None
)
)
|> Option.defaultValue (!- "override ")
<| ctx
)
<| ctx
and genVal astContext (Val(ats, px, ao, s, t, vi, isInline, _) as node) =
let range, synValTyparDecls =
match node with
| ValSpfn(_,_, synValTyparDecls,_,_,_,_,_,_,_,range) -> range, synValTyparDecls
let genericParams =
match synValTyparDecls with
| SynValTyparDecls([], _, _) -> sepNone
| SynValTyparDecls(tpd, _, cst) -> genTypeParamPostfix astContext tpd cst
let (FunType namedArgs) = (t, vi)
genPreXmlDoc px
+> genAttributes astContext ats
+> atCurrentColumn (indent -- "val "
+> onlyIf isInline (!- "inline ")
+> opt sepSpace ao genAccess -- s
+> genericParams
+> addSpaceAfterGenericConstructBeforeColon
+> sepColon
+> ifElse (List.isNotEmpty namedArgs) (genTypeList astContext namedArgs) (genConstraints astContext t)
+> unindent)
|> genTrivia range
and genRecordFieldName astContext (RecordFieldName(s, eo) as node) =
let (rfn,_,_) = node
let range = (fst rfn).Range
opt sepNone eo (fun e ->
let expr =
match e with
| MultilineString _ -> sepSpace +> genExpr astContext e
| _ -> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!- s +> sepEq +> expr)
|> genTrivia range
and genAnonRecordFieldName astContext (AnonRecordFieldName(s, e)) =
let expr =
match e with
| MultilineString _ -> sepSpace +> genExpr astContext e
| _ -> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!- s +> sepEq +> expr
and genTuple astContext es =
let f = addParenForTupleWhen (genExpr astContext)
let shortExpression = col sepComma es f
let longExpression = col (sepComma +> sepNln) es f
atCurrentColumn (expressionFitsOnRestOfLine shortExpression longExpression)
and genExpr astContext synExpr =
let appNlnFun e =
match e with
| MultilineString _
| Lambda _
| Paren (Lambda _)
| Paren (MatchLambda _) -> id
| _ -> autoNlnIfExpressionExceedsPageWidth
let kw tokenName f = tokN synExpr.Range tokenName f
let sepOpenT = tokN synExpr.Range "LPAREN" sepOpenT
let sepCloseT = tokN synExpr.Range "RPAREN" sepCloseT
match synExpr with
| SingleExpr(Lazy, e) ->
// Always add braces when dealing with lazy
let hasParenthesis = hasParenthesis e
let isInfixExpr =
match e with
| InfixApps _ -> true
| _ -> false
let genInfixExpr (ctx: Context) =
isShortExpression
ctx.Config.MaxInfixOperatorExpression
// if this fits on the rest of line right after the lazy keyword, it should be wrapped in parenthesis.
(sepOpenT +> genExpr astContext e +> sepCloseT)
// if it is multiline there is no need for parenthesis, because of the indentation
(indent +> sepNln +> genExpr astContext e +> unindent)
ctx
let genNonInfixExpr =
autoIndentAndNlnIfExpressionExceedsPageWidth
(onlyIfNot hasParenthesis sepOpenT
+> genExpr astContext e
+> onlyIfNot hasParenthesis sepCloseT)
str "lazy "
+> ifElse isInfixExpr genInfixExpr genNonInfixExpr
| SingleExpr(kind, e) -> str kind +> genExpr astContext e
| ConstExpr(c,r) -> genConst c r
| NullExpr -> !- "null"
// Not sure about the role of e1
| Quote(_, e2, isRaw) ->
let e = genExpr astContext e2
ifElse isRaw (!- "<@@ " +> e -- " @@>") (!- "<@ " +> e -- " @>")
| TypedExpr(TypeTest, e, t) -> genExpr astContext e -- " :? " +> genType astContext false t
| TypedExpr(New, e, t) ->
!- "new " +> genType astContext false t +> ifElse (hasParenthesis e) sepNone sepSpace +> genExpr astContext e
| TypedExpr(Downcast, e, t) -> genExpr astContext e -- " :?> " +> genType astContext false t
| TypedExpr(Upcast, e, t) -> genExpr astContext e -- " :> " +> genType astContext false t
| TypedExpr(Typed, e, t) -> genExpr astContext e +> sepColon +> genType astContext false t
| Tuple es -> genTuple astContext es
| StructTuple es -> !- "struct " +> sepOpenT +> genTuple astContext es +> sepCloseT
| ArrayOrList(isArray, [], _) ->
ifElse isArray (sepOpenAFixed +> sepCloseAFixed) (sepOpenLFixed +> sepCloseLFixed)
| ArrayOrList(isArray, xs, _) as alNode ->
let shortExpression =
ifElse isArray sepOpenA sepOpenL
+> col sepSemi xs (genExpr astContext)
+> ifElse isArray sepCloseA sepCloseL
let multilineExpression =
ifAlignBrackets
(genMultiLineArrayOrListAlignBrackets isArray xs alNode astContext)
(genMultiLineArrayOrList isArray xs alNode astContext)
fun ctx ->
// If an array or list has any form of line comments inside them, they cannot fit on a single line
// check for any comments inside the range of the node
if (TriviaHelpers.``has line comments inside`` alNode.Range ctx.Trivia) then
multilineExpression ctx
else
isShortExpression ctx.Config.MaxArrayOrListWidth shortExpression multilineExpression ctx
| Record(inheritOpt, xs, eo) ->
let shortRecordExpr =
sepOpenS +>
leaveLeftBrace synExpr.Range +>
optSingle
(fun (inheritType, inheritExpr) -> !- "inherit " +> genType astContext false inheritType +> genExpr astContext inheritExpr +> onlyIf (List.isNotEmpty xs) sepSemi)
inheritOpt +>
optSingle (fun e -> genExpr astContext e +> !- " with ") eo +>
col sepSemi xs (genRecordFieldName astContext) +>
sepCloseS
let multilineRecordExpr =
ifAlignBrackets
(genMultilineRecordInstanceAlignBrackets inheritOpt xs eo astContext)
(genMultilineRecordInstance inheritOpt xs eo synExpr astContext)
fun ctx ->
isShortExpression
ctx.Config.MaxRecordWidth
shortRecordExpr
multilineRecordExpr
ctx
| AnonRecord(isStruct, fields, copyInfo) ->
let shortExpression =
onlyIf isStruct !- "struct "
+> sepOpenAnonRecd
+> optSingle (fun e -> genExpr astContext e +> !- " with ") copyInfo
+> col sepSemi fields (genAnonRecordFieldName astContext)
+> sepCloseAnonRecd
let longExpression =
ifAlignBrackets
(genMultilineAnonRecordAlignBrackets isStruct fields copyInfo astContext)
(genMultilineAnonRecord isStruct fields copyInfo astContext)
fun (ctx: Context) ->
isShortExpression
ctx.Config.MaxRecordWidth
shortExpression
longExpression
ctx
| ObjExpr(t, eio, bd, ims, range) ->
ifAlignBrackets
(genObjExprAlignBrackets t eio bd ims range astContext)
(genObjExpr t eio bd ims range astContext)
| While(e1, e2) ->
atCurrentColumn (!- "while " +> genExpr astContext e1 -- " do"
+> indent +> sepNln +> genExpr astContext e2 +> unindent)
| For(s, e1, e2, e3, isUp) ->
atCurrentColumn (!- (sprintf "for %s = " s) +> genExpr astContext e1
+> ifElse isUp (!- " to ") (!- " downto ") +> genExpr astContext e2 -- " do"
+> indent +> sepNln +> genExpr astContext e3 +> unindent)
// Handle the form 'for i in e1 -> e2'
| ForEach(p, e1, e2, isArrow) ->
atCurrentColumn (
!- "for " +> genPat astContext p -- " in " +> genExpr { astContext with IsNakedRange = true } e1
+> ifElse isArrow
(sepArrow +> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e2))
(!- " do" +> indent +> sepNln +> genExpr astContext e2 +> unindent))
| CompExpr(isArrayOrList, e) ->
ifElse isArrayOrList
(genExpr astContext e)
// The opening { of the CompExpr is being added at the App(_,_,Ident(_),CompExr(_)) level
(expressionFitsOnRestOfLine
(genExpr astContext e +> sepCloseS)
(genExpr astContext e +> unindent +> sepNln +> sepCloseSFixed))
| ArrayOrListOfSeqExpr(isArray, e) as aNode ->
let astContext = { astContext with IsNakedRange = true }
let shortExpression =
ifElse isArray
(sepOpenA +> genExpr astContext e +> enterRightBracketBar aNode.Range +> sepCloseA)
(sepOpenL +> genExpr astContext e +> enterRightBracket aNode.Range +> sepCloseL)
let bracketsOnSameColumn =
ifElse isArray sepOpenAFixed sepOpenLFixed
+> indent +> sepNln
+> genExpr astContext e
+> unindent +> sepNln
+> ifElse isArray sepCloseAFixed sepCloseLFixed
let multilineExpression =
ifAlignBrackets bracketsOnSameColumn shortExpression
fun ctx -> isShortExpression ctx.Config.MaxArrayOrListWidth shortExpression multilineExpression ctx
| JoinIn(e1, e2) -> genExpr astContext e1 -- " in " +> genExpr astContext e2
| Paren(DesugaredLambda(cps, e)) ->
fun (ctx: Context) ->
let lastLineOnlyContainsParenthesis = lastLineOnlyContains [| ' ';'('|] ctx
let hasLineCommentAfterArrow =
findTriviaTokenFromName synExpr.Range ctx.Trivia "RARROW"
|> Option.isSome
let expr =
sepOpenT
-- "fun "
+> col sepSpace cps (genComplexPats astContext)
+> triviaAfterArrow synExpr.Range
+> ifElse hasLineCommentAfterArrow (genExpr astContext e)
(ifElse lastLineOnlyContainsParenthesis (autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e))
(autoNlnIfExpressionExceedsPageWidth (genExpr astContext e)))
+> sepCloseT
expr ctx
| DesugaredLambda(cps, e) ->
!- "fun " +> col sepSpace cps (genComplexPats astContext) +> sepArrow
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| Paren(Lambda(e, sps)) ->
fun (ctx: Context) ->
let lastLineOnlyContainsParenthesis = lastLineOnlyContains [| ' ';'('|] ctx
let hasLineCommentAfterArrow =
findTriviaTokenFromName synExpr.Range ctx.Trivia "RARROW"
|> Option.isSome
let expr =
sepOpenT
-- "fun "
+> col sepSpace sps (genSimplePats astContext)
+> triviaAfterArrow synExpr.Range
+> ifElse hasLineCommentAfterArrow (genExpr astContext e)
(ifElse lastLineOnlyContainsParenthesis (autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e))
(autoNlnIfExpressionExceedsPageWidth (genExpr astContext e)))
+> sepCloseT
expr ctx
// When there are parentheses, most likely lambda will appear in function application
| Lambda(e, sps) ->
!- "fun " +> col sepSpace sps (genSimplePats astContext) +> sepArrow
+> autoIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| MatchLambda(sp, _) -> !- "function " +> colPre sepNln sepNln sp (genClause astContext true)
| Match(e, cs) ->
atCurrentColumn (!- "match " +> genExpr astContext e -- " with" +> colPre sepNln sepNln cs (genClause astContext true))
| MatchBang(e, cs) ->
atCurrentColumn (!- "match! " +> genExpr astContext e -- " with" +> colPre sepNln sepNln cs (genClause astContext true))
| TraitCall(tps, msg, e) ->
genTyparList astContext tps +> sepColon +> sepOpenT +> genMemberSig astContext msg +> sepCloseT
+> sepSpace +> genExpr astContext e
| Paren (ILEmbedded r) ->
// Just write out original code inside (# ... #)
fun ctx -> !- (defaultArg (lookup r ctx) "") ctx
| Paren e ->
// Parentheses nullify effects of no space inside DotGet
sepOpenT +> genExpr { astContext with IsInsideDotGet = false } e +> sepCloseT
| CompApp(s, e) ->
!- s +> sepSpace +> sepOpenS +> genExpr { astContext with IsNakedRange = true } e +> sepCloseS
// This supposes to be an infix function, but for some reason it isn't picked up by InfixApps
| App(Var "?", e::es) ->
match es with
| SynExpr.Const(SynConst.String(_,_),_)::_ ->