Repository navigation
Expand file tree
/
Copy pathPrettyNaming.fs
More file actions
executable file
·1150 lines (959 loc) · 38.8 KB
/
Copy pathPrettyNaming.fs
File metadata and controls
executable file
·1150 lines (959 loc) · 38.8 KB
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
/// Some general F# utilities for mangling / unmangling / manipulating names.
/// Anything to do with special names of identifiers and other lexical rules
module public FSharp.Compiler.Syntax.PrettyNaming
open System
open System.Collections.Generic
open System.Collections.Concurrent
open System.Globalization
open System.Text
open Internal.Utilities.Library
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Layout
//------------------------------------------------------------------------
// Operator name compilation
//-----------------------------------------------------------------------
[<Literal>]
let parenGet = ".()"
[<Literal>]
let parenSet = ".()<-"
[<Literal>]
let qmark = "?"
[<Literal>]
let qmarkSet = "?<-"
/// Prefix for compiled (mangled) operator names.
[<Literal>]
let opNamePrefix = "op_"
let opNameTable =
[|
("[]", "op_Nil")
("::", "op_ColonColon")
("+", "op_Addition")
("~%", "op_Splice")
("~%%", "op_SpliceUntyped")
("~++", "op_Increment")
("~--", "op_Decrement")
("-", "op_Subtraction")
("*", "op_Multiply")
("**", "op_Exponentiation")
("/", "op_Division")
("@", "op_Append")
("^", "op_Concatenate")
("%", "op_Modulus")
("&&&", "op_BitwiseAnd")
("|||", "op_BitwiseOr")
("^^^", "op_ExclusiveOr")
("<<<", "op_LeftShift")
("~~~", "op_LogicalNot")
(">>>", "op_RightShift")
("~+", "op_UnaryPlus")
("~-", "op_UnaryNegation")
("~&", "op_AddressOf")
("~&&", "op_IntegerAddressOf")
("&&", "op_BooleanAnd")
("||", "op_BooleanOr")
("<=", "op_LessThanOrEqual")
("=", "op_Equality")
("<>", "op_Inequality")
(">=", "op_GreaterThanOrEqual")
("<", "op_LessThan")
(">", "op_GreaterThan")
("|>", "op_PipeRight")
("||>", "op_PipeRight2")
("|||>", "op_PipeRight3")
("<|", "op_PipeLeft")
("<||", "op_PipeLeft2")
("<|||", "op_PipeLeft3")
("!", "op_Dereference")
(">>", "op_ComposeRight")
("<<", "op_ComposeLeft")
("<< >>", "op_TypedQuotationUnicode")
("<<| |>>", "op_ChevronsBar")
("<@ @>", "op_Quotation")
("<@@ @@>", "op_QuotationUntyped")
("+=", "op_AdditionAssignment")
("-=", "op_SubtractionAssignment")
("*=", "op_MultiplyAssignment")
("/=", "op_DivisionAssignment")
("..", "op_Range")
(".. ..", "op_RangeStep")
(qmark, "op_Dynamic")
(qmarkSet, "op_DynamicAssignment")
(parenGet, "op_ArrayLookup")
(parenSet, "op_ArrayAssign")
|]
let opCharTranslateTable =
[|
('>', "Greater")
('<', "Less")
('+', "Plus")
('-', "Minus")
('*', "Multiply")
('=', "Equals")
('~', "Twiddle")
('%', "Percent")
('.', "Dot")
('$', "Dollar")
('&', "Amp")
('|', "Bar")
('@', "At")
('#', "Hash")
('^', "Hat")
('!', "Bang")
('?', "Qmark")
('/', "Divide")
(':', "Colon")
('(', "LParen")
(',', "Comma")
(')', "RParen")
(' ', "Space")
('[', "LBrack")
(']', "RBrack")
|]
/// The set of characters usable in custom operators.
let opCharSet =
let t = HashSet<_>()
for c, _ in opCharTranslateTable do
t.Add(c) |> ignore
t
/// The characters that are allowed to be the first character of an identifier.
let IsIdentifierFirstCharacter c =
if c = '_' then
true
else
match Char.GetUnicodeCategory c with
// Letters
| UnicodeCategory.UppercaseLetter
| UnicodeCategory.LowercaseLetter
| UnicodeCategory.TitlecaseLetter
| UnicodeCategory.ModifierLetter
| UnicodeCategory.OtherLetter
| UnicodeCategory.LetterNumber -> true
| _ -> false
/// The characters that are allowed to be in an identifier.
let IsIdentifierPartCharacter c =
if c = '\'' then
true // Tick
else
match Char.GetUnicodeCategory c with
// Letters
| UnicodeCategory.UppercaseLetter
| UnicodeCategory.LowercaseLetter
| UnicodeCategory.TitlecaseLetter
| UnicodeCategory.ModifierLetter
| UnicodeCategory.OtherLetter
| UnicodeCategory.LetterNumber
// Numbers
| UnicodeCategory.DecimalDigitNumber
// Connectors
| UnicodeCategory.ConnectorPunctuation
// Combiners
| UnicodeCategory.NonSpacingMark
| UnicodeCategory.SpacingCombiningMark -> true
| _ -> false
/// Keywords paired with their descriptions. Used in completion and quick info.
let keywordsWithDescription: (string * string) list =
[
"abstract", FSComp.SR.keywordDescriptionAbstract ()
"and", FSComp.SR.keywordDescriptionAnd ()
"as", FSComp.SR.keywordDescriptionAs ()
"assert", FSComp.SR.keywordDescriptionAssert ()
"base", FSComp.SR.keywordDescriptionBase ()
"begin", FSComp.SR.keywordDescriptionBegin ()
"class", FSComp.SR.keywordDescriptionClass ()
"const", FSComp.SR.keywordDescriptionConst ()
"default", FSComp.SR.keywordDescriptionDefault ()
"delegate", FSComp.SR.keywordDescriptionDelegate ()
"do", FSComp.SR.keywordDescriptionDo ()
"done", FSComp.SR.keywordDescriptionDone ()
"downcast", FSComp.SR.keywordDescriptionDowncast ()
"downto", FSComp.SR.keywordDescriptionDownto ()
"elif", FSComp.SR.keywordDescriptionElif ()
"else", FSComp.SR.keywordDescriptionElse ()
"end", FSComp.SR.keywordDescriptionEnd ()
"exception", FSComp.SR.keywordDescriptionException ()
"extern", FSComp.SR.keywordDescriptionExtern ()
"false", FSComp.SR.keywordDescriptionTrueFalse ()
"finally", FSComp.SR.keywordDescriptionFinally ()
"for", FSComp.SR.keywordDescriptionFor ()
"fun", FSComp.SR.keywordDescriptionFun ()
"function", FSComp.SR.keywordDescriptionFunction ()
"global", FSComp.SR.keywordDescriptionGlobal ()
"if", FSComp.SR.keywordDescriptionIf ()
"in", FSComp.SR.keywordDescriptionIn ()
"inherit", FSComp.SR.keywordDescriptionInherit ()
"inline", FSComp.SR.keywordDescriptionInline ()
"interface", FSComp.SR.keywordDescriptionInterface ()
"internal", FSComp.SR.keywordDescriptionInternal ()
"lazy", FSComp.SR.keywordDescriptionLazy ()
"let", FSComp.SR.keywordDescriptionLet ()
"let!", FSComp.SR.keywordDescriptionLetBang ()
"match", FSComp.SR.keywordDescriptionMatch ()
"match!", FSComp.SR.keywordDescriptionMatchBang ()
"member", FSComp.SR.keywordDescriptionMember ()
"module", FSComp.SR.keywordDescriptionModule ()
"mutable", FSComp.SR.keywordDescriptionMutable ()
"namespace", FSComp.SR.keywordDescriptionNamespace ()
"new", FSComp.SR.keywordDescriptionNew ()
"not", FSComp.SR.keywordDescriptionNot ()
"null", FSComp.SR.keywordDescriptionNull ()
"of", FSComp.SR.keywordDescriptionOf ()
"open", FSComp.SR.keywordDescriptionOpen ()
"or", FSComp.SR.keywordDescriptionOr ()
"override", FSComp.SR.keywordDescriptionOverride ()
"private", FSComp.SR.keywordDescriptionPrivate ()
"public", FSComp.SR.keywordDescriptionPublic ()
"rec", FSComp.SR.keywordDescriptionRec ()
"return", FSComp.SR.keywordDescriptionReturn ()
"return!", FSComp.SR.keywordDescriptionReturnBang ()
"sig", FSComp.SR.keywordDescriptionSig ()
"static", FSComp.SR.keywordDescriptionStatic ()
"struct", FSComp.SR.keywordDescriptionStruct ()
"then", FSComp.SR.keywordDescriptionThen ()
"to", FSComp.SR.keywordDescriptionTo ()
"true", FSComp.SR.keywordDescriptionTrueFalse ()
"try", FSComp.SR.keywordDescriptionTry ()
"type", FSComp.SR.keywordDescriptionType ()
"upcast", FSComp.SR.keywordDescriptionUpcast ()
"use", FSComp.SR.keywordDescriptionUse ()
"use!", FSComp.SR.keywordDescriptionUseBang ()
"val", FSComp.SR.keywordDescriptionVal ()
"void", FSComp.SR.keywordDescriptionVoid ()
"when", FSComp.SR.keywordDescriptionWhen ()
"while", FSComp.SR.keywordDescriptionWhile ()
"while!", FSComp.SR.keywordDescriptionWhileBang ()
"with", FSComp.SR.keywordDescriptionWith ()
"yield", FSComp.SR.keywordDescriptionYield ()
"yield!", FSComp.SR.keywordDescriptionYieldBang ()
"->", FSComp.SR.keywordDescriptionRightArrow ()
"<-", FSComp.SR.keywordDescriptionLeftArrow ()
":>", FSComp.SR.keywordDescriptionCast ()
":?", FSComp.SR.keywordDescriptionTypeTest ()
":?>", FSComp.SR.keywordDescriptionDynamicCast ()
"<@", FSComp.SR.keywordDescriptionTypedQuotation ()
"@>", FSComp.SR.keywordDescriptionTypedQuotation ()
"<@@", FSComp.SR.keywordDescriptionUntypedQuotation ()
"@@>", FSComp.SR.keywordDescriptionUntypedQuotation ()
]
let keywordLookup = set (List.map fst keywordsWithDescription)
let IsUnencodedOpName (name: string) =
match name with
| "mod" -> true
| _ -> false
let IsIdentifierName (name: string) =
not (keywordLookup.Contains name)
&& not (IsUnencodedOpName name)
&& let nameLen = name.Length in
nameLen > 0
&& IsIdentifierFirstCharacter name[0]
&& let rec loop i =
(i >= nameLen || (IsIdentifierPartCharacter(name[i]) && loop (i + 1))) in
loop 1
let rec isCoreActivePatternName (name: string) idx seenNonOpChar =
if idx = name.Length - 1 then
seenNonOpChar
else
let c = name[idx]
if opCharSet.Contains(c) && c <> '|' && c <> ' ' then
false
else
isCoreActivePatternName name (idx + 1) (seenNonOpChar || c <> '|')
/// Determines if the specified name is a valid name for an active pattern.
let IsActivePatternName (name: string) =
// The name must contain at least one character between the starting and ending delimiters.
let nameLen = name.Length
if nameLen < 3 || name[0] <> '|' || name[nameLen - 1] <> '|' then
false
else
isCoreActivePatternName name 1 false
/// Returns `true` if given string is an operator display name (DisplayName), e.g.
/// (::)
/// ([])
/// (|>>)
/// (+)
/// ( * )
/// Also returns true for core display names (DisplayNameCore) without the parens:
/// ::
/// []
/// |>>
/// +
/// *
let IsOperatorDisplayName (name: string) =
let rec loop (name: string) idx endIndex =
if idx = endIndex then
true
else
let c = name[idx]
if not (opCharSet.Contains(c)) || c = ' ' then
false
else
loop name (idx + 1) endIndex
let skipParens2 = name.StartsWithOrdinal("( ") && name.EndsWithOrdinal(" )")
let skipParens1 = name.StartsWithOrdinal("(") && name.EndsWithOrdinal(")")
let skip =
if skipParens2 then 2
elif skipParens1 then 1
else 0
let startIndex = skip
let endIndex = name.Length - skip
(startIndex < endIndex && loop name startIndex endIndex)
|| (name = ".. ..")
|| (name = "(.. ..)")
//IsOperatorDisplayName "+"
//IsOperatorDisplayName "(+)"
//IsOperatorDisplayName "(::)"
//IsOperatorDisplayName "::"
//IsOperatorDisplayName "([])"
//IsOperatorDisplayName "(*)"
//IsOperatorDisplayName "( ** )"
//IsOperatorDisplayName "( )" // false
//IsOperatorDisplayName "( +)" // false
let IsPossibleOpName (name: string) = name.StartsWithOrdinal(opNamePrefix)
let ordinalStringComparer: IEqualityComparer<string> = StringComparer.Ordinal
/// Compiles a custom operator into a mangled operator name.
/// For example, "!%" becomes "op_DereferencePercent".
/// This function should only be used for custom operators
/// if an operator is or potentially may be a built-in operator,
/// use the 'CompileOpName' function instead.
let compileCustomOpName =
let t2 =
let t2 = Dictionary<_, _> opCharTranslateTable.Length
for x, y in opCharTranslateTable do
t2.Add(x, y)
t2
/// The maximum length of the name for a custom operator character.
/// This value is used when initializing StringBuilders to avoid resizing.
let maxOperatorNameLength =
opCharTranslateTable
|> Array.maxBy (snd >> String.length)
|> snd
|> String.length
/// Memoize compilation of custom operators.
/// They're typically used more than once so this avoids some CPU and GC overhead.
let compiledOperators = ConcurrentDictionary<string, string> ordinalStringComparer
// Cache this as a delegate.
let compiledOperatorsAddDelegate =
Func<string, string>(fun (op: string) ->
let opLength = op.Length
let sb =
StringBuilder(opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength))
for i = 0 to opLength - 1 do
let c = op[i]
match t2.TryGetValue c with
| true, x -> sb.Append(x) |> ignore
| false, _ -> sb.Append(c) |> ignore
/// The compiled (mangled) operator name.
let opName = sb.ToString()
// Cache the compiled name so it can be reused.
opName)
fun opp ->
// Has this operator already been compiled?
compiledOperators.GetOrAdd(opp, compiledOperatorsAddDelegate)
/// Maps the built-in F# operators to their mangled operator names.
let standardOpNames =
let opNames = Dictionary<_, _>(opNameTable.Length, ordinalStringComparer)
for x, y in opNameTable do
opNames.Add(x, y)
opNames
let CompileOpName op =
match standardOpNames.TryGetValue op with
| true, x -> x
| false, _ ->
if IsUnencodedOpName op || IsIdentifierName op then
op
else
compileCustomOpName op
/// Decompiles the mangled name of a custom operator back into an operator.
/// For example, "op_DereferencePercent" becomes "!%".
/// This function should only be used for mangled names of custom operators
/// if a mangled name potentially represents a built-in operator,
/// use the 'ConvertValLogicalNameToDisplayNameCore' function instead.
let decompileCustomOpName =
// Memoize this operation. Custom operators are typically used more than once
// so this avoids repeating decompilation.
let decompiledOperators = ConcurrentDictionary<_, _> ordinalStringComparer
/// The minimum length of the name for a custom operator character.
/// This value is used when initializing StringBuilders to avoid resizing.
let minOperatorNameLength =
opCharTranslateTable
|> Array.minBy (snd >> String.length)
|> snd
|> String.length
fun opName ->
// Has this operator name already been decompiled?
match decompiledOperators.TryGetValue opName with
| true, op -> op
| false, _ ->
let opNameLen = opName.Length
/// Function which decompiles the mangled operator name back into a string of operator characters.
/// Returns None if the name contains text which doesn't correspond to an operator
/// otherwise returns Some containing the original operator.
let rec decompile (sb: StringBuilder) idx =
// Have we reached the end of 'opName'?
if idx = opNameLen then
// Finished decompiling.
// Cache the decompiled operator before returning so it can be reused.
let decompiledOp = sb.ToString()
decompiledOperators.TryAdd(opName, decompiledOp) |> ignore
decompiledOp
else
let choice =
opCharTranslateTable
|> Array.tryFind (fun (_, opCharName) ->
// If this operator character name is longer than the remaining piece of 'opName',
// it's obviously not a match.
let opCharNameLen = opCharName.Length
if opNameLen - idx < opCharNameLen then
false
else
// Does 'opCharName' match the current position in 'opName'?
String.Compare(opName, idx, opCharName, 0, opCharNameLen, StringComparison.Ordinal) = 0)
match choice with
| None ->
// Couldn't decompile, so just return the original 'opName'.
opName
| Some(opChar, opCharName) ->
// 'opCharName' matched the current position in 'opName'.
// Append the corresponding operator character to the StringBuilder
// and continue decompiling at the index following this instance of 'opCharName'.
sb.Append opChar |> ignore
decompile sb (idx + opCharName.Length)
let opNamePrefixLen = opNamePrefix.Length
let sb =
/// The maximum number of operator characters that could be contained in the
/// decompiled operator given the length of the mangled custom operator name.
let maxPossibleOpCharCount = (opNameLen - opNamePrefixLen) / minOperatorNameLength
StringBuilder maxPossibleOpCharCount
// Start decompiling just after the operator prefix.
decompile sb opNamePrefixLen
/// Maps the mangled operator names of built-in F# operators back to the operators.
let standardOpsDecompile =
let ops = Dictionary<string, string>(opNameTable.Length, ordinalStringComparer)
for x, y in opNameTable do
ops.Add(y, x)
ops
let ConvertValLogicalNameToDisplayNameCore opName =
match standardOpsDecompile.TryGetValue opName with
| true, res -> res
| false, _ ->
if IsPossibleOpName opName then
decompileCustomOpName opName
else
opName
/// Escape active pattern case names that need backticks for display/signatures.
/// E.g. |A B| becomes |``A B``| (only for display, not for name resolution)
let EscapeActivePatternCases (opName: string) =
if IsActivePatternName opName then
let inner = opName.[1 .. opName.Length - 2]
let cases = inner.Split('|')
let escapedCases =
cases
|> Array.map (fun c ->
if c = "_" then c
elif not (IsIdentifierName c) then "``" + c + "``"
else c)
"|" + (escapedCases |> String.concat "|") + "|"
else
opName
let DoesIdentifierNeedBackticks (name: string) : bool =
not (IsUnencodedOpName name)
&& not (IsIdentifierName name)
&& not (IsActivePatternName name)
/// A utility to help determine if an identifier needs to be quoted
let AddBackticksToIdentifierIfNeeded (name: string) : string =
if
DoesIdentifierNeedBackticks name
&& not (name.StartsWithOrdinal("``"))
&& not (name.EndsWithOrdinal("``"))
then
"``" + name + "``"
else
name
/// Quote identifier with double backticks if needed, remove unnecessary double backticks quotation.
let NormalizeIdentifierBackticks (name: string) : string =
let s =
if name.StartsWithOrdinal("``") && name.EndsWithOrdinal("``") then
name[2 .. name.Length - 3]
else
name
AddBackticksToIdentifierIfNeeded s
let ConvertLogicalNameToDisplayName name = AddBackticksToIdentifierIfNeeded name
let ConvertValLogicalNameToDisplayName isBaseVal name =
if isBaseVal && name = "base" then
"base"
elif IsUnencodedOpName name || IsPossibleOpName name || IsActivePatternName name then
let nm = ConvertValLogicalNameToDisplayNameCore name |> EscapeActivePatternCases
// Check for no decompilation, e.g. op_Implicit, op_NotAMangledOpName, op_A-B
if IsPossibleOpName name && (nm = name) then
AddBackticksToIdentifierIfNeeded nm
// Add parentheses for multiply-like symbols, with spacing to avoid confusion with comments
elif nm <> "*" && (nm.StartsWithOrdinal "*" || nm.EndsWithOrdinal "*") then
"( " + nm + " )"
// Add parentheses for other symbols, no spacing
else
"(" + nm + ")"
else
ConvertLogicalNameToDisplayName name
let ConvertLogicalNameToDisplayLayout nonOpLayout name =
if DoesIdentifierNeedBackticks name then
leftL (TaggedText.tagPunctuation "``")
^^ wordL (TaggedText.tagOperator name)
^^ rightL (TaggedText.tagPunctuation "``")
else
nonOpLayout name
let ConvertValLogicalNameToDisplayLayout isBaseVal nonOpLayout name =
if isBaseVal && name = "base" then
nonOpLayout "base"
elif IsUnencodedOpName name || IsPossibleOpName name || IsActivePatternName name then
let nm = ConvertValLogicalNameToDisplayNameCore name |> EscapeActivePatternCases
// Check for no decompilation, e.g. op_Implicit, op_NotAMangledOpName, op_A-B
if IsPossibleOpName name && (nm = name) then
ConvertLogicalNameToDisplayLayout nonOpLayout name
elif nm.StartsWithOrdinal "*" || nm.EndsWithOrdinal "*" then
wordL (TaggedText.tagPunctuation "(")
^^ wordL (TaggedText.tagOperator nm)
^^ wordL (TaggedText.tagPunctuation ")")
else
leftL (TaggedText.tagPunctuation "(")
^^ wordL (TaggedText.tagOperator nm)
^^ rightL (TaggedText.tagPunctuation ")")
elif name = "get_Zero" then
ConvertLogicalNameToDisplayLayout nonOpLayout "Zero"
else
ConvertLogicalNameToDisplayLayout nonOpLayout name
let opNameCons = CompileOpName "::"
let opNameNil = CompileOpName "[]"
let opNameEquals = CompileOpName "="
let opNameEqualsNullable = CompileOpName "=?"
let opNameNullableEquals = CompileOpName "?="
let opNameNullableEqualsNullable = CompileOpName "?=?"
/// Is this character a part of a long identifier?
let IsLongIdentifierPartCharacter c = c = '.' || IsIdentifierPartCharacter c
let isTildeOnlyString (s: string) =
let rec loop (s: string) idx =
if idx >= s.Length then true
elif s[idx] <> '~' then false
else loop s (idx + 1)
loop s 0
let IsValidPrefixOperatorUse s =
if String.IsNullOrEmpty s then
false
else
match !!s with
| "?+"
| "?-"
| "+"
| "-"
| "+."
| "-."
| "%"
| "%%"
| "&"
| "&&" -> true
| s -> s[0] = '!' || isTildeOnlyString s
let IsValidPrefixOperatorDefinitionName s =
if String.IsNullOrEmpty s then
false
else
let s = !!s
match s[0] with
| '~' ->
isTildeOnlyString s
||
match s with
| "~?+"
| "~?-"
| "~+"
| "~-"
| "~+."
| "~-."
| "~%"
| "~%%"
| "~&"
| "~&&" -> true
| _ -> false
| '!' -> s <> "!="
| _ -> false
let IsLogicalPrefixOperator logicalName =
if String.IsNullOrEmpty logicalName then
false
else
let displayName = ConvertValLogicalNameToDisplayNameCore logicalName
displayName <> logicalName && IsValidPrefixOperatorDefinitionName displayName
let IsLogicalTernaryOperator logicalName =
let displayName = ConvertValLogicalNameToDisplayNameCore logicalName
displayName <> logicalName && (displayName = qmarkSet)
let IsPunctuation s =
if String.IsNullOrEmpty s then
false
else
match s with
| ","
| ";"
| "|"
| ":"
| "."
| "*"
| "("
| ")"
| "["
| "]"
| "{"
| "}"
| "<"
| ">"
| "[|"
| "|]"
| "[<"
| ">]" -> true
| _ -> false
/// EQUALS, INFIX_COMPARE_OP, LESS, GREATER
let relational = [| "="; "!="; "<"; ">"; "$" |]
/// INFIX_AT_HAT_OP
let concat = [| "@"; "^" |]
/// PLUS_MINUS_OP, MINUS
let plusMinus = [| "+"; "-" |]
/// PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP
let otherMath = [| "*"; "/"; "%" |]
/// Characters ignored at the start of the operator name
/// when determining whether an operator is an infix operator.
let ignoredChars = [| '.'; '?' |]
// Certain operator idents are parsed as infix expression operators.
// The parsing as infix operators is hardwired in the grammar [see declExpr productions]
// where certain operator tokens are accepted in infix forms, i.e. <expr> <op> <expr>.
// The lexer defines the strings that lead to those tokens.
//------
// This function recognizes these "infix operator" names.
let IsLogicalInfixOpName logicalName =
let s = ConvertValLogicalNameToDisplayNameCore logicalName
let skipIgnoredChars = s.TrimStart(ignoredChars)
let afterSkipStartsWith prefix =
skipIgnoredChars.StartsWithOrdinal(prefix)
let afterSkipStarts prefixes =
Array.exists afterSkipStartsWith prefixes
// The following conditions follow the declExpr infix clauses.
// The test corresponds to the lexer definition for the token.
s <> logicalName
&& ((s = // COLON_EQUALS
":=")
||
// BAR_BAR, INFIX_BAR_OP
afterSkipStartsWith "|"
||
// AMP, AMP_AMP, INFIX_AMP_OP
afterSkipStartsWith "&"
||
// EQUALS, INFIX_COMPARE_OP, LESS, GREATER
afterSkipStarts relational
||
// DOLLAR
(s = "$")
||
// INFIX_AT_HAT_OP
afterSkipStarts concat
||
// COLON_COLON
(s = "::")
|| (s = qmark)
|| (s = qmarkSet)
|| (s = parenGet)
|| (s = parenSet)
||
// PLUS_MINUS_OP, MINUS
afterSkipStarts plusMinus
||
// PERCENT_OP, STAR, INFIX_STAR_DIV_MOD_OP
afterSkipStarts otherMath
||
// INFIX_STAR_STAR_OP
(s = "**"))
let IsLogicalOpName (logicalName: string) =
IsLogicalPrefixOperator logicalName
|| IsLogicalInfixOpName logicalName
|| IsLogicalTernaryOperator logicalName
let (|Control|Equality|Relational|Indexer|FixedTypes|Other|) opName =
match opName with
| "&&"
| "||" -> Control
| "<>"
| "=" -> Equality
| "<"
| ">"
| "<="
| ">=" -> Relational
| "<<"
| "<|"
| "<||"
| "<||"
| "|>"
| "||>"
| "|||>"
| ">>"
| "^"
| ":="
| "@" -> FixedTypes
| ".[]" -> Indexer
| _ -> Other
[<Literal>]
let compilerGeneratedMarker = "@"
[<Literal>]
let compilerGeneratedMarkerChar = '@'
let IsCompilerGeneratedName (nm: string) =
nm.IndexOf compilerGeneratedMarkerChar <> -1
let CompilerGeneratedName nm =
if IsCompilerGeneratedName nm then
nm
else
nm + compilerGeneratedMarker
let GetBasicNameOfPossibleCompilerGeneratedName (name: string) =
match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with
| -1
| 0 -> name
| n -> name[0 .. n - 1]
let CompilerGeneratedNameSuffix (basicName: string) suffix =
basicName + compilerGeneratedMarker + suffix
//-------------------------------------------------------------------------
// Handle mangled .NET generic type names
//-------------------------------------------------------------------------
[<Literal>]
let mangledGenericTypeNameSym = '`'
let TryDemangleGenericNameAndPos (n: string) =
// check what comes after the symbol is a number
let pos = n.LastIndexOf mangledGenericTypeNameSym
if pos = -1 then
ValueNone
else
let mutable res = pos < n.Length - 1
let mutable i = pos + 1
while res && i < n.Length do
let char = n[i]
if not (char >= '0' && char <= '9') then
res <- false
i <- i + 1
if res then ValueSome pos else ValueNone
type NameArityPair = NameArityPair of string * int
let DemangleGenericTypeNameWithPos pos (mangledName: string) = mangledName.Substring(0, pos)
let DecodeGenericTypeNameWithPos pos (mangledName: string) =
let res = DemangleGenericTypeNameWithPos pos mangledName
let num = mangledName.Substring(pos + 1, mangledName.Length - pos - 1)
NameArityPair(res, int32 num)
let DemangleGenericTypeName (mangledName: string) =
match TryDemangleGenericNameAndPos mangledName with
| ValueSome pos -> DemangleGenericTypeNameWithPos pos mangledName
| _ -> mangledName
let DecodeGenericTypeName (mangledName: string) =
match TryDemangleGenericNameAndPos mangledName with
| ValueSome pos -> DecodeGenericTypeNameWithPos pos mangledName
| _ -> NameArityPair(mangledName, 0)
let chopStringTo (s: string) (c: char) =
match s.IndexOf c with
| -1 -> s
| idx ->
let i = idx + 1
s.Substring(i, s.Length - i)
/// Try to chop "get_" or "set_" from a string
let TryChopPropertyName (s: string) =
// extract the logical name from any mangled name produced by MakeMemberDataAndMangledNameForMemberVal
if s.Length <= 4 then
None
else if s.StartsWithOrdinal("get_") || s.StartsWithOrdinal("set_") then
Some(s.Substring(4, s.Length - 4))
else
let s = chopStringTo s '.'
if s.StartsWithOrdinal("get_") || s.StartsWithOrdinal("set_") then
Some(s.Substring(4, s.Length - 4))
else
None
/// Try to chop "get_" or "set_" from a string.
/// If the string does not start with "get_" or "set_", this function raises an exception.
let ChopPropertyName s =
match TryChopPropertyName s with
| None -> failwithf "Invalid internal property name: '%s'" s
| Some res -> res
let SplitNamesForILPath (s: string) : string list =
if s.StartsWithOrdinal("``") && s.EndsWithOrdinal("``") && s.Length > 4 then
[ s.Substring(2, s.Length - 4) ] // identifier is enclosed in `` .. ``, so it is only a single element (this is very approximate)
else
s.Split [| '.'; '`' |] |> Array.toList // '.' chops members / namespaces / modules; '`' chops generic parameters for .NET types
/// Return a string array delimited by the given separator.
/// Note that a quoted string is not going to be mangled into pieces.
let inline isNotQuotedQuotation (text: string) n = n > 0 && text[n - 1] <> '\\'
let splitAroundQuotation (text: string) (separator: char) =
let length = text.Length
let result = ResizeArray()
let mutable insideQuotation = false
let mutable start = 0
for i = 0 to length - 1 do
match text[i], insideQuotation with
// split when seeing a separator
| c, false when c = separator ->
result.Add(text.Substring(start, i - start))
insideQuotation <- false
start <- i + 1
| _, _ when i = length - 1 -> result.Add(text.Substring(start, i - start + 1))
// keep reading if a separator is inside quotation
| c, true when c = separator -> insideQuotation <- true
// open or close quotation
| '\"', _ when isNotQuotedQuotation text i -> insideQuotation <- not insideQuotation
// keep reading
| _ -> ()
result.ToArray()
/// Return a string array delimited by the given separator up to the maximum number.
/// Note that a quoted string is not going to be mangled into pieces.
let splitAroundQuotationWithCount (text: string) (separator: char) (count: int) =
if count <= 1 then
[| text |]
else
let mangledText = splitAroundQuotation text separator
match mangledText.Length > count with
| true -> Array.append mangledText[0 .. (count - 2)] [| mangledText[(count - 1) ..] |> String.concat (Char.ToString separator) |]
| false -> mangledText
[<Literal>]
let FSharpModuleSuffix = "Module"
/// Prefix for union case tester properties (e.g., "get_IsCase" for union case "Case")
[<Literal>]
let unionCaseTesterPropertyPrefix = "get_Is"
/// The length of unionCaseTesterPropertyPrefix
[<Literal>]
let unionCaseTesterPropertyPrefixLength = 6 // "get_Is".Length
let IsUnionCaseTesterPropertyName (name: string) =
name.StartsWithOrdinal(unionCaseTesterPropertyPrefix)
[<Literal>]
let MangledGlobalName = "`global`"
let IllegalCharactersInTypeAndNamespaceNames =
[| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |]
type ActivePatternInfo =
| APInfo of bool * (string * range) list * range
member x.IsTotal = let (APInfo(p, _, _)) = x in p
member x.ActiveTags = let (APInfo(_, tags, _)) = x in List.map fst tags
member x.ActiveTagsWithRanges = let (APInfo(_, tags, _)) = x in tags
member x.LogicalName =
let (APInfo(isTotal, tags, _)) = x
tags
|> List.map fst
|> String.concat "|"
|> (fun s -> if isTotal then "(|" + s + "|)" else "(|" + s + "|_|)")
member x.Range = let (APInfo(_, _, m)) = x in m
let ActivePatternInfoOfValName nm (m: range) =
// Note: The approximate range calculations in this code assume the name is of the form "(|A|B|)" not "(| A | B |)"
// The ranges are used for IDE refactoring support etc. If names of the second type are used,
// renaming may be inaccurate/buggy. However names of the first form are dominant in F# code.
let rec loop (nm: string) (mp: range) =
let n = nm.IndexOf '|'
if n > 0 then
let m1 = Range.withEnd (Position.mkPos mp.StartLine (mp.StartColumn + n)) mp
let m2 = Range.withStart (Position.mkPos mp.StartLine (mp.StartColumn + n + 1)) mp
(nm[0 .. n - 1], m1) :: loop nm[n + 1 ..] m2
else
let m1 = Range.withEnd (Position.mkPos mp.StartLine (mp.StartColumn + nm.Length)) mp
[ (nm, m1) ]