-
Notifications
You must be signed in to change notification settings - Fork 158
/
GenerateModel.fs
3185 lines (2560 loc) · 119 KB
/
GenerateModel.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 rec FSharp.Formatting.ApiDocs
open System
open System.Reflection
open System.Collections.Generic
open System.Text
open System.IO
open System.Web
open System.Xml
open System.Xml.Linq
open FSharp.Compiler.Symbols
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Formatting.Common
open FSharp.Formatting.Internal
open FSharp.Formatting.CodeFormat
open FSharp.Formatting.Literate
open FSharp.Formatting.Markdown
open FSharp.Formatting.HtmlModel
open FSharp.Formatting.HtmlModel.Html
open FSharp.Formatting.Templating
open FSharp.Patterns
open FSharp.Compiler.Syntax
[<AutoOpen>]
module internal Utils =
let (|AllAndLast|_|) (list: 'T list) =
if list.IsEmpty then
None
else
let revd = List.rev list in Some(List.rev revd.Tail, revd.Head)
let isAttrib<'T> (attrib: FSharpAttribute) =
attrib.AttributeType.CompiledName = typeof<'T>.Name
let hasAttrib<'T> (attribs: IList<FSharpAttribute>) =
attribs |> Seq.exists (fun a -> isAttrib<'T> (a))
let tryFindAttrib<'T> (attribs: IList<FSharpAttribute>) =
attribs |> Seq.tryFind (fun a -> isAttrib<'T> (a))
let (|MeasureProd|_|) (typ: FSharpType) =
if
typ.HasTypeDefinition
&& typ.TypeDefinition.LogicalName = "*"
&& typ.GenericArguments.Count = 2
then
Some(typ.GenericArguments.[0], typ.GenericArguments.[1])
else
None
let (|MeasureInv|_|) (typ: FSharpType) =
if
typ.HasTypeDefinition
&& typ.TypeDefinition.LogicalName = "/"
&& typ.GenericArguments.Count = 1
then
Some typ.GenericArguments.[0]
else
None
[<return: Struct>]
let (|MeasureOne|_|) (typ: FSharpType) =
if
typ.HasTypeDefinition
&& typ.TypeDefinition.LogicalName = "1"
&& typ.GenericArguments.Count = 0
then
ValueSome()
else
ValueNone
let tryGetLocation (symbol: FSharpSymbol) =
match symbol.ImplementationLocation with
| Some loc -> Some loc
| None -> symbol.DeclarationLocation
let isUnitType (ty: FSharpType) =
ty.HasTypeDefinition
&& ty.TypeDefinition.XmlDocSig = "T:Microsoft.FSharp.Core.unit"
module List =
let tailOrEmpty xs =
match xs with
| [] -> []
| _ :: t -> t
let sepWith sep xs =
match xs with
| [] -> []
| _ ->
[ for x in xs do
yield sep
yield x ]
|> List.tail
module Html =
let sepWith s l = l |> List.sepWith (!!s) |> span []
type System.Xml.Linq.XElement with
member x.TryAttr(attr: string) =
let a = x.Attribute(XName.Get attr)
if isNull a then None
else if String.IsNullOrEmpty a.Value then None
else Some a.Value
/// Represents some HTML formatted by model generation
type ApiDocHtml(html: string, id: string option) =
/// Get the HTML text of the HTML section
member _.HtmlText = html
/// Get the Id of the element when rendered to html, if any
member _.Id = id
/// Represents a documentation comment attached to source code
type ApiDocComment(xmldoc, summary, remarks, parameters, returns, examples, notes, exceptions, rawData) =
/// The XElement for the XML doc if available
member _.Xml: XElement option = xmldoc
/// The summary for the comment
member _.Summary: ApiDocHtml = summary
/// The remarks html for comment
member _.Remarks: ApiDocHtml option = remarks
/// The param sections of the comment
member _.Parameters: (string * ApiDocHtml) list = parameters
/// The examples sections of the comment
member _.Examples: ApiDocHtml list = examples
/// The notes sections of the comment
member _.Notes: ApiDocHtml list = notes
/// The return sections of the comment
member _.Returns: ApiDocHtml option = returns
/// The notes sections of the comment
member _.Exceptions: (string * string option * ApiDocHtml) list = exceptions
/// The raw data of the comment
member _.RawData: KeyValuePair<string, string> list = rawData
static member internal Empty = ApiDocComment(None, ApiDocHtml("", None), None, [], None, [], [], [], [])
/// Represents a custom attribute attached to source code
type ApiDocAttribute(name, fullName, constructorArguments, namedConstructorArguments) =
/// The name of the attribute
member _.Name: string = name
/// The qualified name of the attribute
member _.FullName: string = fullName
/// The arguments to the constructor for the attribute
member _.ConstructorArguments: obj list = constructorArguments
/// The named arguments for the attribute
member _.NamedConstructorArguments: (string * obj) list = namedConstructorArguments
/// Gets a value indicating whether this attribute is System.ObsoleteAttribute
member x.IsObsoleteAttribute = x.FullName = "System.ObsoleteAttribute"
/// Gets a value indicating whether this attribute is RequireQualifiedAccessAttribute
member x.IsRequireQualifiedAccessAttribute = x.FullName = typeof<RequireQualifiedAccessAttribute>.FullName
/// Returns the obsolete message, when this attribute is the System.ObsoleteAttribute. When its not or no message was specified, an empty string is returned
member x.ObsoleteMessage =
let tryFindObsoleteMessage =
x.ConstructorArguments
|> List.tryPick (fun x ->
match x with
| :? string as s -> Some s
| _ -> None)
|> Option.defaultValue ""
if x.IsObsoleteAttribute then tryFindObsoleteMessage else ""
/// Gets a value indicating whether this attribute the CustomOperationAttribute
member x.IsCustomOperationAttribute = x.FullName = "Microsoft.FSharp.Core.CustomOperationAttribute"
/// Returns the custom operation name, when this attribute is the CustomOperationAttribute. When its not an empty string is returned
member x.CustomOperationName =
let tryFindCustomOperation =
x.ConstructorArguments
|> List.tryPick (fun x ->
match x with
| :? string as s -> Some s
| _ -> None)
|> Option.defaultValue ""
if x.IsCustomOperationAttribute then
tryFindCustomOperation
else
""
/// Formats the attribute with the given name
member private x.Format(attributeName: string, removeAttributeSuffix: bool) =
let dropSuffix (s: string) (t: string) = s.[0 .. s.Length - t.Length - 1]
let attributeName =
if
removeAttributeSuffix
&& attributeName.EndsWith("Attribute", StringComparison.Ordinal)
then
dropSuffix attributeName "Attribute"
else
attributeName
let join sep (items: string seq) = String.Join(sep, items)
let inline append (s: string) (sb: StringBuilder) = sb.Append(s)
let inline appendIfTrue p s sb = if p then append s sb else sb
let rec formatValue (v: obj) =
match v with
| :? string as s -> sprintf "\"%s\"" s
| :? (obj array) as a -> a |> Seq.map formatValue |> join "; " |> sprintf "[|%s|]"
| :? bool as b -> if b then "true" else "false"
| _ -> string<obj> v
let formatedConstructorArguments = x.ConstructorArguments |> Seq.map formatValue |> join ", "
let formatedNamedConstructorArguments =
x.NamedConstructorArguments
|> Seq.map (fun (n, v) -> sprintf "%s = %s" n (formatValue v))
|> join ", "
let needsBraces = not (List.isEmpty x.ConstructorArguments && List.isEmpty x.NamedConstructorArguments)
let needsListSeperator = not (List.isEmpty x.ConstructorArguments || List.isEmpty x.NamedConstructorArguments)
StringBuilder()
|> append "[<"
|> append attributeName
|> appendIfTrue needsBraces "("
|> append formatedConstructorArguments
|> appendIfTrue needsListSeperator ", "
|> append formatedNamedConstructorArguments
|> appendIfTrue needsBraces ")"
|> append ">]"
|> string<StringBuilder>
/// Formats the attribute using the Name. Removes the "Attribute"-suffix. E.g Obsolete
member x.Format() = x.Format(x.Name, true)
/// Formats the attribute using the FullName. Removes the "Attribute"-suffix. E.g System.Obsolete
member x.FormatFullName() = x.Format(x.FullName, true)
/// Formats the attribute using the Name. Keeps the "Attribute"-suffix. E.g ObsoleteAttribute
member x.FormatLongForm() = x.Format(x.Name, false)
/// Formats the attribute using the FullName. Keeps the "Attribute"-suffix. E.g System.ObsoleteAttribute
member x.FormatFullNameLongForm() = x.Format(x.FullName, false)
/// Tries to find the System.ObsoleteAttribute and return its obsolete message
static member internal TryGetObsoleteMessage(attributes: ApiDocAttribute seq) =
attributes
|> Seq.tryFind (fun a -> a.IsObsoleteAttribute)
|> Option.map (fun a -> a.ObsoleteMessage)
|> Option.defaultValue ""
/// Tries to find the CustomOperationAttribute and return its obsolete message
static member internal TryGetCustomOperationName(attributes: ApiDocAttribute seq) =
attributes
|> Seq.tryFind (fun a -> a.IsCustomOperationAttribute)
|> Option.map (fun a -> a.CustomOperationName)
/// Represents the kind of member
type ApiDocMemberKind =
// In a module
| ValueOrFunction = 0
| TypeExtension = 1
| ActivePattern = 2
// In a class
| Constructor = 3
| InstanceMember = 4
| StaticMember = 5
// In a class, F# special members
| UnionCase = 100
| RecordField = 101
| StaticParameter = 102
type ApiDocMemberDetails =
| ApiDocMemberDetails of
usageHtml: ApiDocHtml *
paramTypes: (Choice<FSharpParameter, FSharpField> * string * ApiDocHtml) list *
returnType: (FSharpType * ApiDocHtml) option *
modifiers: string list *
typars: string list *
extendedType: (FSharpEntity * ApiDocHtml) option *
location: string option *
compiledName: string option
/// Represents an method, property, constructor, function or value, record field, union case or static parameter
/// integrated with its associated documentation. Includes extension members.
type ApiDocMember
(
displayName: string,
attributes: ApiDocAttribute list,
entityUrlBaseName: string,
kind,
cat,
catidx: int,
exclude: bool,
details: ApiDocMemberDetails,
comment: ApiDocComment,
symbol: FSharpSymbol,
warn
) =
let (ApiDocMemberDetails(usageHtml, paramTypes, returnType, modifiers, typars, extendedType, location, compiledName)) =
details
let m = defaultArg symbol.DeclarationLocation range0
// merge the parameter docs and parameter types
let parameters =
let paramTypes =
[ for (psym, _pnameText, _pty) in paramTypes ->
let pnm =
match psym with
| Choice1Of2 p -> p.Name
| Choice2Of2 f -> Some f.Name
(psym, pnm, _pnameText, _pty) ]
let tnames = Set.ofList [ for (_psym, pnm, _pnameText, _pty) in paramTypes -> pnm ]
let tdocs = Map.ofList [ for pnm, doc in comment.Parameters -> Some pnm, doc ]
if warn then
for (pn, _pdoc) in comment.Parameters do
if not (tnames.Contains(Some pn)) then
printfn
"%s(%d,%d): warning: extraneous docs for unknown parameter '%s'"
m.FileName
m.StartLine
m.StartColumn
pn
for (_psym, pnm, _pn, _pty) in paramTypes do
match pnm with
| None ->
printfn "%s(%d,%d): warning: a parameter was missing a name" m.FileName m.StartLine m.StartColumn
| Some nm ->
if not (tdocs.ContainsKey pnm) then
printfn
"%s(%d,%d): warning: missing docs for parameter '%s'"
m.FileName
m.StartLine
m.StartColumn
nm
[ for (psym, pnm, pn, pty) in paramTypes ->
{| ParameterSymbol = psym
ParameterNameText = pn
ParameterType = pty
ParameterDocs = tdocs.TryFind pnm |} ]
do
let knownExampleIds = comment.Examples |> List.choose (fun x -> x.Id) |> List.countBy id
for (id, count) in knownExampleIds do
if count > 1 then
if warn then
printfn "%s(%d,%d): warning: duplicate id for example '%s'" m.FileName m.StartLine m.StartColumn id
else
printfn "%s(%d,%d): error: duplicate id for example '%s'" m.FileName m.StartLine m.StartColumn id
for (id, _count) in knownExampleIds do
if id.StartsWith("example-", StringComparison.Ordinal) then
let potentialInteger = id.["example-".Length ..]
match System.Int32.TryParse potentialInteger with
| true, id ->
if warn then
printfn
"%s(%d,%d): warning: automatic identifer generated for example '%d'. Consider adding an explicit example id attribute."
m.FileName
m.StartLine
m.StartColumn
id
else
printfn
"%s(%d,%d): error: automatic identifer generated for example '%d'. Consider adding an explicit example id attribute."
m.FileName
m.StartLine
m.StartColumn
id
| _ -> ()
/// The member's modifiers
member x.Modifiers: string list = modifiers
/// The member's type arguments
member x.TypeArguments: string list = typars
/// The usage section in a typical tooltip
member x.UsageHtml: ApiDocHtml = usageHtml
/// The return section in a typical tooltip
member x.ReturnInfo =
{| ReturnDocs = comment.Returns
ReturnType = returnType |}
// /// The full signature section in a typical tooltip
// member x.SignatureTooltip : ApiDocHtml = signatureTooltip
/// The member's parameters and associated documentation
member x.Parameters = parameters
/// The URL of the member's source location, if any
member x.SourceLocation: string option = location
/// The type extended by an extension member, if any
member x.ExtendedType: (FSharpEntity * ApiDocHtml) option = extendedType
/// The members details
member x.Details = details
/// The member's compiled name, if any
member x.CompiledName: string option = compiledName
/// Formats type arguments
member x.FormatTypeArguments =
// We suppress the display of ill-formatted type parameters for places
// where these have not been explicitly declared. This could likely be done
// in a better way
let res = String.concat ", " x.TypeArguments
if x.TypeArguments.IsEmpty || res.Contains("?") then
None
else
Some res
/// Formats modifiers
member x.FormatModifiers = String.concat " " x.Modifiers
/// Formats the compiled name
member x.FormatCompiledName = defaultArg x.CompiledName ""
/// Name of the member
member x.Name = displayName
/// The URL base name of the best link documentation for the item (without the http://site.io/reference)
member x.UrlBaseName = entityUrlBaseName
/// The URL of the best link documentation for the item relative to "reference" directory (without the http://site.io/reference)
static member GetUrl(entityUrlBaseName, displayName, root, collectionName, qualify, extension) =
sprintf
"%sreference/%s%s%s#%s"
root
(if qualify then collectionName + "/" else "")
entityUrlBaseName
extension
displayName
/// The URL of the best link documentation for the item relative to "reference" directory (without the http://site.io/reference)
member x.Url(root, collectionName, qualify, extension) =
ApiDocMember.GetUrl(entityUrlBaseName, displayName, root, collectionName, qualify, extension)
/// The declared attributes of the member
member x.Attributes = attributes
/// The category
member x.Category: string = cat
/// The category index
member x.CategoryIndex: int = catidx
/// The exclude flag
member x.Exclude: bool = exclude
/// The kind of the member
member x.Kind: ApiDocMemberKind = kind
/// The attached comment
member x.Comment: ApiDocComment = comment
/// The symbol this member is related to
member x.Symbol: FSharpSymbol = symbol
/// Gets a value indicating whether this member is obsolete
member x.IsObsolete = x.Attributes |> List.exists (fun a -> a.IsObsoleteAttribute)
/// Returns the obsolete message, when this member is obsolete. When its not or no message was specified, an empty string is returned
member x.ObsoleteMessage = ApiDocAttribute.TryGetObsoleteMessage(x.Attributes)
member x.IsRequireQualifiedAccessAttribute =
x.Attributes |> List.exists (fun a -> a.IsRequireQualifiedAccessAttribute)
/// Returns the custom operation name, when this attribute is the CustomOperationAttribute.
member x.CustomOperationName = ApiDocAttribute.TryGetCustomOperationName(x.Attributes)
/// Represents a type definition integrated with its associated documentation
type ApiDocEntity
(
tdef,
name,
cat: string,
catidx: int,
exclude: bool,
urlBaseName,
comment,
assembly: AssemblyName,
attributes,
cases,
fields,
statParams,
ctors,
inst,
stat,
allInterfaces,
baseType,
abbreviatedType,
delegateSignature,
symbol: FSharpEntity,
nested,
vals,
exts,
pats,
rqa,
location: string option,
substitutions: Substitutions
) =
/// Indicates if the entity is a type definition
member x.IsTypeDefinition: bool = tdef
/// The name of the entity
member x.Name: string = name
/// The category of the type
member x.Category = cat
/// The category index of the type
member x.CategoryIndex = catidx
/// The exclude flag
member x.Exclude = exclude
/// The URL of the member's source location, if any
member x.SourceLocation: string option = location
/// The URL base name of the primary documentation for the entity (without the http://site.io/reference)
member x.UrlBaseName: string = urlBaseName
/// Compute the URL of the best link for the entity relative to "reference" directory (without the http://site.io/reference)
static member GetUrl(urlBaseName, root, collectionName, qualify, extension) =
sprintf "%sreference/%s%s%s" root (if qualify then collectionName + "/" else "") urlBaseName extension
/// The URL of the best link for the entity relative to "reference" directory (without the http://site.io/reference)
member x.Url(root, collectionName, qualify, extension) =
ApiDocEntity.GetUrl(urlBaseName, root, collectionName, qualify, extension)
/// The name of the file generated for this entity
member x.OutputFile(collectionName, qualify, extension) =
sprintf "reference/%s%s%s" (if qualify then collectionName + "/" else "") urlBaseName extension
/// The attached comment
member x.Comment: ApiDocComment = comment
/// The name of the type's assembly
member x.Assembly = assembly
/// The declared attributes of the type
member x.Attributes: ApiDocAttribute list = attributes
/// The cases of a union type
member x.UnionCases: ApiDocMember list = cases
/// The fields of a record type
member x.RecordFields: ApiDocMember list = fields
/// Static parameters
member x.StaticParameters: ApiDocMember list = statParams
/// All members of the type
member x.AllMembers: ApiDocMember list =
List.concat [ ctors; inst; stat; cases; fields; statParams; vals; exts; pats ]
/// All interfaces of the type, formatted
member x.AllInterfaces: (FSharpType * ApiDocHtml) list = allInterfaces
/// The base type of the type, formatted
member x.BaseType: (FSharpType * ApiDocHtml) option = baseType
/// If this is a type abbreviation, then the abbreviated type
member x.AbbreviatedType: (FSharpType * ApiDocHtml) option = abbreviatedType
/// If this is a delegate, then e formatted signature
member x.DelegateSignature: (FSharpDelegateSignature * ApiDocHtml) option = delegateSignature
/// The constuctorsof the type
member x.Constructors: ApiDocMember list = ctors
/// The instance members of the type
member x.InstanceMembers: ApiDocMember list = inst
/// The static members of the type
member x.StaticMembers: ApiDocMember list = stat
/// Gets a value indicating whether this member is obsolete
member x.IsObsolete = x.Attributes |> List.exists (fun a -> a.IsObsoleteAttribute)
/// Returns the obsolete message, when this member is obsolete. When its not or no message was specified, an empty string is returned
member x.ObsoleteMessage = ApiDocAttribute.TryGetObsoleteMessage(x.Attributes)
/// The F# compiler symbol for the type definition
member x.Symbol = symbol
/// Does the module have the RequiresQualifiedAccess attribute
member x.RequiresQualifiedAccess: bool = rqa
/// All nested modules and types
member x.NestedEntities: ApiDocEntity list = nested |> List.filter (fun e -> not e.Exclude)
/// Values and functions of the module
member x.ValuesAndFuncs: ApiDocMember list = vals
/// Type extensions of the module
member x.TypeExtensions: ApiDocMember list = exts
/// Active patterns of the module
member x.ActivePatterns: ApiDocMember list = pats
/// The substitution parameters active for generating thist content
member x.Substitutions = substitutions
/// Represents a namespace integrated with its associated documentation
type ApiDocNamespace(name: string, modifiers, substitutions: Substitutions, nsdocs: ApiDocComment option) =
let urlBaseName = name.Replace(".", "-").ToLower()
/// The name of the namespace
member x.Name: string = name
/// The hash label for the URL with the overall namespaces file
member x.UrlHash = urlBaseName
/// The base name for the generated file
member x.UrlBaseName = urlBaseName
/// The URL of the best link documentation for the item (without the http://site.io/reference)
member x.Url(root, collectionName, qualify, extension) =
sprintf "%sreference/%s%s%s" root (if qualify then collectionName + "/" else "") urlBaseName extension
/// The name of the file generated for this entity
member x.OutputFile(collectionName, qualify, extension) =
sprintf "reference/%s%s%s" (if qualify then collectionName + "/" else "") urlBaseName extension
/// All modules in the namespace
member x.Entities: ApiDocEntity list = modifiers
/// The summary text for the namespace
member x.NamespaceDocs = nsdocs
/// The substitution substitutions active for generating thist content
member x.Substitutions = substitutions
/// Represents a group of assemblies integrated with its associated documentation
type ApiDocCollection(name: string, asms: AssemblyName list, nss: ApiDocNamespace list) =
/// Name of the collection
member x.CollectionName = name
/// All assemblies in the collection
member x.Assemblies = asms
/// All namespaces in the collection
member x.Namespaces = nss
/// High-level information about a module definition
type ApiDocEntityInfo
(entity: ApiDocEntity, collection: ApiDocCollection, ns: ApiDocNamespace, parent: ApiDocEntity option) =
/// The actual entity
member x.Entity = entity
/// The collection of assemblies the entity belongs to
member x.Collection = collection
/// The namespace the entity belongs to
member x.Namespace = ns
/// The parent module, if any.
member x.ParentModule = parent
[<AutoOpen>]
module internal CrossReferences =
let getXmlDocSigForType (typ: FSharpEntity) =
if not (String.IsNullOrWhiteSpace typ.XmlDocSig) then
typ.XmlDocSig
else
try
defaultArg (Option.map (sprintf "T:%s") typ.TryFullName) ""
with _ ->
""
let getMemberXmlDocsSigPrefix (memb: FSharpMemberOrFunctionOrValue) =
if memb.IsEvent then "E"
elif memb.IsProperty then "P"
else "M"
let getXmlDocSigForMember (memb: FSharpMemberOrFunctionOrValue) =
if not (String.IsNullOrWhiteSpace memb.XmlDocSig) then
memb.XmlDocSig
else
let memberName =
try
let name = memb.CompiledName.Replace(".ctor", "#ctor")
let typeGenericParameters =
match memb.DeclaringEntity with
| None -> Seq.empty
| Some declaringEntity ->
declaringEntity.GenericParameters
|> Seq.mapi (fun num par -> par.Name, sprintf "`%d" num)
let methodGenericParameters =
memb.GenericParameters |> Seq.mapi (fun num par -> par.Name, sprintf "``%d" num)
let typeArgsMap =
Seq.append methodGenericParameters typeGenericParameters
|> Seq.groupBy fst
|> Seq.map (fun (_name, grp) -> grp |> Seq.head)
|> dict
let typeArgs =
if memb.GenericParameters.Count > 0 then
sprintf "``%d" memb.GenericParameters.Count
else
""
let paramList =
if
memb.CurriedParameterGroups.Count > 0
&& memb.CurriedParameterGroups.[0].Count > 0
then
let head = memb.CurriedParameterGroups.[0]
let paramTypeList =
head
|> Seq.map (fun param ->
if param.Type.IsGenericParameter then
typeArgsMap.[param.Type.GenericParameter.Name]
else
param.Type.TypeDefinition.FullName)
"(" + System.String.Join(", ", paramTypeList) + ")"
else
""
sprintf "%s%s%s" name typeArgs paramList
with exn ->
printfn "Error while building fsdocs-member-name for %s because: %s" memb.FullName exn.Message
Log.verbf "Full Exception details of previous message: %O" exn
memb.CompiledName
match
memb.DeclaringEntity
|> Option.bind (fun declaringEntity -> declaringEntity.TryFullName)
with
| None -> ""
| Some fullName -> sprintf "%s:%s.%s" (getMemberXmlDocsSigPrefix memb) fullName memberName
type internal CrefReference =
{ IsInternal: bool
ReferenceLink: string
NiceName: string }
type internal CrossReferenceResolver(root, collectionName, qualify, extensions) =
let toReplace =
([ ("Microsoft.", ""); (".", "-"); ("`", "-"); ("<", "_"); (">", "_"); (" ", "_"); ("#", "_") ]
@ (Path.GetInvalidPathChars()
|> Seq.append (Path.GetInvalidFileNameChars())
|> Seq.map (fun inv -> (inv.ToString(), "_"))
|> Seq.toList))
|> Seq.distinctBy fst
|> Seq.toList
let usedNames = Dictionary<_, _>()
let registeredSymbolsToUrlBaseName = Dictionary<FSharpSymbol, string>()
let xmlDocNameToSymbol = Dictionary<string, FSharpSymbol>()
let niceNameEntityLookup = Dictionary<_, _>()
let extensions = extensions
let nameGen (name: string) =
let nice =
(toReplace
|> List.fold (fun (s: string) (inv, repl) -> s.Replace(inv, repl)) name)
.ToLower()
let found =
seq {
yield nice
for i in Seq.initInfinite id do
yield sprintf "%s-%d" nice i
}
|> Seq.find (usedNames.ContainsKey >> not)
usedNames.Add(found, true)
found
let registerMember (memb: FSharpMemberOrFunctionOrValue) =
let xmlsig = getXmlDocSigForMember memb
if (not (System.String.IsNullOrEmpty xmlsig)) then
assert
(xmlsig.StartsWith("M:", StringComparison.Ordinal)
|| xmlsig.StartsWith("P:", StringComparison.Ordinal)
|| xmlsig.StartsWith("F:", StringComparison.Ordinal)
|| xmlsig.StartsWith("E:", StringComparison.Ordinal))
xmlDocNameToSymbol.[xmlsig] <- memb
let rec registerEntity (entity: FSharpEntity) =
let newName = nameGen (sprintf "%s.%s" entity.AccessPath entity.CompiledName)
registeredSymbolsToUrlBaseName.[entity] <- newName
let xmlsig = getXmlDocSigForType entity
if (not (System.String.IsNullOrEmpty xmlsig)) then
assert (xmlsig.StartsWith("T:", StringComparison.Ordinal))
xmlDocNameToSymbol.[xmlsig] <- entity
if (not (niceNameEntityLookup.ContainsKey(entity.LogicalName))) then
niceNameEntityLookup.[entity.LogicalName] <- System.Collections.Generic.List<_>()
niceNameEntityLookup.[entity.LogicalName].Add(entity)
for nested in entity.NestedEntities do
registerEntity nested
for memb in entity.TryGetMembersFunctionsAndValues() do
registerMember memb
let getUrlBaseNameForRegisteredEntity (entity: FSharpEntity) =
match registeredSymbolsToUrlBaseName.TryGetValue(entity) with
| true, v -> v
| _ ->
failwithf "The entity %s was not registered before!" (sprintf "%s.%s" entity.AccessPath entity.CompiledName)
let removeParen (memberName: string) =
let firstParen = memberName.IndexOf('(')
if firstParen > 0 then
memberName.Substring(0, firstParen)
else
memberName
let tryGetTypeFromMemberName (memberName: string) =
let sub = removeParen memberName
let lastPeriod = sub.LastIndexOf(".")
if lastPeriod > 0 then
Some(memberName.Substring(0, lastPeriod))
else
None
let tryGetShortMemberNameFromMemberName (memberName: string) =
let sub = removeParen memberName
let lastPeriod = sub.LastIndexOf(".")
if lastPeriod > 0 then
Some(memberName.Substring(lastPeriod + 1))
else
None
let getMemberName keepParts hasModuleSuffix (memberNameNoParen: string) =
let splits = memberNameNoParen.Split('.') |> Array.toList
let noNamespaceParts =
if splits.Length > keepParts then
splits.[splits.Length - keepParts ..]
else
splits
let noNamespaceParts =
if hasModuleSuffix then
match noNamespaceParts with
| h :: t when h.EndsWith("Module", StringComparison.Ordinal) -> h.[0 .. h.Length - 7] :: t
| s -> s
else
noNamespaceParts
let res = String.concat "." noNamespaceParts
let noGenerics =
match res.Split([| '`' |], StringSplitOptions.RemoveEmptyEntries) with
| [||] -> ""
| [| s |] -> s
| arr -> String.Join("`", arr.[0 .. arr.Length - 2])
noGenerics
let externalDocsLink isMember simple (typeName: string) (fullName: string) =
if
fullName.StartsWith("FSharp.", StringComparison.Ordinal)
|| fullName.StartsWith("Microsoft.FSharp.", StringComparison.Ordinal)
then
let noParen = removeParen typeName
let docs =
noParen
.Replace("Microsoft.FSharp.", "FSharp.")
.Replace("``", "-")
.Replace("`", "-")
.Replace(".", "-")
.ToLower()
let link = sprintf "https://fsharp.github.io/fsharp-core-docs/reference/%s" docs
let link =
if isMember then
link + "#" + (getMemberName 1 false fullName)
else
link
let niceName =
match simple with
| "FSharpAsync" -> "Async"
| "FSharpAsyncBuilder" -> "AsyncBuilder"
| "FSharpEvent" -> "Event"
| "FSharpDelegateEvent" -> "DelegateEvent"
| "FSharpAsyncReplyChannel" -> "AsyncReplyChannel"
| "FSharpMailboxProcessor" -> "MailboxProcessor"
| "FSharpMap" -> "Map"
| "FSharpChoice" -> "Choice"
| "FSharpRef" -> "ref"
| "FSharpList" -> "list"
| "FSharpOption" -> "option"
| "FSharpValueOption" -> "voption"
| "FSharpHandler" -> "Handler"
| "FSharpVar" -> "Var"
| "FSharpExpr" -> "Expr"
| "FSharpSet" -> "Set"
| "StringModule" -> "String"
| "OptionModule" -> "Option"
| "SeqModule" -> "Seq"
| "ArrayModule" -> "Array"
| "ListModule" -> "List"
| _ -> simple
{ IsInternal = false
ReferenceLink = link
NiceName = niceName }
else
let noParen = removeParen fullName
let docs = noParen.Replace("``", "").Replace("`", "-").ToLower()
let link = sprintf "https://learn.microsoft.com/dotnet/api/%s" docs
{ IsInternal = false
ReferenceLink = link
NiceName = simple }
let internalCrossReference urlBaseName =
ApiDocEntity.GetUrl(urlBaseName, root, collectionName, qualify, extensions.InUrl)
let internalCrossReferenceForMember entityUrlBaseName (memb: FSharpMemberOrFunctionOrValue) =
ApiDocMember.GetUrl(entityUrlBaseName, memb.DisplayName, root, collectionName, qualify, extensions.InUrl)
let tryResolveCrossReferenceForEntity (entity: FSharpEntity) =
match registeredSymbolsToUrlBaseName.TryGetValue(entity) with
| true, _v ->
let urlBaseName = getUrlBaseNameForRegisteredEntity entity
Some
{ IsInternal = true
ReferenceLink = internalCrossReference urlBaseName
NiceName = entity.LogicalName }
| _ ->
match entity.TryFullName with
| None -> None
| Some nm -> Some(externalDocsLink false entity.DisplayName nm nm)
let resolveCrossReferenceForTypeByXmlSig (typeXmlSig: string) =
assert (typeXmlSig.StartsWith("T:", StringComparison.Ordinal))
match xmlDocNameToSymbol.TryGetValue(typeXmlSig) with
| true, (:? FSharpEntity as entity) ->
let urlBaseName = getUrlBaseNameForRegisteredEntity entity
{ IsInternal = true
ReferenceLink = internalCrossReference urlBaseName
NiceName = entity.DisplayName }
| _ ->
let typeName = typeXmlSig.Substring(2)