forked from dotnet/fsharp
/
il.fs
4375 lines (3463 loc) · 161 KB
/
il.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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
module FSharp.Compiler.AbstractIL.IL
#nowarn "49"
#nowarn "343" // The type 'ILAssemblyRef' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'.
#nowarn "346" // The struct, record or union type 'IlxExtensionType' has an explicit implementation of 'Object.Equals'. ...
open System
open System.Diagnostics
open System.IO
open System.Collections
open System.Collections.Generic
open System.Collections.Concurrent
open System.Collections.ObjectModel
open System.Reflection
open System.Text
open System.Threading
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AbstractIL.Internal
open FSharp.Compiler.AbstractIL.Internal.Library
open Internal.Utilities
let logging = false
let _ = if logging then dprintn "* warning: Il.logging is on"
let int_order = LanguagePrimitives.FastGenericComparer<int>
let notlazy v = Lazy<_>.CreateFromValue v
/// A little ugly, but the idea is that if a data structure does not
/// contain lazy values then we don't add laziness. So if the thing to map
/// is already evaluated then immediately apply the function.
let lazyMap f (x: Lazy<_>) =
if x.IsValueCreated then notlazy (f (x.Force())) else lazy (f (x.Force()))
[<RequireQualifiedAccess>]
type PrimaryAssembly =
| Mscorlib
| System_Runtime
| NetStandard
member this.Name =
match this with
| Mscorlib -> "mscorlib"
| System_Runtime -> "System.Runtime"
| NetStandard -> "netstandard"
// --------------------------------------------------------------------
// Utilities: type names
// --------------------------------------------------------------------
let splitNameAt (nm: string) idx =
if idx < 0 then failwith "splitNameAt: idx < 0"
let last = nm.Length - 1
if idx > last then failwith "splitNameAt: idx > last"
(nm.Substring (0, idx)),
(if idx < last then nm.Substring (idx+1, last - idx) else "")
let rec splitNamespaceAux (nm: string) =
match nm.IndexOf '.' with
| -1 -> [nm]
| idx ->
let s1, s2 = splitNameAt nm idx
s1 :: splitNamespaceAux s2
/// Global State. All namespace splits ever seen
// ++GLOBAL MUTABLE STATE (concurrency-safe)
let memoizeNamespaceTable = new ConcurrentDictionary<string, string list>()
// ++GLOBAL MUTABLE STATE (concurrency-safe)
let memoizeNamespaceRightTable = new ConcurrentDictionary<string, string option * string>()
let splitNamespace nm =
memoizeNamespaceTable.GetOrAdd (nm, splitNamespaceAux)
let splitNamespaceMemoized nm = splitNamespace nm
// ++GLOBAL MUTABLE STATE (concurrency-safe)
let memoizeNamespaceArrayTable =
Concurrent.ConcurrentDictionary<string, string[]>()
let splitNamespaceToArray nm =
memoizeNamespaceArrayTable.GetOrAdd (nm, fun nm ->
let x = Array.ofList (splitNamespace nm)
x)
let splitILTypeName (nm: string) =
match nm.LastIndexOf '.' with
| -1 -> [], nm
| idx ->
let s1, s2 = splitNameAt nm idx
splitNamespace s1, s2
let emptyStringArray = ([| |] : string[])
// Duplicate of comment in import.fs:
// The type names that flow to the point include the "mangled" type names used for static parameters for provided types.
// For example,
// Foo.Bar,"1.0"
// This is because the ImportSystemType code goes via Abstract IL type references. Ultimately this probably isn't
// the best way to do things.
let splitILTypeNameWithPossibleStaticArguments (nm: string) =
let nm, suffix =
match nm.IndexOf ',' with
| -1 -> nm, None
| idx -> let s1, s2 = splitNameAt nm idx in s1, Some s2
let nsp, nm =
match nm.LastIndexOf '.' with
| -1 -> emptyStringArray, nm
| idx ->
let s1, s2 = splitNameAt nm idx
splitNamespaceToArray s1, s2
nsp, (match suffix with None -> nm | Some s -> nm + "," + s)
(*
splitILTypeNameWithPossibleStaticArguments "Foo" = ([| |], "Foo")
splitILTypeNameWithPossibleStaticArguments "Foo.Bar" = ([| "Foo" |], "Bar")
splitILTypeNameWithPossibleStaticArguments "Foo.Bar,3" = ([| "Foo" |], "Bar, 3")
splitILTypeNameWithPossibleStaticArguments "Foo.Bar," = ([| "Foo" |], "Bar,")
splitILTypeNameWithPossibleStaticArguments "Foo.Bar,\"1.0\"" = ([| "Foo" |], "Bar,\"1.0\"")
splitILTypeNameWithPossibleStaticArguments "Foo.Bar.Bar,\"1.0\"" = ([| "Foo"; "Bar" |], "Bar,\"1.0\"")
*)
let unsplitTypeName (ns, n) =
match ns with
| [] -> String.concat "." ns + "." + n
| _ -> n
let splitTypeNameRightAux (nm: string) =
let idx = nm.LastIndexOf '.'
if idx = -1 then None, nm else
let s1, s2 = splitNameAt nm idx
Some s1, s2
let splitTypeNameRight nm =
memoizeNamespaceRightTable.GetOrAdd (nm, splitTypeNameRightAux)
// --------------------------------------------------------------------
// Ordered lists with a lookup table
// --------------------------------------------------------------------
/// This is used to store event, property and field maps.
type LazyOrderedMultiMap<'Key, 'Data when 'Key : equality>(keyf : 'Data -> 'Key, lazyItems : Lazy<'Data list>) =
let quickMap =
lazyItems |> lazyMap (fun entries ->
let t = new Dictionary<_, _>(entries.Length, HashIdentity.Structural)
do entries |> List.iter (fun y ->
let key = keyf y
let v =
match t.TryGetValue key with
| true, v -> v
| _ -> []
t.[key] <- y :: v)
t)
member self.Entries() = lazyItems.Force()
member self.Add y = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (fun x -> y :: x))
member self.Filter f = new LazyOrderedMultiMap<'Key, 'Data>(keyf, lazyItems |> lazyMap (List.filter f))
member self.Item
with get x =
match quickMap.Force().TryGetValue x with
| true, v -> v
| _ -> []
//---------------------------------------------------------------------
// SHA1 hash-signing algorithm. Used to get the public key token from
// the public key.
//---------------------------------------------------------------------
let b0 n = (n &&& 0xFF)
let b1 n = ((n >>> 8) &&& 0xFF)
let b2 n = ((n >>> 16) &&& 0xFF)
let b3 n = ((n >>> 24) &&& 0xFF)
module SHA1 =
let inline (>>>&) (x: int) (y: int) = int32 (uint32 x >>> y)
let f(t, b, c, d) =
if t < 20 then (b &&& c) ||| ((~~~b) &&& d)
elif t < 40 then b ^^^ c ^^^ d
elif t < 60 then (b &&& c) ||| (b &&& d) ||| (c &&& d)
else b ^^^ c ^^^ d
let [<Literal>] k0to19 = 0x5A827999
let [<Literal>] k20to39 = 0x6ED9EBA1
let [<Literal>] k40to59 = 0x8F1BBCDC
let [<Literal>] k60to79 = 0xCA62C1D6
let k t =
if t < 20 then k0to19
elif t < 40 then k20to39
elif t < 60 then k40to59
else k60to79
type SHAStream =
{ stream: byte[]
mutable pos: int
mutable eof: bool }
let rotLeft32 x n = (x <<< n) ||| (x >>>& (32-n))
// padding and length (in bits!) recorded at end
let shaAfterEof sha =
let n = sha.pos
let len = sha.stream.Length
if n = len then 0x80
else
let padded_len = (((len + 9 + 63) / 64) * 64) - 8
if n < padded_len - 8 then 0x0
elif (n &&& 63) = 56 then int32 ((int64 len * int64 8) >>> 56) &&& 0xff
elif (n &&& 63) = 57 then int32 ((int64 len * int64 8) >>> 48) &&& 0xff
elif (n &&& 63) = 58 then int32 ((int64 len * int64 8) >>> 40) &&& 0xff
elif (n &&& 63) = 59 then int32 ((int64 len * int64 8) >>> 32) &&& 0xff
elif (n &&& 63) = 60 then int32 ((int64 len * int64 8) >>> 24) &&& 0xff
elif (n &&& 63) = 61 then int32 ((int64 len * int64 8) >>> 16) &&& 0xff
elif (n &&& 63) = 62 then int32 ((int64 len * int64 8) >>> 8) &&& 0xff
elif (n &&& 63) = 63 then (sha.eof <- true; int32 (int64 len * int64 8) &&& 0xff)
else 0x0
let shaRead8 sha =
let s = sha.stream
let b = if sha.pos >= s.Length then shaAfterEof sha else int32 s.[sha.pos]
sha.pos <- sha.pos + 1
b
let shaRead32 sha =
let b0 = shaRead8 sha
let b1 = shaRead8 sha
let b2 = shaRead8 sha
let b3 = shaRead8 sha
let res = (b0 <<< 24) ||| (b1 <<< 16) ||| (b2 <<< 8) ||| b3
res
let sha1Hash sha =
let mutable h0 = 0x67452301
let mutable h1 = 0xEFCDAB89
let mutable h2 = 0x98BADCFE
let mutable h3 = 0x10325476
let mutable h4 = 0xC3D2E1F0
let mutable a = 0
let mutable b = 0
let mutable c = 0
let mutable d = 0
let mutable e = 0
let w = Array.create 80 0x00
while (not sha.eof) do
for i = 0 to 15 do
w.[i] <- shaRead32 sha
for t = 16 to 79 do
w.[t] <- rotLeft32 (w.[t-3] ^^^ w.[t-8] ^^^ w.[t-14] ^^^ w.[t-16]) 1
a <- h0
b <- h1
c <- h2
d <- h3
e <- h4
for t = 0 to 79 do
let temp = (rotLeft32 a 5) + f (t, b, c, d) + e + w.[t] + k t
e <- d
d <- c
c <- rotLeft32 b 30
b <- a
a <- temp
h0 <- h0 + a
h1 <- h1 + b
h2 <- h2 + c
h3 <- h3 + d
h4 <- h4 + e
h0, h1, h2, h3, h4
let sha1HashBytes s =
let (_h0, _h1, _h2, h3, h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4
Array.map byte [| b0 h4; b1 h4; b2 h4; b3 h4; b0 h3; b1 h3; b2 h3; b3 h3; |]
let sha1HashInt64 s =
let (_h0,_h1,_h2,h3,h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4
(int64 h3 <<< 32) ||| int64 h4
let sha1HashBytes s = SHA1.sha1HashBytes s
let sha1HashInt64 s = SHA1.sha1HashInt64 s
// --------------------------------------------------------------------
//
// --------------------------------------------------------------------
[<Struct>]
type ILVersionInfo =
val Major: uint16
val Minor: uint16
val Build: uint16
val Revision: uint16
new (major, minor, build, revision) =
{ Major = major; Minor = minor; Build = build; Revision = revision }
/// For debugging
override x.ToString() = sprintf "ILVersionInfo: %u %u %u %u" (x.Major) (x.Minor) (x.Build) (x.Revision)
type Locale = string
[<StructuralEquality; StructuralComparison>]
type PublicKey =
| PublicKey of byte[]
| PublicKeyToken of byte[]
member x.IsKey=match x with PublicKey _ -> true | _ -> false
member x.IsKeyToken=match x with PublicKeyToken _ -> true | _ -> false
member x.Key=match x with PublicKey b -> b | _ -> invalidOp "not a key"
member x.KeyToken=match x with PublicKeyToken b -> b | _ -> invalidOp"not a key token"
member x.ToToken() =
match x with
| PublicKey bytes -> SHA1.sha1HashBytes bytes
| PublicKeyToken token -> token
static member KeyAsToken key = PublicKeyToken (PublicKey(key).ToToken())
[<StructuralEquality; StructuralComparison>]
type AssemblyRefData =
{ assemRefName: string
assemRefHash: byte[] option
assemRefPublicKeyInfo: PublicKey option
assemRefRetargetable: bool
assemRefVersion: ILVersionInfo option
assemRefLocale: Locale option }
/// Global state: table of all assembly references keyed by AssemblyRefData.
let AssemblyRefUniqueStampGenerator = new UniqueStampGenerator<AssemblyRefData>()
let isMscorlib data =
data.assemRefName = "mscorlib"
[<Sealed>]
type ILAssemblyRef(data) =
let pkToken key =
match key with
| Some (PublicKey bytes) -> Some (PublicKey (SHA1.sha1HashBytes bytes))
| Some (PublicKeyToken token) -> Some (PublicKey (token))
| None -> None
let uniqueStamp =
AssemblyRefUniqueStampGenerator.Encode { data with assemRefPublicKeyInfo = pkToken (data.assemRefPublicKeyInfo) }
let uniqueIgnoringVersionStamp =
AssemblyRefUniqueStampGenerator.Encode { data with assemRefVersion = None; assemRefPublicKeyInfo = pkToken (data.assemRefPublicKeyInfo) }
member x.Name=data.assemRefName
member x.Hash=data.assemRefHash
member x.PublicKey=data.assemRefPublicKeyInfo
member x.Retargetable=data.assemRefRetargetable
member x.Version=data.assemRefVersion
member x.Locale=data.assemRefLocale
member x.UniqueStamp=uniqueStamp
member x.UniqueIgnoringVersionStamp=uniqueIgnoringVersionStamp
member x.EqualsIgnoringVersion (aref: ILAssemblyRef) =
aref.UniqueIgnoringVersionStamp = uniqueIgnoringVersionStamp
override x.GetHashCode() = uniqueStamp
override x.Equals yobj = ((yobj :?> ILAssemblyRef).UniqueStamp = uniqueStamp)
interface IComparable with
override x.CompareTo yobj = compare (yobj :?> ILAssemblyRef).UniqueStamp uniqueStamp
static member Create (name, hash, publicKey, retargetable, version, locale) =
ILAssemblyRef
{ assemRefName=name
assemRefHash=hash
assemRefPublicKeyInfo=publicKey
assemRefRetargetable=retargetable
assemRefVersion=version
assemRefLocale=locale }
static member FromAssemblyName (aname: AssemblyName) =
let locale = None
let publicKey =
match aname.GetPublicKey() with
| null | [| |] ->
match aname.GetPublicKeyToken() with
| null | [| |] -> None
| bytes -> Some (PublicKeyToken bytes)
| bytes ->
Some (PublicKey bytes)
let version =
match aname.Version with
| null -> None
| v -> Some (ILVersionInfo (uint16 v.Major, uint16 v.Minor, uint16 v.Build, uint16 v.Revision))
let retargetable = aname.Flags = AssemblyNameFlags.Retargetable
ILAssemblyRef.Create (aname.Name, None, publicKey, retargetable, version, locale)
member aref.QualifiedName =
let b = StringBuilder(100)
let add (s: string) = b.Append s |> ignore
let addC (s: char) = b.Append s |> ignore
add aref.Name
match aref.Version with
| None -> ()
| Some (version) ->
add ", Version="
add (string (int version.Major))
add "."
add (string (int version.Minor))
add "."
add (string (int version.Build))
add "."
add (string (int version.Revision))
add ", Culture="
match aref.Locale with
| None -> add "neutral"
| Some b -> add b
add ", PublicKeyToken="
match aref.PublicKey with
| None -> add "null"
| Some pki ->
let pkt = pki.ToToken()
let convDigit digit =
let digitc =
if digit < 10
then Convert.ToInt32 '0' + digit
else Convert.ToInt32 'a' + (digit - 10)
Convert.ToChar digitc
for i = 0 to pkt.Length-1 do
let v = pkt.[i]
addC (convDigit (int32 v / 16))
addC (convDigit (int32 v % 16))
// retargetable can be true only for system assemblies that definitely have Version
if aref.Retargetable then
add ", Retargetable=Yes"
b.ToString()
[<StructuralEquality; StructuralComparison>]
type ILModuleRef =
{ name: string
hasMetadata: bool
hash: byte[] option }
static member Create (name, hasMetadata, hash) =
{ name=name
hasMetadata= hasMetadata
hash=hash }
member x.Name=x.name
member x.HasMetadata=x.hasMetadata
member x.Hash=x.hash
[<StructuralEquality; StructuralComparison>]
[<RequireQualifiedAccess>]
type ILScopeRef =
| Local
| Module of ILModuleRef
| Assembly of ILAssemblyRef
| PrimaryAssembly
member x.IsLocalRef = match x with ILScopeRef.Local -> true | _ -> false
member x.QualifiedName =
match x with
| ILScopeRef.Local -> ""
| ILScopeRef.Module mref -> "module "+mref.Name
| ILScopeRef.Assembly aref -> aref.QualifiedName
| ILScopeRef.PrimaryAssembly -> ""
type ILArrayBound = int32 option
type ILArrayBounds = ILArrayBound * ILArrayBound
[<StructuralEquality; StructuralComparison>]
type ILArrayShape =
| ILArrayShape of ILArrayBounds list (* lobound/size pairs *)
member x.Rank = (let (ILArrayShape l) = x in l.Length)
static member SingleDimensional = ILArrayShapeStatics.SingleDimensional
static member FromRank n = if n = 1 then ILArrayShape.SingleDimensional else ILArrayShape (List.replicate n (Some 0, None))
and ILArrayShapeStatics() =
static let singleDimensional = ILArrayShape [(Some 0, None)]
static member SingleDimensional = singleDimensional
/// Calling conventions. These are used in method pointer types.
[<StructuralEquality; StructuralComparison; RequireQualifiedAccess>]
type ILArgConvention =
| Default
| CDecl
| StdCall
| ThisCall
| FastCall
| VarArg
[<StructuralEquality; StructuralComparison; RequireQualifiedAccess>]
type ILThisConvention =
| Instance
| InstanceExplicit
| Static
[<StructuralEquality; StructuralComparison>]
type ILCallingConv =
| Callconv of ILThisConvention * ILArgConvention
member x.ThisConv = let (Callconv (a, _b)) = x in a
member x.BasicConv = let (Callconv (_a, b)) = x in b
member x.IsInstance = match x.ThisConv with ILThisConvention.Instance -> true | _ -> false
member x.IsInstanceExplicit = match x.ThisConv with ILThisConvention.InstanceExplicit -> true | _ -> false
member x.IsStatic = match x.ThisConv with ILThisConvention.Static -> true | _ -> false
static member Instance = ILCallingConvStatics.Instance
static member Static = ILCallingConvStatics.Static
/// Static storage to amortize the allocation of <c>ILCallingConv.Instance</c> and <c>ILCallingConv.Static</c>.
and ILCallingConvStatics() =
static let instanceCallConv = Callconv (ILThisConvention.Instance, ILArgConvention.Default)
static let staticCallConv = Callconv (ILThisConvention.Static, ILArgConvention.Default)
static member Instance = instanceCallConv
static member Static = staticCallConv
type ILBoxity =
| AsObject
| AsValue
// IL type references have a pre-computed hash code to enable quick lookup tables during binary generation.
[<CustomEquality; CustomComparison; StructuredFormatDisplay("{DebugText}")>]
type ILTypeRef =
{ trefScope: ILScopeRef
trefEnclosing: string list
trefName: string
hashCode : int
mutable asBoxedType: ILType }
static member ComputeHash(scope, enclosing, name) =
hash scope * 17 ^^^ (hash enclosing * 101 <<< 1) ^^^ (hash name * 47 <<< 2)
static member Create (scope, enclosing, name) =
let hashCode = ILTypeRef.ComputeHash(scope, enclosing, name)
{ trefScope=scope
trefEnclosing=enclosing
trefName=name
hashCode=hashCode
asBoxedType = Unchecked.defaultof<_> }
member x.Scope = x.trefScope
member x.Enclosing = x.trefEnclosing
member x.Name = x.trefName
member x.ApproxId = x.hashCode
member x.AsBoxedType (tspec: ILTypeSpec) =
if isNil tspec.tspecInst then
let v = x.asBoxedType
match box v with
| null ->
let r = ILType.Boxed tspec
x.asBoxedType <- r
r
| _ -> v
else
ILType.Boxed tspec
override x.GetHashCode() = x.hashCode
override x.Equals yobj =
let y = (yobj :?> ILTypeRef)
(x.ApproxId = y.ApproxId) &&
(x.Scope = y.Scope) &&
(x.Name = y.Name) &&
(x.Enclosing = y.Enclosing)
member x.EqualsWithPrimaryScopeRef(primaryScopeRef:ILScopeRef, yobj:obj) =
let y = (yobj :?> ILTypeRef)
let isPrimary (v:ILTypeRef) =
match v.Scope with
| ILScopeRef.PrimaryAssembly -> true
| _ -> false
// Since we can remap the scope, we need to recompute hash ... this is not an expensive operation
let isPrimaryX = isPrimary x
let isPrimaryY = isPrimary y
let xApproxId = if isPrimaryX && not(isPrimaryY) then ILTypeRef.ComputeHash(primaryScopeRef, x.Enclosing, x.Name) else x.ApproxId
let yApproxId = if isPrimaryY && not(isPrimaryX) then ILTypeRef.ComputeHash(primaryScopeRef, y.Enclosing, y.Name) else y.ApproxId
let xScope = if isPrimaryX then primaryScopeRef else x.Scope
let yScope = if isPrimaryY then primaryScopeRef else y.Scope
(xApproxId = yApproxId) &&
(xScope = yScope) &&
(x.Name = y.Name) &&
(x.Enclosing = y.Enclosing)
interface IComparable with
override x.CompareTo yobj =
let y = (yobj :?> ILTypeRef)
let c = compare x.ApproxId y.ApproxId
if c <> 0 then c else
let c = compare x.Scope y.Scope
if c <> 0 then c else
let c = compare x.Name y.Name
if c <> 0 then c else
compare x.Enclosing y.Enclosing
member tref.FullName = String.concat "." (tref.Enclosing @ [tref.Name])
member tref.BasicQualifiedName =
(String.concat "+" (tref.Enclosing @ [ tref.Name ] )).Replace(",", @"\,")
member tref.AddQualifiedNameExtension basic =
let sco = tref.Scope.QualifiedName
if sco = "" then basic else String.concat ", " [basic;sco]
member tref.QualifiedName =
tref.AddQualifiedNameExtension tref.BasicQualifiedName
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
/// For debugging
override x.ToString() = x.FullName
and [<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
ILTypeSpec =
{ tspecTypeRef: ILTypeRef
/// The type instantiation if the type is generic.
tspecInst: ILGenericArgs }
member x.TypeRef=x.tspecTypeRef
member x.Scope=x.TypeRef.Scope
member x.Enclosing=x.TypeRef.Enclosing
member x.Name=x.TypeRef.Name
member x.GenericArgs=x.tspecInst
static member Create (typeRef, instantiation) = { tspecTypeRef =typeRef; tspecInst=instantiation }
member x.BasicQualifiedName =
let tc = x.TypeRef.BasicQualifiedName
if isNil x.GenericArgs then
tc
else
tc + "[" + String.concat "," (x.GenericArgs |> List.map (fun arg -> "[" + arg.QualifiedName + "]")) + "]"
member x.AddQualifiedNameExtension basic =
x.TypeRef.AddQualifiedNameExtension basic
member x.FullName=x.TypeRef.FullName
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
member x.EqualsWithPrimaryScopeRef(primaryScopeRef:ILScopeRef, yobj:obj) =
let y = (yobj :?> ILTypeSpec)
x.tspecTypeRef.EqualsWithPrimaryScopeRef(primaryScopeRef, y.TypeRef) && (x.GenericArgs = y.GenericArgs)
override x.ToString() = x.TypeRef.ToString() + if isNil x.GenericArgs then "" else "<...>"
and [<RequireQualifiedAccess; StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
ILType =
| Void
| Array of ILArrayShape * ILType
| Value of ILTypeSpec
| Boxed of ILTypeSpec
| Ptr of ILType
| Byref of ILType
| FunctionPointer of ILCallingSignature
| TypeVar of uint16
| Modified of bool * ILTypeRef * ILType
member x.BasicQualifiedName =
match x with
| ILType.TypeVar n -> "!" + string n
| ILType.Modified (_, _ty1, ty2) -> ty2.BasicQualifiedName
| ILType.Array (ILArrayShape s, ty) -> ty.BasicQualifiedName + "[" + String(',', s.Length-1) + "]"
| ILType.Value tr | ILType.Boxed tr -> tr.BasicQualifiedName
| ILType.Void -> "void"
| ILType.Ptr _ty -> failwith "unexpected pointer type"
| ILType.Byref _ty -> failwith "unexpected byref type"
| ILType.FunctionPointer _mref -> failwith "unexpected function pointer type"
member x.AddQualifiedNameExtension basic =
match x with
| ILType.TypeVar _n -> basic
| ILType.Modified (_, _ty1, ty2) -> ty2.AddQualifiedNameExtension basic
| ILType.Array (ILArrayShape(_s), ty) -> ty.AddQualifiedNameExtension basic
| ILType.Value tr | ILType.Boxed tr -> tr.AddQualifiedNameExtension basic
| ILType.Void -> failwith "void"
| ILType.Ptr _ty -> failwith "unexpected pointer type"
| ILType.Byref _ty -> failwith "unexpected byref type"
| ILType.FunctionPointer _mref -> failwith "unexpected function pointer type"
member x.QualifiedName =
x.AddQualifiedNameExtension(x.BasicQualifiedName)
member x.TypeSpec =
match x with
| ILType.Boxed tr | ILType.Value tr -> tr
| _ -> invalidOp "not a nominal type"
member x.Boxity =
match x with
| ILType.Boxed _ -> AsObject
| ILType.Value _ -> AsValue
| _ -> invalidOp "not a nominal type"
member x.TypeRef =
match x with
| ILType.Boxed tspec | ILType.Value tspec -> tspec.TypeRef
| _ -> invalidOp "not a nominal type"
member x.IsNominal =
match x with
| ILType.Boxed _ | ILType.Value _ -> true
| _ -> false
member x.GenericArgs =
match x with
| ILType.Boxed tspec | ILType.Value tspec -> tspec.GenericArgs
| _ -> []
member x.IsTyvar =
match x with
| ILType.TypeVar _ -> true | _ -> false
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = x.QualifiedName
and [<StructuralEquality; StructuralComparison>]
ILCallingSignature =
{ CallingConv: ILCallingConv
ArgTypes: ILTypes
ReturnType: ILType }
and ILGenericArgs = list<ILType>
and ILTypes = list<ILType>
let mkILCallSig (cc, args, ret) = { ArgTypes=args; CallingConv=cc; ReturnType=ret}
let mkILBoxedType (tspec: ILTypeSpec) = tspec.TypeRef.AsBoxedType tspec
[<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILMethodRef =
{ mrefParent: ILTypeRef
mrefCallconv: ILCallingConv
mrefGenericArity: int
mrefName: string
mrefArgs: ILTypes
mrefReturn: ILType }
member x.DeclaringTypeRef = x.mrefParent
member x.CallingConv = x.mrefCallconv
member x.Name = x.mrefName
member x.GenericArity = x.mrefGenericArity
member x.ArgCount = List.length x.mrefArgs
member x.ArgTypes = x.mrefArgs
member x.ReturnType = x.mrefReturn
member x.CallingSignature = mkILCallSig (x.CallingConv, x.ArgTypes, x.ReturnType)
static member Create (enclosingTypeRef, callingConv, name, genericArity, argTypes, returnType) =
{ mrefParent=enclosingTypeRef
mrefCallconv=callingConv
mrefName=name
mrefGenericArity=genericArity
mrefArgs=argTypes
mrefReturn=returnType }
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = x.DeclaringTypeRef.ToString() + "::" + x.Name + "(...)"
[<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILFieldRef =
{ DeclaringTypeRef: ILTypeRef
Name: string
Type: ILType }
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = x.DeclaringTypeRef.ToString() + "::" + x.Name
[<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILMethodSpec =
{ mspecMethodRef: ILMethodRef
mspecDeclaringType: ILType
mspecMethodInst: ILGenericArgs }
static member Create (a, b, c) = { mspecDeclaringType=a; mspecMethodRef=b; mspecMethodInst=c }
member x.MethodRef = x.mspecMethodRef
member x.DeclaringType=x.mspecDeclaringType
member x.GenericArgs=x.mspecMethodInst
member x.Name=x.MethodRef.Name
member x.CallingConv=x.MethodRef.CallingConv
member x.GenericArity = x.MethodRef.GenericArity
member x.FormalArgTypes = x.MethodRef.ArgTypes
member x.FormalReturnType = x.MethodRef.ReturnType
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = x.MethodRef.ToString() + "(...)"
[<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILFieldSpec =
{ FieldRef: ILFieldRef
DeclaringType: ILType }
member x.FormalType = x.FieldRef.Type
member x.Name = x.FieldRef.Name
member x.DeclaringTypeRef = x.FieldRef.DeclaringTypeRef
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = x.FieldRef.ToString()
// --------------------------------------------------------------------
// Debug info.
// --------------------------------------------------------------------
type ILGuid = byte[]
type ILPlatform =
| X86
| AMD64
| IA64
type ILSourceDocument =
{ sourceLanguage: ILGuid option
sourceVendor: ILGuid option
sourceDocType: ILGuid option
sourceFile: string }
static member Create (language, vendor, documentType, file) =
{ sourceLanguage=language
sourceVendor=vendor
sourceDocType=documentType
sourceFile=file }
member x.Language=x.sourceLanguage
member x.Vendor=x.sourceVendor
member x.DocumentType=x.sourceDocType
member x.File=x.sourceFile
[<StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILSourceMarker =
{ sourceDocument: ILSourceDocument
sourceLine: int
sourceColumn: int
sourceEndLine: int
sourceEndColumn: int }
static member Create (document, line, column, endLine, endColumn) =
{ sourceDocument=document
sourceLine=line
sourceColumn=column
sourceEndLine=endLine
sourceEndColumn=endColumn }
member x.Document=x.sourceDocument
member x.Line=x.sourceLine
member x.Column=x.sourceColumn
member x.EndLine=x.sourceEndLine
member x.EndColumn=x.sourceEndColumn
/// For debugging
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
member x.DebugText = x.ToString()
override x.ToString() = sprintf "(%d, %d)-(%d, %d)" x.Line x.Column x.EndLine x.EndColumn
type ILAttribElem =
| String of string option
| Bool of bool
| Char of char
| SByte of int8
| Int16 of int16
| Int32 of int32
| Int64 of int64
| Byte of uint8
| UInt16 of uint16
| UInt32 of uint32
| UInt64 of uint64
| Single of single
| Double of double
| Null
| Type of ILType option
| TypeRef of ILTypeRef option
| Array of ILType * ILAttribElem list
type ILAttributeNamedArg = (string * ILType * bool * ILAttribElem)
[<RequireQualifiedAccess; StructuralEquality; StructuralComparison; StructuredFormatDisplay("{DebugText}")>]
type ILAttribute =
| Encoded of method: ILMethodSpec * data: byte[] * elements: ILAttribElem list
| Decoded of method: ILMethodSpec * fixedArgs: ILAttribElem list * namedArgs: ILAttributeNamedArg list
member x.Method =
match x with
| Encoded (method, _, _)
| Decoded (method, _, _) -> method
member x.Elements =
match x with
| Encoded (_, _, elements) -> elements
| Decoded (_, fixedArgs, namedArgs) -> fixedArgs @ (namedArgs |> List.map (fun (_, _, _, e) -> e))
member x.WithMethod (method: ILMethodSpec) =