-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
CodePrinter.fs
5072 lines (4476 loc) · 187 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
/// Check whether the context is inside a SynExpr.DotIndexedGet
IsInsideDotIndexed: bool
/// Inside a SynPat of MatchClause
IsInsideMatchClausePattern: bool }
static member Default =
{ TopLevelModuleName = ""
IsFirstChild = false
InterfaceRange = None
IsCStylePattern = false
IsNakedRange = false
HasVerticalBar = false
IsUnionField = false
IsFirstTypeParam = false
IsInsideDotGet = false
IsMemberDefinition = false
IsInsideDotIndexed = false
IsInsideMatchClausePattern = 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 (spaceBeforeSetting: bool) (functionOrMethod: string) args =
let isLastPartUppercase =
let parts = functionOrMethod.Split '.'
Char.IsUpper parts.[parts.Length - 1].[0]
match functionOrMethod, args with
| "new", _ -> false
| _, PatParen _ -> spaceBeforeSetting
| _, PatNamed _
| _, SynPat.Wild _ -> true
| (_: string), _ -> not isLastPartUppercase
| _ -> true
let rec genParsedInput astContext ast =
match ast with
| ImplFile im -> genImpFile astContext im
| SigFile si -> genSigFile astContext si
+> ifElseCtx lastWriteEventIsNewline sepNone sepNln
(*
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) =
Map.tryFind ParsedHashDirective_ ctx.TriviaMainNodes
|> Option.defaultValue []
|> List.tryFind (fun t -> RangeHelpers.rangeEq 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
and genModuleOrNamespace astContext (ModuleOrNamespace (ats, px, ao, s, mds, isRecursive, moduleKind) as node) =
let sepModuleAndFirstDecl =
let firstDecl = List.tryHead mds
match firstDecl with
| None ->
if moduleKind.IsModule then
sepNlnForEmptyModule SynModuleOrNamespace_NamedModule node.Range
+> sepNln
else
sepNlnForEmptyNamespace node.Range +> sepNln
| Some mdl ->
let attrs =
getRangesFromAttributesFromModuleDeclaration mdl
sepNln
+> sepNlnConsideringTriviaContentBeforeWithAttributesFor (synModuleDeclToFsAstType mdl) mdl.Range attrs
let genTriviaForLongIdent (f: Context -> Context) =
match node with
| SynModuleOrNamespace.SynModuleOrNamespace (lid, _, SynModuleOrNamespaceKind.DeclaredNamespace, _, _, _, _, _) ->
lid
|> List.fold (fun (acc: Context -> Context) (ident: Ident) -> acc |> (genTriviaFor Ident_ 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
sepNone
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
+> genTriviaFor SynModuleOrNamespace_GlobalNamespace node.Range (genModuleDeclList astContext mds)
else
expr +> genModuleDeclList astContext mds
|> (match moduleKind with
| SynModuleOrNamespaceKind.AnonModule -> genTriviaFor SynModuleOrNamespace_AnonModule node.Range
| SynModuleOrNamespaceKind.NamedModule -> genTriviaFor SynModuleOrNamespace_NamedModule node.Range
| _ -> id)
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 ->
if moduleKind.IsModule then
sepNlnForEmptyModule SynModuleOrNamespaceSig_NamedModule range
+> rep 2 sepNln
else
sepNlnForEmptyNamespace range +> sepNln
| Some mdl ->
match mdl with
| SynModuleSigDecl.Types _ ->
let attrs =
getRangesFromAttributesFromSynModuleSigDeclaration mdl
sepNlnConsideringTriviaContentBeforeWithAttributesFor SynModuleSigDecl_Types mdl.Range attrs
| SynModuleSigDecl.Val _ -> sepNlnConsideringTriviaContentBeforeForMainNode ValSpfn_ mdl.Range
| _ -> sepNone
+> sepNln
let genTriviaForLongIdent (f: Context -> Context) =
match node with
| SynModuleOrNamespaceSig (lid, _, SynModuleOrNamespaceKind.DeclaredNamespace, _, _, _, _, _) ->
lid
|> List.fold (fun (acc: Context -> Context) (ident: Ident) -> acc |> (genTriviaFor Ident_ 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 (enterNodeFor SynModuleOrNamespaceSig_NamedModule range) sepNone
+> genPreXmlDoc px
+> genAttributes astContext ats
+> ifElse
(moduleKind = AnonModule)
sepNone
(genTriviaForLongIdent (
moduleOrNamespace +> opt sepSpace ao genAccess
-- s
+> sepModuleAndFirstDecl
))
+> genSigModuleDeclList astContext mds
+> leaveNodeFor SynModuleOrNamespaceSig_NamedModule range
and genModuleDeclList astContext e =
let rec collectItems e =
match e with
| [] -> []
| OpenL (xs, ys) ->
let expr = col sepNln xs (genModuleDecl astContext)
let r = List.head xs |> fun mdl -> mdl.Range
// SynModuleDecl.Open cannot have attributes
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Open r
[ expr, sepNln, r ] @ collectItems ys
| AttributesL (xs, y :: rest) ->
let attrs =
getRangesFromAttributesFromModuleDeclaration y
let expr =
col sepNln xs (genModuleDecl astContext)
+> sepNlnConsideringTriviaContentBeforeWithAttributesFor (synModuleDeclToFsAstType y) y.Range attrs
+> (fun ctx ->
match y with
| SynModuleDecl.DoExpr _ ->
let doKeyWordRange =
let lastAttribute = List.last xs
mkRange "doKeyword" lastAttribute.Range.End y.Range.Start
// the do keyword range is not part of SynModuleDecl.DoExpr
// So Trivia before `do` cannot be printed in genModuleDecl
enterNodeTokenByName doKeyWordRange DO ctx
| _ -> ctx)
+> genModuleDecl astContext y
let r = List.head xs |> fun mdl -> mdl.Range
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Attributes r
[ expr, sepNln, r ] @ collectItems rest
| m :: rest ->
let attrs =
getRangesFromAttributesFromModuleDeclaration m
let sepNln =
sepNlnConsideringTriviaContentBeforeWithAttributesFor (synModuleDeclToFsAstType m) m.Range attrs
let expr = genModuleDecl astContext m
(expr, sepNln, m.Range) :: (collectItems rest)
collectItems e |> colWithNlnWhenItemIsMultiline
and genSigModuleDeclList astContext node =
match node with
| [ x ] -> genSigModuleDecl astContext x
| SigOpenL (xs, ys) ->
let sepXsAndYs =
match List.tryHead ys with
| Some _ -> sepNln
| 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 _ -> sepNln
| None -> rep 2 sepNln
col sepNln xs (genSigModuleDecl astContext)
+> sepXsYs
+> genSigModuleDeclList astContext ys
| SigMultilineModuleDeclL (xs, ys) ->
match ys with
| [] ->
colEx
(fun (x: SynModuleSigDecl) ->
let attrs =
getRangesFromAttributesFromSynModuleSigDeclaration x
sepNln
+> sepNlnConsideringTriviaContentBeforeWithAttributesFor
(synModuleSigDeclToFsAstType x)
x.Range
attrs)
xs
(genSigModuleDecl astContext)
| _ ->
let sepXsYs =
match List.tryHead ys with
| Some y ->
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synModuleSigDeclToFsAstType y) y.Range
| None -> rep 2 sepNln
colEx
(fun (x: SynModuleSigDecl) ->
let attrs =
getRangesFromAttributesFromSynModuleSigDeclaration x
sepNln
+> sepNlnConsideringTriviaContentBeforeWithAttributesFor
(synModuleSigDeclToFsAstType x)
x.Range
attrs)
xs
(genSigModuleDecl astContext)
+> sepXsYs
+> genSigModuleDeclList astContext ys
| _ -> sepNone
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
(sepNlnConsideringTriviaContentBeforeForMainNode SynModuleDecl_Attributes a.Range)
+> ((col sepNln a.Attributes (genAttribute astContext))
|> genTriviaFor SynAttributeList_ a.Range)
let hasContentAfter =
TriviaHelpers.``has content after after that matches``
(fun tn -> RangeHelpers.rangeEq tn.Range a.Range)
(function
| Newline
| Comment (LineCommentOnSingleLine _)
| Directive _ -> true
| _ -> false)
(Map.tryFindOrEmptyList SynAttributeList_ ctx.TriviaMainNodes)
(hasContentAfter, prevExpr +> expr))
(true, sepNone)
ats
|> snd
(attributesExpr) 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'.RangeOfBindingAndRhs
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType b) r
| None -> id
genLetBinding { astContext with IsFirstChild = true } "let rec " b
+> sepBAndBs
+> colEx
(fun (b': SynBinding) ->
let r = b'.RangeOfBindingAndRhs
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType b) r)
bs
(fun andBinding ->
enterNodeFor (synBindingToFsAstType b) andBinding.RangeOfBindingAndRhs
+> genLetBinding { astContext with IsFirstChild = false } "and " andBinding)
| 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)
| OpenType (s) -> !-(sprintf "open type %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 t ->
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode TypeDefn_ t.Range
| None -> rep 2 sepNln
genTypeDefn { astContext with IsFirstChild = true } t
+> colPreEx
sepTs
(fun (ty: SynTypeDefn) ->
sepNln
+> sepNlnConsideringTriviaContentBeforeForMainNode TypeDefn_ ty.Range)
ts
(genTypeDefn { astContext with IsFirstChild = false })
| md -> failwithf "Unexpected module declaration: %O" md
|> genTriviaFor (synModuleDeclToFsAstType node) 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)
| SigOpenType (s) -> !-(sprintf "open type %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
|> (match node with
| SynModuleSigDecl.Types _ -> genTriviaFor SynModuleSigDecl_Types node.Range
| SynModuleSigDecl.NestedModule _ -> genTriviaFor SynModuleSigDecl_NestedModule node.Range
| SynModuleSigDecl.Open (SynOpenDeclTarget.ModuleOrNamespace _, _) ->
genTriviaFor SynModuleSigDecl_Open node.Range
| SynModuleSigDecl.Open (SynOpenDeclTarget.Type _, _) -> genTriviaFor SynModuleSigDecl_OpenType node.Range
| _ -> id)
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 sepColon target (!-) -- s -- ">]"
| e ->
let argSpacing =
if hasParenthesis e then
id
else
sepSpace
!- "[<" +> opt sepColon target (!-) -- s
+> argSpacing
+> genExpr astContext e
-- ">]"
and genAttributesCore astContext (ats: SynAttribute seq) =
let genAttributeExpr astContext (Attribute (s, e, target) as attr) =
match e with
| ConstExpr (Const "()", _) -> opt sepColon target (!-) -- s
| e ->
let argSpacing =
if hasParenthesis e then
id
else
sepSpace
opt sepColon target (!-) -- s
+> argSpacing
+> genExpr astContext e
|> genTriviaFor SynAttribute_ attr.Range
let shortExpression =
!- "[<"
+> atCurrentColumn (col sepSemi ats (genAttributeExpr astContext))
-- ">]"
let longExpression =
!- "[<"
+> atCurrentColumn (col (sepSemi +> sepNln) ats (genAttributeExpr astContext))
-- ">]"
ifElse (Seq.isEmpty ats) sepNone (expressionFitsOnRestOfLine shortExpression longExpression)
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 (ctx: Context) ->
let dontAddNewline =
TriviaHelpers.``has content after that ends with``
(fun t -> RangeHelpers.rangeEq t.Range a.Range)
(function
| Directive _
| Newline
| Comment (LineCommentOnSingleLine _) -> true
| _ -> false)
(Map.tryFindOrEmptyList SynAttributeList_ ctx.TriviaMainNodes)
let chain =
acc
+> (genAttributesCore astContext a.Attributes
|> genTriviaFor SynAttributeList_ 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 lastWriteEventOnLastLine ctx
|> Option.bind Seq.tryLast with
| Some ('>') -> sepSpace
| _ -> sepNone
else
sepNone)
<| ctx
and genExprSepEqPrependType (astContext: ASTContext) (e: SynExpr) =
match e with
| TypedExpr (Typed, e, t) ->
sepColon
+> genType astContext false t
+> sepEq
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| _ ->
sepEq
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
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 ->
genTyparDecl
{ astContext with
IsFirstTypeParam = i = 0 })
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext)
-- closeSep)
if List.isEmpty tds then
!-typeName
elif preferPostfix then
!-typeName +> types "<" ">"
elif List.atMostOne tds then
genTyparDecl
{ astContext with
IsFirstTypeParam = true }
(List.head tds)
+> sepSpace
-- typeName
+> colPre (!- " when ") wordAnd tcs (genTypeConstraint astContext)
else
types "(" ")" -- " " -- typeName
and genTypeParamPostfix astContext tds tcs =
genTypeAndParam astContext "" tds tcs true
and genLetBinding astContext pref b =
let genPref = !-pref
match b with
| LetBinding (ats, px, ao, isInline, isMutable, p, e, valInfo) ->
match e, p with
| TypedExpr (Typed, e, t), PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunctionWithReturnType
astContext
px
ats
genPref
ao
isInline
isMutable
s
p.Range
ps
tpso
t
valInfo
e
| e, PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunction astContext px ats genPref ao isInline isMutable s p.Range ps tpso valInfo e
| TypedExpr (Typed, e, t), pat ->
genSynBindingValue astContext px ats genPref ao isInline isMutable pat (Some t) valInfo e
| _, PatTuple _ -> genLetBindingDestructedTuple astContext px ats pref ao isInline isMutable p e
| _, pat -> genSynBindingValue astContext px ats genPref ao isInline isMutable pat None valInfo e
| _ -> sepNone
| 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
+> leaveNodeFor (synBindingToFsAstType b) b.RangeOfBindingAndRhs
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 e
| ps ->
!-prefix +> opt sepSpace ao genAccess
-- propertyKind
+> col sepSpace ps (genPat astContext)
+> genExprSepEqPrependType astContext e
and genPropertyWithGetSet astContext (b1, b2) rangeOfMember =
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
+> !-s1
+> indent
+> sepNln
+> optSingle (fun rom -> enterNodeTokenByName rom WITH) rangeOfMember
+> genProperty astContext "with " ao1 "get " ps1 e1
+> sepNln
+> genProperty astContext "and " ao2 "set " ps2 e2
+> unindent
| _ -> sepNone
and genMemberBindingList astContext node =
let rec collectItems (node: SynBinding list) =
match node with
| [] -> []
| mb :: rest ->
let expr = genMemberBinding astContext mb
let r = mb.RangeOfBindingAndRhs
let sepNln =
sepNlnConsideringTriviaContentBeforeForMainNode (synBindingToFsAstType mb) r
(expr, sepNln, r) :: (collectItems rest)
collectItems node |> colWithNlnWhenItemIsMultiline
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
+> genExprSepEqPrependType astContext 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, synValInfo) ->
let prefix =
genMemberFlagsForMemberBinding astContext mf b.RangeOfBindingAndRhs
let astContext =
{ astContext with
IsMemberDefinition = true }
match e, p with
| TypedExpr (Typed, e, t), PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunctionWithReturnType
astContext
px
ats
prefix
ao
isInline
false
s
p.Range
ps
tpso
t
synValInfo
e
| e, PatLongIdent (ao, s, ps, tpso) when (List.isNotEmpty ps) ->
genSynBindingFunction astContext px ats prefix ao isInline false s p.Range ps tpso synValInfo e
| TypedExpr (Typed, e, t), pat ->
genSynBindingValue astContext px ats prefix ao isInline false pat (Some t) synValInfo e
| _, pat -> genSynBindingValue astContext px ats prefix ao isInline false pat None synValInfo e
| ExplicitCtor (ats, px, ao, p, e, so) ->
let prefix =
let genPat ctx =
match p with
| PatExplicitCtor (ao, pat) ->
(opt sepSpace ao genAccess
+> !- "new"
+> sepSpaceBeforeClassConstructor
+> genPat astContext pat)
ctx
| _ -> genPat astContext p ctx
genPreXmlDoc px
+> genAttributes astContext ats
+> opt sepSpace ao genAccess
+> genPat
+> 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
+> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
| b -> failwithf "%O isn't a member binding" b
|> genTriviaFor (synBindingToFsAstType b) b.RangeOfBindingAndRhs
and genMemberFlags astContext (mf: MemberFlags) =
match mf with
| MFMember _ -> !- "member "
| MFStaticMember _ -> !- "static member "
| MFConstructor _ -> sepNone
| MFOverride _ -> ifElse astContext.InterfaceRange.IsSome (!- "member ") (!- "override ")
and genMemberFlagsForMemberBinding astContext (mf: MemberFlags) (rangeOfBindingAndRhs: range) =
fun ctx ->
let keywordFromTrivia =
[ yield! (Map.tryFindOrEmptyList SynMemberDefn_Member ctx.TriviaMainNodes)
yield! (Map.tryFindOrEmptyList SynMemberSig_Member ctx.TriviaMainNodes)
yield! (Map.tryFindOrEmptyList MEMBER ctx.TriviaTokenNodes) ]
|> 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
| _ -> false)
|> Option.bind
(fun tn ->
tn.ContentItself
|> Option.bind
(fun tc ->
match tc with
| Keyword ({ Content = ("override" | "default" | "member" | "abstract" | "abstract member") as kw }) ->
Some(!-(kw + " "))
| _ -> None))
match mf with
| MFStaticMember _
| MFConstructor _ -> genMemberFlags astContext mf
| MFMember _ ->
keywordFromTrivia
|> Option.defaultValue (genMemberFlags astContext mf)
| MFOverride _ ->
keywordFromTrivia
|> Option.defaultValue (!- "override ")
<| 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)
(autoNlnIfExpressionExceedsPageWidth (genTypeList astContext namedArgs))
(genConstraints astContext t)
+> unindent
)
|> genTriviaFor ValSpfn_ 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
| _ -> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!-s +> sepEq +> expr)
|> genTriviaFor RecordField_ range
and genAnonRecordFieldName astContext (AnonRecordFieldName (s, e)) =
let expr =
match e with
| MultilineString _ -> sepSpace +> genExpr astContext e
| _ -> sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth (genExpr astContext e)
!-s +> sepEq +> expr
and genTuple astContext es =
let genShortExpr astContext e =
addParenForTupleWhen (genExpr astContext) e
let shortExpression =
col sepComma es (genShortExpr astContext)
let longExpression =
let containsLambdaOrMatchExpr =
es
|> List.pairwise