-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
TokenParser.fs
1181 lines (975 loc) · 42.1 KB
/
TokenParser.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.TokenParser
open System
open System.Text
open FSharp.Compiler.Syntax
open FSharp.Compiler.Tokenization
open Fantomas
open Fantomas.TokenParserBoolExpr
open Fantomas.TriviaTypes
let private whiteSpaceTag = 4
let private lineCommentTag = 8
let private commentTag = 3
let private greaterTag = 160
let private identTag = 192
// workaround for cases where tokenizer dont output "delayed" part of operator after ">."
// See https://github.com/fsharp/FSharp.Compiler.Service/issues/874
let private isTokenAfterGreater token (greaterToken: Token) =
let greaterToken = greaterToken.TokenInfo
greaterToken.Tag = greaterTag
&& token.Tag <> greaterTag
&& greaterToken.RightColumn <> (token.LeftColumn + 1)
let private getTokenText (sourceCodeLines: string list) line (token: FSharpTokenInfo) =
sourceCodeLines.[line - 1]
.Substring(token.LeftColumn, token.RightColumn - token.LeftColumn + 1)
|> String.normalizeNewLine
/// Tokenize a single line of F# code
let rec private tokenizeLine (tokenizer: FSharpLineTokenizer) sourceCodeLines state lineNumber tokens =
match tokenizer.ScanToken(state), List.tryHead tokens with
| (Some tok, state), Some greaterToken when (isTokenAfterGreater tok greaterToken) ->
let extraTokenInfo =
{ tok with
TokenName = "DELAYED"
LeftColumn = greaterToken.TokenInfo.RightColumn + 1
Tag = -1
CharClass = FSharpTokenCharKind.Operator
RightColumn = tok.LeftColumn - 1 }
let extraToken =
{ TokenInfo = extraTokenInfo
LineNumber = lineNumber
Content = getTokenText sourceCodeLines lineNumber extraTokenInfo }
let token =
{ TokenInfo = tok
LineNumber = lineNumber
Content = getTokenText sourceCodeLines lineNumber tok }
tokenizeLine tokenizer sourceCodeLines state lineNumber (token :: extraToken :: tokens)
| (Some tok, state), _ ->
let token: Token =
{ TokenInfo = tok
LineNumber = lineNumber
Content = getTokenText sourceCodeLines lineNumber tok }
// Tokenize the rest, in the new state
tokenizeLine tokenizer sourceCodeLines state lineNumber (token :: tokens)
| (None, state), _ -> state, tokens
let private tokenizeLines (sourceTokenizer: FSharpSourceTokenizer) allLines state =
allLines
|> List.mapi (fun index line -> line, (index + 1)) // line number is needed in tokenizeLine
|> List.fold
(fun (state, tokens) (line, lineNumber) ->
let tokenizer = sourceTokenizer.CreateLineTokenizer(line)
let nextState, tokensOfLine = tokenizeLine tokenizer allLines state lineNumber []
let allTokens = List.append tokens (List.rev tokensOfLine) // tokens of line are add in reversed order
(nextState, allTokens))
(state, []) // empty tokens to start with
|> snd // ignore the state
let private createHashToken lineNumber content offset =
let left, right = offset, String.length content + offset
{ LineNumber = lineNumber
Content = content
TokenInfo =
{ TokenName = "HASH_IF"
LeftColumn = left
RightColumn = right
ColorClass = FSharpTokenColorKind.PreprocessorKeyword
CharClass = FSharpTokenCharKind.WhiteSpace
FSharpTokenTriggerClass = FSharpTokenTriggerClass.None
Tag = 0
FullMatchedLength = String.length content } }
type SourceCodeState =
| Normal
| InsideString
| InsideTripleQuoteString of startIndex: int
| InsideVerbatimString of startIndex: int
| InsideMultilineComment
| InsideLineComment
type SourceCodeParserState =
{ State: SourceCodeState
NewlineIndexes: int list
Defines: Token list list }
let rec private getTokenizedHashes (sourceCode: string) : Token list =
let hasNoHashDirectiveStart (source: string) = not (source.Contains("#if"))
if hasNoHashDirectiveStart sourceCode then
[]
else
let equalsChar c v = if c = v then Some() else None
let differsFromChar c v = if c <> v then Some() else None
let (|DoubleQuoteChar|_|) = equalsChar '"'
let (|TripleQuoteChars|_|) v =
match v with
| DoubleQuoteChar, DoubleQuoteChar, DoubleQuoteChar -> Some()
| _ -> None
let (|OpenParenChar|_|) = equalsChar '('
let (|AsteriskChar|_|) = equalsChar '*'
let (|NoCloseParenChar|_|) = differsFromChar ')'
let (|NewlineChar|_|) = equalsChar '\n'
let (|HashChar|_|) = equalsChar '#'
let (|BackSlashChar|_|) = equalsChar '\\'
let (|NoBackSlashChar|_|) = differsFromChar '\\'
let (|CloseParenChar|_|) = equalsChar ')'
let (|ForwardSlashChar|_|) = equalsChar '/'
let (|AtChar|_|) = equalsChar '@'
let (|LineCommentStart|_|) v =
match v with
| ForwardSlashChar, ForwardSlashChar, _ -> Some()
| _ -> None
let isSpace = (=) ' '
let processLine (hashContent: string) (lineContent: string) (lineNumber: int) (offset: int) : Token list =
let hashContentLength = String.length hashContent
let tokens =
let defineExpressionWithHash = lineContent.Substring(hashContentLength)
if String.isNotNullOrEmpty defineExpressionWithHash then
tokenize [] [] defineExpressionWithHash
else
[]
tokens
|> List.map (fun t ->
let info =
{ t.TokenInfo with
LeftColumn =
t.TokenInfo.LeftColumn
+ hashContentLength
+ offset
RightColumn =
t.TokenInfo.RightColumn
+ hashContentLength
+ offset }
{ t with
LineNumber = lineNumber
TokenInfo = info })
|> fun rest ->
(createHashToken lineNumber hashContent offset)
:: rest
let sourceLength = String.length sourceCode
// stop scanning the source code three characters before the end
// three because of how triple quote string are opened and closed
// the scan looks three characters ahead (zero, plusOne, plusTwo)
// and sometimes also two characters behind (minusTwo, minusOne)
// In theory there is will also never be any new hash detect inside the last three characters
let lastIndex = sourceLength - 3
// check if the current # char is part of an define expression
// if so add to defines
let captureHashDefine (state: SourceCodeParserState) idx =
let lastNewlineIdx =
Seq.tryHead state.NewlineIndexes
|> Option.defaultValue -1
let leadingCharactersBeforeLastNewlineAreSpaces =
let take = Math.Max(idx - lastNewlineIdx - 1, 0)
sourceCode
|> Seq.skip (lastNewlineIdx + 1)
|> Seq.take take
|> Seq.forall isSpace
if leadingCharactersBeforeLastNewlineAreSpaces then
let skip =
if lastNewlineIdx = -1 then
0
else
lastNewlineIdx + 1 // zero when the source starts with an #
let currentLine =
sourceCode
|> Seq.skip skip
|> Seq.takeWhile (function
| NewlineChar -> false
| _ -> true)
|> Seq.toArray
|> fun chars -> new string (chars)
let trimmed = currentLine.TrimStart()
let offset = (String.length currentLine - String.length trimmed)
let lineNumber = List.length state.NewlineIndexes + 1 // line numbers are 1 based.
if trimmed.StartsWith("#if") then
{ state with
Defines =
(processLine "#if" trimmed lineNumber offset)
:: state.Defines }
elif trimmed.StartsWith("#elseif") then
{ state with
Defines =
(processLine "#elseif" trimmed lineNumber offset)
:: state.Defines }
elif trimmed.StartsWith("#else") then
{ state with
Defines =
(processLine "#else" trimmed lineNumber offset)
:: state.Defines }
elif trimmed.StartsWith("#endif") then
{ state with
Defines =
(processLine "#endif" trimmed lineNumber offset)
:: state.Defines }
else
state
else
state
let initialState =
{ State = Normal
NewlineIndexes = []
Defines = [] }
[ 0..lastIndex ]
|> List.fold
(fun acc idx ->
let zero = sourceCode.[idx]
let plusOne = sourceCode.[idx + 1]
let plusTwo = sourceCode.[idx + 2]
if idx < 2 then
match acc.State, (zero, plusOne, plusTwo) with
| Normal, TripleQuoteChars -> { acc with State = InsideTripleQuoteString(idx) }
| Normal, (AtChar, DoubleQuoteChar, _) -> { acc with State = InsideVerbatimString idx }
| Normal, (DoubleQuoteChar, _, _) -> { acc with State = InsideString }
| Normal, (OpenParenChar, AsteriskChar, NoCloseParenChar) when (sourceLength > 3) ->
{ acc with State = InsideMultilineComment }
| Normal, (NewlineChar, _, _) -> { acc with NewlineIndexes = idx :: acc.NewlineIndexes }
| Normal, (HashChar, _, _) -> captureHashDefine acc idx
| Normal, LineCommentStart -> { acc with State = InsideLineComment }
| _ -> acc
elif idx < lastIndex then
let minusTwo = sourceCode.[idx - 2]
let minusOne = sourceCode.[idx - 1]
match acc.State, (zero, plusOne, plusTwo) with
| Normal, TripleQuoteChars -> { acc with State = InsideTripleQuoteString idx }
| Normal, (AtChar, DoubleQuoteChar, _) -> { acc with State = InsideVerbatimString idx }
| Normal, (DoubleQuoteChar, _, _) -> { acc with State = InsideString }
| Normal, (OpenParenChar, AsteriskChar, NoCloseParenChar) ->
{ acc with State = InsideMultilineComment }
| Normal, (NewlineChar, _, _) -> { acc with NewlineIndexes = idx :: acc.NewlineIndexes }
| Normal, (HashChar, _, _) -> captureHashDefine acc idx
| Normal, LineCommentStart -> { acc with State = InsideLineComment }
| InsideString, (NewlineChar, _, _) -> { acc with NewlineIndexes = idx :: acc.NewlineIndexes }
| InsideString, (DoubleQuoteChar, _, _) ->
let minusThree = sourceCode.[idx - 3]
match minusOne, minusTwo, minusThree with
| BackSlashChar, NoBackSlashChar, _
| BackSlashChar, BackSlashChar, BackSlashChar -> acc
| _ -> { acc with State = Normal }
| InsideString, (DoubleQuoteChar, _, _) -> { acc with State = Normal }
| InsideTripleQuoteString _, (NewlineChar, _, _) ->
{ acc with NewlineIndexes = idx :: acc.NewlineIndexes }
| InsideTripleQuoteString startIndex, _ when (startIndex + 2 < idx) ->
match (minusTwo, minusOne, zero) with
| TripleQuoteChars when ((startIndex - 1) > 0) ->
let minusThree = sourceCode.[idx - 3]
// check if there is no backslash before the first `"` of `"""`
// so no `\"""` characters
match minusThree with
| NoBackSlashChar -> { acc with State = Normal }
| _ -> acc
| _ -> acc
| InsideVerbatimString _, (DoubleQuoteChar, DoubleQuoteChar, _) -> acc
| InsideVerbatimString startIndex, (DoubleQuoteChar, _, _) ->
if idx = startIndex + 1 then
// Still at the start of the verbatim string @"
acc
else
{ acc with State = Normal }
| InsideMultilineComment, (NewlineChar, _, _) ->
{ acc with NewlineIndexes = idx :: acc.NewlineIndexes }
| InsideMultilineComment, (CloseParenChar, _, _) ->
match minusOne with
| AsteriskChar -> { acc with State = Normal }
| _ -> acc
| InsideLineComment, (NewlineChar, _, _) ->
{ acc with
State = Normal
NewlineIndexes = idx :: acc.NewlineIndexes }
| _ -> acc
else
acc)
initialState
|> fun state -> state.Defines |> List.rev |> List.collect id
and tokenize defines (hashTokens: Token list) (content: string) : Token list =
let sourceTokenizer = FSharpSourceTokenizer(defines, Some "/tmp.fsx")
let lines =
String.normalizeThenSplitNewLine content
|> Array.toList
let tokens =
tokenizeLines sourceTokenizer lines FSharpTokenizerLexState.Initial
|> List.filter (fun t -> t.TokenInfo.TokenName <> "INACTIVECODE")
let existingLines =
tokens
|> List.map (fun t -> t.LineNumber)
|> List.distinct
if List.isNotEmpty hashTokens then
let filteredHashes =
hashTokens
|> List.filter (fun t -> not (List.contains t.LineNumber existingLines))
// filter hashes that are present in source code parsed by the Tokenizer.
tokens @ filteredHashes
|> List.sortBy (fun t -> t.LineNumber, t.TokenInfo.LeftColumn)
else
tokens
let getDefinesWords (tokens: Token list) =
tokens
|> List.filter (fun { TokenInfo = { TokenName = tn } } -> tn = "IDENT" || tn = "FALSE" || tn = "TRUE")
|> List.map (fun t -> t.Content)
|> List.distinct
let getDefineExprs (hashTokens: Token list) =
let parseHashContent tokens =
let allowedContent = set [ "||"; "&&"; "!"; "("; ")" ]
tokens
|> Seq.filter (fun t ->
t.TokenInfo.TokenName = "IDENT"
|| t.TokenInfo.TokenName = "TRUE"
|| t.TokenInfo.TokenName = "FALSE"
|| Set.contains t.Content allowedContent)
|> Seq.map (fun t -> t.Content)
|> Seq.toList
|> BoolExprParser.parse
let tokensByLine =
hashTokens
|> List.groupBy (fun t -> t.LineNumber)
|> List.sortBy fst
let result =
(([], []), tokensByLine)
||> List.fold (fun (contextExprs, exprAcc) (_, lineTokens) ->
let contextExpr e =
e :: contextExprs
|> List.reduce (fun x y -> BoolExpr.And(x, y))
let t =
lineTokens
|> Seq.tryFind (fun x -> x.TokenInfo.TokenName = "HASH_IF")
match t |> Option.map (fun x -> x.Content) with
| Some "#if" ->
parseHashContent lineTokens
|> Option.map (fun e -> e :: contextExprs, contextExpr e :: exprAcc)
|> Option.defaultValue (contextExprs, exprAcc)
| Some "#else" ->
contextExprs,
BoolExpr.Not(
contextExprs
|> List.reduce (fun x y -> BoolExpr.And(x, y))
)
:: exprAcc
| Some "#endif" -> List.tail contextExprs, exprAcc
| _ -> contextExprs, exprAcc)
|> snd
|> List.rev
result
let internal getOptimizedDefinesSets (hashTokens: Token list) =
let maxSteps = FormatConfig.satSolveMaxStepsMaxSteps
match getDefineExprs hashTokens
|> BoolExpr.mergeBoolExprs maxSteps
|> List.map snd
with
| [] -> [ [] ]
| xs -> xs
let getDefines sourceCode =
let hashTokens = getTokenizedHashes sourceCode
let defineCombinations =
getOptimizedDefinesSets hashTokens
@ (getDefinesWords hashTokens
|> List.map List.singleton)
@ [ [] ]
|> List.distinct
defineCombinations, hashTokens
let private getRangeBetween (mkRange: MkRange) startToken endToken =
let l = startToken.TokenInfo.LeftColumn
let r = endToken.TokenInfo.RightColumn
mkRange (startToken.LineNumber, l) (endToken.LineNumber, (if l = r then r + 1 else r))
let private getRangeForSingleToken (mkRange: MkRange) token =
let l = token.TokenInfo.LeftColumn
let r = l + token.TokenInfo.FullMatchedLength
mkRange (token.LineNumber, l) (token.LineNumber, r)
let private hasOnlySpacesAndLineCommentsOnLine lineNumber tokens =
if List.isEmpty tokens then
false
else
tokens
|> List.filter (fun t -> t.LineNumber = lineNumber)
|> List.forall (fun t ->
t.TokenInfo.Tag = whiteSpaceTag
|| t.TokenInfo.Tag = lineCommentTag)
let private getContentFromTokens tokens =
tokens
|> List.map (fun t -> t.Content)
|> String.concat String.Empty
let private keywordTrivia =
[ "OVERRIDE"
"MEMBER"
"DEFAULT"
"ABSTRACT"
"KEYWORD_STRING"
"QMARK"
"IN" ]
let private numberTrivia =
[ "UINT8"
"INT8"
"UINT16"
"INT16"
"UINT32"
"INT32"
"UINT64"
"INT64"
"IEEE32"
"DECIMAL"
"IEEE64"
"BIGNUM"
"NATIVEINT"
"UNATIVEINT" ]
let private isOperatorOrKeyword { TokenInfo = { CharClass = cc } } =
cc = FSharpTokenCharKind.Keyword
|| cc = FSharpTokenCharKind.Operator
let private (|KeywordOrOperatorToken|_|) (token: Token) =
let isOperatorOrKeyword = isOperatorOrKeyword token
let isKnownKeywordTrivia () =
List.exists (fun k -> token.TokenInfo.TokenName = k) keywordTrivia
if isOperatorOrKeyword && isKnownKeywordTrivia () then
Some token
else
None
let private onlyNumberRegex = System.Text.RegularExpressions.Regex(@"^\d+$")
let private isNumber { TokenInfo = tn; Content = content } =
tn.ColorClass = FSharpTokenColorKind.Number
&& List.contains tn.TokenName numberTrivia
&& not (onlyNumberRegex.IsMatch(content))
let private digitOrLetterCharRegex =
System.Text.RegularExpressions.Regex(@"^'(\d|[a-zA-Z])'$")
let private (|CharToken|_|) token =
if
token.TokenInfo.TokenName = "CHAR"
&& not (digitOrLetterCharRegex.IsMatch(token.Content))
then
Some token
else
None
let private (|StringTextToken|_|) token =
if token.TokenInfo.TokenName = "STRING_TEXT" then
Some token
else
None
let private (|InterpStringEndOrPartToken|_|) token =
if token.TokenInfo.TokenName = "INTERP_STRING_END"
|| token.TokenInfo.TokenName = "INTERP_STRING_PART" then
Some token
else
None
let escapedCharacterRegex =
System.Text.RegularExpressions.Regex("(\\\\(a|b|f|n|r|t|u|v|x|'|\\\"|\\\\))+")
let private (|MultipleStringTextTokens|_|) tokens =
let f _ =
function
| StringTextToken _ -> true
| _ -> false
tokens
|> List.partitionWhile f
|> fun (before, after) ->
if List.isEmpty before then
None
else
Some(before, after)
let private (|EndOfInterpolatedString|_|) tokens =
match tokens with
| MultipleStringTextTokens (stringTokens, rest) ->
match rest with
| InterpStringEndOrPartToken endToken :: rest2 -> Some(stringTokens, endToken, rest2)
| _ -> None
| _ -> None
let private (|StringText|_|) tokens =
match tokens with
| StringTextToken head :: rest ->
let stringTokens =
rest
|> List.takeWhile (fun { TokenInfo = { TokenName = tn } } -> tn = "STRING_TEXT")
|> fun others ->
let length = List.length others
let closingQuote = rest.[length]
[ yield head
yield! others
yield closingQuote ]
let stringContent =
let builder = StringBuilder()
stringTokens
|> List.fold
(fun (b: StringBuilder, currentLine) st ->
if currentLine <> st.LineNumber then
let delta = st.LineNumber - currentLine
[ 1..delta ]
|> List.iter (fun _ -> b.Append("\n") |> ignore)
b.Append(st.Content), st.LineNumber
else
b.Append(st.Content), st.LineNumber)
(builder, head.LineNumber)
|> fst
|> fun b -> b.ToString()
let stringStartIsSpecial () =
if stringContent.Length > 2 then
match stringContent.[0], stringContent.[1], stringContent.[2] with
| '@', '"', _
| '$', '"', _
| '$', '@', '"'
| '"', '"', '"' -> true
| _ -> false
else
false
let hasEscapedCharacter () =
escapedCharacterRegex.IsMatch(stringContent)
let hasNewlines () = stringContent.Contains("\n")
let endsWithBinaryCharacter () = stringContent.EndsWith("\"B")
if stringStartIsSpecial ()
|| hasEscapedCharacter ()
|| hasNewlines ()
|| endsWithBinaryCharacter () then
Some(head, stringTokens, rest, stringContent)
else
None
| _ -> None
let private identIsDecompiledOperator (token: Token) =
let decompiledName () =
PrettyNaming.DecompileOpName token.Content
token.TokenInfo.Tag = identTag
&& (decompiledName () <> token.Content)
let private (|DecompiledOperatorToken|_|) (token: Token) =
if identIsDecompiledOperator token then
Some token
else
None
let private (|IdentBetweenTicksToken|_|) (token: Token) =
if
token.TokenInfo.Tag = identTag
&& token.Content.StartsWith("``")
&& token.Content.EndsWith("``")
then
Some token
else
None
let private extractContentPreservingNewLines (tokens: Token list) =
let rec loop result =
function
| [] -> result
| [ final ] -> final.Content :: result
| current :: (next :: _ as rest) when (current.LineNumber <> next.LineNumber) ->
let delta = next.LineNumber - current.LineNumber
let newlines = [ 1..delta ] |> List.map (fun _ -> "\n")
loop
[ yield! newlines
yield current.Content
yield! result ]
rest
| current :: rest -> loop (current.Content :: result) rest
loop [] tokens |> List.rev
let ``only whitespaces were found in the remainder of the line`` lineNumber tokens =
tokens
|> List.exists (fun t ->
t.LineNumber = lineNumber
&& t.TokenInfo.Tag <> whiteSpaceTag)
|> not
let private (|LineCommentToken|_|) (token: Token) =
if token.TokenInfo.Tag = lineCommentTag then
Some token
else
None
let private (|NoCommentToken|_|) (token: Token) =
if token.TokenInfo.Tag <> lineCommentTag
&& token.TokenInfo.Tag <> commentTag then
Some token
else
None
let private (|CommentToken|_|) (token: Token) =
if token.TokenInfo.Tag = commentTag then
Some token
else
None
let private (|WhiteSpaceToken|_|) (token: Token) =
if token.TokenInfo.Tag = whiteSpaceTag then
Some token
else
None
let private (|NonWhiteSpaceToken|_|) (token: Token) =
if token.TokenInfo.Tag <> whiteSpaceTag then
Some token
else
None
let private (|SemicolonToken|_|) (token: Token) =
if token.TokenInfo.Tag = 83 then
Some token
else
None
let private (|LineComments|_|) (tokens: Token list) =
let rec collect
(tokens: Token list)
(lastLineNumber: int)
(finalContinuation: Token list -> Token list)
: Token list * Token list =
match tokens with
| LineCommentToken lc :: rest when (lc.LineNumber <= lastLineNumber + 1) ->
collect rest lc.LineNumber (fun commentTokens -> lc :: commentTokens |> finalContinuation)
| _ -> finalContinuation [], tokens
match tokens with
| LineCommentToken h :: _ ->
let commentTokens, rest = collect tokens h.LineNumber id
Some(commentTokens, rest)
| _ -> None
let private collectComment (commentTokens: Token list) =
commentTokens
|> List.groupBy (fun t -> t.LineNumber)
|> List.map (snd >> getContentFromTokens)
|> String.concat "\n"
let private (|EmbeddedILTokens|_|) (tokens: Token list) =
match tokens with
| { TokenInfo = { TokenName = "LPAREN"
CharClass = FSharpTokenCharKind.Delimiter } } :: { TokenInfo = { TokenName = "HASH"
CharClass = FSharpTokenCharKind.Delimiter } } :: { TokenInfo = { TokenName = "WHITESPACE"
CharClass = FSharpTokenCharKind.WhiteSpace } } :: rest ->
let embeddedTokens =
tokens
|> List.takeWhile (fun t ->
not (
t.TokenInfo.CharClass = FSharpTokenCharKind.Delimiter
&& t.TokenInfo.TokenName = "RPAREN"
))
let lastTokens = embeddedTokens.[(embeddedTokens.Length - 2) ..]
match lastTokens with
| [ { TokenInfo = { TokenName = "WHITESPACE"
CharClass = FSharpTokenCharKind.WhiteSpace } }
{ TokenInfo = { TokenName = "HASH"
CharClass = FSharpTokenCharKind.Delimiter } } ] ->
Some(List.take (embeddedTokens.Length + 1) tokens, rest)
| _ -> None
| _ -> None
let rec private (|HashTokens|_|) (tokens: Token list) =
match tokens with
| { TokenInfo = { TokenName = "HASH_IF" } } as head :: rest ->
let tokensFromSameLine =
List.takeWhile (fun t -> t.LineNumber = head.LineNumber) rest
let nextTokens =
List.skip tokensFromSameLine.Length rest
|> List.skipWhile (fun t -> t.TokenInfo.Tag = whiteSpaceTag)
match nextTokens with
| HashTokens (nextHashTokens, rest) ->
let totalHashTokens =
[ yield head
yield! tokensFromSameLine
yield! nextHashTokens ]
Some(totalHashTokens, rest)
| _ -> Some(head :: tokensFromSameLine, rest)
| _ -> None
let private (|BlockCommentTokens|_|) (tokens: Token list) =
let rec collectTokens (rest: Token list) (finalContinuation: Token list -> Token list) : Token list * Token list =
match rest with
| CommentToken ct :: rest -> collectTokens rest (fun commentTokens -> ct :: commentTokens |> finalContinuation)
| _ -> finalContinuation [], rest
match tokens with
| CommentToken { Content = "(*" } :: _ ->
let comments, rest = collectTokens tokens id
Some(comments, rest)
| _ -> None
let private (|MinusToken|_|) (token: Token) =
if token.TokenInfo.Tag = 62 then
Some token
else
None
let private (|NumberToken|_|) (token: Token) =
if isNumber token then
Some token
else
None
let rec private lastTwoItems
(project: 't -> 'ret)
(fallbackLastButOne: 'ret)
(fallbackLast: 'ret)
(items: 't list)
: 'ret * 'ret =
match items with
| [ f; s ] -> project f, project s
| [ s ] -> fallbackLast, project s
| [] -> fallbackLastButOne, fallbackLast
| _ :: tail -> lastTwoItems project fallbackLastButOne fallbackLast tail
let rec private getTriviaFromTokensThemSelves
(mkRange: MkRange)
(lastButOneNonWhiteSpaceToken: Token option)
(lastNonWhiteSpaceToken: Token option)
(tokens: Token list)
foundTrivia
=
match tokens with
| LineComments ({ LineNumber = headLineNumber } :: _ as commentTokens, rest) ->
let isAfterSourceCode =
match lastButOneNonWhiteSpaceToken, lastNonWhiteSpaceToken with
| Some otherLineToken, Some (SemicolonToken sc) when otherLineToken.LineNumber <> sc.LineNumber ->
// IDENT SEMICOLON LINE_COMMENT
// See https://github.com/fsprojects/fantomas/issues/1643
false
| _, Some t -> headLineNumber = t.LineNumber
| _ -> false
let info =
if isAfterSourceCode then
// Only capture the first line of the comment as LineCommentAfterSourceCode
// The next line(s) will be a LineCommentOnSingleLine
let commentsByLine =
commentTokens
|> List.groupBy (fun t -> t.LineNumber)
let firstComment = List.tryHead commentsByLine |> Option.map snd
match firstComment with
| Some (headToken :: _ as afterSourceTokens) ->
let afterSourceCodeTrivia =
let tc =
collectComment afterSourceTokens
|> LineCommentAfterSourceCode
|> Comment
let lastToken = List.tryLast afterSourceTokens
let r = getRangeBetween mkRange headToken (Option.defaultValue headToken lastToken)
Trivia.Create tc r
let lineCommentOnSingleLine =
if commentTokens.Length > afterSourceTokens.Length then
let commentTokens =
commentTokens
|> List.skip afterSourceTokens.Length
let triviaContent =
collectComment commentTokens
|> LineCommentOnSingleLine
|> Comment
let range =
let headToken = List.head commentTokens
let lastToken = List.tryLast commentTokens
getRangeBetween mkRange headToken (Option.defaultValue headToken lastToken)
Trivia.Create triviaContent range |> Some
else
None
match lineCommentOnSingleLine with
| Some lcsl -> afterSourceCodeTrivia :: lcsl :: foundTrivia
| None -> afterSourceCodeTrivia :: foundTrivia
| _ ->
// We should not hit this branch
foundTrivia
else
let triviaContent =
collectComment commentTokens
|> LineCommentOnSingleLine
|> Comment
let range =
let headToken = List.head commentTokens
let lastToken = List.tryLast commentTokens
getRangeBetween mkRange headToken (Option.defaultValue headToken lastToken)
(Trivia.Create triviaContent range :: foundTrivia)
getTriviaFromTokensThemSelves mkRange lastButOneNonWhiteSpaceToken lastNonWhiteSpaceToken rest info
| BlockCommentTokens (headToken :: _ as blockCommentTokens, rest) ->
let comment =
let groupedByLineNumber =
blockCommentTokens
|> List.groupBy (fun t -> t.LineNumber)
let newLines =
let min, _ = List.minBy fst groupedByLineNumber
let max, _ = List.maxBy fst groupedByLineNumber
[ min..max ]
|> List.filter (fun l -> not (List.exists (fst >> ((=) l)) groupedByLineNumber))
|> List.map (fun l -> l, String.Empty)
groupedByLineNumber
|> List.map (fun (l, g) -> l, getContentFromTokens g)
|> (@) newLines
|> List.sortBy fst
|> List.map snd
|> String.concat Environment.NewLine
|> String.normalizeNewLine
let lastButOne, lastToken =
lastTwoItems Some lastNonWhiteSpaceToken (Some headToken) blockCommentTokens
let range =
getRangeBetween mkRange headToken (Option.defaultValue headToken lastToken)
let info =
Trivia.Create(Comment(BlockComment(comment, false, false))) range
|> List.prependItem foundTrivia
getTriviaFromTokensThemSelves mkRange lastButOne lastToken rest info
| KeywordOrOperatorToken koo :: rest ->
let range = getRangeBetween mkRange koo koo
let info =
Trivia.Create(Keyword(koo)) range
|> List.prependItem foundTrivia
getTriviaFromTokensThemSelves mkRange lastNonWhiteSpaceToken (Some koo) rest info
| HashTokens (hashTokens, rest) ->
let directiveContent =
let sb = StringBuilder()
hashTokens
|> List.fold
(fun (acc: StringBuilder, lastLine) token ->
let sb =
let delta = token.LineNumber - lastLine
if delta > 0 then
[ 1..delta ]
|> List.fold (fun (sb: StringBuilder) _ -> sb.Append("\n")) acc
else
acc
sb.Append(token.Content), token.LineNumber)
(sb, hashTokens.[0].LineNumber)
|> fun (sb, _) -> sb.ToString()
let range = getRangeBetween mkRange (List.head hashTokens) (List.last hashTokens)
let info =
Trivia.Create(Directive(directiveContent)) range
|> List.prependItem foundTrivia
getTriviaFromTokensThemSelves mkRange lastButOneNonWhiteSpaceToken lastNonWhiteSpaceToken rest info
| EndOfInterpolatedString (stringTokens, interpStringEnd, rest) ->
let stringContent =
let addExtraNewline =
match List.tryLast stringTokens with
| Some lst ->
let delta = interpStringEnd.LineNumber - lst.LineNumber
if delta > 0 then
[ 1..delta ] |> List.map (fun _ -> "\n")
else
[]
| _ -> []
[ yield! extractContentPreservingNewLines stringTokens
yield! addExtraNewline
yield interpStringEnd.Content ]
|> String.concat String.Empty
let range = getRangeBetween mkRange stringTokens.Head interpStringEnd
let info =
Trivia.Create(StringContent(stringContent)) range
|> List.prependItem foundTrivia
let prevButOne, prev = List.tryLast stringTokens, Some interpStringEnd
getTriviaFromTokensThemSelves mkRange prevButOne prev rest info
| StringText (head, stringTokens, rest, stringContent) ->
let lastButOne, lastToken = lastTwoItems Some None (Some head) stringTokens
let range = getRangeBetween mkRange head (Option.defaultValue head lastToken)
let info =
Trivia.Create(StringContent(stringContent)) range
|> List.prependItem foundTrivia
let nextRest =
match rest with
| [] -> []
| _ -> List.skip (List.length stringTokens - 1) rest
getTriviaFromTokensThemSelves mkRange lastButOne lastToken nextRest info
| MinusToken minus :: NumberToken number :: rest ->
let range = getRangeBetween mkRange minus number
let info =