-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Context.fs
1560 lines (1321 loc) · 51.9 KB
/
Context.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 Fantomas.Context
open System
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Text.Pos
open FSharp.Compiler.SyntaxTree
open Fantomas
open Fantomas.FormatConfig
open Fantomas.TriviaTypes
type WriterEvent =
| Write of string
| WriteLine
| WriteLineInsideStringConst
| WriteBeforeNewline of string
| WriteLineBecauseOfTrivia
| WriteLineInsideTrivia
| IndentBy of int
| UnIndentBy of int
| SetIndent of int
| RestoreIndent of int
| SetAtColumn of int
| RestoreAtColumn of int
let private (|CommentOrDefineEvent|_|) we =
match we with
| Write w when (String.startsWithOrdinal "//" w) -> Some we
| Write w when (String.startsWithOrdinal "#if" w) -> Some we
| Write w when (String.startsWithOrdinal "#else" w) -> Some we
| Write w when (String.startsWithOrdinal "#endif" w) -> Some we
| Write w when (String.startsWithOrdinal "(*" w) -> Some we
| _ -> None
type ShortExpressionInfo =
{ MaxWidth: int
StartColumn: int
ConfirmedMultiline: bool }
member x.IsTooLong maxPageWidth currentColumn =
currentColumn - x.StartColumn > x.MaxWidth // expression is not too long according to MaxWidth
|| (currentColumn > maxPageWidth) // expression at current position is not going over the page width
type Size =
| CharacterWidth of maxWidth: Num
| NumberOfItems of items: Num * maxItems: Num
type WriteModelMode =
| Standard
| Dummy
| ShortExpression of ShortExpressionInfo list
type WriterModel =
{
/// lines of resulting text, in reverse order (to allow more efficient adding line to end)
Lines: string list
/// current indentation
Indent: int
/// helper indentation information, if AtColumn > Indent after NewLine, Indent will be set to AtColumn
AtColumn: int
/// text to be written before next newline
WriteBeforeNewline: string
/// dummy = "fake" writer used in `autoNln`, `autoNlnByFuture`
Mode: WriteModelMode
/// current length of last line of output
Column: int }
member __.IsDummy =
match __.Mode with
| Dummy -> true
| _ -> false
module WriterModel =
let init =
{ Lines = [ "" ]
Indent = 0
AtColumn = 0
WriteBeforeNewline = ""
Mode = Standard
Column = 0 }
let update maxPageWidth cmd m =
let doNewline m =
let m =
{ m with
Indent = max m.Indent m.AtColumn }
{ m with
Lines =
String.replicate m.Indent " "
:: (List.head m.Lines + m.WriteBeforeNewline)
:: (List.tail m.Lines)
WriteBeforeNewline = ""
Column = m.Indent }
let updateCmd cmd =
match cmd with
| WriteLine
| WriteLineBecauseOfTrivia -> doNewline m
| WriteLineInsideStringConst
| WriteLineInsideTrivia ->
{ m with
Lines = "" :: m.Lines
Column = 0 }
| Write s ->
{ m with
Lines = (List.head m.Lines + s) :: (List.tail m.Lines)
Column = m.Column + (String.length s) }
| WriteBeforeNewline s -> { m with WriteBeforeNewline = s }
| IndentBy x ->
{ m with
Indent =
if m.AtColumn >= m.Indent + x then
m.AtColumn + x
else
m.Indent + x }
| UnIndentBy x ->
{ m with
Indent = max m.AtColumn <| m.Indent - x }
| SetAtColumn c -> { m with AtColumn = c }
| RestoreAtColumn c -> { m with AtColumn = c }
| SetIndent c -> { m with Indent = c }
| RestoreIndent c -> { m with Indent = c }
match m.Mode with
| Dummy
| Standard -> updateCmd cmd
| ShortExpression infos when (List.exists (fun info -> info.ConfirmedMultiline) infos) -> m
| ShortExpression infos ->
let nextCmdCausesMultiline =
match cmd with
| WriteLine
| WriteLineBecauseOfTrivia -> true
| WriteLineInsideStringConst -> true
| Write _ when (String.isNotNullOrEmpty m.WriteBeforeNewline) -> true
| _ -> false
let updatedInfos =
infos
|> List.map
(fun info ->
let tooLong = info.IsTooLong maxPageWidth m.Column
{ info with
ConfirmedMultiline = tooLong || nextCmdCausesMultiline })
if List.exists (fun i -> i.ConfirmedMultiline) updatedInfos then
{ m with
Mode = ShortExpression(updatedInfos) }
else
updateCmd cmd
module WriterEvents =
let normalize ev =
match ev with
| Write s when s.Contains("\n") ->
let writeLine =
match ev with
| CommentOrDefineEvent _ -> WriteLineInsideTrivia
| _ -> WriteLineInsideStringConst
s.Split('\n')
|> Seq.map (fun x -> [ Write x ])
|> Seq.reduce (fun x y -> x @ [ writeLine ] @ y)
|> Seq.toList
| _ -> [ ev ]
let isMultiline evs =
evs
|> Queue.toSeq
|> Seq.exists
(function
| WriteLine
| WriteLineBecauseOfTrivia -> true
| _ -> false)
type internal Context =
{ Config: FormatConfig
WriterModel: WriterModel
WriterEvents: Queue<WriterEvent>
BreakLines: bool
BreakOn: string -> bool
/// The original source string to query as a last resort
Content: string
TriviaMainNodes: Map<FsAstType, TriviaNode list>
TriviaTokenNodes: Map<FsTokenType, TriviaNode list>
RecordBraceStart: int list
FileName: string }
/// Initialize with a string writer and use space as delimiter
static member Default =
{ Config = FormatConfig.Default
WriterModel = WriterModel.init
WriterEvents = Queue.empty
BreakLines = true
BreakOn = (fun _ -> false)
Content = ""
TriviaMainNodes = Map.empty
TriviaTokenNodes = Map.empty
RecordBraceStart = []
FileName = String.Empty }
static member Create
config
defines
(fileName: string)
(hashTokens: Token list)
(content: string)
(maybeAst: ParsedInput option)
=
let content = String.normalizeNewLine content
let tokens =
TokenParser.tokenize defines hashTokens content
let trivia =
match maybeAst, config.StrictMode with
| Some ast, false ->
let mkRange (startLine, startCol) (endLine, endCol) =
mkRange fileName (mkPos startLine startCol) (mkPos endLine endCol)
Trivia.collectTrivia mkRange tokens ast
| _ -> []
let triviaByNodes =
trivia
|> List.choose
(fun tn ->
match tn.Type with
| MainNode mn -> Some(mn, tn)
| _ -> None)
|> List.groupBy fst
|> List.map (fun (k, g) -> k, List.map snd g)
|> Map.ofList
let triviaByTokenNames =
trivia
|> List.choose
(fun tn ->
match tn.Type with
| Token (tname, _) -> Some(tname, tn)
| _ -> None)
|> List.groupBy fst
|> List.map (fun (k, g) -> k, List.map snd g)
|> Map.ofList
{ Context.Default with
Config = config
Content = content
TriviaMainNodes = triviaByNodes
TriviaTokenNodes = triviaByTokenNames
FileName = fileName }
member x.WithDummy(writerCommands, ?keepPageWidth) =
let keepPageWidth =
keepPageWidth |> Option.defaultValue false
let mkModel m =
{ m with
Mode = Dummy
Lines = [ String.replicate x.WriterModel.Column " " ]
WriteBeforeNewline = "" }
// Use infinite column width to encounter worst-case scenario
let config =
{ x.Config with
MaxLineLength =
if keepPageWidth then
x.Config.MaxLineLength
else
Int32.MaxValue }
{ x with
WriterModel = mkModel x.WriterModel
WriterEvents = writerCommands
Config = config }
member x.WithShortExpression(maxWidth, ?startColumn) =
let info =
{ MaxWidth = maxWidth
StartColumn = Option.defaultValue x.WriterModel.Column startColumn
ConfirmedMultiline = false }
match x.WriterModel.Mode with
| ShortExpression infos ->
if List.exists (fun i -> i = info) infos then
x
else
{ x with
WriterModel =
{ x.WriterModel with
Mode = ShortExpression(info :: infos) } }
| _ ->
{ x with
WriterModel =
{ x.WriterModel with
Mode = ShortExpression([ info ]) } }
member x.MkRange (startPos: pos) (endPos: pos) = mkRange x.FileName startPos endPos
member x.MkRangeWith (startLine, startColumn) (endLine, endColumn) =
x.MkRange(mkPos startLine startColumn) (mkPos endLine endColumn)
let internal writerEvent e ctx =
let evs = WriterEvents.normalize e
let ctx' =
{ ctx with
WriterEvents = Queue.append ctx.WriterEvents evs
WriterModel =
(ctx.WriterModel, evs)
||> Seq.fold (fun m e -> WriterModel.update ctx.Config.MaxLineLength e m) }
ctx'
let internal finalizeWriterModel (ctx: Context) =
if ctx.WriterModel.WriteBeforeNewline <> "" then
writerEvent (Write ctx.WriterModel.WriteBeforeNewline) ctx
else
ctx
let internal dump (ctx: Context) =
let ctx = finalizeWriterModel ctx
ctx.WriterModel.Lines
|> List.rev
|> List.skipWhile ((=) "")
|> List.map (fun line -> line.TrimEnd())
|> String.concat ctx.Config.EndOfLine.NewLineString
let internal dumpAndContinue (ctx: Context) =
#if DEBUG
let m = finalizeWriterModel ctx
let lines = m.WriterModel.Lines |> List.rev
let code =
String.concat ctx.Config.EndOfLine.NewLineString lines
printfn "%s" code
#endif
ctx
type Context with
member x.Column = x.WriterModel.Column
member x.FinalizeModel = finalizeWriterModel x
let internal writeEventsOnLastLine ctx =
ctx.WriterEvents
|> Queue.rev
|> Seq.takeWhile
(function
| WriteLine
| WriteLineBecauseOfTrivia
| WriteLineInsideStringConst -> false
| _ -> true)
|> Seq.choose
(function
| Write w when (String.length w > 0) -> Some w
| _ -> None)
let internal lastWriteEventIsNewline ctx =
ctx.WriterEvents
|> Queue.rev
|> Seq.skipWhile
(function
| RestoreIndent _
| RestoreAtColumn _
| UnIndentBy _
| Write "" -> true
| _ -> false)
|> Seq.tryHead
|> Option.map
(function
| WriteLineBecauseOfTrivia
| WriteLine -> true
| _ -> false)
|> Option.defaultValue false
let private (|EmptyHashDefineBlock|_|) (events: WriterEvent array) =
match Array.tryHead events, Array.tryLast events with
| Some (CommentOrDefineEvent _), Some (CommentOrDefineEvent _) ->
// Check if there is an empty block between hash defines
// Example:
// #if FOO
//
// #endif
let emptyLinesInBetween =
Array.forall
(function
| WriteLineInsideStringConst
| Write "" -> true
| _ -> false)
events.[1..(events.Length - 2)]
if emptyLinesInBetween then
Some events
else
None
| _ -> None
/// Validate if there is a complete blank line between the last write event and the last event
let internal newlineBetweenLastWriteEvent ctx =
ctx.WriterEvents
|> Queue.rev
|> Seq.takeWhile
(function
| Write ""
| WriteLine
| IndentBy _
| UnIndentBy _
| SetIndent _
| RestoreIndent _
| SetAtColumn _
| RestoreAtColumn _ -> true
| _ -> false)
|> Seq.filter
(function
| WriteLine _ -> true
| _ -> false)
|> Seq.length
|> fun writeLines -> writeLines > 1
let internal lastWriteEventOnLastLine ctx =
writeEventsOnLastLine ctx |> Seq.tryHead
let internal forallCharsOnLastLine f ctx =
writeEventsOnLastLine ctx
|> Seq.collect id
|> Seq.forall f
// A few utility functions from https://github.com/fsharp/powerpack/blob/master/src/FSharp.Compiler.CodeDom/generator.fs
/// Indent one more level based on configuration
let internal indent (ctx: Context) =
// if atColumn is bigger then after indent, then we use atColumn as base for indent
writerEvent (IndentBy ctx.Config.IndentSize) ctx
/// Unindent one more level based on configuration
let internal unindent (ctx: Context) =
writerEvent (UnIndentBy ctx.Config.IndentSize) ctx
/// Increase indent by i spaces
let internal incrIndent i (ctx: Context) = writerEvent (IndentBy i) ctx
/// Decrease indent by i spaces
let internal decrIndent i (ctx: Context) = writerEvent (UnIndentBy i) ctx
/// Apply function f at an absolute indent level (use with care)
let internal atIndentLevel alsoSetIndent level (f: Context -> Context) (ctx: Context) =
if level < 0 then
invalidArg "level" "The indent level cannot be negative."
let m = ctx.WriterModel
let oldIndent = m.Indent
let oldColumn = m.AtColumn
(writerEvent (SetAtColumn level)
>> if alsoSetIndent then
writerEvent (SetIndent level)
else
id
>> f
>> writerEvent (RestoreAtColumn oldColumn)
>> writerEvent (RestoreIndent oldIndent))
ctx
/// Set minimal indentation (`atColumn`) at current column position - next newline will be indented on `max indent atColumn`
/// Example:
/// { X = // indent=0, atColumn=2
/// "some long string" // indent=4, atColumn=2
/// Y = 1 // indent=0, atColumn=2
/// }
/// `atCurrentColumn` was called on `X`, then `indent` was called, but "some long string" have indent only 4, because it is bigger than `atColumn` (2).
let internal atCurrentColumn (f: _ -> Context) (ctx: Context) = atIndentLevel false ctx.Column f ctx
/// Like atCurrentColumn, but use current column after applying prependF
let internal atCurrentColumnWithPrepend (prependF: _ -> Context) (f: _ -> Context) (ctx: Context) =
let col = ctx.Column
(prependF >> atIndentLevel false col f) ctx
/// Write everything at current column indentation, set `indent` and `atColumn` on current column position
/// /// Example (same as above):
/// { X = // indent=2, atColumn=2
/// "some long string" // indent=6, atColumn=2
/// Y = 1 // indent=2, atColumn=2
/// }
/// `atCurrentColumn` was called on `X`, then `indent` was called, "some long string" have indent 6, because it is indented from `atCurrentColumn` pos (2).
let internal atCurrentColumnIndent (f: _ -> Context) (ctx: Context) = atIndentLevel true ctx.Column f ctx
/// Function composition operator
let internal (+>) (ctx: Context -> Context) (f: _ -> Context) x =
let y = ctx x
match y.WriterModel.Mode with
| ShortExpression infos when
infos
|> Seq.exists (fun x -> x.ConfirmedMultiline)
->
y
| _ -> f y
/// Break-line and append specified string
let internal (++) (ctx: Context -> Context) (str: string) x =
ctx x
|> writerEvent WriteLine
|> writerEvent (Write str)
/// Break-line if config says so
let internal (+-) (ctx: Context -> Context) (str: string) x =
let c = ctx x
let c =
if c.BreakOn str then
writerEvent WriteLine c
else
writerEvent (Write " ") c
writerEvent (Write str) c
/// Append specified string without line-break
let internal (--) (ctx: Context -> Context) (str: string) x = ctx x |> writerEvent (Write str)
/// Break-line unless we are on empty line
let internal (+~) (ctx: Context -> Context) (str: string) x =
let addNewline ctx =
not (forallCharsOnLastLine Char.IsWhiteSpace ctx)
let c = ctx x
let c =
if addNewline c then
writerEvent WriteLine c
else
c
writerEvent (Write str) c
let internal (!-) (str: string) = id -- str
let internal (!+) (str: string) = id ++ str
let internal (!+-) (str: string) = id +- str
let internal (!+~) (str: string) = id +~ str
/// Print object converted to string
let internal str (o: 'T) (ctx: Context) =
ctx |> writerEvent (Write(o.ToString()))
/// Similar to col, and supply index as well
let internal coli f' (c: seq<'T>) f (ctx: Context) =
let mutable tryPick = true
let mutable st = ctx
let mutable i = 0
let e = c.GetEnumerator()
while (e.MoveNext()) do
if tryPick then
tryPick <- false
else
st <- f' st
st <- f i e.Current st
i <- i + 1
st
/// Process collection - keeps context through the whole processing
/// calls f for every element in sequence and f' between every two elements
/// as a separator. This is a variant that works on typed collections.
let internal col f' (c: seq<'T>) f (ctx: Context) =
let mutable tryPick = true
let mutable st = ctx
let e = c.GetEnumerator()
while (e.MoveNext()) do
if tryPick then
tryPick <- false
else
st <- f' st
st <- f e.Current st
st
// Similar to col but pass the item of 'T to f' as well
let internal colEx f' (c: seq<'T>) f (ctx: Context) =
let mutable tryPick = true
let mutable st = ctx
let e = c.GetEnumerator()
while (e.MoveNext()) do
if tryPick then
tryPick <- false
else
st <- f' e.Current st
st <- f e.Current st
st
/// Similar to col, apply one more function f2 at the end if the input sequence is not empty
let internal colPost f2 f1 (c: seq<'T>) f (ctx: Context) =
if Seq.isEmpty c then
ctx
else
f2 (col f1 c f ctx)
/// Similar to col, apply one more function f2 at the beginning if the input sequence is not empty
let internal colPre f2 f1 (c: seq<'T>) f (ctx: Context) =
if Seq.isEmpty c then
ctx
else
col f1 c f (f2 ctx)
let internal colPreEx f2 f1 (c: seq<'T>) f (ctx: Context) =
if Seq.isEmpty c then
ctx
else
colEx f1 c f (f2 ctx)
/// If there is a value, apply f and f' accordingly, otherwise do nothing
let internal opt (f': Context -> _) o f (ctx: Context) =
match o with
| Some x -> f' (f x ctx)
| None -> ctx
/// similar to opt, only takes a single function f to apply when there is a value
let internal optSingle f o ctx =
match o with
| Some x -> f x ctx
| None -> ctx
/// Similar to opt, but apply f2 at the beginning if there is a value
let internal optPre (f2: _ -> Context) (f1: Context -> _) o f (ctx: Context) =
match o with
| Some x -> f1 (f x (f2 ctx))
| None -> ctx
let internal getListOrArrayExprSize ctx maxWidth xs =
match ctx.Config.ArrayOrListMultilineFormatter with
| MultilineFormatterType.CharacterWidth -> Size.CharacterWidth maxWidth
| MultilineFormatterType.NumberOfItems -> Size.NumberOfItems(List.length xs, ctx.Config.MaxArrayOrListNumberOfItems)
let internal getRecordSize ctx fields =
match ctx.Config.RecordMultilineFormatter with
| MultilineFormatterType.CharacterWidth -> Size.CharacterWidth ctx.Config.MaxRecordWidth
| MultilineFormatterType.NumberOfItems -> Size.NumberOfItems(List.length fields, ctx.Config.MaxRecordNumberOfItems)
/// b is true, apply f1 otherwise apply f2
let internal ifElse b (f1: Context -> Context) f2 (ctx: Context) = if b then f1 ctx else f2 ctx
let internal ifElseCtx cond (f1: Context -> Context) f2 (ctx: Context) = if cond ctx then f1 ctx else f2 ctx
/// apply f only when cond is true
let internal onlyIf cond f ctx = if cond then f ctx else ctx
let internal onlyIfCtx cond f ctx = if cond ctx then f ctx else ctx
let internal onlyIfNot cond f ctx = if cond then ctx else f ctx
let internal whenShortIndent f ctx =
onlyIf (ctx.Config.IndentSize < 3) f ctx
/// Repeat application of a function n times
let internal rep n (f: Context -> Context) (ctx: Context) =
[ 1 .. n ] |> List.fold (fun c _ -> f c) ctx
let internal wordAnd = !- " and "
let internal wordOr = !- " or "
let internal wordOf = !- " of "
// Separator functions
let internal sepNone = id
let internal sepDot = !- "."
let internal sepSpace (ctx: Context) =
if ctx.WriterModel.IsDummy then
(!- " ") ctx
else
match lastWriteEventOnLastLine ctx with
| Some w when (w.EndsWith(" ") || w.EndsWith Environment.NewLine) -> ctx
| None -> ctx
| _ -> (!- " ") ctx
let internal sepNln = !+ ""
// Use a different WriteLine event to indicate that the newline was introduces due to trivia
// This is later useful when checking if an expression was multiline when checking for ColMultilineItem
let internal sepNlnForTrivia = writerEvent WriteLineBecauseOfTrivia
let internal sepNlnUnlessLastEventIsNewline (ctx: Context) =
if lastWriteEventIsNewline ctx then
ctx
else
sepNln ctx
let internal sepStar = !- " * "
let internal sepStarFixed = !- "* "
let internal sepEq = !- " ="
let internal sepEqFixed = !- "="
let internal sepArrow = !- " -> "
let internal sepArrowFixed = !- "->"
let internal sepArrowRev = !- " <- "
let internal sepWild = !- "_"
let internal sepBar = !- "| "
/// opening token of list
let internal sepOpenL (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str "[ " ctx
else
str "[" ctx
/// closing token of list
let internal sepCloseL (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str " ]" ctx
else
str "]" ctx
/// opening token of list
let internal sepOpenLFixed = !- "["
/// closing token of list
let internal sepCloseLFixed = !- "]"
/// opening token of array
let internal sepOpenA (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str "[| " ctx
else
str "[|" ctx
/// closing token of array
let internal sepCloseA (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str " |]" ctx
else
str "|]" ctx
/// opening token of list
let internal sepOpenAFixed = !- "[|"
/// closing token of list
let internal sepCloseAFixed = !- "|]"
/// opening token of sequence or record
let internal sepOpenS (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str "{ " ctx
else
str "{" ctx
/// closing token of sequence or record
let internal sepCloseS (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str " }" ctx
else
str "}" ctx
/// opening token of anon record
let internal sepOpenAnonRecd (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str "{| " ctx
else
str "{|" ctx
/// closing token of anon record
let internal sepCloseAnonRecd (ctx: Context) =
if ctx.Config.SpaceAroundDelimiter then
str " |}" ctx
else
str "|}" ctx
/// opening token of anon record
let internal sepOpenAnonRecdFixed = !- "{|"
/// closing token of anon record
let internal sepCloseAnonRecdFixed = !- "|}"
/// opening token of sequence
let internal sepOpenSFixed = !- "{"
/// closing token of sequence
let internal sepCloseSFixed = !- "}"
/// opening token of tuple
let internal sepOpenT = !- "("
/// closing token of tuple
let internal sepCloseT = !- ")"
// we need to make sure each expression in the function application has offset at least greater than
// indentation of the function expression itself
// we replace sepSpace in such case
// remarks: https://github.com/fsprojects/fantomas/issues/1611
let internal indentIfNeeded f (ctx: Context) =
let savedColumn = ctx.WriterModel.AtColumn
if savedColumn >= ctx.Column then
// missingSpaces needs to be at least one more than the column
// of function expression being applied upon, otherwise (as known up to F# 4.7)
// this would lead to a compile error for the function application
let missingSpaces =
(savedColumn - ctx.FinalizeModel.Column)
+ ctx.Config.IndentSize
atIndentLevel true savedColumn (!-(String.replicate missingSpaces " ")) ctx
else
f ctx
let internal eventsWithoutMultilineWrite ctx =
{ ctx with
WriterEvents =
ctx.WriterEvents
|> Queue.toSeq
|> Seq.filter
(function
| Write s when s.Contains("\n") -> false
| _ -> true)
|> Queue.ofSeq }
let private shortExpressionWithFallback
(shortExpression: Context -> Context)
fallbackExpression
maxWidth
startColumn
(ctx: Context)
=
// if the context is already inside a ShortExpression mode and tries to figure out if the expression will go over the page width,
// we should try the shortExpression in this case.
match ctx.WriterModel.Mode with
| ShortExpression infos when
(List.exists
(fun info ->
info.ConfirmedMultiline
|| info.IsTooLong ctx.Config.MaxLineLength ctx.Column)
infos)
->
ctx
| _ ->
// create special context that will process the writer events slightly different
let shortExpressionContext =
match startColumn with
| Some sc -> ctx.WithShortExpression(maxWidth, sc)
| None -> ctx.WithShortExpression(maxWidth)
let resultContext = shortExpression shortExpressionContext
match resultContext.WriterModel.Mode with
| ShortExpression infos ->
// verify the expression is not longer than allowed
if List.exists
(fun info ->
info.ConfirmedMultiline
|| info.IsTooLong ctx.Config.MaxLineLength resultContext.Column)
infos then
fallbackExpression ctx
else
{ resultContext with
WriterModel =
{ resultContext.WriterModel with
Mode = ctx.WriterModel.Mode } }
| _ ->
// you should never hit this branch
fallbackExpression ctx
let internal isShortExpression maxWidth (shortExpression: Context -> Context) fallbackExpression (ctx: Context) =
shortExpressionWithFallback shortExpression fallbackExpression maxWidth None ctx
let internal isShortExpressionOrAddIndentAndNewline maxWidth expr (ctx: Context) =
shortExpressionWithFallback expr (indent +> sepNln +> expr +> unindent) maxWidth None ctx
let internal sepSpaceIfShortExpressionOrAddIndentAndNewline maxWidth expr (ctx: Context) =
shortExpressionWithFallback (sepSpace +> expr) (indent +> sepNln +> expr +> unindent) maxWidth None ctx
let internal expressionFitsOnRestOfLine expression fallbackExpression (ctx: Context) =
shortExpressionWithFallback expression fallbackExpression ctx.Config.MaxLineLength (Some 0) ctx
let internal isSmallExpression size (smallExpression: Context -> Context) fallbackExpression (ctx: Context) =
match size with
| CharacterWidth maxWidth -> isShortExpression maxWidth smallExpression fallbackExpression ctx
| NumberOfItems (items, maxItems) ->
if items > maxItems then
fallbackExpression ctx
else
expressionFitsOnRestOfLine smallExpression fallbackExpression ctx
/// provide the line and column before and after the leadingExpression to to the continuation expression
let internal leadingExpressionResult leadingExpression continuationExpression (ctx: Context) =
let lineCountBefore, columnBefore =
List.length ctx.WriterModel.Lines, ctx.WriterModel.Column
let contextAfterLeading = leadingExpression ctx
let lineCountAfter, columnAfter =
List.length contextAfterLeading.WriterModel.Lines, contextAfterLeading.WriterModel.Column
continuationExpression ((lineCountBefore, columnBefore), (lineCountAfter, columnAfter)) contextAfterLeading
/// combines two expression and let the second expression know if the first expression was longer than a given threshold.
let internal leadingExpressionLong threshold leadingExpression continuationExpression (ctx: Context) =
let lineCountBefore, columnBefore =
List.length ctx.WriterModel.Lines, ctx.WriterModel.Column
let contextAfterLeading = leadingExpression ctx
let lineCountAfter, columnAfter =
List.length contextAfterLeading.WriterModel.Lines, contextAfterLeading.WriterModel.Column
continuationExpression
(lineCountAfter > lineCountBefore
|| (columnAfter - columnBefore > threshold))
contextAfterLeading
/// A leading expression is not consider multiline if it has a comment before it.
/// For example
/// let a = 7
/// // foo
/// let b = 8
/// let c = 9
/// The second binding b is not consider multiline.
let internal leadingExpressionIsMultiline leadingExpression continuationExpression (ctx: Context) =
let eventCountBeforeExpression = Queue.length ctx.WriterEvents
let contextAfterLeading = leadingExpression ctx
let hasWriteLineEventsAfterExpression =
contextAfterLeading.WriterEvents
|> Queue.skipExists
eventCountBeforeExpression
(function
| WriteLine _ -> true
| _ -> false)
(fun e ->
match e with
| [| CommentOrDefineEvent _ |]
| [| WriteLine |]
| [| Write "" |]
| EmptyHashDefineBlock _ -> true
| _ -> false)
continuationExpression hasWriteLineEventsAfterExpression contextAfterLeading
let private expressionExceedsPageWidth beforeShort afterShort beforeLong afterLong expr (ctx: Context) =
// if the context is already inside a ShortExpression mode, we should try the shortExpression in this case.
match ctx.WriterModel.Mode with
| ShortExpression infos when
(List.exists
(fun info ->
info.ConfirmedMultiline
|| info.IsTooLong ctx.Config.MaxLineLength ctx.Column)
infos)
->
ctx
| ShortExpression _ ->
// if the context is already inside a ShortExpression mode, we should try the shortExpression in this case.
(beforeShort +> expr +> afterShort) ctx
| _ ->
let shortExpressionContext =
ctx.WithShortExpression(ctx.Config.MaxLineLength, 0)
let resultContext =
(beforeShort +> expr +> afterShort) shortExpressionContext
let fallbackExpression = beforeLong +> expr +> afterLong
match resultContext.WriterModel.Mode with
| ShortExpression infos ->
// verify the expression is not longer than allowed
if List.exists
(fun info ->
info.ConfirmedMultiline
|| info.IsTooLong ctx.Config.MaxLineLength resultContext.Column)
infos then
fallbackExpression ctx
else
{ resultContext with
WriterModel =
{ resultContext.WriterModel with
Mode = ctx.WriterModel.Mode } }
| _ ->
// you should never hit this branch
fallbackExpression ctx
/// try and write the expression on the remainder of the current line
/// add an indent and newline if the expression is longer
let internal autoIndentAndNlnIfExpressionExceedsPageWidth expr (ctx: Context) =
expressionExceedsPageWidth
sepNone
sepNone // before and after for short expressions
(indent +> sepNln)
unindent // before and after for long expressions
expr
ctx
let internal sepSpaceOrIndentAndNlnIfExpressionExceedsPageWidth expr (ctx: Context) =
expressionExceedsPageWidth
sepSpace
sepNone // before and after for short expressions
(indent +> sepNln)
unindent // before and after for long expressions
expr
ctx
let internal sepSpaceWhenOrIndentAndNlnIfExpressionExceedsPageWidth (addSpace: Context -> bool) expr (ctx: Context) =
expressionExceedsPageWidth