-
Notifications
You must be signed in to change notification settings - Fork 802
/
Copy pathIncrementalBuild.fs
1652 lines (1400 loc) · 72.2 KB
/
IncrementalBuild.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.
namespace FSharp.Compiler.CodeAnalysis
open System
open System.Collections.Generic
open System.Collections.Immutable
open System.Diagnostics
open System.IO
open System.Threading
open Internal.Utilities.Library
open Internal.Utilities.Collections
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.CheckBasics
open FSharp.Compiler.CheckDeclarations
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.CompilerOptions
open FSharp.Compiler.CreateILModule
open FSharp.Compiler.DependencyManager
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.EditorServices
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.IO
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.NameResolution
open FSharp.Compiler.ParseAndCheckInputs
open FSharp.Compiler.ScriptClosure
open FSharp.Compiler.Syntax
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Xml
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.BuildGraph
[<AutoOpen>]
module internal IncrementalBuild =
let mutable injectCancellationFault = false
let LocallyInjectCancellationFault() =
injectCancellationFault <- true
{ new IDisposable with member _.Dispose() = injectCancellationFault <- false }
// Record the most recent IncrementalBuilder events, so we can more easily unit test/debug the
// 'incremental' behavior of the product.
module IncrementalBuilderEventTesting =
type internal FixedLengthMRU<'T>() =
let MAX = 400 // Length of the MRU. For our current unit tests, 400 is enough.
let data = Array.create MAX None
let mutable curIndex = 0
let mutable numAdds = 0
// called by the product, to note when a parse/typecheck happens for a file
member _.Add(fileName:'T) =
numAdds <- numAdds + 1
data[curIndex] <- Some fileName
curIndex <- (curIndex + 1) % MAX
member _.CurrentEventNum = numAdds
// called by unit tests, returns 'n' most recent additions.
member _.MostRecentList(n: int) : 'T list =
if n < 0 || n > MAX then
raise <| ArgumentOutOfRangeException("n", sprintf "n must be between 0 and %d, inclusive, but got %d" MAX n)
let mutable remaining = n
let mutable s = []
let mutable i = curIndex - 1
while remaining <> 0 do
if i < 0 then
i <- MAX - 1
match data[i] with
| None -> ()
| Some x -> s <- x :: s
i <- i - 1
remaining <- remaining - 1
List.rev s
type IBEvent =
| IBEParsed of fileName: string
| IBETypechecked of fileName: string
| IBECreated
// ++GLOBAL MUTABLE STATE FOR TESTING++
let MRU = FixedLengthMRU<IBEvent>()
let GetMostRecentIncrementalBuildEvents n = MRU.MostRecentList n
let GetCurrentIncrementalBuildEventNum() = MRU.CurrentEventNum
module Tc = CheckExpressions
type internal FSharpFile = {
Range: range
Source: FSharpSource
Flags: bool * bool
}
// This module is only here to contain the SyntaxTree type as to avoid ambiguity with the module FSharp.Compiler.Syntax.
[<AutoOpen>]
module IncrementalBuildSyntaxTree =
type ParseResult = ParsedInput * range * string * (PhasedDiagnostic * FSharpDiagnosticSeverity) array
/// Information needed to lazily parse a file to get a ParsedInput. Internally uses a weak cache.
[<Sealed>]
type SyntaxTree (
tcConfig: TcConfig,
fileParsed: Event<string>,
lexResourceManager,
file: FSharpFile,
hasSignature
) =
let fileName = file.Source.FilePath
let sourceRange = file.Range
let source = file.Source
let isLastCompiland = file.Flags
let skippedImplFilePlaceholder sigName =
ParsedInput.ImplFile(
ParsedImplFileInput(
fileName,
false,
sigName,
[],
[],
[],
isLastCompiland,
{ ConditionalDirectives = []; CodeComments = [] },
Set.empty
)
), sourceRange, fileName, [||]
let parse (source: FSharpSource) =
node {
IncrementalBuilderEventTesting.MRU.Add(IncrementalBuilderEventTesting.IBEParsed fileName)
use _ =
Activity.start "IncrementalBuildSyntaxTree.parse"
[|
Activity.Tags.fileName, fileName
Activity.Tags.buildPhase, BuildPhase.Parse.ToString()
|]
try
let diagnosticsLogger = CompilationDiagnosticLogger("Parse", tcConfig.diagnosticsOptions)
// Return the disposable object that cleans up
use _holder = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parse)
use! text = source.GetTextContainer() |> NodeCode.AwaitAsync
let input =
match text :?> TextContainer with
| TextContainer.Stream(stream) ->
ParseOneInputStream(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, false, stream)
| TextContainer.SourceText(sourceText) ->
ParseOneInputSourceText(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText)
| TextContainer.OnDisk ->
ParseOneInputFile(tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, true)
fileParsed.Trigger fileName
return input, sourceRange, fileName, diagnosticsLogger.GetDiagnostics()
with exn ->
let msg = sprintf "unexpected failure in SyntaxTree.parse\nerror = %s" (exn.ToString())
System.Diagnostics.Debug.Assert(false, msg)
failwith msg
return Unchecked.defaultof<_>
}
/// Parse the given file and return the given input.
member val ParseNode : GraphNode<ParseResult> = parse source |> GraphNode
member _.Invalidate() =
SyntaxTree(tcConfig, fileParsed, lexResourceManager, file, hasSignature)
member _.Skip = skippedImplFilePlaceholder
member _.FileName = fileName
member _.HasSignature = hasSignature
member _.SourceRange = sourceRange
/// Accumulated results of type checking. The minimum amount of state in order to continue type-checking following files.
[<NoEquality; NoComparison>]
type 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
}
member x.TcDiagnostics =
Array.concat (List.rev x.tcDiagnosticsRev)
/// Accumulated results of type checking. Optional data that isn't needed to type-check a file, but needed for more information for in tooling.
[<NoEquality; NoComparison>]
type TcInfoExtras =
{
tcResolutions: TcResolutions
tcSymbolUses: TcSymbolUses
tcOpenDeclarations: OpenDeclaration[]
/// Result of checking most recent file, if any
latestImplFile: CheckedImplFile option
/// If enabled, stores a linear list of ranges and strings that identify an Item(symbol) in a file. Used for background find all references.
itemKeyStore: ItemKeyStore option
/// If enabled, holds semantic classification information for Item(symbol)s in a file.
semanticClassificationKeyStore: SemanticClassificationKeyStore option
}
member x.TcSymbolUses =
x.tcSymbolUses
module ValueOption =
let toOption = function
| ValueSome x -> Some x
| _ -> None
type private SingleFileDiagnostics = (PhasedDiagnostic * FSharpDiagnosticSeverity) array
type private TypeCheck = TcInfo * TcResultsSinkImpl * CheckedImplFile option * string * SingleFileDiagnostics
/// Bound model of an underlying syntax and typed tree.
type BoundModel private (
tcConfig: TcConfig,
tcGlobals,
tcImports: TcImports,
keepAssemblyContents, keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked: Event<string>,
fileChecked: Event<string>,
prevTcInfo: TcInfo,
syntaxTreeOpt: SyntaxTree option,
?tcStateOpt: GraphNode<TcInfo> * GraphNode<TcInfoExtras>
) =
let getTypeCheck (syntaxTree: SyntaxTree) : NodeCode<TypeCheck> =
node {
let! input, _sourceRange, fileName, parseErrors = syntaxTree.ParseNode.GetOrComputeValue()
use _ = Activity.start "BoundModel.TypeCheck" [|Activity.Tags.fileName, fileName|]
IncrementalBuilderEventTesting.MRU.Add(IncrementalBuilderEventTesting.IBETypechecked fileName)
let capturingDiagnosticsLogger = CapturingDiagnosticsLogger("TypeCheck")
let diagnosticsLogger = GetDiagnosticsLoggerFilteringByScopedPragmas(false, input.ScopedPragmas, tcConfig.diagnosticsOptions, capturingDiagnosticsLogger)
use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.TypeCheck)
beforeFileChecked.Trigger fileName
ApplyMetaCommandsFromInputToTcConfig (tcConfig, input, Path.GetDirectoryName fileName, tcImports.DependencyProvider) |> ignore
let sink = TcResultsSinkImpl(tcGlobals)
let hadParseErrors = not (Array.isEmpty parseErrors)
let input, moduleNamesDict = DeduplicateParsedInputModuleName prevTcInfo.moduleNamesDict input
let! (tcEnvAtEndOfFile, topAttribs, implFile, ccuSigForFile), tcState =
CheckOneInput (
(fun () -> hadParseErrors || diagnosticsLogger.ErrorCount > 0),
tcConfig, tcImports,
tcGlobals,
None,
TcResultsSink.WithSink sink,
prevTcInfo.tcState, input )
|> NodeCode.FromCancellable
fileChecked.Trigger fileName
let newErrors = Array.append parseErrors (capturingDiagnosticsLogger.Diagnostics |> List.toArray)
let tcEnvAtEndOfFile = if keepAllBackgroundResolutions then tcEnvAtEndOfFile else tcState.TcEnvFromImpls
let tcInfo =
{
tcState = tcState
tcEnvAtEndOfFile = tcEnvAtEndOfFile
moduleNamesDict = moduleNamesDict
latestCcuSigForFile = Some ccuSigForFile
tcDiagnosticsRev = newErrors :: prevTcInfo.tcDiagnosticsRev
topAttribs = Some topAttribs
tcDependencyFiles = fileName :: prevTcInfo.tcDependencyFiles
sigNameOpt =
match input with
| ParsedInput.SigFile sigFile ->
Some(sigFile.FileName, sigFile.QualifiedName)
| _ ->
None
}
return tcInfo, sink, implFile, fileName, newErrors
}
let skippedImplemetationTypeCheck =
match syntaxTreeOpt, prevTcInfo.sigNameOpt with
| Some syntaxTree, Some (_, qualifiedName) when syntaxTree.HasSignature ->
let input, _, fileName, _ = syntaxTree.Skip qualifiedName
SkippedImplFilePlaceholder(tcConfig, tcImports, tcGlobals, prevTcInfo.tcState, input)
|> Option.map (fun ((_, topAttribs, _, ccuSigForFile), tcState) ->
{
tcState = tcState
tcEnvAtEndOfFile = tcState.TcEnvFromImpls
moduleNamesDict = prevTcInfo.moduleNamesDict
latestCcuSigForFile = Some ccuSigForFile
tcDiagnosticsRev = prevTcInfo.tcDiagnosticsRev
topAttribs = Some topAttribs
tcDependencyFiles = fileName :: prevTcInfo.tcDependencyFiles
sigNameOpt = Some(fileName, qualifiedName)
})
| _ -> None
let getTcInfo (typeCheck: GraphNode<TypeCheck>) =
node {
let! tcInfo , _, _, _, _ = typeCheck.GetOrComputeValue()
return tcInfo
} |> GraphNode
let getTcInfoExtras (typeCheck: GraphNode<TypeCheck>) =
node {
let! _ , sink, implFile, fileName, _ = typeCheck.GetOrComputeValue()
// Build symbol keys
let itemKeyStore, semanticClassification =
if enableBackgroundItemKeyStoreAndSemanticClassification then
use _ = Activity.start "IncrementalBuild.CreateItemKeyStoreAndSemanticClassification" [|Activity.Tags.fileName, fileName|]
let sResolutions = sink.GetResolutions()
let builder = ItemKeyStoreBuilder(tcGlobals)
let preventDuplicates = HashSet({ new IEqualityComparer<struct(pos * pos)> with
member _.Equals((s1, e1): struct(pos * pos), (s2, e2): struct(pos * pos)) = Position.posEq s1 s2 && Position.posEq e1 e2
member _.GetHashCode o = o.GetHashCode() })
sResolutions.CapturedNameResolutions
|> Seq.iter (fun cnr ->
let r = cnr.Range
if preventDuplicates.Add struct(r.Start, r.End) then
builder.Write(cnr.Range, cnr.Item))
let semanticClassification = sResolutions.GetSemanticClassification(tcGlobals, tcImports.GetImportMap(), sink.GetFormatSpecifierLocations(), None)
let sckBuilder = SemanticClassificationKeyStoreBuilder()
sckBuilder.WriteAll semanticClassification
let res = builder.TryBuildAndReset(), sckBuilder.TryBuildAndReset()
res
else
None, None
return
{
// Only keep the typed interface files when doing a "full" build for fsc.exe, otherwise just throw them away
latestImplFile = if keepAssemblyContents then implFile else None
tcResolutions = (if keepAllBackgroundResolutions then sink.GetResolutions() else TcResolutions.Empty)
tcSymbolUses = (if keepAllBackgroundSymbolUses then sink.GetSymbolUses() else TcSymbolUses.Empty)
tcOpenDeclarations = sink.GetOpenDeclarations()
itemKeyStore = itemKeyStore
semanticClassificationKeyStore = semanticClassification
}
} |> GraphNode
let defaultTypeCheck = node { return prevTcInfo, TcResultsSinkImpl(tcGlobals), None, "default typecheck - no syntaxTree", [||] }
let typeCheckNode = syntaxTreeOpt |> Option.map getTypeCheck |> Option.defaultValue defaultTypeCheck |> GraphNode
let tcInfoExtras = getTcInfoExtras typeCheckNode
let diagnostics =
node {
let! _, _, _, _, diags = typeCheckNode.GetOrComputeValue()
return diags
} |> GraphNode
let startComputingFullTypeCheck =
node {
let! _ = tcInfoExtras.GetOrComputeValue()
return! diagnostics.GetOrComputeValue()
}
let tcInfo, tcInfoExtras =
match tcStateOpt with
| Some tcState -> tcState
| _ ->
match skippedImplemetationTypeCheck with
| Some tcInfo ->
// For skipped implementation sources do full type check only when requested.
GraphNode.FromResult tcInfo, tcInfoExtras
| _ ->
// start computing extras, so that typeCheckNode can be GC'd quickly
startComputingFullTypeCheck |> Async.AwaitNodeCode |> Async.Catch |> Async.Ignore |> Async.Start
getTcInfo typeCheckNode, tcInfoExtras
member val Diagnostics = diagnostics
member val TcInfo = tcInfo
member val TcInfoExtras = tcInfoExtras
member _.TcConfig = tcConfig
member _.TcGlobals = tcGlobals
member _.TcImports = tcImports
member this.TryPeekTcInfo() = this.TcInfo.TryPeekValue() |> ValueOption.toOption
member this.TryPeekTcInfoWithExtras() =
(this.TcInfo.TryPeekValue(), this.TcInfoExtras.TryPeekValue())
||> ValueOption.map2 (fun a b -> a, b)
|> ValueOption.toOption
member this.GetOrComputeTcInfo = this.TcInfo.GetOrComputeValue
member this.GetOrComputeTcInfoExtras = this.TcInfoExtras.GetOrComputeValue
member this.GetOrComputeTcInfoWithExtras() = node {
let! tcInfo = this.TcInfo.GetOrComputeValue()
let! tcInfoExtras = this.TcInfoExtras.GetOrComputeValue()
return tcInfo, tcInfoExtras
}
member this.Next(syntaxTree) = node {
let! tcInfo = this.TcInfo.GetOrComputeValue()
return
BoundModel(
tcConfig,
tcGlobals,
tcImports,
keepAssemblyContents,
keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked,
fileChecked,
tcInfo,
Some syntaxTree
)
}
member this.Finish(finalTcDiagnosticsRev, finalTopAttribs) =
node {
let! tcInfo = this.TcInfo.GetOrComputeValue()
let finishState = { tcInfo with tcDiagnosticsRev = finalTcDiagnosticsRev; topAttribs = finalTopAttribs }
return
BoundModel(
tcConfig,
tcGlobals,
tcImports,
keepAssemblyContents,
keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked,
fileChecked,
prevTcInfo,
syntaxTreeOpt,
(GraphNode.FromResult finishState, this.TcInfoExtras)
)
}
static member Create(
tcConfig: TcConfig,
tcGlobals: TcGlobals,
tcImports: TcImports,
keepAssemblyContents, keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked: Event<string>,
fileChecked: Event<string>,
prevTcInfo: TcInfo,
syntaxTreeOpt: SyntaxTree option
) =
BoundModel(
tcConfig, tcGlobals, tcImports,
keepAssemblyContents, keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked,
fileChecked,
prevTcInfo,
syntaxTreeOpt
)
/// Global service state
type FrameworkImportsCacheKey =
| FrameworkImportsCacheKey of resolvedpath: string list * assemblyName: string * targetFrameworkDirectories: string list * fsharpBinaries: string * langVersion: decimal
interface ICacheKey<string, FrameworkImportsCacheKey> with
member this.GetKey() =
this |> function FrameworkImportsCacheKey(assemblyName=a) -> a
member this.GetLabel() =
this |> function FrameworkImportsCacheKey(assemblyName=a) -> a
member this.GetVersion() = this
/// Represents a cache of 'framework' references that can be shared between multiple incremental builds
type FrameworkImportsCache(size) =
let gate = obj()
// Mutable collection protected via CompilationThreadToken
let frameworkTcImportsCache = AgedLookup<AnyCallerThreadToken, FrameworkImportsCacheKey, GraphNode<TcGlobals * TcImports>>(size, areSimilar=(fun (x, y) -> x = y))
/// Reduce the size of the cache in low-memory scenarios
member _.Downsize() = frameworkTcImportsCache.Resize(AnyCallerThread, newKeepStrongly=0)
/// Clear the cache
member _.Clear() = frameworkTcImportsCache.Clear AnyCallerThread
/// This function strips the "System" assemblies from the tcConfig and returns a age-cached TcImports for them.
member _.GetNode(tcConfig: TcConfig, frameworkDLLs: AssemblyResolution list, nonFrameworkResolutions: AssemblyResolution list) =
let frameworkDLLsKey =
frameworkDLLs
|> List.map (fun ar->ar.resolvedPath) // The cache key. Just the minimal data.
|> List.sort // Sort to promote cache hits.
// Prepare the frameworkTcImportsCache
//
// 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)
let node =
lock gate (fun () ->
match frameworkTcImportsCache.TryGet (AnyCallerThread, key) with
| Some lazyWork -> lazyWork
| None ->
let lazyWork = GraphNode(node {
let tcConfigP = TcConfigProvider.Constant tcConfig
return! TcImports.BuildFrameworkTcImports (tcConfigP, frameworkDLLs, nonFrameworkResolutions)
})
frameworkTcImportsCache.Put(AnyCallerThread, key, lazyWork)
lazyWork
)
node
/// This function strips the "System" assemblies from the tcConfig and returns a age-cached TcImports for them.
member this.Get(tcConfig: TcConfig) =
node {
// Split into installed and not installed.
let frameworkDLLs, nonFrameworkResolutions, unresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(tcConfig)
let node = this.GetNode(tcConfig, frameworkDLLs, nonFrameworkResolutions)
let! tcGlobals, frameworkTcImports = node.GetOrComputeValue()
return tcGlobals, frameworkTcImports, nonFrameworkResolutions, unresolved
}
/// Represents the interim state of checking an assembly
[<Sealed>]
type PartialCheckResults (boundModel: BoundModel, timeStamp: DateTime, projectTimeStamp: DateTime) =
member _.TcImports = boundModel.TcImports
member _.TcGlobals = boundModel.TcGlobals
member _.TcConfig = boundModel.TcConfig
member _.TimeStamp = timeStamp
member _.ProjectTimeStamp = projectTimeStamp
member _.TryPeekTcInfo() = boundModel.TryPeekTcInfo()
member _.TryPeekTcInfoWithExtras() = boundModel.TryPeekTcInfoWithExtras()
member _.GetOrComputeTcInfo() = boundModel.GetOrComputeTcInfo()
member _.GetOrComputeTcInfoWithExtras() = boundModel.GetOrComputeTcInfoWithExtras()
member _.GetOrComputeItemKeyStoreIfEnabled() =
node {
let! info = boundModel.GetOrComputeTcInfoExtras()
return info.itemKeyStore
}
member _.GetOrComputeSemanticClassificationIfEnabled() =
node {
let! info = boundModel.GetOrComputeTcInfoExtras()
return info.semanticClassificationKeyStore
}
[<AutoOpen>]
module Utilities =
let TryFindFSharpStringAttribute tcGlobals attribSpec attribs =
match TryFindFSharpAttribute tcGlobals attribSpec attribs with
| Some (Attrib(_, _, [ AttribStringArg s ], _, _, _, _)) -> Some s
| _ -> None
/// The implementation of the information needed by TcImports in CompileOps.fs for an F# assembly reference.
///
/// Constructs the build data (IRawFSharpAssemblyData) representing the assembly when used
/// as a cross-assembly reference. Note the assembly has not been generated on disk, so this is
/// a virtualized view of the assembly contents as computed by background checking.
[<Sealed>]
type RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, generatedCcu: CcuThunk, outfile, topAttrs, assemblyName, ilAssemRef) =
let exportRemapping = MakeExportRemapping generatedCcu generatedCcu.Contents
let sigData =
let _sigDataAttributes, sigDataResources = EncodeSignatureData(tcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, true)
[ for r in sigDataResources do
GetResourceNameAndSignatureDataFunc r
]
let autoOpenAttrs = topAttrs.assemblyAttrs |> List.choose (List.singleton >> TryFindFSharpStringAttribute tcGlobals tcGlobals.attrib_AutoOpenAttribute)
let ivtAttrs = topAttrs.assemblyAttrs |> List.choose (List.singleton >> TryFindFSharpStringAttribute tcGlobals tcGlobals.attrib_InternalsVisibleToAttribute)
interface IRawFSharpAssemblyData with
member _.GetAutoOpenAttributes() = autoOpenAttrs
member _.GetInternalsVisibleToAttributes() = ivtAttrs
member _.TryGetILModuleDef() = None
member _.GetRawFSharpSignatureData(_m, _ilShortAssemName, _filename) = sigData
member _.GetRawFSharpOptimizationData(_m, _ilShortAssemName, _filename) = [ ]
member _.GetRawTypeForwarders() = mkILExportedTypes [] // TODO: cross-project references with type forwarders
member _.ShortAssemblyName = assemblyName
member _.ILScopeRef = ILScopeRef.Assembly ilAssemRef
member _.ILAssemblyRefs = [] // These are not significant for service scenarios
member _.HasAnyFSharpSignatureDataAttribute = true
member _.HasMatchingFSharpSignatureDataAttribute = true
[<AutoOpen>]
module IncrementalBuilderHelpers =
/// Timestamps of referenced assemblies are taken from the file's timestamp.
let StampReferencedAssemblyTask (cache: TimeStampCache) (_ref, timeStamper) =
timeStamper cache
// 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,
keepAssemblyContents,
keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked,
fileChecked
#if !NO_TYPEPROVIDERS
,importsInvalidatedByTypeProvider: Event<unit>
#endif
) : NodeCode<BoundModel * SingleFileDiagnostics> =
node {
let diagnosticsLogger = CompilationDiagnosticLogger("CombineImportedAssembliesTask", tcConfig.diagnosticsOptions)
use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.Parameter)
let! tcImports =
node {
try
let! tcImports = TcImports.BuildNonFrameworkTcImports(tcConfigP, frameworkTcImports, nonFrameworkResolutions, unresolvedReferences, dependencyProvider)
#if !NO_TYPEPROVIDERS
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
return tcImports
with 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
}
return
BoundModel.Create(
tcConfig,
tcGlobals,
tcImports,
keepAssemblyContents,
keepAllBackgroundResolutions,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
beforeFileChecked,
fileChecked,
tcInfo,
None
), initialErrors
}
/// Finish up the typechecking to produce outputs for the rest of the compilation process
let FinalizeTypeCheckTask (tcConfig: TcConfig) tcGlobals partialCheck assemblyName outfile (boundModels: GraphNode<BoundModel> seq) =
node {
let diagnosticsLogger = CompilationDiagnosticLogger("FinalizeTypeCheckTask", tcConfig.diagnosticsOptions)
use _ = new CompilationGlobalsScope(diagnosticsLogger, BuildPhase.TypeCheck)
let! computedBoundModels = boundModels |> Seq.map (fun g -> g.GetOrComputeValue()) |> NodeCode.Sequential
let! tcInfos =
computedBoundModels
|> Seq.map (fun boundModel -> node { return! boundModel.GetOrComputeTcInfo() })
|> NodeCode.Sequential
// tcInfoExtras can be computed in parallel. This will check any previously skipped implementation files in parallel, too.
let! latestImplFiles =
computedBoundModels
|> Seq.map (fun boundModel -> node {
if partialCheck then
return None
else
let! tcInfoExtras = boundModel.GetOrComputeTcInfoExtras()
return tcInfoExtras.latestImplFile
})
|> NodeCode.Parallel
let results = [
for tcInfo, latestImplFile in Seq.zip tcInfos latestImplFiles ->
tcInfo.tcEnvAtEndOfFile, defaultArg tcInfo.topAttribs EmptyTopAttrs, latestImplFile, tcInfo.latestCcuSigForFile
]
// Get the state at the end of the type-checking of the last file
let finalInfo = Array.last tcInfos
// Finish the checking
let (_tcEnvAtEndOfLastFile, topAttrs, mimpls, _), tcState =
CheckMultipleInputsFinish (results, finalInfo.tcState)
let ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt =
try
let tcState, tcAssemblyExpr, ccuContents = CheckClosedInputSetFinish (mimpls, tcState)
let generatedCcu = tcState.Ccu.CloneWithFinalizedContents(ccuContents)
// Compute the identity of the generated assembly based on attributes, options etc.
// Some of this is duplicated from fsc.fs
let ilAssemRef =
let publicKey =
try
let signingInfo = ValidateKeySigningAttributes (tcConfig, tcGlobals, topAttrs)
match GetStrongNameSigner signingInfo with
| None -> None
| Some s -> Some (PublicKey.KeyAsToken(s.PublicKey))
with exn ->
errorRecoveryNoRange exn
None
let locale = TryFindFSharpStringAttribute tcGlobals (tcGlobals.FindSysAttrib "System.Reflection.AssemblyCultureAttribute") topAttrs.assemblyAttrs
let assemVerFromAttrib =
TryFindFSharpStringAttribute tcGlobals (tcGlobals.FindSysAttrib "System.Reflection.AssemblyVersionAttribute") topAttrs.assemblyAttrs
|> Option.bind (fun v -> try Some (parseILVersion v) with _ -> None)
let ver =
match assemVerFromAttrib with
| None -> tcConfig.version.GetVersionInfo(tcConfig.implicitIncludeDir)
| Some v -> v
ILAssemblyRef.Create(assemblyName, None, publicKey, false, Some ver, locale)
let tcAssemblyDataOpt =
try
// Assemblies containing type provider components can not successfully be used via cross-assembly references.
// We return 'None' for the assembly portion of the cross-assembly reference
let hasTypeProviderAssemblyAttrib =
topAttrs.assemblyAttrs |> List.exists (fun (Attrib(tcref, _, _, _, _, _, _)) ->
let nm = tcref.CompiledRepresentationForNamedType.BasicQualifiedName
nm = typeof<Microsoft.FSharp.Core.CompilerServices.TypeProviderAssemblyAttribute>.FullName)
if tcState.CreatesGeneratedProvidedTypes || hasTypeProviderAssemblyAttrib then
ProjectAssemblyDataResult.Unavailable true
else
ProjectAssemblyDataResult.Available (RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, generatedCcu, outfile, topAttrs, assemblyName, ilAssemRef) :> IRawFSharpAssemblyData)
with exn ->
errorRecoveryNoRange exn
ProjectAssemblyDataResult.Unavailable true
ilAssemRef, tcAssemblyDataOpt, Some tcAssemblyExpr
with exn ->
errorRecoveryNoRange exn
mkSimpleAssemblyRef assemblyName, ProjectAssemblyDataResult.Unavailable true, None
let finalBoundModel = Array.last computedBoundModels
// Collect diagnostics. This will type check in parallel any implementation files skipped so far.
let! partialDiagnostics =
computedBoundModels
|> Seq.map (fun m -> m.Diagnostics.GetOrComputeValue())
|> NodeCode.Parallel
let diagnostics = [
diagnosticsLogger.GetDiagnostics()
yield! partialDiagnostics |> Seq.rev
]
let! finalBoundModelWithErrors = finalBoundModel.Finish(diagnostics, Some topAttrs)
return ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt, finalBoundModelWithErrors
}
[<NoComparison;NoEquality>]
type IncrementalBuilderInitialState =
{
initialBoundModel: BoundModel
initialErrors: SingleFileDiagnostics
tcGlobals: TcGlobals
referencedAssemblies: ImmutableArray<Choice<string, IProjectReference> * (TimeStampCache -> DateTime)>
tcConfig: TcConfig
outfile: string
assemblyName: string
lexResourceManager: Lexhelp.LexResourceManager
fileNames: FSharpFile list
enablePartialTypeChecking: bool
beforeFileChecked: Event<string>
fileChecked: Event<string>
fileParsed: Event<string>
projectChecked: Event<unit>
#if !NO_TYPEPROVIDERS
importsInvalidatedByTypeProvider: Event<unit>
#endif
allDependencies: string []
defaultTimeStamp: DateTime
mutable isImportsInvalidated: bool
useChangeNotifications: bool
useSyntaxTreeCache: bool
}
static member Create
(
initialBoundModel: BoundModel,
initialErrors: SingleFileDiagnostics,
tcGlobals,
nonFrameworkAssemblyInputs,
tcConfig: TcConfig,
outfile,
assemblyName,
lexResourceManager,
sourceFiles,
enablePartialTypeChecking,
beforeFileChecked: Event<string>,
fileChecked: Event<string>,
#if !NO_TYPEPROVIDERS
importsInvalidatedByTypeProvider: Event<unit>,
#endif
allDependencies,
defaultTimeStamp: DateTime,
useChangeNotifications: bool,
useSyntaxTreeCache
) =
let initialState =
{
initialBoundModel = initialBoundModel
initialErrors = initialErrors
tcGlobals = tcGlobals
referencedAssemblies = nonFrameworkAssemblyInputs |> ImmutableArray.ofSeq
tcConfig = tcConfig
outfile = outfile
assemblyName = assemblyName
lexResourceManager = lexResourceManager
fileNames = sourceFiles
enablePartialTypeChecking = enablePartialTypeChecking
beforeFileChecked = beforeFileChecked
fileChecked = fileChecked
fileParsed = Event<string>()
projectChecked = Event<unit>()
#if !NO_TYPEPROVIDERS
importsInvalidatedByTypeProvider = importsInvalidatedByTypeProvider
#endif
allDependencies = allDependencies
defaultTimeStamp = defaultTimeStamp
isImportsInvalidated = false
useChangeNotifications = useChangeNotifications
useSyntaxTreeCache = useSyntaxTreeCache
}
#if !NO_TYPEPROVIDERS
importsInvalidatedByTypeProvider.Publish.Add(fun () -> initialState.isImportsInvalidated <- true)
#endif
initialState
// Stamp represent the real stamp of the file.
// Notified indicates that there is pending file change.
// LogicalStamp represent the stamp of the file that is used to calculate the project's logical timestamp.
type Slot =
{
HasSignature: bool
Stamp: DateTime
LogicalStamp: DateTime
SyntaxTree: SyntaxTree
Notified: bool
BoundModel: GraphNode<BoundModel>
}
member this.Notify timeStamp =
if this.Stamp <> timeStamp then { this with Stamp = timeStamp; Notified = true } else this
[<NoComparison;NoEquality>]
type IncrementalBuilderState =
{
slots: Slot list
stampedReferencedAssemblies: ImmutableArray<DateTime>
finalizedBoundModel: GraphNode<(ILAssemblyRef * ProjectAssemblyDataResult * CheckedImplFile list option * BoundModel) * DateTime>
}
member this.stampedFileNames = this.slots |> List.map (fun s -> s.Stamp)
member this.logicalStampedFileNames = this.slots |> List.map (fun s -> s.LogicalStamp)
member this.boundModels = this.slots |> List.map (fun s -> s.BoundModel)
[<AutoOpen>]
module IncrementalBuilderStateHelpers =
// Used to thread the status of the build in computeStampedFileNames mapFold.
type BuildStatus = Invalidated | Good
let createBoundModelGraphNode (prevBoundModel: GraphNode<BoundModel>) syntaxTree =
GraphNode(node {
let! prevBoundModel = prevBoundModel.GetOrComputeValue()
return! prevBoundModel.Next(syntaxTree)
})
let createFinalizeBoundModelGraphNode (initialState: IncrementalBuilderInitialState) (boundModels: GraphNode<BoundModel> seq) =
GraphNode(node {
use _ = Activity.start "GetCheckResultsAndImplementationsForProject" [|Activity.Tags.project, initialState.outfile|]
let! result =
FinalizeTypeCheckTask
initialState.tcConfig
initialState.tcGlobals
initialState.enablePartialTypeChecking
initialState.assemblyName
initialState.outfile
boundModels
return result, DateTime.UtcNow
})
let computeStampedFileNames (initialState: IncrementalBuilderInitialState) (state: IncrementalBuilderState) (cache: TimeStampCache) =
let slots =
if initialState.useChangeNotifications then
state.slots
else
[ for slot in state.slots -> cache.GetFileTimeStamp slot.SyntaxTree.FileName |> slot.Notify ]
let slots =
[ for slot in slots do
if slot.Notified then { slot with SyntaxTree = slot.SyntaxTree.Invalidate() } else slot ]
let mapping (status, prevNode) slot =
let update newStatus =
let boundModel = createBoundModelGraphNode prevNode slot.SyntaxTree
{ slot with
LogicalStamp = slot.Stamp
Notified = false
BoundModel = boundModel },
(newStatus, boundModel)
let noChange = slot, (Good, slot.BoundModel)
match status with
// Modifying implementation file that has signature file does not invalidate the build.
// So we just pass along previous status.
| status when slot.Notified && slot.HasSignature -> update status
| Invalidated -> update Invalidated
| Good when slot.Notified -> update Invalidated
| _ -> noChange