-
Notifications
You must be signed in to change notification settings - Fork 789
/
TransparentCompiler.fs
2527 lines (2075 loc) · 108 KB
/
TransparentCompiler.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 FSharp.Compiler.CodeAnalysis.TransparentCompiler
open System
open System.Linq
open System.Collections.Generic
open System.Runtime.CompilerServices
open System.Diagnostics
open System.IO
open Internal.Utilities.Collections
open Internal.Utilities.Library
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.BuildGraph
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.CompilerOptions
open FSharp.Compiler.CheckBasics
open FSharp.Compiler.DependencyManager
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.IO
open FSharp.Compiler.ScriptClosure
open FSharp.Compiler.Symbols
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Xml
open System.Threading.Tasks
open FSharp.Compiler.ParseAndCheckInputs
open FSharp.Compiler.GraphChecking
open FSharp.Compiler.Syntax
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.NameResolution
open Internal.Utilities.Library.Extras
open FSharp.Compiler.TypedTree
open FSharp.Compiler.CheckDeclarations
open FSharp.Compiler.EditorServices
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.CreateILModule
open FSharp.Compiler.TypedTreeOps
open System.Threading
open Internal.Utilities.Hashing
open FSharp.Compiler.CodeAnalysis.ProjectSnapshot
/// Accumulated results of type checking. The minimum amount of state in order to continue type-checking following files.
[<NoEquality; NoComparison>]
type internal TcInfo =
{
tcState: TcState
tcEnvAtEndOfFile: TcEnv
/// Disambiguation table for module names
moduleNamesDict: ModuleNamesDict
topAttribs: TopAttribs option
latestCcuSigForFile: ModuleOrNamespaceType option
/// Accumulated diagnostics, last file first
tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] list
tcDependencyFiles: string list
sigNameOpt: (string * QualifiedNameOfFile) option
graphNode: NodeToTypeCheck option
stateContainsNodes: Set<NodeToTypeCheck>
sink: TcResultsSinkImpl list
}
member x.TcDiagnostics = Array.concat (List.rev x.tcDiagnosticsRev)
[<NoEquality; NoComparison>]
type internal TcIntermediate =
{
finisher: Finisher<NodeToTypeCheck, TcState, PartialResult>
//tcEnvAtEndOfFile: TcEnv
/// Disambiguation table for module names
moduleNamesDict: ModuleNamesDict
/// Accumulated diagnostics, last file first
tcDiagnosticsRev: (PhasedDiagnostic * FSharpDiagnosticSeverity)[] list
tcDependencyFiles: string list
sink: TcResultsSinkImpl
}
/// Things we need to start parsing and checking files for a given project snapshot
type internal BootstrapInfo =
{
// Each instance gets an Id on creation, unfortunately partial type check results using different instances are not compatible
// So if this needs to be recreated for whatever reason then we need to re type check all files
Id: int
AssemblyName: string
OutFile: string
TcConfig: TcConfig
TcImports: TcImports
TcGlobals: TcGlobals
InitialTcInfo: TcInfo
// TODO: Figure out how these work and if they need to be added to the snapshot...
LoadedSources: (range * FSharpFileSnapshot) list
// TODO: Might be a bit more complicated if we want to support adding files to the project via OtherOptions
// ExtraSourceFilesAfter: FSharpFileSnapshot list
LoadClosure: LoadClosure option
LastFileName: string
ImportsInvalidatedByTypeProvider: Event<unit>
}
type internal TcIntermediateResult = TcInfo * TcResultsSinkImpl * CheckedImplFile option * string
[<RequireQualifiedAccess>]
type internal DependencyGraphType =
/// A dependency graph for a single file - it will be missing files which this file does not depend on
| File
/// A dependency graph for a project - it will contain all files in the project
| Project
[<Extension>]
type internal Extensions =
[<Extension>]
static member Key<'T when 'T :> IFileSnapshot>(fileSnapshots: 'T list, ?extraKeyFlag) =
{ new ICacheKey<_, _> with
member _.GetLabel() =
let lastFile =
fileSnapshots
|> List.tryLast
|> Option.map (fun f -> f.FileName |> shortPath)
|> Option.defaultValue "[no file]"
$"%d{fileSnapshots.Length} files ending with {lastFile}"
member _.GetKey() =
Md5Hasher.empty
|> Md5Hasher.addStrings (fileSnapshots |> Seq.map (fun f -> f.FileName))
|> pair extraKeyFlag
member _.GetVersion() =
Md5Hasher.empty
|> Md5Hasher.addBytes' (fileSnapshots |> Seq.map (fun f -> f.Version))
|> Md5Hasher.toString
}
[<AutoOpen>]
module private TypeCheckingGraphProcessing =
open FSharp.Compiler.GraphChecking.GraphProcessing
// TODO Do we need to suppress some error logging if we
// TODO apply the same partial results multiple times?
// TODO Maybe we can enable logging only for the final fold
/// <summary>
/// Combine type-checking results of dependencies needed to type-check a 'higher' node in the graph
/// </summary>
/// <param name="emptyState">Initial state</param>
/// <param name="deps">Direct dependencies of a node</param>
/// <param name="transitiveDeps">Transitive dependencies of a node</param>
/// <param name="folder">A way to fold a single result into existing state</param>
let private combineResults
(emptyState: TcInfo)
(deps: ProcessedNode<NodeToTypeCheck, TcInfo * Finisher<NodeToTypeCheck, TcInfo, PartialResult>> array)
(transitiveDeps: ProcessedNode<NodeToTypeCheck, TcInfo * Finisher<NodeToTypeCheck, TcInfo, PartialResult>> array)
(folder: TcInfo -> Finisher<NodeToTypeCheck, TcInfo, PartialResult> -> TcInfo)
: TcInfo =
match deps with
| [||] -> emptyState
| _ ->
// Instead of starting with empty state,
// reuse state produced by the dependency with the biggest number of transitive dependencies.
// This is to reduce the number of folds required to achieve the final state.
let biggestDependency =
let sizeMetric (node: ProcessedNode<_, _>) = node.Info.TransitiveDeps.Length
deps |> Array.maxBy sizeMetric
let firstState = biggestDependency.Result |> fst
// Find items not already included in the state.
let itemsPresent =
set
[|
yield! biggestDependency.Info.TransitiveDeps
yield biggestDependency.Info.Item
|]
let resultsToAdd =
transitiveDeps
|> Array.filter (fun dep -> itemsPresent.Contains dep.Info.Item = false)
|> Array.distinctBy (fun dep -> dep.Info.Item)
|> Array.sortWith (fun a b ->
// We preserve the order in which items are folded to the state.
match a.Info.Item, b.Info.Item with
| NodeToTypeCheck.PhysicalFile aIdx, NodeToTypeCheck.PhysicalFile bIdx
| NodeToTypeCheck.ArtificialImplFile aIdx, NodeToTypeCheck.ArtificialImplFile bIdx -> aIdx.CompareTo bIdx
| NodeToTypeCheck.PhysicalFile _, NodeToTypeCheck.ArtificialImplFile _ -> -1
| NodeToTypeCheck.ArtificialImplFile _, NodeToTypeCheck.PhysicalFile _ -> 1)
|> Array.map (fun dep -> dep.Result |> snd)
// Fold results not already included and produce the final state
let state = Array.fold folder firstState resultsToAdd
state
/// <summary>
/// Process a graph of items.
/// A version of 'GraphProcessing.processGraph' with a signature specific to type-checking.
/// </summary>
let processTypeCheckingGraph
(graph: Graph<NodeToTypeCheck>)
(work: NodeToTypeCheck -> TcInfo -> Async<Finisher<NodeToTypeCheck, TcInfo, PartialResult>>)
(emptyState: TcInfo)
: Async<(int * PartialResult) list * TcInfo> =
async {
let workWrapper
(getProcessedNode:
NodeToTypeCheck -> ProcessedNode<NodeToTypeCheck, TcInfo * Finisher<NodeToTypeCheck, TcInfo, PartialResult>>)
(node: NodeInfo<NodeToTypeCheck>)
: Async<TcInfo * Finisher<NodeToTypeCheck, TcInfo, PartialResult>> =
async {
let folder (state: TcInfo) (Finisher(finisher = finisher)) : TcInfo = finisher state |> snd
let deps = node.Deps |> Array.except [| node.Item |] |> Array.map getProcessedNode
let transitiveDeps =
node.TransitiveDeps
|> Array.except [| node.Item |]
|> Array.map getProcessedNode
let inputState = combineResults emptyState deps transitiveDeps folder
let! singleRes = work node.Item inputState
let state = folder inputState singleRes
return state, singleRes
}
let! results = processGraphAsync graph workWrapper
let finalFileResults, state =
(([], emptyState),
results
|> Array.choose (fun (item, res) ->
match item with
| NodeToTypeCheck.ArtificialImplFile _ -> None
| NodeToTypeCheck.PhysicalFile file -> Some(file, res)))
||> Array.fold (fun (fileResults, state) (item, (_, Finisher(finisher = finisher))) ->
let fileResult, state = finisher state
(item, fileResult) :: fileResults, state)
return finalFileResults, state
}
type internal CompilerCaches(sizeFactor: int) =
let sf = sizeFactor
member _.SizeFactor = sf
member val ParseFile = AsyncMemoize(keepStrongly = 50 * sf, keepWeakly = 20 * sf, name = "ParseFile")
member val ParseFileWithoutProject =
AsyncMemoize<string, string, FSharpParseFileResults>(keepStrongly = 5 * sf, keepWeakly = 2 * sf, name = "ParseFileWithoutProject")
member val ParseAndCheckFileInProject = AsyncMemoize(sf, 2 * sf, name = "ParseAndCheckFileInProject")
member val ParseAndCheckAllFilesInProject = AsyncMemoizeDisabled(sf, 2 * sf, name = "ParseAndCheckFullProject")
member val ParseAndCheckProject = AsyncMemoize(sf, 2 * sf, name = "ParseAndCheckProject")
member val FrameworkImports = AsyncMemoize(sf, 2 * sf, name = "FrameworkImports")
member val BootstrapInfoStatic = AsyncMemoize(sf, 2 * sf, name = "BootstrapInfoStatic")
member val BootstrapInfo = AsyncMemoize(sf, 2 * sf, name = "BootstrapInfo")
member val TcLastFile = AsyncMemoizeDisabled(sf, 2 * sf, name = "TcLastFile")
member val TcIntermediate = AsyncMemoize(20 * sf, 20 * sf, name = "TcIntermediate")
member val DependencyGraph = AsyncMemoize(sf, 2 * sf, name = "DependencyGraph")
member val ProjectExtras = AsyncMemoizeDisabled(sf, 2 * sf, name = "ProjectExtras")
member val AssemblyData = AsyncMemoize(sf, 2 * sf, name = "AssemblyData")
member val SemanticClassification = AsyncMemoize(sf, 2 * sf, name = "SemanticClassification")
member val ItemKeyStore = AsyncMemoize(sf, 2 * sf, name = "ItemKeyStore")
member val ScriptClosure = AsyncMemoize(sf, 2 * sf, name = "ScriptClosure")
member this.Clear(projects: Set<ProjectIdentifier>) =
let shouldClear project = projects |> Set.contains project
this.ParseFile.Clear(fst >> shouldClear)
this.ParseAndCheckFileInProject.Clear(snd >> shouldClear)
this.ParseAndCheckProject.Clear(shouldClear)
this.BootstrapInfoStatic.Clear(shouldClear)
this.BootstrapInfo.Clear(shouldClear)
this.TcIntermediate.Clear(snd >> shouldClear)
this.AssemblyData.Clear(shouldClear)
this.SemanticClassification.Clear(snd >> shouldClear)
this.ItemKeyStore.Clear(snd >> shouldClear)
this.ScriptClosure.Clear(snd >> shouldClear)
type internal TransparentCompiler
(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
getSource: (string -> Async<ISourceText option>) option,
useChangeNotifications,
useSyntaxTreeCache
) as self =
let documentSource =
match getSource with
| Some getSource -> DocumentSource.Custom getSource
| None -> DocumentSource.FileSystem
// Is having just one of these ok?
let lexResourceManager = Lexhelp.LexResourceManager()
// Mutable so we can easily clear them by creating a new instance
let mutable caches = CompilerCaches(100)
// TODO: do we need this?
//let maxTypeCheckingParallelism = max 1 (Environment.ProcessorCount / 2)
//let maxParallelismSemaphore = new SemaphoreSlim(maxTypeCheckingParallelism)
// We currently share one global dependency provider for all scripts for the FSharpChecker.
// For projects, one is used per project.
//
// Sharing one for all scripts is necessary for good performance from GetProjectOptionsFromScript,
// which requires a dependency provider to process through the project options prior to working out
// if the cached incremental builder can be used for the project.
let dependencyProviderForScripts = new DependencyProvider()
// Legacy events, they're used in tests... eventually they should go away
let beforeFileChecked = Event<string * FSharpProjectOptions>()
let fileParsed = Event<string * FSharpProjectOptions>()
let fileChecked = Event<string * FSharpProjectOptions>()
let projectChecked = Event<FSharpProjectOptions>()
// use this to process not-yet-implemented tasks
let backgroundCompiler =
BackgroundCompiler(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
getSource,
useChangeNotifications,
useSyntaxTreeCache
)
:> IBackgroundCompiler
let ComputeScriptClosureInner
(fileName: string)
(source: ISourceTextNew)
(defaultFSharpBinariesDir: string)
(useSimpleResolution: bool)
(useFsiAuxLib: bool)
(useSdkRefs: bool)
(sdkDirOverride: string option)
(assumeDotNetFramework: bool)
(otherOptions: string list)
=
let reduceMemoryUsage = ReduceMemoryFlag.Yes
let applyCompilerOptions tcConfig =
let fsiCompilerOptions = GetCoreFsiCompilerOptions tcConfig
ParseCompilerOptions(ignore, fsiCompilerOptions, otherOptions)
let closure =
LoadClosure.ComputeClosureOfScriptText(
legacyReferenceResolver,
defaultFSharpBinariesDir,
fileName,
source,
CodeContext.Editing,
useSimpleResolution,
useFsiAuxLib,
useSdkRefs,
sdkDirOverride,
Lexhelp.LexResourceManager(),
applyCompilerOptions,
assumeDotNetFramework,
tryGetMetadataSnapshot,
reduceMemoryUsage,
dependencyProviderForScripts
)
closure
let mkScriptClosureCacheKey
(fileName: string)
(source: ISourceTextNew)
(useSimpleResolution: bool)
(useFsiAuxLib: bool)
(useSdkRefs: bool)
(assumeDotNetFramework: bool)
(projectIdentifier: ProjectIdentifier)
(otherOptions: string list)
(stamp: int64 option)
=
{ new ICacheKey<string * ProjectIdentifier, string> with
member _.GetKey() = fileName, projectIdentifier
member _.GetLabel() = $"ScriptClosure for %s{fileName}"
member _.GetVersion() =
Md5Hasher.empty
|> Md5Hasher.addStrings
[|
yield! otherOptions
match stamp with
| None -> ()
| Some stamp -> string stamp
|]
|> Md5Hasher.addBytes (source.GetChecksum().ToArray())
|> Md5Hasher.addBool useSimpleResolution
|> Md5Hasher.addBool useFsiAuxLib
|> Md5Hasher.addBool useSdkRefs
|> Md5Hasher.addBool assumeDotNetFramework
|> Md5Hasher.toString
}
let ComputeScriptClosure
(fileName: string)
(source: ISourceTextNew)
(defaultFSharpBinariesDir: string)
(useSimpleResolution: bool)
(useFsiAuxLib: bool option)
(useSdkRefs: bool option)
(sdkDirOverride: string option)
(assumeDotNetFramework: bool option)
(projectIdentifier: ProjectIdentifier)
(otherOptions: string list)
(stamp: int64 option)
=
let useFsiAuxLib = defaultArg useFsiAuxLib true
let useSdkRefs = defaultArg useSdkRefs true
let assumeDotNetFramework = defaultArg assumeDotNetFramework false
let key: ICacheKey<string * ProjectIdentifier, string> =
mkScriptClosureCacheKey
fileName
source
useSimpleResolution
useFsiAuxLib
useSdkRefs
assumeDotNetFramework
projectIdentifier
otherOptions
stamp
caches.ScriptClosure.Get(
key,
async {
return
ComputeScriptClosureInner
fileName
source
defaultFSharpBinariesDir
useSimpleResolution
useFsiAuxLib
useSdkRefs
sdkDirOverride
assumeDotNetFramework
otherOptions
}
)
let ComputeFrameworkImports (tcConfig: TcConfig) frameworkDLLs nonFrameworkResolutions =
let frameworkDLLsKey =
frameworkDLLs
|> List.map (fun ar -> ar.resolvedPath) // The cache key. Just the minimal data.
|> List.sort // Sort to promote cache hits.
// The data elements in this key are very important. There should be nothing else in the TcConfig that logically affects
// the import of a set of framework DLLs into F# CCUs. That is, the F# CCUs that result from a set of DLLs (including
// FSharp.Core.dll and mscorlib.dll) must be logically invariant of all the other compiler configuration parameters.
let key =
FrameworkImportsCacheKey(
frameworkDLLsKey,
tcConfig.primaryAssembly.Name,
tcConfig.GetTargetFrameworkDirectories(),
tcConfig.fsharpBinariesDir,
tcConfig.langVersion.SpecifiedVersion,
tcConfig.checkNullness
)
caches.FrameworkImports.Get(
key,
async {
use _ = Activity.start "ComputeFrameworkImports" []
let tcConfigP = TcConfigProvider.Constant tcConfig
return! TcImports.BuildFrameworkTcImports(tcConfigP, frameworkDLLs, nonFrameworkResolutions)
}
)
// Link all the assemblies together and produce the input typecheck accumulator
let CombineImportedAssembliesTask
(
assemblyName,
tcConfig: TcConfig,
tcConfigP,
tcGlobals,
frameworkTcImports,
nonFrameworkResolutions,
unresolvedReferences,
dependencyProvider,
loadClosureOpt: LoadClosure option,
basicDependencies,
importsInvalidatedByTypeProvider: Event<unit>
) =
async {
let diagnosticsLogger =
CompilationDiagnosticLogger("CombineImportedAssembliesTask", tcConfig.diagnosticsOptions)
use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parameter)
let! tcImports =
async {
try
let! tcImports =
TcImports.BuildNonFrameworkTcImports(
tcConfigP,
frameworkTcImports,
nonFrameworkResolutions,
unresolvedReferences,
dependencyProvider
)
#if !NO_TYPEPROVIDERS
// TODO: review and handle the event
tcImports.GetCcusExcludingBase()
|> Seq.iter (fun ccu ->
// When a CCU reports an invalidation, merge them together and just report a
// general "imports invalidated". This triggers a rebuild.
//
// We are explicit about what the handler closure captures to help reason about the
// lifetime of captured objects, especially in case the type provider instance gets leaked
// or keeps itself alive mistakenly, e.g. via some global state in the type provider instance.
//
// The handler only captures
// 1. a weak reference to the importsInvalidated event.
//
// The IncrementalBuilder holds the strong reference the importsInvalidated event.
//
// In the invalidation handler we use a weak reference to allow the IncrementalBuilder to
// be collected if, for some reason, a TP instance is not disposed or not GC'd.
let capturedImportsInvalidated = WeakReference<_>(importsInvalidatedByTypeProvider)
ccu.Deref.InvalidateEvent.Add(fun _ ->
match capturedImportsInvalidated.TryGetTarget() with
| true, tg -> tg.Trigger()
| _ -> ()))
#endif
#if NO_TYPEPROVIDERS
ignore importsInvalidatedByTypeProvider
#endif
return tcImports
with
| :? OperationCanceledException ->
// if it's been canceled then it shouldn't be needed anymore
return frameworkTcImports
| exn ->
Debug.Assert(false, sprintf "Could not BuildAllReferencedDllTcImports %A" exn)
diagnosticsLogger.Warning exn
return frameworkTcImports
}
let tcInitial, openDecls0 =
GetInitialTcEnv(assemblyName, rangeStartup, tcConfig, tcImports, tcGlobals)
let tcState =
GetInitialTcState(rangeStartup, assemblyName, tcConfig, tcGlobals, tcImports, tcInitial, openDecls0)
let loadClosureErrors =
[
match loadClosureOpt with
| None -> ()
| Some loadClosure ->
for inp in loadClosure.Inputs do
yield! inp.MetaCommandDiagnostics
]
let initialErrors =
Array.append (Array.ofList loadClosureErrors) (diagnosticsLogger.GetDiagnostics())
let tcInfo =
{
tcState = tcState
tcEnvAtEndOfFile = tcInitial
topAttribs = None
latestCcuSigForFile = None
tcDiagnosticsRev = [ initialErrors ]
moduleNamesDict = Map.empty
tcDependencyFiles = basicDependencies
sigNameOpt = None
graphNode = None
stateContainsNodes = Set.empty
sink = []
}
return tcImports, tcInfo
}
let getProjectReferences (project: ProjectSnapshotBase<_>) userOpName =
[
for r in project.ReferencedProjects do
match r with
| FSharpReferencedProjectSnapshot.FSharpReference(nm, projectSnapshot) ->
// Don't use cross-project references for FSharp.Core, since various bits of code
// require a concrete FSharp.Core to exist on-disk. The only solutions that have
// these cross-project references to FSharp.Core are VisualFSharp.sln and FSharp.sln. The ramification
// of this is that you need to build FSharp.Core to get intellisense in those projects.
if
(try
Path.GetFileNameWithoutExtension(nm)
with _ ->
"")
<> GetFSharpCoreLibraryName()
then
{ new IProjectReference with
member x.EvaluateRawContents() =
async {
Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "GetAssemblyData", nm)
return!
self.GetAssemblyData(
projectSnapshot.ProjectSnapshot,
nm,
userOpName + ".CheckReferencedProject(" + nm + ")"
)
}
member x.TryGetLogicalTimeStamp(cache) =
// TODO:
None
member x.FileName = nm
}
| FSharpReferencedProjectSnapshot.PEReference(getStamp, delayedReader) ->
{ new IProjectReference with
member x.EvaluateRawContents() =
async {
let! ilReaderOpt = delayedReader.TryGetILModuleReader() |> Cancellable.toAsync
match ilReaderOpt with
| Some ilReader ->
let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs
let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData
return ProjectAssemblyDataResult.Available data
| _ ->
// Note 'false' - if a PEReference doesn't find an ILModuleReader then we don't
// continue to try to use an on-disk DLL
return ProjectAssemblyDataResult.Unavailable false
}
member x.TryGetLogicalTimeStamp _ = getStamp () |> Some
member x.FileName = delayedReader.OutputFile
}
| FSharpReferencedProjectSnapshot.ILModuleReference(nm, getStamp, getReader) ->
{ new IProjectReference with
member x.EvaluateRawContents() =
cancellable {
let ilReader = getReader ()
let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs
let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData
return ProjectAssemblyDataResult.Available data
}
|> Cancellable.toAsync
member x.TryGetLogicalTimeStamp _ = getStamp () |> Some
member x.FileName = nm
}
]
let ComputeTcConfigBuilder (projectSnapshot: ProjectSnapshot) =
async {
let useSimpleResolutionSwitch = "--simpleresolution"
let commandLineArgs = projectSnapshot.CommandLineOptions
let defaultFSharpBinariesDir = FSharpCheckerResultsSettings.defaultFSharpBinariesDir
let useScriptResolutionRules = projectSnapshot.UseScriptResolutionRules
let projectReferences =
getProjectReferences projectSnapshot "ComputeTcConfigBuilder"
let getSwitchValue (switchString: string) =
match commandLineArgs |> List.tryFindIndex (fun s -> s.StartsWithOrdinal switchString) with
| Some idx -> Some(commandLineArgs[idx].Substring(switchString.Length))
| _ -> None
let useSimpleResolution =
(getSwitchValue useSimpleResolutionSwitch) |> Option.isSome
let! (loadClosureOpt: LoadClosure option) =
let lastScriptFile =
match List.tryLast projectSnapshot.SourceFiles with
| None -> None
| Some file -> if IsScript file.FileName then Some file else None
match lastScriptFile, projectSnapshot.UseScriptResolutionRules with
| Some fsxFile, true -> // assuming UseScriptResolutionRules and a single source file means we are doing this for a script
async {
let! source = fsxFile.GetSource() |> Async.AwaitTask
let! closure =
ComputeScriptClosure
fsxFile.FileName
source
defaultFSharpBinariesDir
useSimpleResolution
None
None
None
None
projectSnapshot.Identifier
projectSnapshot.OtherOptions
projectSnapshot.Stamp
return (Some closure)
}
| _ -> async { return None }
let sdkDirOverride =
match loadClosureOpt with
| None -> None
| Some loadClosure -> loadClosure.SdkDirOverride
// see also fsc.fs: runFromCommandLineToImportingAssemblies(), as there are many similarities to where the PS creates a tcConfigB
let tcConfigB =
TcConfigBuilder.CreateNew(
legacyReferenceResolver,
defaultFSharpBinariesDir,
implicitIncludeDir = projectSnapshot.ProjectDirectory,
reduceMemoryUsage = ReduceMemoryFlag.Yes,
isInteractive = useScriptResolutionRules,
isInvalidationSupported = true,
defaultCopyFSharpCore = CopyFSharpCoreFlag.No,
tryGetMetadataSnapshot = tryGetMetadataSnapshot,
sdkDirOverride = sdkDirOverride,
rangeForErrors = range0
)
tcConfigB.primaryAssembly <-
match loadClosureOpt with
| None -> PrimaryAssembly.Mscorlib
| Some loadClosure ->
if loadClosure.UseDesktopFramework then
PrimaryAssembly.Mscorlib
else
PrimaryAssembly.System_Runtime
tcConfigB.resolutionEnvironment <- (LegacyResolutionEnvironment.EditingOrCompilation true)
tcConfigB.conditionalDefines <-
let define =
if useScriptResolutionRules then
"INTERACTIVE"
else
"COMPILED"
define :: tcConfigB.conditionalDefines
tcConfigB.realsig <-
List.contains "--realsig" commandLineArgs
|| List.contains "--realsig+" commandLineArgs
tcConfigB.projectReferences <- projectReferences
tcConfigB.useSimpleResolution <- useSimpleResolution
// Apply command-line arguments and collect more source files if they are in the arguments
let sourceFilesNew =
ApplyCommandLineArgs(tcConfigB, projectSnapshot.SourceFileNames, commandLineArgs)
// Never open PDB files for the language service, even if --standalone is specified
tcConfigB.openDebugInformationForLaterStaticLinking <- false
tcConfigB.xmlDocInfoLoader <-
{ new IXmlDocumentationInfoLoader with
/// Try to load xml documentation associated with an assembly by the same file path with the extension ".xml".
member _.TryLoad(assemblyFileName) =
let xmlFileName = !! Path.ChangeExtension(assemblyFileName, ".xml")
// REVIEW: File IO - Will eventually need to change this to use a file system interface of some sort.
XmlDocumentationInfo.TryCreateFromFile(xmlFileName)
}
|> Some
tcConfigB.parallelReferenceResolution <- parallelReferenceResolution
tcConfigB.captureIdentifiersWhenParsing <- captureIdentifiersWhenParsing
return tcConfigB, sourceFilesNew, loadClosureOpt
}
let mutable BootstrapInfoIdCounter = 0
/// Bootstrap info that does not depend source files
let ComputeBootstrapInfoStatic (projectSnapshot: ProjectCore, tcConfig: TcConfig, assemblyName: string, loadClosureOpt) =
let cacheKey = projectSnapshot.CacheKeyWith("BootstrapInfoStatic", assemblyName)
caches.BootstrapInfoStatic.Get(
cacheKey,
async {
use _ =
Activity.start
"ComputeBootstrapInfoStatic"
[|
Activity.Tags.project, projectSnapshot.ProjectFileName |> Path.GetFileName |> (!!)
"references", projectSnapshot.ReferencedProjects.Length.ToString()
|]
// Resolve assemblies and create the framework TcImports. This caches a level of "system" references. No type providers are
// included in these references.
let frameworkDLLs, nonFrameworkResolutions, unresolvedReferences =
TcAssemblyResolutions.SplitNonFoundationalResolutions(tcConfig)
// Prepare the frameworkTcImportsCache
let! tcGlobals, frameworkTcImports = ComputeFrameworkImports tcConfig frameworkDLLs nonFrameworkResolutions
// Note we are not calling diagnosticsLogger.GetDiagnostics() anywhere for this task.
// This is ok because not much can actually go wrong here.
let diagnosticsLogger =
CompilationDiagnosticLogger("nonFrameworkAssemblyInputs", tcConfig.diagnosticsOptions)
use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parameter)
let tcConfigP = TcConfigProvider.Constant tcConfig
let importsInvalidatedByTypeProvider = Event<unit>()
let basicDependencies =
[
for UnresolvedAssemblyReference(referenceText, _) in unresolvedReferences do
// Exclude things that are definitely not a file name
if not (FileSystem.IsInvalidPathShim referenceText) then
let file =
if FileSystem.IsPathRootedShim referenceText then
referenceText
else
Path.Combine(projectSnapshot.ProjectDirectory, referenceText)
yield file
for r in nonFrameworkResolutions do
yield r.resolvedPath
]
// For scripts, the dependency provider is already available.
// For projects create a fresh one for the project.
let dependencyProvider =
if projectSnapshot.UseScriptResolutionRules then
dependencyProviderForScripts
else
new DependencyProvider()
let! tcImports, initialTcInfo =
CombineImportedAssembliesTask(
assemblyName,
tcConfig,
tcConfigP,
tcGlobals,
frameworkTcImports,
nonFrameworkResolutions,
unresolvedReferences,
dependencyProvider,
loadClosureOpt,
basicDependencies,
importsInvalidatedByTypeProvider
)
let bootstrapId = Interlocked.Increment &BootstrapInfoIdCounter
// TODO: In the future it might make sense to expose the event on the ProjectSnapshot and let the consumer deal with this.
// We could include a timestamp as part of the ProjectSnapshot key that represents the last time since the TypeProvider assembly was invalidated.
// When the event trigger, the consumer could then create a new snapshot based on the updated time.
importsInvalidatedByTypeProvider.Publish.Add(fun () -> caches.Clear(Set.singleton projectSnapshot.Identifier))
return bootstrapId, tcImports, tcGlobals, initialTcInfo, importsInvalidatedByTypeProvider
}
)
let computeBootstrapInfoInner (projectSnapshot: ProjectSnapshot) =
async {
let! tcConfigB, sourceFiles, loadClosureOpt = ComputeTcConfigBuilder projectSnapshot
// If this is a builder for a script, re-apply the settings inferred from the
// script and its load closure to the configuration.
//
// NOTE: it would probably be cleaner and more accurate to re-run the load closure at this point.
let setupConfigFromLoadClosure () =
match loadClosureOpt with
| Some loadClosure ->
let dllReferences =
[
for reference in tcConfigB.referencedDLLs do
// If there's (one or more) resolutions of closure references then yield them all
match
loadClosure.References
|> List.tryFind (fun (resolved, _) -> resolved = reference.Text)
with
| Some(resolved, closureReferences) ->
for closureReference in closureReferences do
yield AssemblyReference(closureReference.originalReference.Range, resolved, None)
| None -> yield reference
]
tcConfigB.referencedDLLs <- []
tcConfigB.primaryAssembly <-
(if loadClosure.UseDesktopFramework then
PrimaryAssembly.Mscorlib
else
PrimaryAssembly.System_Runtime)
// Add one by one to remove duplicates
dllReferences
|> List.iter (fun dllReference -> tcConfigB.AddReferencedAssemblyByPath(dllReference.Range, dllReference.Text))
tcConfigB.knownUnresolvedReferences <- loadClosure.UnresolvedReferences
| None -> ()
setupConfigFromLoadClosure ()
let tcConfig = TcConfig.Create(tcConfigB, validate = true)
let outFile, _, assemblyName = tcConfigB.DecideNames sourceFiles
let! bootstrapId, tcImports, tcGlobals, initialTcInfo, importsInvalidatedByTypeProvider =
ComputeBootstrapInfoStatic(projectSnapshot.ProjectCore, tcConfig, assemblyName, loadClosureOpt)
// Check for the existence of loaded sources and prepend them to the sources list if present.
let loadedSources =
tcConfig.GetAvailableLoadedSources()
|> List.map (fun (m, fileName) -> m, FSharpFileSnapshot.CreateFromFileSystem(fileName))
return
match sourceFiles with
| [] -> None
| _ ->
Some
{
Id = bootstrapId
AssemblyName = assemblyName
OutFile = outFile
TcConfig = tcConfig
TcImports = tcImports
TcGlobals = tcGlobals
InitialTcInfo = initialTcInfo
LoadedSources = loadedSources
LoadClosure = loadClosureOpt
LastFileName = sourceFiles |> List.tryLast |> Option.defaultValue ""
ImportsInvalidatedByTypeProvider = importsInvalidatedByTypeProvider
}
}
let ComputeBootstrapInfo (projectSnapshot: ProjectSnapshot) =
caches.BootstrapInfo.Get(
projectSnapshot.NoFileVersionsKey,
async {
use _ =
Activity.start
"ComputeBootstrapInfo"
[|
Activity.Tags.project, projectSnapshot.ProjectFileName |> Path.GetFileName |> (!!)
|]