-
Notifications
You must be signed in to change notification settings - Fork 805
/
Copy pathservice.fs
1807 lines (1500 loc) · 76.6 KB
/
service.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.Diagnostics
open System.IO
open System.Reflection
open System.Reflection.Emit
open System.Threading
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.AbstractIL.ILDynamicAssemblyWriter
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.CompilerOptions
open FSharp.Compiler.DependencyManager
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.Driver
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.IO
open FSharp.Compiler.ParseAndCheckInputs
open FSharp.Compiler.ScriptClosure
open FSharp.Compiler.Symbols
open FSharp.Compiler.Syntax
open FSharp.Compiler.Tokenization
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.BuildGraph
[<AutoOpen>]
module EnvMisc =
let braceMatchCacheSize = GetEnvInteger "FCS_BraceMatchCacheSize" 5
let parseFileCacheSize = GetEnvInteger "FCS_ParseFileCacheSize" 2
let checkFileInProjectCacheSize = GetEnvInteger "FCS_CheckFileInProjectCacheSize" 10
let projectCacheSizeDefault = GetEnvInteger "FCS_ProjectCacheSizeDefault" 3
let frameworkTcImportsCacheStrongSize = GetEnvInteger "FCS_frameworkTcImportsCacheStrongSizeDefault" 8
//----------------------------------------------------------------------------
// BackgroundCompiler
//
/// Callback that indicates whether a requested result has become obsolete.
[<NoComparison; NoEquality>]
type IsResultObsolete = IsResultObsolete of (unit -> bool)
[<AutoOpen>]
module Helpers =
/// Determine whether two (fileName,options) keys are identical w.r.t. affect on checking
let AreSameForChecking2 ((fileName1: string, options1: FSharpProjectOptions), (fileName2, options2)) =
(fileName1 = fileName2)
&& FSharpProjectOptions.AreSameForChecking(options1, options2)
/// Determine whether two (fileName,options) keys should be identical w.r.t. resource usage
let AreSubsumable2 ((fileName1: string, o1: FSharpProjectOptions), (fileName2: string, o2: FSharpProjectOptions)) =
(fileName1 = fileName2) && FSharpProjectOptions.UseSameProject(o1, o2)
/// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. parsing
let AreSameForParsing ((fileName1: string, source1Hash: int64, options1), (fileName2, source2Hash, options2)) =
fileName1 = fileName2 && options1 = options2 && source1Hash = source2Hash
let AreSimilarForParsing ((fileName1, _, _), (fileName2, _, _)) = fileName1 = fileName2
/// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. checking
let AreSameForChecking3 ((fileName1: string, source1Hash: int64, options1: FSharpProjectOptions), (fileName2, source2Hash, options2)) =
(fileName1 = fileName2)
&& FSharpProjectOptions.AreSameForChecking(options1, options2)
&& source1Hash = source2Hash
/// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. resource usage
let AreSubsumable3 ((fileName1: string, _, o1: FSharpProjectOptions), (fileName2: string, _, o2: FSharpProjectOptions)) =
(fileName1 = fileName2) && FSharpProjectOptions.UseSameProject(o1, o2)
module CompileHelpers =
let mkCompilationDiagnosticsHandlers () =
let diagnostics = ResizeArray<_>()
let diagnosticSink isError exn =
let main, related = SplitRelatedDiagnostics exn
let oneDiagnostic e =
diagnostics.Add(FSharpDiagnostic.CreateFromException(e, isError, range0, true)) // Suggest names for errors
oneDiagnostic main
List.iter oneDiagnostic related
let diagnosticsLogger =
{ new DiagnosticsLogger("CompileAPI") with
member _.DiagnosticSink(exn, isError) = diagnosticSink isError exn
member _.ErrorCount =
diagnostics
|> Seq.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error)
|> Seq.length
}
let loggerProvider =
{ new DiagnosticsLoggerProvider() with
member _.CreateDiagnosticsLoggerUpToMaxErrors(_tcConfigBuilder, _exiter) = diagnosticsLogger
}
diagnostics, diagnosticsLogger, loggerProvider
let tryCompile diagnosticsLogger f =
use unwindParsePhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse
use unwindEL_2 = PushDiagnosticsLoggerPhaseUntilUnwind(fun _ -> diagnosticsLogger)
let exiter =
{ new Exiter with
member x.Exit n = raise StopProcessing
}
try
f exiter
0
with e ->
stopProcessingRecovery e range0
1
/// Compile using the given flags. Source files names are resolved via the FileSystem API. The output file must be given by a -o flag.
let compileFromArgs (ctok, argv: string[], legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) =
let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers ()
let result =
tryCompile diagnosticsLogger (fun exiter ->
CompileFromCommandLineArguments(
ctok,
argv,
legacyReferenceResolver,
true,
ReduceMemoryFlag.Yes,
CopyFSharpCoreFlag.No,
exiter,
loggerProvider,
tcImportsCapture,
dynamicAssemblyCreator
))
diagnostics.ToArray(), result
let compileFromAsts
(
ctok,
legacyReferenceResolver,
asts,
assemblyName,
outFile,
dependencies,
noframework,
pdbFile,
executable,
tcImportsCapture,
dynamicAssemblyCreator
) =
let diagnostics, diagnosticsLogger, loggerProvider = mkCompilationDiagnosticsHandlers ()
let executable = defaultArg executable true
let target =
if executable then
CompilerTarget.ConsoleExe
else
CompilerTarget.Dll
let result =
tryCompile diagnosticsLogger (fun exiter ->
CompileFromSyntaxTrees(
ctok,
legacyReferenceResolver,
ReduceMemoryFlag.Yes,
assemblyName,
target,
outFile,
pdbFile,
dependencies,
noframework,
exiter,
loggerProvider,
asts,
tcImportsCapture,
dynamicAssemblyCreator
))
diagnostics.ToArray(), result
let createDynamicAssembly
(debugInfo: bool, tcImportsRef: TcImports option ref, execute: bool, assemblyBuilderRef: _ option ref)
(tcConfig: TcConfig, tcGlobals: TcGlobals, outfile, ilxMainModule)
=
// Create an assembly builder
let assemblyName = AssemblyName(Path.GetFileNameWithoutExtension outfile)
let flags = AssemblyBuilderAccess.Run
#if FX_NO_APP_DOMAINS
let assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(assemblyName, flags)
let moduleBuilder = assemblyBuilder.DefineDynamicModule("IncrementalModule")
#else
let assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, flags)
let moduleBuilder = assemblyBuilder.DefineDynamicModule("IncrementalModule", debugInfo)
#endif
// Omit resources in dynamic assemblies, because the module builder is constructed without a file name the module
// is tagged as transient and as such DefineManifestResource will throw an invalid operation if resources are present.
//
// Also, the dynamic assembly creator can't currently handle types called "<Module>" from statically linked assemblies.
let ilxMainModule =
{ ilxMainModule with
TypeDefs =
ilxMainModule.TypeDefs.AsList()
|> List.filter (fun td -> not (isTypeNameForGlobalFunctions td.Name))
|> mkILTypeDefs
Resources = mkILResources []
}
// The function used to resolve types while emitting the code
let assemblyResolver s =
match tcImportsRef.Value.Value.TryFindExistingFullyQualifiedPathByExactAssemblyRef s with
| Some res -> Some(Choice1Of2 res)
| None -> None
// Emit the code
let _emEnv, execs =
EmitDynamicAssemblyFragment(
tcGlobals.ilg,
tcConfig.emitTailcalls,
emEnv0,
assemblyBuilder,
moduleBuilder,
ilxMainModule,
debugInfo,
assemblyResolver,
tcGlobals.TryFindSysILTypeRef
)
// Execute the top-level initialization, if requested
if execute then
for exec in execs do
match exec () with
| None -> ()
| Some exn ->
PreserveStackTrace exn
raise exn
// Register the reflected definitions for the dynamically generated assembly
for resource in ilxMainModule.Resources.AsList() do
if IsReflectedDefinitionsResource resource then
Quotations.Expr.RegisterReflectedDefinitions(assemblyBuilder, moduleBuilder.Name, resource.GetBytes().ToArray())
// Save the result
assemblyBuilderRef.Value <- Some assemblyBuilder
let setOutputStreams execute =
// Set the output streams, if requested
match execute with
| Some (writer, error) ->
Console.SetOut writer
Console.SetError error
| None -> ()
type SourceTextHash = int64
type CacheStamp = int64
type FileName = string
type FilePath = string
type ProjectPath = string
type FileVersion = int
type ParseCacheLockToken() =
interface LockToken
type ScriptClosureCacheToken() =
interface LockToken
type CheckFileCacheKey = FileName * SourceTextHash * FSharpProjectOptions
type CheckFileCacheValue = FSharpParseFileResults * FSharpCheckFileResults * SourceTextHash * DateTime
// There is only one instance of this type, held in FSharpChecker
type BackgroundCompiler
(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking
) as self =
let beforeFileChecked = Event<string * FSharpProjectOptions>()
let fileParsed = Event<string * FSharpProjectOptions>()
let fileChecked = Event<string * FSharpProjectOptions>()
let projectChecked = Event<FSharpProjectOptions>()
// STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.scriptClosureCache
/// Information about the derived script closure.
let scriptClosureCache =
MruCache<AnyCallerThreadToken, FSharpProjectOptions, LoadClosure>(
projectCacheSize,
areSame = FSharpProjectOptions.AreSameForChecking,
areSimilar = FSharpProjectOptions.UseSameProject
)
let frameworkTcImportsCache = FrameworkImportsCache(frameworkTcImportsCacheStrongSize)
// 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()
let getProjectReferences (options: FSharpProjectOptions) userOpName =
[
for r in options.ReferencedProjects do
match r with
| FSharpReferencedProject.FSharpReference (nm, opts) ->
// 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() =
node {
Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "GetAssemblyData", nm)
return! self.GetAssemblyData(opts, userOpName + ".CheckReferencedProject(" + nm + ")")
}
member x.TryGetLogicalTimeStamp(cache) =
self.TryGetLogicalTimeStampForProject(cache, opts)
member x.FileName = nm
}
| FSharpReferencedProject.PEReference (nm, getStamp, delayedReader) ->
{ new IProjectReference with
member x.EvaluateRawContents() =
node {
let! ilReaderOpt = delayedReader.TryGetILModuleReader() |> NodeCode.FromCancellable
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 = nm
}
| FSharpReferencedProject.ILModuleReference (nm, getStamp, getReader) ->
{ new IProjectReference with
member x.EvaluateRawContents() =
node {
let ilReader = getReader ()
let ilModuleDef, ilAsmRefs = ilReader.ILModuleDef, ilReader.ILAssemblyRefs
let data = RawFSharpAssemblyData(ilModuleDef, ilAsmRefs) :> IRawFSharpAssemblyData
return ProjectAssemblyDataResult.Available data
}
member x.TryGetLogicalTimeStamp _ = getStamp () |> Some
member x.FileName = nm
}
]
/// CreateOneIncrementalBuilder (for background type checking). Note that fsc.fs also
/// creates an incremental builder used by the command line compiler.
let CreateOneIncrementalBuilder (options: FSharpProjectOptions, userOpName) =
node {
Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CreateOneIncrementalBuilder", options.ProjectFileName)
let projectReferences = getProjectReferences options userOpName
let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options)
let dependencyProvider =
if options.UseScriptResolutionRules then
Some dependencyProviderForScripts
else
None
let! builderOpt, diagnostics =
IncrementalBuilder.TryCreateIncrementalBuilderForProjectOptions(
legacyReferenceResolver,
FSharpCheckerResultsSettings.defaultFSharpBinariesDir,
frameworkTcImportsCache,
loadClosure,
Array.toList options.SourceFiles,
Array.toList options.OtherOptions,
projectReferences,
options.ProjectDirectory,
options.UseScriptResolutionRules,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
dependencyProvider
)
match builderOpt with
| None -> ()
| Some builder ->
#if !NO_TYPEPROVIDERS
// Register the behaviour that responds to CCUs being invalidated because of type
// provider Invalidate events. This invalidates the configuration in the build.
builder.ImportsInvalidatedByTypeProvider.Add(fun () -> self.InvalidateConfiguration(options, userOpName))
#endif
// Register the callback called just before a file is typechecked by the background builder (without recording
// errors or intellisense information).
//
// This indicates to the UI that the file type check state is dirty. If the file is open and visible then
// the UI will sooner or later request a typecheck of the file, recording errors and intellisense information.
builder.BeforeFileChecked.Add(fun file -> beforeFileChecked.Trigger(file, options))
builder.FileParsed.Add(fun file -> fileParsed.Trigger(file, options))
builder.FileChecked.Add(fun file -> fileChecked.Trigger(file, options))
builder.ProjectChecked.Add(fun () -> projectChecked.Trigger options)
return (builderOpt, diagnostics)
}
let parseCacheLock = Lock<ParseCacheLockToken>()
// STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseFileInProjectCache. Most recently used cache for parsing files.
let parseFileCache =
MruCache<ParseCacheLockToken, _ * SourceTextHash * _, _>(parseFileCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing)
// STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.checkFileInProjectCache
//
/// Cache which holds recently seen type-checks.
/// This cache may hold out-of-date entries, in two senses
/// - there may be a more recent antecedent state available because the background build has made it available
/// - the source for the file may have changed
// Also keyed on source. This can only be out of date if the antecedent is out of date
let checkFileInProjectCache =
MruCache<ParseCacheLockToken, CheckFileCacheKey, GraphNode<CheckFileCacheValue>>(
keepStrongly = checkFileInProjectCacheSize,
areSame = AreSameForChecking3,
areSimilar = AreSubsumable3
)
// STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.backgroundCompiler.incrementalBuildersCache. This root typically holds more
// live information than anything else in the F# Language Service, since it holds up to 3 (projectCacheStrongSize) background project builds
// strongly.
//
/// Cache of builds keyed by options.
let gate = obj ()
let incrementalBuildersCache =
MruCache<AnyCallerThreadToken, FSharpProjectOptions, GraphNode<IncrementalBuilder option * FSharpDiagnostic[]>>(
keepStrongly = projectCacheSize,
keepMax = projectCacheSize,
areSame = FSharpProjectOptions.AreSameForChecking,
areSimilar = FSharpProjectOptions.UseSameProject
)
let tryGetBuilderNode options =
incrementalBuildersCache.TryGet(AnyCallerThread, options)
let tryGetBuilder options : NodeCode<IncrementalBuilder option * FSharpDiagnostic[]> option =
tryGetBuilderNode options |> Option.map (fun x -> x.GetOrComputeValue())
let tryGetSimilarBuilder options : NodeCode<IncrementalBuilder option * FSharpDiagnostic[]> option =
incrementalBuildersCache.TryGetSimilar(AnyCallerThread, options)
|> Option.map (fun x -> x.GetOrComputeValue())
let tryGetAnyBuilder options : NodeCode<IncrementalBuilder option * FSharpDiagnostic[]> option =
incrementalBuildersCache.TryGetAny(AnyCallerThread, options)
|> Option.map (fun x -> x.GetOrComputeValue())
let createBuilderNode (options, userOpName, ct: CancellationToken) =
lock gate (fun () ->
if ct.IsCancellationRequested then
GraphNode(node.Return(None, [||]))
else
let getBuilderNode = GraphNode(CreateOneIncrementalBuilder(options, userOpName))
incrementalBuildersCache.Set(AnyCallerThread, options, getBuilderNode)
getBuilderNode)
let createAndGetBuilder (options, userOpName) =
node {
let! ct = NodeCode.CancellationToken
let getBuilderNode = createBuilderNode (options, userOpName, ct)
return! getBuilderNode.GetOrComputeValue()
}
let getOrCreateBuilder (options, userOpName) : NodeCode<IncrementalBuilder option * FSharpDiagnostic[]> =
match tryGetBuilder options with
| Some getBuilder ->
node {
match! getBuilder with
| builderOpt, creationDiags when builderOpt.IsNone || not builderOpt.Value.IsReferencesInvalidated ->
Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_GettingCache
return builderOpt, creationDiags
| _ ->
// The builder could be re-created,
// clear the check file caches that are associated with it.
// We must do this in order to not return stale results when references
// in the project get changed/added/removed.
parseCacheLock.AcquireLock(fun ltok ->
options.SourceFiles
|> Array.iter (fun sourceFile ->
let key = (sourceFile, 0L, options)
checkFileInProjectCache.RemoveAnySimilar(ltok, key)))
return! createAndGetBuilder (options, userOpName)
}
| _ -> createAndGetBuilder (options, userOpName)
let getSimilarOrCreateBuilder (options, userOpName) =
match tryGetSimilarBuilder options with
| Some res -> res
// The builder does not exist at all. Create it.
| None -> getOrCreateBuilder (options, userOpName)
let getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName) =
if canInvalidateProject then
getOrCreateBuilder (options, userOpName)
else
getSimilarOrCreateBuilder (options, userOpName)
let getAnyBuilder (options, userOpName) =
match tryGetAnyBuilder options with
| Some getBuilder ->
Logger.Log LogCompilerFunctionId.Service_IncrementalBuildersCache_GettingCache
getBuilder
| _ -> getOrCreateBuilder (options, userOpName)
static let mutable actualParseFileCount = 0
static let mutable actualCheckFileCount = 0
/// Should be a fast operation. Ensures that we have only one async lazy object per file and its hash.
let getCheckFileNode (parseResults, sourceText, fileName, options, _fileVersion, builder, tcPrior, tcInfo, creationDiags) =
// Here we lock for the creation of the node, not its execution
parseCacheLock.AcquireLock(fun ltok ->
let key = (fileName, sourceText.GetHashCode() |> int64, options)
match checkFileInProjectCache.TryGet(ltok, key) with
| Some res -> res
| _ ->
let res =
GraphNode(
node {
let! res = self.CheckOneFileImplAux(parseResults, sourceText, fileName, options, builder, tcPrior, tcInfo, creationDiags)
Interlocked.Increment(&actualCheckFileCount) |> ignore
return res
}
)
checkFileInProjectCache.Set(ltok, key, res)
res)
member _.ParseFile(fileName: string, sourceText: ISourceText, options: FSharpParsingOptions, cache: bool, userOpName: string) =
async {
if cache then
let hash = sourceText.GetHashCode() |> int64
match parseCacheLock.AcquireLock(fun ltok -> parseFileCache.TryGet(ltok, (fileName, hash, options))) with
| Some res -> return res
| None ->
Interlocked.Increment(&actualParseFileCount) |> ignore
let parseDiagnostics, parseTree, anyErrors =
ParseAndCheckFile.parseFile (sourceText, fileName, options, userOpName, suggestNamesForErrors)
let res = FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles)
parseCacheLock.AcquireLock(fun ltok -> parseFileCache.Set(ltok, (fileName, hash, options), res))
return res
else
let parseDiagnostics, parseTree, anyErrors =
ParseAndCheckFile.parseFile (sourceText, fileName, options, userOpName, false)
return FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, options.SourceFiles)
}
/// Fetch the parse information from the background compiler (which checks w.r.t. the FileSystem API)
member _.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName) =
node {
let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None ->
let parseTree = EmptyParsedInput(fileName, (false, false))
return FSharpParseFileResults(creationDiags, parseTree, true, [||])
| Some builder ->
let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName
let parseDiagnostics =
DiagnosticHelpers.CreateDiagnostics(builder.TcConfig.diagnosticsOptions, false, fileName, parseDiagnostics, suggestNamesForErrors)
let diagnostics = [| yield! creationDiags; yield! parseDiagnostics |]
let parseResults =
FSharpParseFileResults(
diagnostics = diagnostics,
input = parseTree,
parseHadErrors = false,
dependencyFiles = builder.AllDependenciesDeprecated
)
return parseResults
}
member _.GetCachedCheckFileResult(builder: IncrementalBuilder, fileName, sourceText: ISourceText, options) =
node {
let hash = sourceText.GetHashCode() |> int64
let key = (fileName, hash, options)
let cachedResultsOpt = parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok, key))
match cachedResultsOpt with
| Some cachedResults ->
match! cachedResults.GetOrComputeValue() with
| parseResults, checkResults, _, priorTimeStamp when
(match builder.GetCheckResultsBeforeFileInProjectEvenIfStale fileName with
| None -> false
| Some (tcPrior) ->
tcPrior.ProjectTimeStamp = priorTimeStamp
&& builder.AreCheckResultsBeforeFileInProjectReady(fileName))
->
return Some(parseResults, checkResults)
| _ ->
parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.RemoveAnySimilar(ltok, key))
return None
| _ -> return None
}
member private _.CheckOneFileImplAux
(
parseResults: FSharpParseFileResults,
sourceText: ISourceText,
fileName: string,
options: FSharpProjectOptions,
builder: IncrementalBuilder,
tcPrior: PartialCheckResults,
tcInfo: TcInfo,
creationDiags: FSharpDiagnostic[]
) : NodeCode<CheckFileCacheValue> =
node {
// Get additional script #load closure information if applicable.
// For scripts, this will have been recorded by GetProjectOptionsFromScript.
let tcConfig = tcPrior.TcConfig
let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options)
let! checkAnswer =
FSharpCheckFileResults.CheckOneFile(
parseResults,
sourceText,
fileName,
options.ProjectFileName,
tcConfig,
tcPrior.TcGlobals,
tcPrior.TcImports,
tcInfo.tcState,
tcInfo.moduleNamesDict,
loadClosure,
tcInfo.TcDiagnostics,
options.IsIncompleteTypeCheckEnvironment,
options,
builder,
Array.ofList tcInfo.tcDependencyFiles,
creationDiags,
parseResults.Diagnostics,
keepAssemblyContents,
suggestNamesForErrors
)
|> NodeCode.FromCancellable
GraphNode.SetPreferredUILang tcConfig.preferredUiLang
return (parseResults, checkAnswer, sourceText.GetHashCode() |> int64, tcPrior.ProjectTimeStamp)
}
member private bc.CheckOneFileImpl
(
parseResults: FSharpParseFileResults,
sourceText: ISourceText,
fileName: string,
options: FSharpProjectOptions,
fileVersion: int,
builder: IncrementalBuilder,
tcPrior: PartialCheckResults,
tcInfo: TcInfo,
creationDiags: FSharpDiagnostic[]
) =
node {
match! bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) with
| Some (_, results) -> return FSharpCheckFileAnswer.Succeeded results
| _ ->
let lazyCheckFile =
getCheckFileNode (parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags)
let! _, results, _, _ = lazyCheckFile.GetOrComputeValue()
return FSharpCheckFileAnswer.Succeeded results
}
/// Type-check the result obtained by parsing, but only if the antecedent type checking context is available.
member bc.CheckFileInProjectAllowingStaleCachedResults
(
parseResults: FSharpParseFileResults,
fileName,
fileVersion,
sourceText: ISourceText,
options,
userOpName
) =
node {
let! cachedResults =
node {
let! builderOpt, creationDiags = getAnyBuilder (options, userOpName)
match builderOpt with
| Some builder ->
match! bc.GetCachedCheckFileResult(builder, fileName, sourceText, options) with
| Some (_, checkResults) -> return Some(builder, creationDiags, Some(FSharpCheckFileAnswer.Succeeded checkResults))
| _ -> return Some(builder, creationDiags, None)
| _ -> return None // the builder wasn't ready
}
match cachedResults with
| None -> return None
| Some (_, _, Some x) -> return Some x
| Some (builder, creationDiags, None) ->
Trace.TraceInformation("FCS: {0}.{1} ({2})", userOpName, "CheckFileInProjectAllowingStaleCachedResults.CacheMiss", fileName)
match builder.GetCheckResultsBeforeFileInProjectEvenIfStale fileName with
| Some tcPrior ->
match tcPrior.TryPeekTcInfo() with
| Some tcInfo ->
let! checkResults =
bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags)
return Some checkResults
| None -> return None
| None -> return None // the incremental builder was not up to date
}
/// Type-check the result obtained by parsing. Force the evaluation of the antecedent type checking context if needed.
member bc.CheckFileInProject(parseResults: FSharpParseFileResults, fileName, fileVersion, sourceText: ISourceText, options, userOpName) =
node {
let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None -> return FSharpCheckFileAnswer.Succeeded(FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, keepAssemblyContents))
| Some builder ->
// Check the cache. We can only use cached results when there is no work to do to bring the background builder up-to-date
let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options)
match cachedResults with
| Some (_, checkResults) -> return FSharpCheckFileAnswer.Succeeded checkResults
| _ ->
let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName
let! tcInfo = tcPrior.GetOrComputeTcInfo()
return! bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags)
}
/// Parses and checks the source file and returns untyped AST and check results.
member bc.ParseAndCheckFileInProject(fileName: string, fileVersion, sourceText: ISourceText, options: FSharpProjectOptions, userOpName) =
node {
let strGuid = "_ProjectId=" + (options.ProjectId |> Option.defaultValue "null")
Logger.LogBlockMessageStart (fileName + strGuid) LogCompilerFunctionId.Service_ParseAndCheckFileInProject
let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None ->
Logger.LogBlockMessageStop (fileName + strGuid + "-Failed_Aborted") LogCompilerFunctionId.Service_ParseAndCheckFileInProject
let parseTree = EmptyParsedInput(fileName, (false, false))
let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||])
return (parseResults, FSharpCheckFileAnswer.Aborted)
| Some builder ->
let! cachedResults = bc.GetCachedCheckFileResult(builder, fileName, sourceText, options)
match cachedResults with
| Some (parseResults, checkResults) ->
Logger.LogBlockMessageStop (fileName + strGuid + "-Successful_Cached") LogCompilerFunctionId.Service_ParseAndCheckFileInProject
return (parseResults, FSharpCheckFileAnswer.Succeeded checkResults)
| _ ->
let! tcPrior = builder.GetCheckResultsBeforeFileInProject fileName
let! tcInfo = tcPrior.GetOrComputeTcInfo()
// Do the parsing.
let parsingOptions =
FSharpParsingOptions.FromTcConfig(builder.TcConfig, Array.ofList builder.SourceFiles, options.UseScriptResolutionRules)
GraphNode.SetPreferredUILang tcPrior.TcConfig.preferredUiLang
let parseDiagnostics, parseTree, anyErrors =
ParseAndCheckFile.parseFile (sourceText, fileName, parsingOptions, userOpName, suggestNamesForErrors)
let parseResults =
FSharpParseFileResults(parseDiagnostics, parseTree, anyErrors, builder.AllDependenciesDeprecated)
let! checkResults =
bc.CheckOneFileImpl(parseResults, sourceText, fileName, options, fileVersion, builder, tcPrior, tcInfo, creationDiags)
Logger.LogBlockMessageStop (fileName + strGuid + "-Successful") LogCompilerFunctionId.Service_ParseAndCheckFileInProject
return (parseResults, checkResults)
}
/// Fetch the check information from the background compiler (which checks w.r.t. the FileSystem API)
member _.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName) =
node {
let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None ->
let parseTree = EmptyParsedInput(fileName, (false, false))
let parseResults = FSharpParseFileResults(creationDiags, parseTree, true, [||])
let typedResults = FSharpCheckFileResults.MakeEmpty(fileName, creationDiags, true)
return (parseResults, typedResults)
| Some builder ->
let parseTree, _, _, parseDiagnostics = builder.GetParseResultsForFile fileName
let! tcProj = builder.GetFullCheckResultsAfterFileInProject fileName
let! tcInfo, tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras()
let tcResolutions = tcInfoExtras.tcResolutions
let tcSymbolUses = tcInfoExtras.tcSymbolUses
let tcOpenDeclarations = tcInfoExtras.tcOpenDeclarations
let latestCcuSigForFile = tcInfo.latestCcuSigForFile
let tcState = tcInfo.tcState
let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile
let latestImplementationFile = tcInfoExtras.latestImplFile
let tcDependencyFiles = tcInfo.tcDependencyFiles
let tcDiagnostics = tcInfo.TcDiagnostics
let diagnosticsOptions = builder.TcConfig.diagnosticsOptions
let parseDiagnostics =
DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, false, fileName, parseDiagnostics, suggestNamesForErrors)
let parseDiagnostics = [| yield! creationDiags; yield! parseDiagnostics |]
let tcDiagnostics =
DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, false, fileName, tcDiagnostics, suggestNamesForErrors)
let tcDiagnostics = [| yield! creationDiags; yield! tcDiagnostics |]
let parseResults =
FSharpParseFileResults(
diagnostics = parseDiagnostics,
input = parseTree,
parseHadErrors = false,
dependencyFiles = builder.AllDependenciesDeprecated
)
let loadClosure = scriptClosureCache.TryGet(AnyCallerThread, options)
let typedResults =
FSharpCheckFileResults.Make(
fileName,
options.ProjectFileName,
tcProj.TcConfig,
tcProj.TcGlobals,
options.IsIncompleteTypeCheckEnvironment,
builder,
options,
Array.ofList tcDependencyFiles,
creationDiags,
parseResults.Diagnostics,
tcDiagnostics,
keepAssemblyContents,
Option.get latestCcuSigForFile,
tcState.Ccu,
tcProj.TcImports,
tcEnvAtEnd.AccessRights,
tcResolutions,
tcSymbolUses,
tcEnvAtEnd.NameEnv,
loadClosure,
latestImplementationFile,
tcOpenDeclarations
)
return (parseResults, typedResults)
}
member _.FindReferencesInFile
(
fileName: string,
options: FSharpProjectOptions,
symbol: FSharpSymbol,
canInvalidateProject: bool,
userOpName: string
) =
node {
let! builderOpt, _ = getOrCreateBuilderWithInvalidationFlag (options, canInvalidateProject, userOpName)
match builderOpt with
| None -> return Seq.empty
| Some builder ->
if builder.ContainsFile fileName then
let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName
let! keyStoreOpt = checkResults.GetOrComputeItemKeyStoreIfEnabled()
match keyStoreOpt with
| None -> return Seq.empty
| Some reader -> return reader.FindAll symbol.Item
else
return Seq.empty
}
member _.GetSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, userOpName: string) =
node {
let! builderOpt, _ = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None -> return None
| Some builder ->
let! checkResults = builder.GetFullCheckResultsAfterFileInProject fileName
let! scopt = checkResults.GetOrComputeSemanticClassificationIfEnabled()
match scopt with
| None -> return None
| Some sc -> return Some(sc.GetView())
}
/// Try to get recent approximate type check results for a file.
member _.TryGetRecentCheckResultsForFile(fileName: string, options: FSharpProjectOptions, sourceText: ISourceText option, _userOpName: string) =
match sourceText with
| Some sourceText ->
let hash = sourceText.GetHashCode() |> int64
let resOpt =
parseCacheLock.AcquireLock(fun ltok -> checkFileInProjectCache.TryGet(ltok, (fileName, hash, options)))
match resOpt with
| Some res ->
match res.TryPeekValue() with
| ValueSome (a, b, c, _) -> Some(a, b, c)
| ValueNone -> None
| None -> None
| None -> None
/// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated)
member private _.ParseAndCheckProjectImpl(options, userOpName) =
node {
let! builderOpt, creationDiags = getOrCreateBuilder (options, userOpName)
match builderOpt with
| None ->
let emptyResults =
FSharpCheckProjectResults(options.ProjectFileName, None, keepAssemblyContents, creationDiags, None)
return emptyResults
| Some builder ->
let! tcProj, ilAssemRef, tcAssemblyDataOpt, tcAssemblyExprOpt = builder.GetFullCheckResultsAndImplementationsForProject()
let diagnosticsOptions = tcProj.TcConfig.diagnosticsOptions
let fileName = DummyFileNameForRangesWithoutASpecificLocation
// Although we do not use 'tcInfoExtras', computing it will make sure we get an extra info.
let! tcInfo, _tcInfoExtras = tcProj.GetOrComputeTcInfoWithExtras()
let topAttribs = tcInfo.topAttribs
let tcState = tcInfo.tcState
let tcEnvAtEnd = tcInfo.tcEnvAtEndOfFile
let tcDiagnostics = tcInfo.TcDiagnostics
let tcDependencyFiles = tcInfo.tcDependencyFiles
let tcDiagnostics =
DiagnosticHelpers.CreateDiagnostics(diagnosticsOptions, true, fileName, tcDiagnostics, suggestNamesForErrors)
let diagnostics = [| yield! creationDiags; yield! tcDiagnostics |]