-
Notifications
You must be signed in to change notification settings - Fork 772
/
CompilerImports.fs
2635 lines (2159 loc) · 110 KB
/
CompilerImports.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.
/// Contains logic to coordinate assembly resolution and manage the TcImports table of referenced
/// assemblies.
module internal FSharp.Compiler.CompilerImports
open System
open System.Collections.Generic
open System.Collections.Immutable
open System.Diagnostics
open System.IO
open System.IO.Compression
open System.Reflection
open Internal.Utilities
open Internal.Utilities.Collections
open Internal.Utilities.FSharpEnvironment
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.CheckDeclarations
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.DependencyManager
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Import
open FSharp.Compiler.IO
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Xml
open FSharp.Compiler.TypedTreePickle
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.BuildGraph
#if !NO_TYPEPROVIDERS
open FSharp.Compiler.TypeProviders
open FSharp.Core.CompilerServices
#endif
let (++) x s = x @ [ s ]
//----------------------------------------------------------------------------
// Signature and optimization data blobs
//--------------------------------------------------------------------------
let IsSignatureDataResource (r: ILResource) =
r.Name.StartsWithOrdinal FSharpSignatureDataResourceName
|| r.Name.StartsWithOrdinal FSharpSignatureCompressedDataResourceName
|| r.Name.StartsWithOrdinal FSharpSignatureDataResourceName2
let IsOptimizationDataResource (r: ILResource) =
r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName
|| r.Name.StartsWithOrdinal FSharpOptimizationCompressedDataResourceName
|| r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName2
let decompressResource (r: ILResource) =
use raw = r.GetBytes().AsStream()
use decompressed = new MemoryStream()
use deflator = new DeflateStream(raw, CompressionMode.Decompress)
deflator.CopyTo decompressed
deflator.Close()
ByteStorage.FromByteArray(decompressed.ToArray()).GetByteMemory()
let GetResourceNameAndSignatureDataFunc (r: ILResource) =
let resourceType, ccuName =
if r.Name.StartsWithOrdinal FSharpSignatureDataResourceName then
FSharpSignatureDataResourceName, String.dropPrefix r.Name FSharpSignatureDataResourceName
elif r.Name.StartsWithOrdinal FSharpSignatureCompressedDataResourceName then
FSharpSignatureCompressedDataResourceName, String.dropPrefix r.Name FSharpSignatureCompressedDataResourceName
elif r.Name.StartsWithOrdinal FSharpSignatureDataResourceName2 then
FSharpSignatureDataResourceName2, String.dropPrefix r.Name FSharpSignatureDataResourceName2
else
failwith "GetSignatureDataResourceName"
if resourceType = FSharpSignatureCompressedDataResourceName then
ccuName, (fun () -> decompressResource (r))
else
ccuName, (fun () -> r.GetBytes())
let GetResourceNameAndOptimizationDataFunc (r: ILResource) =
let resourceType, ccuName =
if r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName then
FSharpOptimizationDataResourceName, String.dropPrefix r.Name FSharpOptimizationDataResourceName
elif r.Name.StartsWithOrdinal FSharpOptimizationCompressedDataResourceName then
FSharpOptimizationCompressedDataResourceName, String.dropPrefix r.Name FSharpOptimizationCompressedDataResourceName
elif r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName2 then
FSharpOptimizationDataResourceName2, String.dropPrefix r.Name FSharpOptimizationDataResourceName2
else
failwith "GetOptimizationDataResourceName"
if resourceType = FSharpOptimizationCompressedDataResourceName then
ccuName, (fun () -> decompressResource (r))
else
ccuName, (fun () -> r.GetBytes())
let IsReflectedDefinitionsResource (r: ILResource) =
r.Name.StartsWithOrdinal(QuotationPickler.SerializedReflectedDefinitionsResourceNameBase)
let PickleToResource inMem file (g: TcGlobals) compress scope rName p x =
let file = PathMap.apply g.pathMap file
let bytes =
use bytes = pickleObjWithDanglingCcus inMem file g scope p x
if compress then
let raw = new MemoryStream(bytes.AsMemory().ToArray())
let compressed = new MemoryStream()
use deflator = new DeflateStream(compressed, CompressionLevel.Optimal)
raw.CopyTo deflator
deflator.Close()
compressed.ToArray()
else
bytes.AsMemory().ToArray()
let byteStorage = ByteStorage.FromByteArray(bytes)
{
Name = rName
Location = ILResourceLocation.Local(byteStorage)
Access = ILResourceAccess.Public
CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs
MetadataIndex = NoMetadataIdx
}
let GetSignatureData (file, ilScopeRef, ilModule, byteReader) : PickledDataWithReferences<PickledCcuInfo> =
unpickleObjWithDanglingCcus file ilScopeRef ilModule unpickleCcuInfo (byteReader ())
let WriteSignatureData (tcConfig: TcConfig, tcGlobals, exportRemapping, ccu: CcuThunk, fileName, inMem) : ILResource =
let mspec = ApplyExportRemappingToEntity tcGlobals exportRemapping ccu.Contents
if tcConfig.dumpSignatureData then
tcConfig.outputFile
|> Option.iter (fun outputFile ->
let outputFile = FileSystem.GetFullPathShim(outputFile)
let signatureDataFile =
FileSystem.ChangeExtensionShim(outputFile, ".signature-data.json")
serializeEntity signatureDataFile mspec)
// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers
// don't complain when they see the resource.
let rName, compress =
if tcConfig.compressMetadata then
FSharpSignatureCompressedDataResourceName, true
elif ccu.AssemblyName = getFSharpCoreLibraryName then
FSharpSignatureDataResourceName2, false
else
FSharpSignatureDataResourceName, false
let includeDir =
if String.IsNullOrEmpty tcConfig.implicitIncludeDir then
""
else
tcConfig.implicitIncludeDir
|> FileSystem.GetFullPathShim
|> PathMap.applyDir tcGlobals.pathMap
PickleToResource
inMem
fileName
tcGlobals
compress
ccu
(rName + ccu.AssemblyName)
pickleCcuInfo
{
mspec = mspec
compileTimeWorkingDir = includeDir
usesQuotations = ccu.UsesFSharp20PlusQuotations
}
let GetOptimizationData (file, ilScopeRef, ilModule, byteReader) =
unpickleObjWithDanglingCcus file ilScopeRef ilModule Optimizer.u_CcuOptimizationInfo (byteReader ())
let WriteOptimizationData (tcConfig: TcConfig, tcGlobals, fileName, inMem, ccu: CcuThunk, modulInfo) =
// For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers
// don't complain when they see the resource.
let rName, compress =
if tcConfig.compressMetadata then
FSharpOptimizationCompressedDataResourceName, true
elif ccu.AssemblyName = getFSharpCoreLibraryName then
FSharpOptimizationDataResourceName2, false
else
FSharpOptimizationDataResourceName, false
PickleToResource inMem fileName tcGlobals compress ccu (rName + ccu.AssemblyName) Optimizer.p_CcuOptimizationInfo modulInfo
let EncodeSignatureData (tcConfig: TcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild) =
if tcConfig.GenerateSignatureData then
let resource =
WriteSignatureData(tcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild)
let resources = [ resource ]
let sigAttr =
mkSignatureDataVersionAttr tcGlobals (parseILVersion FSharpBinaryMetadataFormatRevision)
[ sigAttr ], resources
else
[], []
let EncodeOptimizationData (tcGlobals, tcConfig: TcConfig, outfile, exportRemapping, data, isIncrementalBuild) =
if tcConfig.GenerateOptimizationData then
let data = map2Of2 (Optimizer.RemapOptimizationInfo tcGlobals exportRemapping) data
let ccu, optData =
if tcConfig.onlyEssentialOptimizationData then
map2Of2 Optimizer.AbstractOptimizationInfoToEssentials data
else
data
[ WriteOptimizationData(tcConfig, tcGlobals, outfile, isIncrementalBuild, ccu, optData) ]
else
[]
exception AssemblyNotResolved of originalName: string * range: range
exception MSBuildReferenceResolutionWarning of message: string * warningCode: string * range: range
exception MSBuildReferenceResolutionError of message: string * warningCode: string * range: range
let OpenILBinary (fileName, reduceMemoryUsage, pdbDirPath, shadowCopyReferences, tryGetMetadataSnapshot) =
let opts: ILReaderOptions =
{
metadataOnly = MetadataOnlyFlag.Yes
reduceMemoryUsage = reduceMemoryUsage
pdbDirPath = pdbDirPath
tryGetMetadataSnapshot = tryGetMetadataSnapshot
}
let location =
// In order to use memory mapped files on the shadow copied version of the Assembly, we `preload the assembly
// We swallow all exceptions so that we do not change the exception contract of this API
if shadowCopyReferences && not isRunningOnCoreClr then
try
Assembly.ReflectionOnlyLoadFrom(fileName).Location
with _ ->
fileName
else
fileName
AssemblyReader.GetILModuleReader(location, opts)
[<RequireQualifiedAccess>]
type ResolveAssemblyReferenceMode =
| Speculative
| ReportErrors
#if !NO_TYPEPROVIDERS
type ResolvedExtensionReference = ResolvedExtensionReference of string * AssemblyReference list * Tainted<ITypeProvider> list
#endif
#if DEBUG
[<DebuggerDisplay("AssemblyResolution({resolvedPath})")>]
#endif
type AssemblyResolution =
{
/// The original reference to the assembly.
originalReference: AssemblyReference
/// Path to the resolvedFile
resolvedPath: string
/// Create the tooltip text for the assembly reference
prepareToolTip: unit -> string
/// Whether or not this is an installed system assembly (for example, System.dll)
sysdir: bool
/// Lazily populated ilAssemblyRef for this reference.
mutable ilAssemblyRef: ILAssemblyRef option
}
override this.ToString() =
sprintf "%s%s" (if this.sysdir then "[sys]" else "") this.resolvedPath
member this.ProjectReference = this.originalReference.ProjectReference
/// Compute the ILAssemblyRef for a resolved assembly. This is done by reading the binary if necessary. The result
/// is cached.
///
/// Only used in F# Interactive
member this.GetILAssemblyRef(reduceMemoryUsage, tryGetMetadataSnapshot) =
match this.ilAssemblyRef with
| Some assemblyRef -> assemblyRef
| None ->
match this.ProjectReference with
| Some _ -> failwith "IProjectReference is not allowed to be used in GetILAssemblyRef"
| None -> ()
let assemblyRef =
let readerSettings: ILReaderOptions =
{
pdbDirPath = None
reduceMemoryUsage = reduceMemoryUsage
metadataOnly = MetadataOnlyFlag.Yes
tryGetMetadataSnapshot = tryGetMetadataSnapshot
}
use reader = OpenILModuleReader this.resolvedPath readerSettings
mkRefToILAssembly reader.ILModuleDef.ManifestOfAssembly
this.ilAssemblyRef <- Some assemblyRef
assemblyRef
type ImportedBinary =
{
FileName: string
RawMetadata: IRawFSharpAssemblyData
#if !NO_TYPEPROVIDERS
ProviderGeneratedAssembly: Assembly option
IsProviderGenerated: bool
ProviderGeneratedStaticLinkMap: ProvidedAssemblyStaticLinkingMap option
#endif
ILAssemblyRefs: ILAssemblyRef list
ILScopeRef: ILScopeRef
}
type ImportedAssembly =
{
ILScopeRef: ILScopeRef
FSharpViewOfMetadata: CcuThunk
AssemblyAutoOpenAttributes: string list
AssemblyInternalsVisibleToAttributes: string list
#if !NO_TYPEPROVIDERS
IsProviderGenerated: bool
mutable TypeProviders: Tainted<ITypeProvider> list
#endif
FSharpOptimizationData: InterruptibleLazy<Optimizer.LazyModuleInfo option>
}
type AvailableImportedAssembly =
| ResolvedImportedAssembly of ImportedAssembly * range
| UnresolvedImportedAssembly of string * range
type CcuLoadFailureAction =
| RaiseError
| ReturnNone
type TcImportsLockToken() =
interface LockToken
type TcImportsLock = Lock<TcImportsLockToken>
let RequireTcImportsLock (_tcitok: TcImportsLockToken, _thingProtected: 'T) = ()
// if this is a #r reference (not from dummy range), make sure the directory of the declaring
// file is included in the search path. This should ideally already be one of the search paths, but
// during some global checks it won't be. We append to the end of the search list so that this is the last
// place that is checked.
let isHashRReference (r: range) =
not (equals r range0)
&& not (equals r rangeStartup)
&& not (equals r rangeCmdArgs)
&& FileSystem.IsPathRootedShim r.FileName
let IsNetModule fileName =
let ext = Path.GetExtension fileName
String.Compare(ext, ".netmodule", StringComparison.OrdinalIgnoreCase) = 0
let IsDLL fileName =
let ext = Path.GetExtension fileName
String.Compare(ext, ".dll", StringComparison.OrdinalIgnoreCase) = 0
let IsExe fileName =
let ext = Path.GetExtension fileName
String.Compare(ext, ".exe", StringComparison.OrdinalIgnoreCase) = 0
let addConstraintSources(ia: ImportedAssembly) =
let contents = ia.FSharpViewOfMetadata.Contents
let addCxsToMember name (v: Val) =
for typar in fst v.GeneralizedType do
for cx in typar.Constraints do
match cx with
| TyparConstraint.MayResolveMember(TTrait(source=source), _) ->
source.Value <- Some name
| _ -> ()
let rec addCxsToModule name (m: ModuleOrNamespaceType) =
for e in m.ModuleAndNamespaceDefinitions do
if e.IsModuleOrNamespace then
let mname =
if String.length name > 0 then name + "." + e.DisplayName
elif e.IsModule then e.DisplayName
else ""
addCxsToModule mname e.ModuleOrNamespaceType
for memb in m.AllValsAndMembers do addCxsToMember (name + "." + memb.LogicalName) memb
addCxsToModule "" contents.ModuleOrNamespaceType
type TcConfig with
member tcConfig.TryResolveLibWithDirectories(r: AssemblyReference) =
let m, nm = r.Range, r.Text
use _ = UseBuildPhase BuildPhase.Parameter
// See if the language service has already produced the contents of the assembly for us, virtually
match r.ProjectReference with
| Some _ ->
let resolved = r.Text
let sysdir = tcConfig.IsSystemAssembly resolved
Some
{
originalReference = r
resolvedPath = resolved
prepareToolTip = (fun () -> resolved)
sysdir = sysdir
ilAssemblyRef = None
}
| None ->
// Only want to resolve certain extensions (otherwise, 'System.Xml' is ambiguous).
// MSBuild resolution is limited to .exe and .dll so do the same here.
if IsDLL nm || IsExe nm || IsNetModule nm then
let searchPaths =
seq {
yield! tcConfig.GetSearchPathsForLibraryFiles()
if isHashRReference m then
Path.GetDirectoryName(m.FileName)
}
let resolved = TryResolveFileUsingPaths(searchPaths, m, nm)
match resolved with
| Some resolved ->
let sysdir = tcConfig.IsSystemAssembly resolved
Some
{
originalReference = r
resolvedPath = resolved
prepareToolTip =
(fun () ->
let fusionName = AssemblyName.GetAssemblyName(resolved).ToString()
let line (append: string) = append.Trim(' ') + "\n"
line resolved + line fusionName)
sysdir = sysdir
ilAssemblyRef = None
}
| None -> None
else
None
member tcConfig.ResolveLibWithDirectories(ccuLoadFailureAction, r: AssemblyReference) =
let m, nm = r.Range, r.Text
use _ = UseBuildPhase BuildPhase.Parameter
let rs =
if IsExe nm || IsDLL nm || IsNetModule nm then
[ r ]
else
[
AssemblyReference(m, nm + ".dll", None)
AssemblyReference(m, nm + ".exe", None)
AssemblyReference(m, nm + ".netmodule", None)
]
match rs |> List.tryPick (fun r -> tcConfig.TryResolveLibWithDirectories(r)) with
| Some res -> Some res
| None ->
match ccuLoadFailureAction with
| CcuLoadFailureAction.RaiseError ->
let searchMessage = String.concat "\n " (tcConfig.GetSearchPathsForLibraryFiles())
raise (FileNameNotResolved(nm, searchMessage, m))
| CcuLoadFailureAction.ReturnNone -> None
member tcConfig.MsBuildResolve(references, _, errorAndWarningRange, showMessages) =
let logMessage showMessages =
if showMessages && tcConfig.showReferenceResolutions then
(fun (message: string) -> printfn "%s" message)
else
ignore
let logDiagnostic _ =
(fun (_: bool) (_: string) (_: string) -> ())
let targetProcessorArchitecture =
match tcConfig.platform with
| None -> "MSIL"
| Some X86 -> "x86"
| Some AMD64 -> "amd64"
| Some ARM -> "arm"
| Some ARM64 -> "arm64"
| Some IA64 -> "ia64"
try
tcConfig.legacyReferenceResolver.Impl.Resolve(
tcConfig.resolutionEnvironment,
references,
tcConfig.targetFrameworkVersion,
tcConfig.GetTargetFrameworkDirectories(),
targetProcessorArchitecture,
tcConfig.fsharpBinariesDir, // FSharp binaries directory
tcConfig.includes, // Explicit include directories
tcConfig.implicitIncludeDir, // Implicit include directory (likely the project directory)
logMessage showMessages,
logDiagnostic showMessages
)
with LegacyResolutionFailure ->
error (Error(FSComp.SR.buildAssemblyResolutionFailed (), errorAndWarningRange))
// NOTE!! if mode=Speculative then this method must not report ANY warnings or errors through 'warning' or 'error'. Instead
// it must return warnings and errors as data
//
// NOTE!! if mode=ReportErrors then this method must not raise exceptions. It must just report the errors and recover
static member TryResolveLibsUsingMSBuildRules
(
tcConfig: TcConfig,
originalReferences: AssemblyReference list,
errorAndWarningRange: range,
mode: ResolveAssemblyReferenceMode
) : AssemblyResolution list * UnresolvedAssemblyReference list =
use _ = UseBuildPhase BuildPhase.Parameter
if tcConfig.useSimpleResolution then
failwith "MSBuild resolution is not supported."
if List.isEmpty originalReferences then
[], []
else
// Group references by name with range values in the grouped value list.
// In the grouped reference, store the index of the last use of the reference.
let groupedReferences =
originalReferences
|> List.indexed
|> List.groupBy (fun (_, reference) -> reference.Text)
|> List.map (fun (assemblyName, assemblyAndIndexGroup) ->
let assemblyAndIndexGroup = assemblyAndIndexGroup |> List.ofSeq
let highestPosition = assemblyAndIndexGroup |> List.maxBy fst |> fst
let assemblyGroup = assemblyAndIndexGroup |> List.map snd
assemblyName, highestPosition, assemblyGroup)
|> Array.ofList
// First, try to resolve everything as a file using simple resolution
let resolvedAsFile =
[|
for (_filename, maxIndexOfReference, references) in groupedReferences do
let assemblyResolution =
references |> List.choose (tcConfig.TryResolveLibWithDirectories)
if not assemblyResolution.IsEmpty then
(maxIndexOfReference, assemblyResolution)
|]
let toMsBuild =
[|
for i in 0 .. groupedReferences.Length - 1 do
let ref, i0, _ = groupedReferences[i]
if resolvedAsFile |> Array.exists (fun (i1, _) -> i0 = i1) |> not then
ref, string i
|]
let resolutions =
tcConfig.MsBuildResolve(toMsBuild, mode, errorAndWarningRange, true)
// Map back to original assembly resolutions.
let resolvedByMsbuild =
[|
for resolvedFile in resolutions do
let i = int resolvedFile.baggage
let _, maxIndexOfReference, ms = groupedReferences[i]
let assemblyResolutions =
[
for originalReference in ms do
let canonicalItemSpec = FileSystem.GetFullPathShim(resolvedFile.itemSpec)
{
originalReference = originalReference
resolvedPath = canonicalItemSpec
prepareToolTip = (fun () -> resolvedFile.prepareToolTip (originalReference.Text, canonicalItemSpec))
sysdir = tcConfig.IsSystemAssembly canonicalItemSpec
ilAssemblyRef = None
}
]
(maxIndexOfReference, assemblyResolutions)
|]
// When calculating the resulting resolutions, we're going to use the index of the reference
// in the original specification and resort it to match the ordering that we had.
let resultingResolutions =
[ resolvedByMsbuild; resolvedAsFile ]
|> Array.concat
|> Array.sortBy fst
|> Array.map snd
|> List.ofArray
|> List.concat
// O(N^2) here over a small set of referenced assemblies.
let IsResolved (originalName: string) =
if
resultingResolutions
|> List.exists (fun resolution -> resolution.originalReference.Text = originalName)
then
true
else
// MSBuild resolution may have unified the result of two duplicate references. Try to re-resolve now.
// If re-resolution worked then this was a removed duplicate.
let references = [| (originalName, "") |]
let resolutions =
tcConfig.MsBuildResolve(references, mode, errorAndWarningRange, false)
resolutions.Length <> 0
let unresolvedReferences =
groupedReferences |> Array.filter (p13 >> IsResolved >> not) |> List.ofArray
let unresolved =
[
for (name, _, r) in unresolvedReferences -> UnresolvedAssemblyReference(name, r)
]
// If mode=Speculative, then we haven't reported any errors.
// We report the error condition by returning an empty list of resolutions
if
mode = ResolveAssemblyReferenceMode.Speculative
&& unresolvedReferences.Length > 0
then
[], unresolved
else
resultingResolutions, unresolved
[<Sealed>]
type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, unresolved: UnresolvedAssemblyReference list) =
let originalReferenceToResolution =
results |> List.map (fun r -> r.originalReference.Text, r) |> Map.ofList
let resolvedPathToResolution =
results |> List.map (fun r -> r.resolvedPath, r) |> Map.ofList
/// Add some resolutions to the map of resolution results.
member _.AddResolutionResults newResults =
TcAssemblyResolutions(tcConfig, results @ newResults, unresolved)
/// Add some unresolved results.
member _.AddUnresolvedReferences newUnresolved =
TcAssemblyResolutions(tcConfig, results, unresolved @ newUnresolved)
/// Get information about referenced DLLs
member _.GetAssemblyResolutions() = results
member _.GetUnresolvedReferences() = unresolved
member _.TryFindByOriginalReference(assemblyReference: AssemblyReference) =
originalReferenceToResolution.TryFind assemblyReference.Text
/// Only used by F# Interactive
member _.TryFindByExactILAssemblyRef assemblyRef =
results
|> List.tryFind (fun ar ->
let r =
ar.GetILAssemblyRef(tcConfig.reduceMemoryUsage, tcConfig.tryGetMetadataSnapshot)
r = assemblyRef)
/// Only used by F# Interactive
member _.TryFindBySimpleAssemblyName simpleAssemName =
results
|> List.tryFind (fun ar ->
let r =
ar.GetILAssemblyRef(tcConfig.reduceMemoryUsage, tcConfig.tryGetMetadataSnapshot)
r.Name = simpleAssemName)
member _.TryFindByResolvedPath nm = resolvedPathToResolution.TryFind nm
member _.TryFindByOriginalReferenceText nm =
originalReferenceToResolution.TryFind nm
static member ResolveAssemblyReferences
(
tcConfig: TcConfig,
assemblyList: AssemblyReference list,
knownUnresolved: UnresolvedAssemblyReference list
) : TcAssemblyResolutions =
let resolved, unresolved =
if tcConfig.useSimpleResolution then
let resolutions =
assemblyList
|> List.map (fun assemblyReference ->
try
let resolutionOpt =
tcConfig.ResolveLibWithDirectories(CcuLoadFailureAction.RaiseError, assemblyReference)
Choice1Of2 resolutionOpt.Value
with RecoverableException e ->
errorRecovery e assemblyReference.Range
Choice2Of2 assemblyReference)
let successes =
resolutions
|> List.choose (function
| Choice1Of2 x -> Some x
| _ -> None)
let failures =
resolutions
|> List.choose (function
| Choice2Of2 x -> Some(UnresolvedAssemblyReference(x.Text, [ x ]))
| _ -> None)
successes, failures
else
// we don't want to do assembly resolution concurrently, we assume MSBuild doesn't handle this
TcConfig.TryResolveLibsUsingMSBuildRules(tcConfig, assemblyList, rangeStartup, ResolveAssemblyReferenceMode.ReportErrors)
TcAssemblyResolutions(tcConfig, resolved, unresolved @ knownUnresolved)
static member GetAllDllReferences(tcConfig: TcConfig) =
[
let primaryReference = tcConfig.PrimaryAssemblyDllReference()
let assumeDotNetFramework = primaryReference.SimpleAssemblyNameIs("mscorlib")
if not tcConfig.compilingFSharpCore then
tcConfig.CoreLibraryDllReference()
if assumeDotNetFramework then
// When building desktop then we need these additional dependencies
AssemblyReference(rangeStartup, "System.Numerics.dll", None)
AssemblyReference(rangeStartup, "System.dll", None)
let asm = AssemblyReference(rangeStartup, "netstandard.dll", None)
let found =
if tcConfig.useSimpleResolution then
match tcConfig.ResolveLibWithDirectories(CcuLoadFailureAction.ReturnNone, asm) with
| Some _ -> true
| None -> false
else
let references = [| (asm.Text, "") |]
let resolutions =
tcConfig.MsBuildResolve(references, ResolveAssemblyReferenceMode.Speculative, rangeStartup, false)
resolutions.Length = 1
if found then
asm
if tcConfig.implicitlyReferenceDotNetAssemblies then
let references, _useDotNetFramework =
tcConfig.FxResolver.GetDefaultReferences(tcConfig.useFsiAuxLib)
for s in references do
let referenceText =
if s.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then
s
else
s + ".dll"
AssemblyReference(rangeStartup, referenceText, None)
yield! tcConfig.referencedDLLs
]
static member SplitNonFoundationalResolutions(tcConfig: TcConfig) =
let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig
let resolutions =
TcAssemblyResolutions.ResolveAssemblyReferences(tcConfig, assemblyList, tcConfig.knownUnresolvedReferences)
let frameworkDLLs, nonFrameworkReferences =
resolutions.GetAssemblyResolutions() |> List.partition (fun r -> r.sysdir)
let unresolved = resolutions.GetUnresolvedReferences()
#if DEBUG
let mutable itFailed = false
let addedText =
"\nIf you want to debug this right now, attach a debugger, and put a breakpoint in 'CompileOps.fs' near the text '!itFailed', and you can re-step through the assembly resolution logic."
for UnresolvedAssemblyReference (referenceText, _ranges) in unresolved do
if referenceText.Contains("mscorlib") then
Debug.Assert(false, sprintf "whoops, did not resolve mscorlib: '%s'%s" referenceText addedText)
itFailed <- true
for x in frameworkDLLs do
if not (FileSystem.IsPathRootedShim(x.resolvedPath)) then
Debug.Assert(false, sprintf "frameworkDLL should be absolute path: '%s'%s" x.resolvedPath addedText)
itFailed <- true
for x in nonFrameworkReferences do
if not (FileSystem.IsPathRootedShim(x.resolvedPath)) then
Debug.Assert(false, sprintf "nonFrameworkReference should be absolute path: '%s'%s" x.resolvedPath addedText)
itFailed <- true
if itFailed then
// idea is, put a breakpoint here and then step through
let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig
let resolutions =
TcAssemblyResolutions.ResolveAssemblyReferences(tcConfig, assemblyList, [])
let _frameworkDLLs, _nonFrameworkReferences =
resolutions.GetAssemblyResolutions() |> List.partition (fun r -> r.sysdir)
()
#endif
frameworkDLLs, nonFrameworkReferences, unresolved
static member BuildFromPriorResolutions(tcConfig: TcConfig, resolutions, knownUnresolved) =
let references = resolutions |> List.map (fun r -> r.originalReference)
TcAssemblyResolutions.ResolveAssemblyReferences(tcConfig, references, knownUnresolved)
static member GetAssemblyResolutionInformation(tcConfig: TcConfig) =
use _ = UseBuildPhase BuildPhase.Parameter
let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig
let resolutions =
TcAssemblyResolutions.ResolveAssemblyReferences(tcConfig, assemblyList, [])
resolutions.GetAssemblyResolutions(), resolutions.GetUnresolvedReferences()
//----------------------------------------------------------------------------
// Abstraction for project reference
let GetNameOfILModule (m: ILModuleDef) =
match m.Manifest with
| Some manifest -> manifest.Name
| None -> m.Name
let MakeScopeRefForILModule (ilModule: ILModuleDef) =
match ilModule.Manifest with
| Some m -> ILScopeRef.Assembly(mkRefToILAssembly m)
| None -> ILScopeRef.Module(mkRefToILModule ilModule)
let GetCustomAttributesOfILModule (ilModule: ILModuleDef) =
let attrs =
match ilModule.Manifest with
| Some m -> m.CustomAttrs
| None -> ilModule.CustomAttrs
attrs.AsList()
let GetAutoOpenAttributes ilModule =
ilModule |> GetCustomAttributesOfILModule |> List.choose TryFindAutoOpenAttr
let GetInternalsVisibleToAttributes ilModule =
ilModule
|> GetCustomAttributesOfILModule
|> List.choose TryFindInternalsVisibleToAttr
type RawFSharpAssemblyDataBackedByFileOnDisk(ilModule: ILModuleDef, ilAssemblyRefs) =
let externalSigAndOptData = [ "FSharp.Core" ]
interface IRawFSharpAssemblyData with
member _.GetAutoOpenAttributes() = GetAutoOpenAttributes ilModule
member _.GetInternalsVisibleToAttributes() =
GetInternalsVisibleToAttributes ilModule
member _.TryGetILModuleDef() = Some ilModule
member _.GetRawFSharpSignatureData(m, ilShortAssemName, fileName) =
let resources = ilModule.Resources.AsList()
let sigDataReaders =
[
for r in resources do
if IsSignatureDataResource r then
GetResourceNameAndSignatureDataFunc r
]
let sigDataReaders =
if sigDataReaders.IsEmpty && List.contains ilShortAssemName externalSigAndOptData then
let sigFileName = Path.ChangeExtension(fileName, "sigdata")
if not (FileSystem.FileExistsShim sigFileName) then
error (Error(FSComp.SR.buildExpectedSigdataFile (FileSystem.GetFullPathShim sigFileName), m))
[
(ilShortAssemName,
fun () ->
FileSystem
.OpenFileForReadShim(sigFileName, useMemoryMappedFile = true, shouldShadowCopy = true)
.AsByteMemory()
.AsReadOnly())
]
else
sigDataReaders
sigDataReaders
member _.GetRawFSharpOptimizationData(m, ilShortAssemName, fileName) =
let optDataReaders =
ilModule.Resources.AsList()
|> List.choose (fun r ->
if IsOptimizationDataResource r then
Some(GetResourceNameAndOptimizationDataFunc r)
else
None)
// Look for optimization data in a file
let optDataReaders =
if optDataReaders.IsEmpty && List.contains ilShortAssemName externalSigAndOptData then
let optDataFile = Path.ChangeExtension(fileName, "optdata")
if not (FileSystem.FileExistsShim optDataFile) then
let fullPath = FileSystem.GetFullPathShim optDataFile
error (Error(FSComp.SR.buildExpectedFileAlongSideFSharpCore (optDataFile, fullPath), m))
[
(ilShortAssemName,
(fun () ->
FileSystem
.OpenFileForReadShim(optDataFile, useMemoryMappedFile = true, shouldShadowCopy = true)
.AsByteMemory()
.AsReadOnly()))
]
else
optDataReaders
optDataReaders
member _.GetRawTypeForwarders() =
match ilModule.Manifest with
| Some manifest -> manifest.ExportedTypes
| None -> mkILExportedTypes []
member _.ShortAssemblyName = GetNameOfILModule ilModule
member _.ILScopeRef = MakeScopeRefForILModule ilModule
member _.ILAssemblyRefs = ilAssemblyRefs
member _.HasAnyFSharpSignatureDataAttribute =
let attrs = GetCustomAttributesOfILModule ilModule
List.exists IsSignatureDataVersionAttr attrs
member _.HasMatchingFSharpSignatureDataAttribute =
let attrs = GetCustomAttributesOfILModule ilModule
List.exists (IsMatchingSignatureDataVersionAttr(parseILVersion FSharpBinaryMetadataFormatRevision)) attrs
[<Sealed>]
type RawFSharpAssemblyData(ilModule: ILModuleDef, ilAssemblyRefs) =
interface IRawFSharpAssemblyData with
member _.GetAutoOpenAttributes() = GetAutoOpenAttributes ilModule
member _.GetInternalsVisibleToAttributes() =
GetInternalsVisibleToAttributes ilModule
member _.TryGetILModuleDef() = Some ilModule
member _.GetRawFSharpSignatureData(_, _, _) =
let resources = ilModule.Resources.AsList()
[
for r in resources do
if IsSignatureDataResource r then
GetResourceNameAndSignatureDataFunc r
]
member _.GetRawFSharpOptimizationData(_, _, _) =
ilModule.Resources.AsList()
|> List.choose (fun r ->
if IsOptimizationDataResource r then
Some(GetResourceNameAndOptimizationDataFunc r)
else
None)
member _.GetRawTypeForwarders() =
match ilModule.Manifest with
| Some manifest -> manifest.ExportedTypes
| None -> mkILExportedTypes []
member _.ShortAssemblyName = GetNameOfILModule ilModule
member _.ILScopeRef = MakeScopeRefForILModule ilModule
member _.ILAssemblyRefs = ilAssemblyRefs
member _.HasAnyFSharpSignatureDataAttribute =
let attrs = GetCustomAttributesOfILModule ilModule
List.exists IsSignatureDataVersionAttr attrs
member _.HasMatchingFSharpSignatureDataAttribute =
let attrs = GetCustomAttributesOfILModule ilModule
List.exists (IsMatchingSignatureDataVersionAttr(parseILVersion FSharpBinaryMetadataFormatRevision)) attrs
//----------------------------------------------------------------------------