-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathDocumentationFormatter.fs
More file actions
1028 lines (843 loc) · 35.7 KB
/
Copy pathDocumentationFormatter.fs
File metadata and controls
1028 lines (843 loc) · 35.7 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
namespace FsAutoComplete
module DocumentationFormatter =
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.EditorServices
open FSharp.Compiler.Symbols
open FSharp.Compiler.Syntax
open FSharp.Compiler.Tokenization
open System
open System.Text
open System.Text.RegularExpressions
let nl = Environment.NewLine
let maxPadding = 200
type EntityInfo =
{ Constructors: string array
Fields: string array
Functions: string array
Interfaces: string array
Attributes: string array
DeclaredTypes: string array }
static member Empty =
{ Constructors = [||]
Fields = [||]
Functions = [||]
Interfaces = [||]
Attributes = [||]
DeclaredTypes = [||] }
/// Concat two strings with a space between if both a and b are not IsNullOrWhiteSpace
let internal (++) (a: string) (b: string) =
match String.IsNullOrEmpty a, String.IsNullOrEmpty b with
| true, true -> ""
| false, true -> a
| true, false -> b
| false, false -> a + " " + b
let internal formatShowDocumentationLink (name: string) xmlDocSig assemblyName =
if assemblyName = "-" || xmlDocSig = "_" then
name, name.Length
else
let content =
Uri.EscapeDataString(sprintf """[{ "XmlDocSig": "%s", "AssemblyName": "%s" }]""" xmlDocSig assemblyName)
$"<a href='command:fsharp.showDocumentation?%s{content}'>%s{name}</a>", name.Length
let tag = Regex """<.*>"""
let rec formatType (displayContext: FSharpDisplayContext) (typ: FSharpType) : string * int =
let combineParts (parts: (string * int) seq) : string * int =
// make a single type name out of all of the tuple parts, since each part is correct by construction
(("", 0), parts) ||> Seq.fold (fun (s, l) (ps, pl) -> (s + ps), (l + pl))
let resolvedType =
// unwrap any type abbreviations to their wrapped type
if typ.IsAbbreviation then typ.AbbreviatedType else typ
let xmlDocSig =
try
// if this type resolves to an actual type, then get the xmldoc signature of it, if any.
// some times
if resolvedType.HasTypeDefinition then
resolvedType.TypeDefinition.XmlDocSig
else
"-"
with _ ->
"-"
let assemblyName =
try
if resolvedType.IsGenericParameter then
// generic parameters are unsolved, they don't correspond to actual types,
// so we can't get the assembly name from them
"-"
else
resolvedType.TypeDefinition.Assembly.SimpleName
with _ ->
"-"
if typ.IsTupleType || typ.IsStructTupleType then
// tuples are made of individual type names for the elements separated by asterisks
let separator = formatShowDocumentationLink " * " xmlDocSig assemblyName
let parts =
typ.GenericArguments
|> Seq.map (formatType displayContext)
|> Seq.intersperse separator
|> List.ofSeq
combineParts parts
elif typ.HasTypeDefinition && typ.GenericArguments.Count > 0 then
// this type has generic arguments, so we need to format each of them.
// types with generic arguments get rendered as TYPENAME<P1, P2, P3, ..., PN>
let renderedGenericArgumentTypes =
typ.GenericArguments |> Seq.map (formatType displayContext)
// we set this context specifically because we want to enforce prefix-generic form on tooltip displays
let newContext = displayContext.WithPrefixGenericParameters()
let org = typ.Format newContext
let t = tag.Replace(org, "<")
[ yield formatShowDocumentationLink t xmlDocSig assemblyName
if t.EndsWith("<", StringComparison.Ordinal) then
yield! renderedGenericArgumentTypes |> Seq.intersperse (", ", 2)
yield formatShowDocumentationLink ">" xmlDocSig assemblyName ]
|> combineParts
elif typ.IsGenericParameter then
let name = "'" + typ.GenericParameter.Name
formatShowDocumentationLink name xmlDocSig assemblyName
else if typ.HasTypeDefinition then
let name =
typ.TypeDefinition.DisplayName |> FSharpKeywords.NormalizeIdentifierBackticks
formatShowDocumentationLink name xmlDocSig assemblyName
else
let name = typ.Format displayContext
formatShowDocumentationLink name xmlDocSig assemblyName
let format displayContext (typ: FSharpType) : (string * int) = formatType displayContext typ
let formatGenericParameter includeMemberConstraintTypes displayContext (param: FSharpGenericParameter) =
let asGenericParamName (param: FSharpGenericParameter) = "'" + param.Name
let sb = StringBuilder()
let getConstraint (constrainedBy: FSharpGenericParameterConstraint) =
let memberConstraint (c: FSharpGenericParameterMemberConstraint) =
let formattedMemberName, isProperty =
match c.IsProperty, PrettyNaming.TryChopPropertyName c.MemberName with
| true, Some(chopped) when chopped <> c.MemberName -> chopped, true
| _, _ ->
if PrettyNaming.IsLogicalOpName c.MemberName then
PrettyNaming.ConvertValLogicalNameToDisplayNameCore c.MemberName, false
else
c.MemberName, false
seq {
if c.MemberIsStatic then
yield "static "
yield "member "
yield formattedMemberName
if includeMemberConstraintTypes then
yield " : "
if isProperty then
yield (c.MemberReturnType |> format displayContext |> fst)
else
if c.MemberArgumentTypes.Count <= 1 then
yield "unit"
else
yield asGenericParamName param
yield " -> "
yield ((c.MemberReturnType |> format displayContext |> fst).TrimStart())
}
|> String.concat ""
let typeConstraint (tc: FSharpType) = sprintf ":> %s" (tc |> format displayContext |> fst)
let enumConstraint (ec: FSharpType) = sprintf "enum<%s>" (ec |> format displayContext |> fst)
let delegateConstraint (tc: FSharpGenericParameterDelegateConstraint) =
sprintf
"delegate<%s, %s>"
(tc.DelegateTupledArgumentType |> format displayContext |> fst)
(tc.DelegateReturnType |> format displayContext |> fst)
let symbols =
match constrainedBy with
| _ when constrainedBy.IsCoercesToConstraint -> Some(typeConstraint constrainedBy.CoercesToTarget)
| _ when constrainedBy.IsMemberConstraint -> Some(memberConstraint constrainedBy.MemberConstraintData)
| _ when constrainedBy.IsSupportsNullConstraint -> Some("null")
| _ when constrainedBy.IsRequiresDefaultConstructorConstraint -> Some("default constructor")
| _ when constrainedBy.IsReferenceTypeConstraint -> Some("reference")
| _ when constrainedBy.IsEnumConstraint -> Some(enumConstraint constrainedBy.EnumConstraintTarget)
| _ when constrainedBy.IsComparisonConstraint -> Some("comparison")
| _ when constrainedBy.IsEqualityConstraint -> Some("equality")
| _ when constrainedBy.IsDelegateConstraint -> Some(delegateConstraint constrainedBy.DelegateConstraintData)
| _ when constrainedBy.IsUnmanagedConstraint -> Some("unmanaged")
| _ when constrainedBy.IsNonNullableValueTypeConstraint -> Some("struct")
| _ -> None
symbols
if param.Constraints.Count > 0 then
param.Constraints
|> Seq.choose getConstraint
|> Seq.distinct
|> Seq.iteri (fun i symbol ->
if i > 0 then
print sb " and "
print sb symbol)
sb.ToString()
let formatParameter displayContext (p: FSharpParameter) =
try
p.Type |> format displayContext
with :? InvalidOperationException ->
p.DisplayName, p.DisplayName.Length
let getUnionCaseSignature displayContext (unionCase: FSharpUnionCase) =
if unionCase.Fields.Count > 0 then
let typeList =
unionCase.Fields
|> Seq.map (fun unionField ->
if unionField.Name.StartsWith("Item", StringComparison.Ordinal) then //TODO: Some better way of detecting default names for the union cases' fields
unionField.FieldType |> format displayContext |> fst
else
unionField.Name
++ ":"
++ ((unionField.FieldType |> format displayContext |> fst)))
|> String.concat " * "
unionCase.DisplayName + " of " + typeList
else
unionCase.DisplayName
let getFuncSignatureWithIdent displayContext (func: FSharpMemberOrFunctionOrValue) (ident: int) =
let maybeGetter = func.LogicalName.StartsWith("get_", StringComparison.Ordinal)
let indent = String.replicate ident " "
let functionName =
let name =
if func.IsConstructor then
match func.EnclosingEntitySafe with
| Some ent -> ent.DisplayName
| _ -> func.DisplayName
|> FSharpKeywords.NormalizeIdentifierBackticks
elif func.IsOperatorOrActivePattern then
func.DisplayName
elif func.DisplayName.StartsWith("( ", StringComparison.Ordinal) then
FSharpKeywords.NormalizeIdentifierBackticks func.LogicalName
else
FSharpKeywords.NormalizeIdentifierBackticks func.DisplayName
name
let modifiers =
let accessibility =
match func.Accessibility with
| a when a.IsInternal -> "internal"
| a when a.IsPrivate -> "private"
| _ -> ""
let modifier =
//F# types are prefixed with new, should non F# types be too for consistency?
if func.IsConstructor then
match func.EnclosingEntitySafe with
| Some ent ->
if ent.IsFSharp then
"new" ++ accessibility
else
accessibility
| _ -> accessibility
elif func.IsProperty then
if func.IsInstanceMember then
if func.IsDispatchSlot then
"abstract property" ++ accessibility
else
"property" ++ accessibility
else
"static property" ++ accessibility
elif func.IsMember then
if func.IsInstanceMember then
if func.IsDispatchSlot then
"abstract member" ++ accessibility
else
"member" ++ accessibility
else
"static member" ++ accessibility
else if func.InlineAnnotation = FSharpInlineAnnotation.AlwaysInline then
"val" ++ accessibility ++ "inline"
elif func.IsInstanceMember then
"val" ++ accessibility
else
"val" ++ accessibility //does this need to be static prefixed?
modifier
let argInfos = func.CurriedParameterGroups |> Seq.map Seq.toList |> Seq.toList
let retType =
//This try block will be removed when FCS updates
try
func.ReturnParameter.Type |> format displayContext |> fst
with _ex ->
"Unknown"
let retTypeConstraint =
if func.ReturnParameter.Type.IsGenericParameter then
let formattedParam =
formatGenericParameter false displayContext func.ReturnParameter.Type.GenericParameter
if String.IsNullOrWhiteSpace formattedParam then
formattedParam
else
"(requires " + formattedParam + " )"
else
""
let padLength =
let allLengths =
argInfos
|> List.concat
|> List.map (fun p ->
let name = Option.defaultValue p.DisplayName p.Name
let normalisedName = FSharpKeywords.NormalizeIdentifierBackticks name
normalisedName.Length)
match allLengths with
| [] -> 0
| l -> l |> List.maxUnderThreshold maxPadding
let formatName indent padding (parameter: FSharpParameter) =
let name = Option.defaultValue parameter.DisplayName parameter.Name
let normalisedName = FSharpKeywords.NormalizeIdentifierBackticks name
indent + normalisedName.PadRight padding + ":"
let isDelegate =
match func.EnclosingEntitySafe with
| Some ent -> ent.IsDelegate
| _ -> false
match argInfos with
| [] ->
//When does this occur, val type within module?
if isDelegate then
retType
else
modifiers ++ functionName + ":" ++ retType
| [ [] ] ->
if isDelegate then
retType
//A ctor with () parameters seems to be a list with an empty list.
// Also abstract members and abstract member overrides with one () parameter seem to be a list with an empty list.
elif func.IsConstructor || (func.IsMember && (not func.IsPropertyGetterMethod)) then
modifiers + ": unit -> " ++ retType
else
modifiers ++ functionName + ":" ++ retType //Value members seems to be a list with an empty list
| [ [ p ] ] when maybeGetter && formatParameter displayContext p |> fst = "unit" -> //Member or property with only getter
modifiers ++ functionName + ":" ++ retType
| many ->
let allParamsLengths =
many
|> List.map (List.map (fun p -> (formatParameter displayContext p |> snd)) >> List.sum)
let maxLength = (allParamsLengths |> List.maxUnderThreshold maxPadding) + 1
let parameterTypeWithPadding (p: FSharpParameter) length =
(formatParameter displayContext p |> fst)
+ (String.replicate (if length >= maxLength then 1 else maxLength - length) " ")
let formatParameterPadded length p =
let paddedParam =
formatName indent padLength p ++ (parameterTypeWithPadding p length)
if p.Type.IsGenericParameter then
let paramConstraint =
let formattedParam =
formatGenericParameter false displayContext p.Type.GenericParameter
if String.IsNullOrWhiteSpace formattedParam then
formattedParam
else
"(requires " + formattedParam + " )"
if paramConstraint = retTypeConstraint then
paddedParam
else
paddedParam + paramConstraint
else
paddedParam
let allParams =
List.zip many allParamsLengths
|> List.map (fun (paramTypes, length) ->
paramTypes |> List.map (formatParameterPadded length) |> String.concat $" *{nl}")
|> String.concat $"->{nl}"
let typeArguments =
allParams + nl + indent + (String.replicate (max (padLength - 1) 0) " ") + "->"
++ retType
++ retTypeConstraint
if isDelegate then
typeArguments
else
modifiers ++ $"{functionName}:{nl}{typeArguments}"
let getFuncSignatureForTypeSignature
displayContext
(func: FSharpMemberOrFunctionOrValue)
(getter: bool)
(setter: bool)
=
let functionName =
let name =
if func.IsConstructor then
"new"
elif func.IsOperatorOrActivePattern then
func.DisplayName
elif func.DisplayName.StartsWith("( ", StringComparison.Ordinal) then
FSharpKeywords.NormalizeIdentifierBackticks func.LogicalName
elif
func.LogicalName.StartsWith("get_", StringComparison.Ordinal)
|| func.LogicalName.StartsWith("set_", StringComparison.Ordinal)
then
PrettyNaming.TryChopPropertyName func.DisplayName
|> Option.defaultValue func.DisplayName
else
func.DisplayName
fst (formatShowDocumentationLink name func.XmlDocSig func.Assembly.SimpleName)
let modifiers =
let accessibility =
match func.Accessibility with
| a when a.IsInternal -> "internal"
| a when a.IsPrivate -> "private"
| _ -> ""
let modifier =
//F# types are prefixed with new, should non F# types be too for consistency?
if func.IsConstructor then
accessibility
elif func.IsProperty then
if func.IsInstanceMember then
if func.IsDispatchSlot then
"abstract property" ++ accessibility
else
"property" ++ accessibility
else
"static property" ++ accessibility
elif func.IsMember then
if func.IsInstanceMember then
if func.IsDispatchSlot then
"abstract member" ++ accessibility
else
"member" ++ accessibility
else
"static member" ++ accessibility
else if func.InlineAnnotation = FSharpInlineAnnotation.AlwaysInline then
"val" ++ accessibility ++ "inline"
elif func.IsInstanceMember then
"val" ++ accessibility
else
"val" ++ accessibility //does this need to be static prefixed?
modifier
let argInfos = func.CurriedParameterGroups |> Seq.map Seq.toList |> Seq.toList
let retType =
//This try block will be removed when FCS updates
try
if func.IsConstructor then
match func.EnclosingEntitySafe with
| Some ent -> ent.DisplayName
| _ -> func.DisplayName
else
func.ReturnParameter.Type |> format displayContext |> fst
with _ex ->
try
if func.FullType.GenericArguments.Count > 0 then
let lastArg = func.FullType.GenericArguments |> Seq.last
lastArg |> format displayContext |> fst
else
"Unknown"
with _ ->
"Unknown"
let formatName (parameter: FSharpParameter) = parameter.Name |> Option.defaultValue parameter.DisplayName
let isDelegate =
match func.EnclosingEntitySafe with
| Some ent -> ent.IsDelegate
| _ -> false
let res =
match argInfos with
| [] ->
//When does this occur, val type within module?
if isDelegate then
retType
else
modifiers ++ functionName + ": " ++ retType
| [ [] ] ->
if isDelegate then
retType
elif func.IsConstructor then
modifiers + ": unit ->" ++ retType //A ctor with () parameters seems to be a list with an empty list
else
modifiers ++ functionName + ": " ++ retType //Value members seems to be a list with an empty list
| many ->
let allParams =
many
|> List.map (fun (paramTypes) ->
paramTypes
|> List.map (fun p -> formatName p + ":" ++ fst (formatParameter displayContext p))
|> String.concat (" * "))
|> String.concat ("-> ")
let typeArguments = allParams ++ "->" ++ retType
if isDelegate then
typeArguments
else
modifiers ++ functionName + ": " + typeArguments
match getter, setter with
| true, true -> res ++ "with get,set"
| true, false -> res ++ "with get"
| false, true -> res ++ "with set"
| false, false -> res
let getFuncSignature f c = getFuncSignatureWithIdent f c 3
let getValSignature displayContext (v: FSharpMemberOrFunctionOrValue) =
let retType = v.FullType |> format displayContext |> fst
let prefix = if v.IsMutable then "val mutable" else "val"
let name =
(if v.DisplayName.StartsWith("( ", StringComparison.Ordinal) then
v.LogicalName
else
v.DisplayName)
|> FSharpKeywords.NormalizeIdentifierBackticks
let constraints =
match v.FullTypeSafe with
| Some fullType when fullType.IsGenericParameter ->
let formattedParam =
formatGenericParameter false displayContext fullType.GenericParameter
if String.IsNullOrWhiteSpace formattedParam then
None
else
Some formattedParam
| _ -> None
match constraints with
| Some constraints -> prefix ++ name ++ ":" ++ constraints
| None -> prefix ++ name ++ ":" ++ retType
let getFieldSignature displayContext (field: FSharpField) =
let retType = field.FieldType |> format displayContext |> fst
match field.LiteralValue with
| Some lv -> field.DisplayName + ":" ++ retType ++ "=" ++ (string lv)
| None ->
let prefix = if field.IsMutable then "val mutable" else "val"
prefix ++ field.DisplayName + ":" ++ retType
let getAPCaseSignature displayContext (apc: FSharpActivePatternCase) =
let findVal =
apc.Group.DeclaringEntity
|> Option.bind (fun ent ->
ent.MembersFunctionsAndValues
|> Seq.tryFind (fun func -> func.DisplayName.Contains apc.DisplayName)
|> Option.map (getFuncSignature displayContext))
|> Option.bind (fun n ->
try
Some(n.Split([| ':' |], 2).[1])
with _ ->
None)
|> Option.defaultValue ""
sprintf "active pattern %s: %s" apc.Name findVal
let getAttributeSignature (attr: FSharpAttribute) =
let name =
formatShowDocumentationLink
attr.AttributeType.DisplayName
attr.AttributeType.XmlDocSig
attr.AttributeType.Assembly.SimpleName
let attr =
attr.ConstructorArguments |> Seq.map (snd >> string) |> String.concat ", "
sprintf "%s(%s)" (fst name) attr
let getEntitySignature displayContext (fse: FSharpEntity) =
let modifier =
match fse.Accessibility with
| a when a.IsInternal -> "internal "
| a when a.IsPrivate -> "private "
| _ -> ""
let typeName (fse: FSharpEntity) =
match fse with
| _ when fse.IsFSharpModule -> "module"
| _ when fse.IsEnum -> "enum"
| _ when fse.IsValueType -> "struct"
| _ when fse.IsNamespace -> "namespace"
| _ when fse.IsFSharpRecord -> "record"
| _ when fse.IsFSharpUnion -> "union"
| _ when fse.IsInterface -> "interface"
| _ -> "type"
let enumTip () =
$" ={nl} |"
++ (fse.FSharpFields
|> Seq.filter (fun f -> not f.IsCompilerGenerated)
|> Seq.sortBy (fun f ->
match f.LiteralValue with
| None -> -1
| Some lv -> Int32.Parse(string lv))
|> Seq.map (fun field ->
match field.LiteralValue with
| Some lv -> field.Name + " = " + (string lv)
| None -> field.Name)
|> String.concat $"{nl} | ")
let unionTip () =
$" ={nl} |"
++ (fse.UnionCases
|> Seq.map (getUnionCaseSignature displayContext)
|> String.concat ($"{nl} | "))
let delegateTip () =
let delegateSig = fse.FSharpDelegateSignature
let args =
if delegateSig.DelegateArguments.Count = 0 then
"unit"
else
delegateSig.DelegateArguments
|> Seq.map (fun (name, ty) ->
let typeName = ty |> format displayContext |> fst
match name with
| Some n when not (String.IsNullOrWhiteSpace n) ->
let n = FSharpKeywords.NormalizeIdentifierBackticks n
$"{n}: {typeName}"
| _ -> typeName)
|> String.concat " * "
let retType = delegateSig.DelegateReturnType |> format displayContext |> fst
$" ={nl} delegate of {args} -> {retType}"
let typeTip () =
let constructors =
fse.MembersFunctionsAndValues
|> Seq.filter (fun n -> n.IsConstructor && n.Accessibility.IsPublic)
|> Seq.collect (fun f ->
seq {
yield getFuncSignatureForTypeSignature displayContext f false false
yield!
f.GetOverloads false
|> Option.map (Seq.map (fun f -> getFuncSignatureForTypeSignature displayContext f false false))
|> Option.defaultValue Seq.empty
})
|> Seq.toArray
let fields =
fse.FSharpFields
|> Seq.filter (fun n -> n.Accessibility.IsPublic) //TODO: If defined in same project as current scope then show also internals
|> Seq.sortBy (fun n -> n.DisplayName)
|> Seq.map (getFieldSignature displayContext)
|> Seq.toArray
let funcs =
fse.MembersFunctionsAndValues
|> Seq.filter (fun n -> n.Accessibility.IsPublic && (not n.IsConstructor)) //TODO: If defined in same project as current scope then show also internals
|> Seq.sortWith (fun n1 n2 ->
let modifierScore (f: FSharpMemberOrFunctionOrValue) =
if f.IsProperty then
if f.IsInstanceMember then
if f.IsDispatchSlot then 9 else 1
else
8
elif f.IsMember then
if f.IsInstanceMember then
if f.IsDispatchSlot then 11 else 2
else
10
else
3
let n1Score = modifierScore n1
let n2Score = modifierScore n2
if n1Score = n2Score then
n1.DisplayName.CompareTo n2.DisplayName
else
n1Score.CompareTo n2Score)
|> Seq.groupBy (fun n -> n.FullName)
|> Seq.collect (fun (_, v) ->
match v |> Seq.tryFind (fun f -> f.IsProperty) with
| Some prop ->
let getter = v |> Seq.exists (fun f -> f.IsPropertyGetterMethod)
let setter = v |> Seq.exists (fun f -> f.IsPropertySetterMethod)
[ getFuncSignatureForTypeSignature displayContext prop getter setter ] //Ensure properties are displayed only once, properly report
| None ->
[ for f in v do
yield getFuncSignatureForTypeSignature displayContext f false false
yield!
f.GetOverloads false
|> Option.map (Seq.map (fun f -> getFuncSignatureForTypeSignature displayContext f false false))
|> Option.defaultValue Seq.empty ])
|> Seq.toArray
let interfaces =
fse.DeclaredInterfaces
|> Seq.map (fun inf -> fst (format displayContext inf))
|> Seq.toArray
let attrs = fse.Attributes |> Seq.map getAttributeSignature |> Seq.toArray
let types =
fse.NestedEntities
|> Seq.choose (fun ne ->
let isCompilerGenerated =
ne.Attributes
|> Seq.tryFind (fun attribute -> attribute.AttributeType.CompiledName = "CompilerGeneratedAttribute")
|> Option.isSome
if not ne.IsNamespace && not isCompilerGenerated then
(typeName ne)
++ fst (formatShowDocumentationLink ne.DisplayName ne.XmlDocSig ne.Assembly.SimpleName)
|> Some
else
None)
|> Seq.toArray
{ Constructors = constructors
Fields = fields
Functions = funcs
Interfaces = interfaces
Attributes = attrs
DeclaredTypes = types }
let typeDisplay =
let name =
let normalisedName = FSharpKeywords.NormalizeIdentifierBackticks fse.DisplayName
if fse.GenericParameters.Count > 0 then
let paramsAndConstraints =
fse.GenericParameters
|> Seq.groupBy (fun p -> p.Name)
|> Seq.map (fun (name, constraints) ->
let renderedConstraints =
constraints
|> Seq.map (formatGenericParameter false displayContext)
|> String.concat " and"
if String.IsNullOrWhiteSpace renderedConstraints then
"'" + name
else
sprintf "'%s (requires %s)" name renderedConstraints)
normalisedName + "<" + (paramsAndConstraints |> String.concat ",") + ">"
else
normalisedName
let basicName = modifier + (typeName fse) ++ name
if fse.IsFSharpAbbreviation then
let unannotatedType = fse.UnAnnotate()
basicName ++ "=" ++ (unannotatedType.DisplayName)
else
basicName
if fse.IsFSharpUnion then
(typeDisplay + unionTip ()), typeTip ()
elif fse.IsEnum then
(typeDisplay + enumTip ()), EntityInfo.Empty
elif fse.IsDelegate then
(typeDisplay + delegateTip ()), EntityInfo.Empty
else
typeDisplay, typeTip ()
type FSharpSymbol with
/// trims the leading 'Microsoft.' from the full name of the symbol
member m.SafeFullName =
if
m.FullName.StartsWith("Microsoft.", StringComparison.Ordinal)
&& m.Assembly.SimpleName = "FSharp.Core"
then
m.FullName.Substring "Microsoft.".Length
else
m.FullName
let footerForType (entity: FSharpSymbolUse) =
try
match entity with
| SymbolUse.MemberFunctionOrValue m ->
match m.DeclaringEntity with
| None -> sprintf "Full name: %s\nAssembly: %s" m.SafeFullName m.Assembly.SimpleName
| Some e ->
let link =
fst (formatShowDocumentationLink e.DisplayName e.XmlDocSig e.Assembly.SimpleName)
sprintf "Full name: %s\nDeclaring Entity: %s\nAssembly: %s" m.SafeFullName link m.Assembly.SimpleName
| SymbolUse.Entity(c, _) ->
match c.DeclaringEntity with
| None -> sprintf "Full name: %s\nAssembly: %s" c.SafeFullName c.Assembly.SimpleName
| Some e ->
let link =
fst (formatShowDocumentationLink e.DisplayName e.XmlDocSig e.Assembly.SimpleName)
sprintf "Full name: %s\nDeclaring Entity: %s\nAssembly: %s" c.SafeFullName link c.Assembly.SimpleName
| SymbolUse.Field f ->
match f.DeclaringEntity with
| None -> sprintf "Full name: %s\nAssembly: %s" f.SafeFullName f.Assembly.SimpleName
| Some e ->
let link =
fst (formatShowDocumentationLink e.DisplayName e.XmlDocSig e.Assembly.SimpleName)
sprintf "Full name: %s\nDeclaring Entity: %s\nAssembly: %s" f.SafeFullName link f.Assembly.SimpleName
| SymbolUse.ActivePatternCase ap -> sprintf "Full name: %s\nAssembly: %s" ap.SafeFullName ap.Assembly.SimpleName
| SymbolUse.UnionCase uc -> sprintf "Full name: %s\nAssembly: %s" uc.SafeFullName uc.Assembly.SimpleName
| _ -> ""
with _ ->
""
let footerForType' (entity: FSharpSymbol) =
try
match entity with
| MemberFunctionOrValue m -> sprintf "Full name: %s\nAssembly: %s" m.SafeFullName m.Assembly.SimpleName
| EntityFromSymbol(c, _) -> sprintf "Full name: %s\nAssembly: %s" c.SafeFullName c.Assembly.SimpleName
| Field(f, _) -> sprintf "Full name: %s\nAssembly: %s" f.SafeFullName f.Assembly.SimpleName
| ActivePatternCase ap -> sprintf "Full name: %s\nAssembly: %s" ap.SafeFullName ap.Assembly.SimpleName
| UnionCase uc -> sprintf "Full name: %s\nAssembly: %s" uc.SafeFullName uc.Assembly.SimpleName
| _ -> ""
with _ ->
""
let compiledNameType (entity: FSharpSymbolUse) =
try
entity.Symbol.XmlDocSig
with _ ->
""
let compiledNameType' (entity: FSharpSymbol) =
try
entity.XmlDocSig
with _ ->
""
/// Returns formatted symbol signature and footer that can be used to enhance standard FCS' text tooltips
let getTooltipDetailsFromSymbolUse (symbol: FSharpSymbolUse) =
let cn = compiledNameType symbol
match symbol with
| SymbolUse.TypeAbbreviation(fse) ->
try
let parent = fse.GetAbbreviatedParent()
match parent with
| FSharpEntity(ent, _, _) ->
let signature = getEntitySignature symbol.DisplayContext ent
Some(signature, footerForType' parent, cn)
| _ -> None
with _ ->
None
| SymbolUse.Entity(fse, _) ->
try
let signature = getEntitySignature symbol.DisplayContext fse
Some(signature, footerForType symbol, cn)
with _ ->
None
| SymbolUse.Constructor func ->
match func.EnclosingEntitySafe with
| Some ent when ent.IsValueType || ent.IsEnum ->
//ValueTypes
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| _ ->
//ReferenceType constructor
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Operator func ->
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Pattern func ->
//Active pattern or operator
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Property prop ->
let signature = getFuncSignature symbol.DisplayContext prop
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.ClosureOrNestedFunction func ->
//represents a closure or nested function
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Function func ->
let signature = getFuncSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Val func ->
//val name : Type
let signature = getValSignature symbol.DisplayContext func
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.Field fsf ->
let signature = getFieldSignature symbol.DisplayContext fsf
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.UnionCase uc ->
let signature = getUnionCaseSignature symbol.DisplayContext uc
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.ActivePatternCase apc ->
let signature = getAPCaseSignature symbol.DisplayContext apc
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.ActivePattern ap ->
let signature = getFuncSignature symbol.DisplayContext ap
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| SymbolUse.GenericParameter gp ->
let signature =
$"'%s{gp.Name} (requires %s{formatGenericParameter false symbol.DisplayContext gp})"
Some((signature, EntityInfo.Empty), footerForType symbol, cn)
| _ -> None
/// Returns formatted symbol signature and footer that can be used to enhance standard FCS' text tooltips
let getTooltipDetailsFromSymbol (displayContext: FSharpDisplayContext) (symbol: FSharpSymbol) =
let cn = compiledNameType' symbol
match symbol with
| EntityFromSymbol(fse, _) ->
try
let signature = getEntitySignature displayContext fse
Some(signature, footerForType' symbol, cn)
with _ ->
None
| Constructor func ->
match func.EnclosingEntitySafe with
| Some ent when ent.IsValueType || ent.IsEnum ->
//ValueTypes
let signature = getFuncSignature displayContext func
Some((signature, EntityInfo.Empty), footerForType' symbol, cn)
| _ ->
//ReferenceType constructor
let signature = getFuncSignature displayContext func
Some((signature, EntityInfo.Empty), footerForType' symbol, cn)
| SymbolPatterns.Operator func ->
let signature = getFuncSignature displayContext func
Some((signature, EntityInfo.Empty), footerForType' symbol, cn)
| Property prop ->
let signature = getFuncSignature displayContext prop
Some((signature, EntityInfo.Empty), footerForType' symbol, cn)
| ClosureOrNestedFunction func ->
//represents a closure or nested function
let signature = getFuncSignature displayContext func
Some((signature, EntityInfo.Empty), footerForType' symbol, cn)
| Function func ->