-
Notifications
You must be signed in to change notification settings - Fork 789
/
Tokenizer.fs
1077 lines (958 loc) · 46 KB
/
Tokenizer.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
namespace Microsoft.VisualStudio.FSharp.Editor
open System
open System.Collections.Generic
open System.Collections.Concurrent
open System.Diagnostics
open System.Threading
open System.Runtime.Caching
open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.Classification
open Microsoft.CodeAnalysis.Text
open FSharp.Compiler.EditorServices
open FSharp.Compiler.Symbols
open FSharp.Compiler.Syntax
open FSharp.Compiler.Text
open FSharp.Compiler.Tokenization
open Microsoft.VisualStudio.Core.Imaging
open Microsoft.VisualStudio.Imaging
type private FSharpGlyph = FSharp.Compiler.EditorServices.FSharpGlyph
type private Glyph = Microsoft.CodeAnalysis.ExternalAccess.FSharp.FSharpGlyph
[<RequireQualifiedAccess>]
type internal LexerSymbolKind =
| Ident = 0
| Operator = 1
| Punctuation = 2
| GenericTypeParameter = 3
| StaticallyResolvedTypeParameter = 4
| ActivePattern = 5
| String = 6
| Other = 7
| Keyword = 8
| Comment = 9
type internal LexerSymbol =
{
Kind: LexerSymbolKind
/// Last part of `LongIdent`
Ident: Ident
/// All parts of `LongIdent`
FullIsland: string list
}
member x.Range: Range = x.Ident.idRange
[<RequireQualifiedAccess>]
type internal SymbolLookupKind =
/// Position must lay inside symbol range.
| Precise
/// Position may lay one column outside of symbol range to the right.
| Greedy
[<RequireQualifiedAccess>]
module internal Tokenizer =
let (|Public|Internal|Protected|Private|) (a: FSharpAccessibility) =
if a.IsPublic then Public
elif a.IsInternal then Internal
elif a.IsPrivate then Private
else Protected
let FSharpGlyphToRoslynGlyph (glyph: FSharpGlyph, accessibility: FSharpAccessibility) =
match glyph with
| FSharpGlyph.Class
| FSharpGlyph.Exception
| FSharpGlyph.Typedef
| FSharpGlyph.Type ->
match accessibility with
| Public -> Glyph.ClassPublic
| Internal -> Glyph.ClassInternal
| Protected -> Glyph.ClassProtected
| Private -> Glyph.ClassPrivate
| FSharpGlyph.Constant ->
match accessibility with
| Public -> Glyph.ConstantPublic
| Internal -> Glyph.ConstantInternal
| Protected -> Glyph.ConstantProtected
| Private -> Glyph.ConstantPrivate
| FSharpGlyph.Delegate ->
match accessibility with
| Public -> Glyph.DelegatePublic
| Internal -> Glyph.DelegateInternal
| Protected -> Glyph.DelegateProtected
| Private -> Glyph.DelegatePrivate
| FSharpGlyph.Enum
| FSharpGlyph.Union ->
match accessibility with
| Public -> Glyph.EnumPublic
| Internal -> Glyph.EnumInternal
| Protected -> Glyph.EnumProtected
| Private -> Glyph.EnumPrivate
| FSharpGlyph.EnumMember -> Glyph.EnumMemberPublic
| FSharpGlyph.Event ->
match accessibility with
| Public -> Glyph.EventPublic
| Internal -> Glyph.EventInternal
| Protected -> Glyph.EventProtected
| Private -> Glyph.EventPrivate
| FSharpGlyph.Field ->
match accessibility with
| Public -> Glyph.FieldPublic
| Internal -> Glyph.FieldInternal
| Protected -> Glyph.FieldProtected
| Private -> Glyph.FieldPrivate
| FSharpGlyph.Interface ->
match accessibility with
| Public -> Glyph.InterfacePublic
| Internal -> Glyph.InterfaceInternal
| Protected -> Glyph.InterfaceProtected
| Private -> Glyph.InterfacePrivate
| FSharpGlyph.Method
| FSharpGlyph.OverridenMethod ->
match accessibility with
| Public -> Glyph.MethodPublic
| Internal -> Glyph.MethodInternal
| Protected -> Glyph.MethodProtected
| Private -> Glyph.MethodPrivate
| FSharpGlyph.ExtensionMethod ->
match accessibility with
| Public -> Glyph.ExtensionMethodPublic
| Internal -> Glyph.ExtensionMethodInternal
| Protected -> Glyph.ExtensionMethodProtected
| Private -> Glyph.ExtensionMethodPrivate
| FSharpGlyph.Module ->
match accessibility with
| Public -> Glyph.ModulePublic
| Internal -> Glyph.ModuleInternal
| Protected -> Glyph.ModuleProtected
| Private -> Glyph.ModulePrivate
| FSharpGlyph.NameSpace -> Glyph.Namespace
| FSharpGlyph.Property ->
match accessibility with
| Public -> Glyph.PropertyPublic
| Internal -> Glyph.PropertyInternal
| Protected -> Glyph.PropertyProtected
| Private -> Glyph.PropertyPrivate
| FSharpGlyph.Struct ->
match accessibility with
| Public -> Glyph.StructurePublic
| Internal -> Glyph.StructureInternal
| Protected -> Glyph.StructureProtected
| Private -> Glyph.StructurePrivate
| FSharpGlyph.Variable -> Glyph.Local
| FSharpGlyph.Error -> Glyph.Error
| FSharpGlyph.TypeParameter -> Glyph.TypeParameter
let GetImageIdForSymbol (symbolOpt: FSharpSymbol option, kind: LexerSymbolKind) =
let imageId =
match kind with
| LexerSymbolKind.Keyword -> KnownImageIds.IntellisenseKeyword
| LexerSymbolKind.Operator -> KnownImageIds.Operator
| _ ->
match symbolOpt with
| None -> KnownImageIds.Package
| Some symbol ->
match symbol with
| :? FSharpUnionCase as x ->
match x.Accessibility with
| Public -> KnownImageIds.EnumerationPublic
| Internal -> KnownImageIds.EnumerationInternal
| Protected -> KnownImageIds.EnumerationProtected
| Private -> KnownImageIds.EnumerationPrivate
| :? FSharpActivePatternCase -> KnownImageIds.EnumerationPublic
| :? FSharpField as x ->
if x.IsLiteral then
match x.Accessibility with
| Public -> KnownImageIds.ConstantPublic
| Internal -> KnownImageIds.ConstantInternal
| Protected -> KnownImageIds.ConstantProtected
| Private -> KnownImageIds.ConstantPrivate
else
match x.Accessibility with
| Public -> KnownImageIds.FieldPublic
| Internal -> KnownImageIds.FieldInternal
| Protected -> KnownImageIds.FieldProtected
| Private -> KnownImageIds.FieldPrivate
| :? FSharpParameter -> KnownImageIds.Parameter
| :? FSharpMemberOrFunctionOrValue as x ->
if x.LiteralValue.IsSome then
match x.Accessibility with
| Public -> KnownImageIds.ConstantPublic
| Internal -> KnownImageIds.ConstantInternal
| Protected -> KnownImageIds.ConstantProtected
| Private -> KnownImageIds.ConstantPrivate
elif x.IsExtensionMember then
KnownImageIds.ExtensionMethod
elif x.IsProperty || x.IsPropertyGetterMethod || x.IsPropertySetterMethod then
match x.Accessibility with
| Public -> KnownImageIds.PropertyPublic
| Internal -> KnownImageIds.PropertyInternal
| Protected -> KnownImageIds.PropertyProtected
| Private -> KnownImageIds.PropertyPrivate
elif x.IsEvent then
match x.Accessibility with
| Public -> KnownImageIds.EventPublic
| Internal -> KnownImageIds.EventInternal
| Protected -> KnownImageIds.EventProtected
| Private -> KnownImageIds.EventPrivate
else
match x.Accessibility with
| Public -> KnownImageIds.MethodPublic
| Internal -> KnownImageIds.MethodInternal
| Protected -> KnownImageIds.MethodProtected
| Private -> KnownImageIds.MethodPrivate
| :? FSharpEntity as x ->
if x.IsValueType then
match x.Accessibility with
| Public -> KnownImageIds.StructurePublic
| Internal -> KnownImageIds.StructureInternal
| Protected -> KnownImageIds.StructureProtected
| Private -> KnownImageIds.StructurePrivate
elif x.IsFSharpModule then
match x.Accessibility with
| Public -> KnownImageIds.ModulePublic
| Internal -> KnownImageIds.ModuleInternal
| Protected -> KnownImageIds.ModuleProtected
| Private -> KnownImageIds.ModulePrivate
elif x.IsEnum || x.IsFSharpUnion then
match x.Accessibility with
| Public -> KnownImageIds.EnumerationPublic
| Internal -> KnownImageIds.EnumerationInternal
| Protected -> KnownImageIds.EnumerationProtected
| Private -> KnownImageIds.EnumerationPrivate
elif x.IsInterface then
match x.Accessibility with
| Public -> KnownImageIds.InterfacePublic
| Internal -> KnownImageIds.InterfaceInternal
| Protected -> KnownImageIds.InterfaceProtected
| Private -> KnownImageIds.InterfacePrivate
elif x.IsDelegate then
match x.Accessibility with
| Public -> KnownImageIds.DelegatePublic
| Internal -> KnownImageIds.DelegateInternal
| Protected -> KnownImageIds.DelegateProtected
| Private -> KnownImageIds.DelegatePrivate
elif x.IsNamespace then
KnownImageIds.Namespace
else
match x.Accessibility with
| Public -> KnownImageIds.ClassPublic
| Internal -> KnownImageIds.ClassInternal
| Protected -> KnownImageIds.ClassProtected
| Private -> KnownImageIds.ClassPrivate
| :? FSharpGenericParameter -> KnownImageIds.Type
| _ -> KnownImageIds.None
if imageId = KnownImageIds.None then
None
else
Some(ImageId(KnownImageIds.ImageCatalogGuid, imageId))
let GetGlyphForSymbol (symbol: FSharpSymbol, kind: LexerSymbolKind) =
match kind with
| LexerSymbolKind.Operator -> Glyph.Operator
| _ ->
match symbol with
| :? FSharpUnionCase as x ->
match x.Accessibility with
| Public -> Glyph.EnumPublic
| Internal -> Glyph.EnumInternal
| Protected -> Glyph.EnumProtected
| Private -> Glyph.EnumPrivate
| :? FSharpActivePatternCase -> Glyph.EnumPublic
| :? FSharpField as x ->
if x.IsLiteral then
match x.Accessibility with
| Public -> Glyph.ConstantPublic
| Internal -> Glyph.ConstantInternal
| Protected -> Glyph.ConstantProtected
| Private -> Glyph.ConstantPrivate
else
match x.Accessibility with
| Public -> Glyph.FieldPublic
| Internal -> Glyph.FieldInternal
| Protected -> Glyph.FieldProtected
| Private -> Glyph.FieldPrivate
| :? FSharpParameter -> Glyph.Parameter
| :? FSharpMemberOrFunctionOrValue as x ->
if x.LiteralValue.IsSome then
match x.Accessibility with
| Public -> Glyph.ConstantPublic
| Internal -> Glyph.ConstantInternal
| Protected -> Glyph.ConstantProtected
| Private -> Glyph.ConstantPrivate
elif x.IsExtensionMember then
match x.Accessibility with
| Public -> Glyph.ExtensionMethodPublic
| Internal -> Glyph.ExtensionMethodInternal
| Protected -> Glyph.ExtensionMethodProtected
| Private -> Glyph.ExtensionMethodPrivate
elif x.IsProperty || x.IsPropertyGetterMethod || x.IsPropertySetterMethod then
match x.Accessibility with
| Public -> Glyph.PropertyPublic
| Internal -> Glyph.PropertyInternal
| Protected -> Glyph.PropertyProtected
| Private -> Glyph.PropertyPrivate
elif x.IsEvent then
match x.Accessibility with
| Public -> Glyph.EventPublic
| Internal -> Glyph.EventInternal
| Protected -> Glyph.EventProtected
| Private -> Glyph.EventPrivate
else
match x.Accessibility with
| Public -> Glyph.MethodPublic
| Internal -> Glyph.MethodInternal
| Protected -> Glyph.MethodProtected
| Private -> Glyph.MethodPrivate
| :? FSharpEntity as x ->
if x.IsValueType then
match x.Accessibility with
| Public -> Glyph.StructurePublic
| Internal -> Glyph.StructureInternal
| Protected -> Glyph.StructureProtected
| Private -> Glyph.StructurePrivate
elif x.IsFSharpModule then
match x.Accessibility with
| Public -> Glyph.ModulePublic
| Internal -> Glyph.ModuleInternal
| Protected -> Glyph.ModuleProtected
| Private -> Glyph.ModulePrivate
elif x.IsEnum || x.IsFSharpUnion then
match x.Accessibility with
| Public -> Glyph.EnumPublic
| Internal -> Glyph.EnumInternal
| Protected -> Glyph.EnumProtected
| Private -> Glyph.EnumPrivate
elif x.IsInterface then
match x.Accessibility with
| Public -> Glyph.InterfacePublic
| Internal -> Glyph.InterfaceInternal
| Protected -> Glyph.InterfaceProtected
| Private -> Glyph.InterfacePrivate
elif x.IsDelegate then
match x.Accessibility with
| Public -> Glyph.DelegatePublic
| Internal -> Glyph.DelegateInternal
| Protected -> Glyph.DelegateProtected
| Private -> Glyph.DelegatePrivate
elif x.IsNamespace then
Glyph.Namespace
else
match x.Accessibility with
| Public -> Glyph.ClassPublic
| Internal -> Glyph.ClassInternal
| Protected -> Glyph.ClassProtected
| Private -> Glyph.ClassPrivate
| :? FSharpGenericParameter -> Glyph.TypeParameter
| _ -> Glyph.None
type FSharpTokenInfo with
member token.IsIdentifier = (token.CharClass = FSharpTokenCharKind.Identifier)
member token.IsOperator = (token.CharClass = FSharpTokenCharKind.Operator)
member token.IsPunctuation = (token.ColorClass = FSharpTokenColorKind.Punctuation)
member token.IsString = (token.ColorClass = FSharpTokenColorKind.String)
member token.IsComment = (token.ColorClass = FSharpTokenColorKind.Comment)
member token.IsKeyword = (token.ColorClass = FSharpTokenColorKind.Keyword)
/// This is the information we save for each token in a line for each active document.
/// It is a memory-critical data structure - do not make larger. This used to be ~100 bytes class, is now 8-byte struct
[<Literal>]
let TagMask = 0xFFFF000000000000UL // note, there are some spare bits here
[<Literal>]
let KindMask = 0x0000FF0000000000UL
[<Literal>]
let LeftColumnMask = 0x000000FFFFF00000UL
[<Literal>]
let MatchedLengthMask = 0x00000000000FFFFFUL
[<Struct>]
type SavedTokenInfo =
{
Bits: uint64
}
//TagSaved: uint16
//KindSaved: byte
//LeftColumnSaved: uint20 (up to 1048576)
//MatchedLengthSaved: uint20 (up to 1048576)
member token.Tag = int ((token.Bits &&& TagMask) >>> 48)
member token.Kind = enum<LexerSymbolKind> (int ((token.Bits &&& KindMask) >>> 40))
member token.LeftColumn = int ((token.Bits &&& LeftColumnMask) >>> 20)
member token.MatchedLength = int ((token.Bits &&& MatchedLengthMask))
member token.IsIdentifier = (token.Kind = LexerSymbolKind.Ident)
member token.IsOperator = (token.Kind = LexerSymbolKind.Operator)
member token.IsPunctuation = (token.Kind = LexerSymbolKind.Punctuation)
static member inline Create(token: FSharpTokenInfo) =
let kind =
if token.IsOperator then LexerSymbolKind.Operator
elif token.IsIdentifier then LexerSymbolKind.Ident
elif token.IsPunctuation then LexerSymbolKind.Punctuation
elif token.IsString then LexerSymbolKind.String
elif token.IsKeyword then LexerSymbolKind.Keyword
elif token.IsComment then LexerSymbolKind.Comment
else LexerSymbolKind.Other
Debug.Assert(uint32 token.Tag < 0xFFFFu)
Debug.Assert(uint32 kind < 0xFFu)
Debug.Assert(uint32 token.LeftColumn < 0xFFFFFu)
Debug.Assert(uint32 token.FullMatchedLength < 0xFFFFFu)
{
Bits =
((uint64 token.Tag <<< 48) &&& TagMask)
||| ((uint64 kind <<< 40) &&& KindMask)
||| ((uint64 token.LeftColumn <<< 20) &&& LeftColumnMask)
||| (uint64 token.FullMatchedLength &&& MatchedLengthMask)
}
member token.RightColumn = token.LeftColumn + token.MatchedLength - 1
/// An intermediate extraction of information from the token
type private DraftTokenInfo =
{
Kind: LexerSymbolKind
LeftColumn: int
MatchedLength: int
}
static member Create kind (token: SavedTokenInfo) =
{
Kind = kind
LeftColumn = int token.LeftColumn
MatchedLength = int token.MatchedLength
}
member token.RightColumn = token.LeftColumn + token.MatchedLength - 1
/// This is the data saved about each line. It is held strongly while a file is open and
/// is important for memory performance
type private SourceLineData
(
lineStart: int,
lexStateAtStartOfLine: FSharpTokenizerLexState,
lexStateAtEndOfLine: FSharpTokenizerLexState,
hashCode: int,
classifiedSpans: ClassifiedSpan[],
savedTokens: SavedTokenInfo[]
) =
member val LineStart = lineStart
member val LexStateAtStartOfLine = lexStateAtStartOfLine
member val LexStateAtEndOfLine = lexStateAtEndOfLine
member val HashCode = hashCode
member val ClassifiedSpans = classifiedSpans
member val SavedTokens = savedTokens
member data.IsValid(textLine: TextLine) =
data.LineStart = textLine.Start
&& let lineContents = textLine.Text.ToString(textLine.Span) in
data.HashCode = lineContents.GetHashCode()
type private SourceTextData(approxLines: int) =
let data = ResizeArray<SourceLineData option>(approxLines)
let extendTo i =
if i >= data.Count then
data.Capacity <- i + 1
for j in data.Count .. i do
data.Add(None)
member x.Item
with get (i: int) =
extendTo i
data.[i]
and set (i: int) v =
extendTo i
data.[i] <- v
member x.ClearFrom(n) =
let mutable i = n
while i < data.Count && data.[i].IsSome do
data.[i] <- None
i <- i + 1
/// This saves the tokenization data for a file for as long as the DocumentId object is alive.
/// This seems risky - if one single thing leaks a DocumentId (e.g. stores it in some global table of documents
/// that have been closed), then we leak **all** this associated data, forever.
type private PerDocumentSavedData = ConcurrentDictionary<string list, SourceTextData>
let private dataCache = new MemoryCache("FSharp.Editor.Tokenization")
let compilerTokenToRoslynToken (colorKind: FSharpTokenColorKind) : string =
match colorKind with
| FSharpTokenColorKind.Comment -> ClassificationTypeNames.Comment
| FSharpTokenColorKind.Identifier -> ClassificationTypeNames.Identifier
| FSharpTokenColorKind.Keyword -> ClassificationTypeNames.Keyword
| FSharpTokenColorKind.String -> ClassificationTypeNames.StringLiteral
| FSharpTokenColorKind.Text -> ClassificationTypeNames.Text
| FSharpTokenColorKind.UpperIdentifier -> ClassificationTypeNames.Identifier
| FSharpTokenColorKind.Number -> ClassificationTypeNames.NumericLiteral
| FSharpTokenColorKind.InactiveCode -> ClassificationTypeNames.ExcludedCode
| FSharpTokenColorKind.PreprocessorKeyword -> ClassificationTypeNames.PreprocessorKeyword
| FSharpTokenColorKind.Operator -> ClassificationTypeNames.Operator
| FSharpTokenColorKind.Punctuation -> ClassificationTypeNames.Punctuation
| FSharpTokenColorKind.Default
| _ -> ClassificationTypeNames.Text
let private scanSourceLine
(
sourceTokenizer: FSharpSourceTokenizer,
textLine: TextLine,
lineContents: string,
lexState: FSharpTokenizerLexState
) : SourceLineData =
let colorMap = Array.create textLine.Span.Length ClassificationTypeNames.Text
let lineTokenizer = sourceTokenizer.CreateLineTokenizer(lineContents)
let tokens = ResizeArray<SavedTokenInfo>()
let mutable tokenInfoOption = None
let mutable previousLexState = lexState
let processToken () =
let classificationType =
compilerTokenToRoslynToken (tokenInfoOption.Value.ColorClass)
for i = tokenInfoOption.Value.LeftColumn to tokenInfoOption.Value.RightColumn do
Array.set colorMap i classificationType
let token = tokenInfoOption.Value
let savedToken = SavedTokenInfo.Create token
tokens.Add savedToken
let scanAndColorNextToken () =
let info, nextLexState = lineTokenizer.ScanToken(previousLexState)
tokenInfoOption <- info
previousLexState <- nextLexState
// Apply some hacks to clean up the token stream (we apply more later)
match info with
| Some info when info.Tag = FSharpTokenTag.INT32_DOT_DOT ->
tokenInfoOption <-
Some
{
LeftColumn = info.LeftColumn
RightColumn = info.RightColumn - 2
ColorClass = FSharpTokenColorKind.Number
CharClass = FSharpTokenCharKind.Literal
FSharpTokenTriggerClass = info.FSharpTokenTriggerClass
Tag = info.Tag
TokenName = "INT32"
FullMatchedLength = info.FullMatchedLength - 2
}
processToken ()
tokenInfoOption <-
Some
{
LeftColumn = info.RightColumn - 1
RightColumn = info.RightColumn
ColorClass = FSharpTokenColorKind.Operator
CharClass = FSharpTokenCharKind.Operator
FSharpTokenTriggerClass = info.FSharpTokenTriggerClass
Tag = FSharpTokenTag.DOT_DOT
TokenName = "DOT_DOT"
FullMatchedLength = 2
}
processToken ()
| Some _ -> processToken ()
| _ -> ()
scanAndColorNextToken ()
while tokenInfoOption.IsSome do
scanAndColorNextToken ()
let mutable startPosition = 0
let mutable endPosition = startPosition
let classifiedSpans = new List<ClassifiedSpan>()
while startPosition < colorMap.Length do
let classificationType = colorMap.[startPosition]
endPosition <- startPosition
while endPosition < colorMap.Length && classificationType = colorMap.[endPosition] do
endPosition <- endPosition + 1
let textSpan =
new TextSpan(textLine.Start + startPosition, endPosition - startPosition)
classifiedSpans.Add(new ClassifiedSpan(classificationType, textSpan))
startPosition <- endPosition
SourceLineData(textLine.Start, lexState, previousLexState, lineContents.GetHashCode(), classifiedSpans.ToArray(), tokens.ToArray())
// We keep incremental data per-document. When text changes we correlate text line-by-line (by hash codes of lines)
// We index the data by the active defines in the document.
let private getSourceTextData (documentKey: DocumentId, defines: string list, linesCount) =
let key = documentKey.ToString()
let dict =
match dataCache.Get(key) with
| :? PerDocumentSavedData as dict -> dict
| _ ->
let dict = new PerDocumentSavedData(1, 1, HashIdentity.Structural)
let cacheItem = CacheItem(key, dict)
// evict per-document data after a sliding window
let policy =
CacheItemPolicy(SlidingExpiration = DefaultTuning.PerDocumentSavedDataSlidingWindow)
dataCache.Set(cacheItem, policy)
dict
if dict.ContainsKey(defines) then
dict.[defines]
else
let data = SourceTextData(linesCount)
dict.TryAdd(defines, data) |> ignore
data
let private getFromRefreshedTokenCache
(
lines: TextLineCollection,
startLine: int,
endLine: int,
sourceTokenizer: FSharpSourceTokenizer,
sourceTextDataCache: SourceTextData,
ct: CancellationToken
) =
[
// Go backwards to find the last cached scanned line that is valid
let scanStartLine =
let mutable i = startLine
while i > 0
&& (match sourceTextDataCache.[i] with
| Some data -> not (data.IsValid(lines.[i]))
| None -> true) do
i <- i - 1
i
// Rescan the lines if necessary and report the information
let mutable lexState =
if scanStartLine = 0 then
FSharpTokenizerLexState.Initial
else
sourceTextDataCache.[scanStartLine - 1].Value.LexStateAtEndOfLine
for i = scanStartLine to endLine do
ct.ThrowIfCancellationRequested()
let textLine = lines.[i]
let lineContents = textLine.Text.ToString(textLine.Span)
let lineData =
// We can reuse the old data when
// 1. the line starts at the same overall position
// 2. the hash codes match
// 3. the start-of-line lex states are the same
match sourceTextDataCache.[i] with
| Some data when data.IsValid(textLine) && data.LexStateAtStartOfLine.Equals(lexState) -> data
| _ ->
// Otherwise, we recompute
let newData = scanSourceLine (sourceTokenizer, textLine, lineContents, lexState)
sourceTextDataCache.[i] <- Some newData
newData
lexState <- lineData.LexStateAtEndOfLine
if i >= startLine then
yield lineData, lineContents
// If necessary, invalidate all subsequent lines after endLine
if endLine < lines.Count - 1 then
match sourceTextDataCache.[endLine + 1] with
| Some data ->
if not (data.LexStateAtStartOfLine.Equals(lexState)) then
sourceTextDataCache.ClearFrom(endLine + 1)
| None -> ()
]
/// Generates a list of Classified Spans for tokens which undergo syntactic classification (i.e., are not typechecked).
let classifySpans
(
documentKey: DocumentId,
sourceText: SourceText,
textSpan: TextSpan,
fileName: string option,
defines: string list,
langVersion,
strictIndentation,
result: ResizeArray<ClassifiedSpan>,
cancellationToken: CancellationToken
) : unit =
try
let sourceTokenizer =
FSharpSourceTokenizer(defines, fileName, langVersion, strictIndentation)
let lines = sourceText.Lines
let sourceTextData = getSourceTextData (documentKey, defines, lines.Count)
let startLine = lines.GetLineFromPosition(textSpan.Start).LineNumber
let endLine = lines.GetLineFromPosition(textSpan.End).LineNumber
let lineDataResults =
getFromRefreshedTokenCache (lines, startLine, endLine, sourceTokenizer, sourceTextData, cancellationToken)
for lineData, _ in lineDataResults do
for token in lineData.ClassifiedSpans do
if
(token.TextSpan.Start <= textSpan.Start && textSpan.End <= token.TextSpan.End)
|| textSpan.Contains(token.TextSpan.Start)
|| textSpan.Contains(token.TextSpan.End - 1)
then
result.Add token
with
| :? OperationCanceledException -> reraise ()
| ex -> Assert.Exception(ex)
()
let inline (||>) struct (arg1, arg2) ([<InlineIfLambda>] func: 'T1 -> 'T2 -> 'T3) = func arg1 arg2
/// Returns symbol at a given position.
let private getSymbolFromSavedTokens
(
fileName: string,
savedTokens: SavedTokenInfo[],
linePos: LinePosition,
lineStr: string,
lookupKind: SymbolLookupKind,
wholeActivePatterns: bool,
allowStringToken: bool
) : LexerSymbol option =
let (|GenericTypeParameterPrefix|StaticallyResolvedTypeParameterPrefix|ActivePattern|Other|) (token: SavedTokenInfo) =
if token.Tag = FSharpTokenTag.QUOTE then
GenericTypeParameterPrefix
elif token.Tag = FSharpTokenTag.INFIX_AT_HAT_OP then
// The lexer return INFIX_AT_HAT_OP token for both "^" and "@" symbols.
// We have to check the char itself to distinguish one from another.
if
token.MatchedLength = 1
&& token.LeftColumn < lineStr.Length
&& lineStr.[token.LeftColumn] = '^'
then
StaticallyResolvedTypeParameterPrefix
else
Other
elif token.Tag = FSharpTokenTag.LPAREN then
if
token.MatchedLength = 1
&& token.LeftColumn + 1 < lineStr.Length
&& lineStr.[token.LeftColumn + 1] = '|'
then
ActivePattern
else
Other
else
Other
// Operators: Filter out overlapped operators (>>= operator is tokenized as three distinct tokens: GREATER, GREATER, EQUALS.
// Each of them has MatchedLength = 3. So, we take the first GREATER and skip the other two).
//
// Generic type parameters: we convert QUOTE + IDENT tokens into single IDENT token, altering its LeftColumn
// and FullMatchedLength (for "'type" which is tokenized as (QUOTE, left=2) + (IDENT, left=3, length=4)
// we'll get (IDENT, left=2, length=5).
//
// Statically resolved type parameters: we convert INFIX_AT_HAT_OP + IDENT tokens into single IDENT token, altering its LeftColumn
// and FullMatchedLength (for "^type" which is tokenized as (INFIX_AT_HAT_OP, left=2) + (IDENT, left=3, length=4)
// we'll get (IDENT, left=2, length=5).
let draftTokens =
let tokensCount = savedTokens.Length
struct (([], ValueNone), savedTokens)
||> Array.foldi (fun (acc, lastToken: DraftTokenInfo voption) index token ->
match lastToken with
| ValueSome t when token.LeftColumn <= t.RightColumn -> acc, lastToken
| ValueSome({ Kind = LexerSymbolKind.ActivePattern } as lastToken) when
wholeActivePatterns
&& (token.Tag = FSharpTokenTag.BAR
|| token.Tag = FSharpTokenTag.IDENT
|| token.Tag = FSharpTokenTag.UNDERSCORE)
->
let mergedToken =
{ lastToken with
Kind = LexerSymbolKind.Ident
MatchedLength = lastToken.MatchedLength + token.MatchedLength
}
acc, ValueSome mergedToken
| _ ->
let isLastToken = index = tokensCount - 1
match token with
| GenericTypeParameterPrefix when not isLastToken ->
acc, ValueSome(DraftTokenInfo.Create LexerSymbolKind.GenericTypeParameter token)
| StaticallyResolvedTypeParameterPrefix when not isLastToken ->
acc, ValueSome(DraftTokenInfo.Create LexerSymbolKind.StaticallyResolvedTypeParameter token)
| ActivePattern when wholeActivePatterns -> acc, ValueSome(DraftTokenInfo.Create LexerSymbolKind.ActivePattern token)
| _ ->
let draftToken =
match lastToken with
| ValueSome {
Kind = LexerSymbolKind.GenericTypeParameter | LexerSymbolKind.StaticallyResolvedTypeParameter as kind
} when token.IsIdentifier ->
{
Kind = kind
LeftColumn = token.LeftColumn - 1
MatchedLength = token.MatchedLength + 1
}
// ^ operator
| ValueSome {
Kind = LexerSymbolKind.StaticallyResolvedTypeParameter
} ->
{
Kind = LexerSymbolKind.Operator
LeftColumn = token.LeftColumn - 1
MatchedLength = 1
}
| ValueSome({ Kind = LexerSymbolKind.ActivePattern } as ap) when
wholeActivePatterns && token.Tag = FSharpTokenTag.RPAREN
->
{
Kind = LexerSymbolKind.Ident
LeftColumn = ap.LeftColumn
MatchedLength = ap.MatchedLength
}
| _ ->
{
Kind = token.Kind
LeftColumn = token.LeftColumn
MatchedLength = token.MatchedLength
}
draftToken :: acc, ValueSome draftToken)
|> fst
// One or two tokens that in touch with the cursor (for "let x|(g) = ()" the tokens will be "x" and "(")
let tokensUnderCursor =
let rightColumnCorrection =
match lookupKind with
| SymbolLookupKind.Precise -> 0
| SymbolLookupKind.Greedy -> 1
[
for x in draftTokens do
if
x.LeftColumn <= linePos.Character
&& (x.RightColumn + rightColumnCorrection) >= linePos.Character
then
yield x
]
// Select IDENT token. If failed, select OPERATOR token.
let symbol =
tokensUnderCursor
|> List.tryFindV (fun token ->
match token.Kind with
| LexerSymbolKind.Ident
| LexerSymbolKind.Keyword
| LexerSymbolKind.ActivePattern
| LexerSymbolKind.GenericTypeParameter
| LexerSymbolKind.StaticallyResolvedTypeParameter -> true
| _ -> false)
|> ValueOption.orElseWith (fun _ ->
tokensUnderCursor
|> List.tryFindV (fun token -> token.Kind = LexerSymbolKind.Operator))
|> ValueOption.orElseWith (fun _ ->
if allowStringToken then
tokensUnderCursor
|> List.tryFindV (fun token -> token.Kind = LexerSymbolKind.String)
else
ValueNone)
|> ValueOption.map (fun token ->
let partialName = QuickParse.GetPartialLongNameEx(lineStr, token.RightColumn)
let identStr = lineStr.Substring(token.LeftColumn, token.MatchedLength)
{
Kind = token.Kind
Ident =
Ident(
identStr,
Range.mkRange
fileName
(Position.mkPos (linePos.Line + 1) token.LeftColumn)
(Position.mkPos (linePos.Line + 1) (token.RightColumn + 1))
)
FullIsland = partialName.QualifyingIdents @ [ identStr ]
})
ValueOption.toOption symbol
let private getCachedSourceLineData
(
documentKey: DocumentId,
sourceText: SourceText,
position: int,
fileName: string,
defines: string list,
langVersion,
strictIndentation,
cancellationToken
) =
let textLinePos = sourceText.Lines.GetLinePosition(position)
let sourceTokenizer =
FSharpSourceTokenizer(defines, Some fileName, langVersion, strictIndentation)
// We keep incremental data per-document. When text changes we correlate text line-by-line (by hash codes of lines)
let sourceTextData =
getSourceTextData (documentKey, defines, sourceText.Lines.Count)
let lineNo = textLinePos.Line
let lineData, contents =
getFromRefreshedTokenCache (sourceText.Lines, lineNo, lineNo, sourceTokenizer, sourceTextData, cancellationToken)
|> List.exactlyOne
lineData, textLinePos, contents
let tokenizeLine (documentKey, sourceText, position, fileName, defines, langVersion, strictIndentation, cancellationToken) =
try
let lineData, _, _ =
getCachedSourceLineData (
documentKey,
sourceText,
position,
fileName,
defines,
langVersion,
strictIndentation,
cancellationToken
)
lineData.SavedTokens
with ex ->
Assert.Exception(ex)
[||]
let getSymbolAtPosition
(
documentKey: DocumentId,
sourceText: SourceText,
position: int,
fileName: string,
defines: string list,
lookupKind: SymbolLookupKind,
wholeActivePatterns: bool,
allowStringToken: bool,
langVersion,
strictIndentation,
cancellationToken
) : LexerSymbol option =
try
let lineData, textLinePos, lineContents =
getCachedSourceLineData (
documentKey,
sourceText,
position,
fileName,
defines,
langVersion,
strictIndentation,
cancellationToken
)
getSymbolFromSavedTokens (
fileName,
lineData.SavedTokens,
textLinePos,
lineContents,
lookupKind,
wholeActivePatterns,
allowStringToken
)
with
| :? System.OperationCanceledException -> reraise ()
| ex ->
Assert.Exception(ex)
None
[<Literal>]
let private doubleBackTickDelimiter = "``"
/// Fix invalid span if it appears to have redundant suffix and prefix.
let fixupSpan (sourceText: SourceText, span: TextSpan) : TextSpan =
let text = sourceText.GetSubText(span).ToString()
// backticked ident
if text.EndsWith doubleBackTickDelimiter then
match text.LastIndexOf(doubleBackTickDelimiter, text.Length - 3, text.Length - 2) with
| -1
| 0 -> span