From ec3f6928bf10023aa0e9638291f9dfee6e41fd7f Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 00:17:25 +0100 Subject: [PATCH 01/19] fix config change --- .../ProjectCracker.fs | 2 +- src/fsharp/InternalCollections.fs | 37 ++++---- src/fsharp/InternalCollections.fsi | 17 +++- src/fsharp/vs/IncrementalBuild.fs | 4 +- src/fsharp/vs/IncrementalBuild.fsi | 4 +- src/fsharp/vs/service.fs | 89 ++++++++++--------- src/fsharp/vs/service.fsi | 16 +++- tests/service/FileSystemTests.fs | 2 +- tests/service/ProjectOptionsTests.fs | 16 ++-- .../Utils/LanguageServiceProfiling/Options.fs | 4 +- .../LanguageService/LanguageService.fs | 74 +++++++++------ .../BackgroundRequests.fs | 7 +- .../FSharp.LanguageService/FSharpSource.fs | 2 +- .../ProjectSitesAndFiles.fs | 87 +++++++++--------- .../FSharp.ProjectSystem.FSharp/Project.fs | 10 ++- .../Salsa/FSharpLanguageServiceTestable.fs | 4 +- .../unittests/BraceMatchingServiceTests.fs | 2 +- .../unittests/BreakpointResolutionService.fs | 2 +- .../unittests/CompletionProviderTests.fs | 2 +- .../DocumentDiagnosticAnalyzerTests.fs | 2 +- .../DocumentHighlightsServiceTests.fs | 2 +- .../unittests/GoToDefinitionServiceTests.fs | 2 +- .../unittests/HelpContextServiceTests.fs | 2 +- .../tests/unittests/QuickInfoProviderTests.fs | 2 +- .../unittests/SignatureHelpProviderTests.fs | 2 +- .../unittests/Tests.InternalCollections.fs | 4 +- .../unittests/Tests.LanguageService.Script.fs | 4 +- 27 files changed, 229 insertions(+), 172 deletions(-) diff --git a/fcs/FSharp.Compiler.Service.ProjectCracker/ProjectCracker.fs b/fcs/FSharp.Compiler.Service.ProjectCracker/ProjectCracker.fs index baf81022799..2788ed0f10c 100644 --- a/fcs/FSharp.Compiler.Service.ProjectCracker/ProjectCracker.fs +++ b/fcs/FSharp.Compiler.Service.ProjectCracker/ProjectCracker.fs @@ -33,7 +33,7 @@ type ProjectCracker = logMap := Map.add opts.ProjectFile opts.LogOutput !logMap { ProjectFileName = opts.ProjectFile - ProjectFileNames = sourceFiles + SourceFiles = sourceFiles OtherOptions = otherOptions ReferencedProjects = referencedProjects IsIncompleteTypeCheckEnvironment = false diff --git a/src/fsharp/InternalCollections.fs b/src/fsharp/InternalCollections.fs index da204620e2a..da9f838c9cc 100755 --- a/src/fsharp/InternalCollections.fs +++ b/src/fsharp/InternalCollections.fs @@ -13,7 +13,7 @@ type internal ValueStrength<'T when 'T : not struct> = | Weak of WeakReference<'T> #endif -type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStrongly:int, areSame, ?requiredToKeep, ?onStrongDiscard, ?keepMax: int) = +type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStrongly:int, areSimilar, ?requiredToKeep, ?onStrongDiscard, ?keepMax: int) = /// The list of items stored. Youngest is at the end of the list. /// The choice of order is somewhat arbitrary. If the other way then adding /// items would be O(1) and removing O(N). @@ -39,8 +39,8 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro // This function returns true if two keys are the same according to the predicate // function passed in. | []->None - | (key',value)::t-> - if areSame(key,key') then Some(key',value) + | (similarKey,value)::t-> + if areSimilar(key,similarKey) then Some(similarKey,value) else Lookup key t Lookup key data @@ -53,18 +53,18 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro /// Promote a particular key value. let Promote (data, key, value) = - (data |> List.filter (fun (key',_)-> not (areSame(key,key')))) @ [ (key, value) ] + (data |> List.filter (fun (similarKey,_)-> not (areSimilar(key,similarKey)))) @ [ (key, value) ] /// Remove a particular key value. let RemoveImpl (data, key) = - let discard,keep = data |> List.partition (fun (key',_)-> areSame(key,key')) + let discard,keep = data |> List.partition (fun (similarKey,_)-> areSimilar(key,similarKey)) keep, discard let TryGetKeyValueImpl(data,key) = match TryPeekKeyValueImpl(data,key) with - | Some(key', value) as result -> + | Some(similarKey, value) as result -> // If the result existed, move it to the end of the list (more likely to keep it) - result,Promote (data,key',value) + result,Promote (data,similarKey,value) | None -> None,data /// Remove weak entries from the list that have been collected. @@ -154,37 +154,42 @@ type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct>(keepStro -type internal MruCache<'Token, 'Key,'Value when 'Value : not struct>(keepStrongly, areSame, ?isStillValid : 'Key*'Value->bool, ?areSameForSubsumption, ?requiredToKeep, ?onStrongDiscard, ?keepMax) = +type internal MruCache<'Token, 'Key,'Value when 'Value : not struct>(keepStrongly, areSame, ?isStillValid : 'Key*'Value->bool, ?areSimilar, ?requiredToKeep, ?onStrongDiscard, ?keepMax) = - /// Default behavior of areSameForSubsumption function is areSame. - let areSameForSubsumption = defaultArg areSameForSubsumption areSame + /// Default behavior of areSimilar function is areSame. + let areSimilar = defaultArg areSimilar areSame /// The list of items in the cache. Youngest is at the end of the list. /// The choice of order is somewhat arbitrary. If the other way then adding /// items would be O(1) and removing O(N). - let cache = AgedLookup<'Token, 'Key,'Value>(keepStrongly=keepStrongly,areSame=areSameForSubsumption,?onStrongDiscard=onStrongDiscard,?keepMax=keepMax,?requiredToKeep=requiredToKeep) + let cache = AgedLookup<'Token, 'Key,'Value>(keepStrongly=keepStrongly,areSimilar=areSimilar,?onStrongDiscard=onStrongDiscard,?keepMax=keepMax,?requiredToKeep=requiredToKeep) /// Whether or not this result value is still valid. let isStillValid = defaultArg isStillValid (fun _ -> true) + member bc.TryGetAnySimilar(tok, key) = + match cache.TryPeekKeyValue(tok, key) with + | Some(similarKey, value)-> Some(similarKey, value) + | None -> None + member bc.TryGetAny(tok, key) = match cache.TryPeekKeyValue(tok, key) with - | Some(key', value)-> - if areSame(key',key) then Some(value) + | Some(similarKey, value)-> + if areSame(similarKey,key) then Some(value) else None | None -> None member bc.TryGet(tok, key) = match cache.TryGetKeyValue(tok, key) with - | Some(key', value) -> - if areSame(key', key) && isStillValid(key,value) then Some value + | Some(similarKey, value) -> + if areSame(similarKey, key) && isStillValid(key,value) then Some value else None | None -> None member bc.Set(tok, key:'Key,value:'Value) = cache.Put(tok, key,value) - member bc.Remove(tok, key) = + member bc.RemoveAnySimilar(tok, key) = cache.Remove(tok, key) member bc.Clear(tok) = diff --git a/src/fsharp/InternalCollections.fsi b/src/fsharp/InternalCollections.fsi index 88abdc302c0..a9fa058680d 100755 --- a/src/fsharp/InternalCollections.fsi +++ b/src/fsharp/InternalCollections.fsi @@ -44,21 +44,30 @@ namespace Internal.Utilities.Collections new : keepStrongly:int * areSame:('Key * 'Key -> bool) * ?isStillValid:('Key * 'Value -> bool) - * ?areSameForSubsumption:('Key * 'Key -> bool) + * ?areSimilar:('Key * 'Key -> bool) * ?requiredToKeep:('Value -> bool) * ?onDiscard:('Value -> unit) * ?keepMax:int -> MruCache<'Token,'Key,'Value> + /// Clear out the cache. member Clear : 'Token -> unit - /// Get the value for the given key or None if not already available. + + /// Get the similar (subsumable) value for the given key or None if not already available. + member TryGetAnySimilar : 'Token * key:'Key -> ('Key * 'Value) option + + /// Get the value for the given key or None if not still valid. member TryGetAny : 'Token * key:'Key -> 'Value option - /// Get the value for the given key or None if not already available + + /// Get the value for the given key or None, but only if entry is still valid member TryGet : 'Token * key:'Key -> 'Value option + /// Remove the given value from the mru cache. - member Remove : 'Token * key:'Key -> unit + member RemoveAnySimilar : 'Token * key:'Key -> unit + /// Set the given key. member Set : 'Token * key:'Key * value:'Value -> unit + /// Resize member Resize : 'Token * keepStrongly: int * ?keepMax : int -> unit diff --git a/src/fsharp/vs/IncrementalBuild.fs b/src/fsharp/vs/IncrementalBuild.fs index 40e9b2adfbb..35e576e75d3 100755 --- a/src/fsharp/vs/IncrementalBuild.fs +++ b/src/fsharp/vs/IncrementalBuild.fs @@ -1562,7 +1562,7 @@ type IncrementalBuilder(tcGlobals,frameworkTcImports, nonFrameworkAssemblyInputs return true } - member builder.GetCheckResultsBeforeFileInProjectIfReady (filename): PartialCheckResults option = + member builder.GetCheckResultsBeforeFileInProjectEvenIfStale (filename): PartialCheckResults option = let slotOfFile = builder.GetSlotOfFileName filename let result = match slotOfFile with @@ -1676,7 +1676,7 @@ type IncrementalBuilder(tcGlobals,frameworkTcImports, nonFrameworkAssemblyInputs #endif } - member __.ProjectFileNames = sourceFiles |> List.map (fun (_,f,_) -> f) + member __.SourceFiles = sourceFiles |> List.map (fun (_,f,_) -> f) /// CreateIncrementalBuilder (for background type checking). Note that fsc.fs also /// creates an incremental builder used by the command line compiler. diff --git a/src/fsharp/vs/IncrementalBuild.fsi b/src/fsharp/vs/IncrementalBuild.fsi index f857cdc7250..e9eca6905a1 100755 --- a/src/fsharp/vs/IncrementalBuild.fsi +++ b/src/fsharp/vs/IncrementalBuild.fsi @@ -76,7 +76,7 @@ type internal IncrementalBuilder = member TcConfig : TcConfig /// The full set of source files including those from options - member ProjectFileNames : string list + member SourceFiles : string list /// Raised just before a file is type-checked, to invalidate the state of the file in VS and force VS to request a new direct typecheck of the file. /// The incremental builder also typechecks the file (error and intellisense results from the background builder are not @@ -110,7 +110,7 @@ type internal IncrementalBuilder = /// This is a very quick operation. /// /// This is safe for use from non-compiler threads but the objects returned must in many cases be accessed only from the compiler thread. - member GetCheckResultsBeforeFileInProjectIfReady: filename:string -> PartialCheckResults option + member GetCheckResultsBeforeFileInProjectEvenIfStale: filename:string -> PartialCheckResults option /// Get the preceding typecheck state of a slot, but only if it is up-to-date w.r.t. /// the timestamps on files and referenced DLLs prior to this one. Return None if the result is not available. diff --git a/src/fsharp/vs/service.fs b/src/fsharp/vs/service.fs index ac63c743662..8bbfc5c196a 100644 --- a/src/fsharp/vs/service.fs +++ b/src/fsharp/vs/service.fs @@ -1582,7 +1582,7 @@ type UnresolvedReferencesSet = UnresolvedReferencesSet of UnresolvedAssemblyRef type FSharpProjectOptions = { ProjectFileName: string - ProjectFileNames: string[] + SourceFiles: string[] OtherOptions: string[] ReferencedProjects: (string * FSharpProjectOptions)[] IsIncompleteTypeCheckEnvironment : bool @@ -1595,7 +1595,7 @@ type FSharpProjectOptions = } member x.ProjectOptions = x.OtherOptions /// Whether the two parse options refer to the same project. - static member AreSubsumable(options1,options2) = + static member UseSameProjectFileName(options1,options2) = options1.ProjectFileName = options2.ProjectFileName /// Compare two options sets with respect to the parts of the options that are important to parsing. @@ -1613,7 +1613,7 @@ type FSharpProjectOptions = | Some x, Some y -> (x = y) | _ -> options1.ProjectFileName = options2.ProjectFileName && - options1.ProjectFileNames = options2.ProjectFileNames && + options1.SourceFiles = options2.SourceFiles && options1.OtherOptions = options2.OtherOptions && options1.UnresolvedReferences = options2.UnresolvedReferences && options1.OriginalLoadReferences = options2.OriginalLoadReferences && @@ -1626,7 +1626,7 @@ type FSharpProjectOptions = override this.ToString() = let files = let sb = new StringBuilder() - this.ProjectFileNames |> Array.iter (fun file -> sb.AppendFormat(" {0}\n", file) |> ignore) + this.SourceFiles |> Array.iter (fun file -> sb.AppendFormat(" {0}\n", file) |> ignore) sb.ToString() let options = let sb = new StringBuilder() @@ -1931,7 +1931,7 @@ module Helpers = /// 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.AreSubsumable(o1,o2) + && FSharpProjectOptions.UseSameProjectFileName(o1,o2) /// Determine whether two (fileName,sourceText,options) keys should be identical w.r.t. parsing let AreSameForParsing3((fileName1: string, source1: string, options1: FSharpProjectOptions), (fileName2, source2, options2)) = @@ -1948,7 +1948,7 @@ module Helpers = /// 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.AreSubsumable(o1,o2) + && FSharpProjectOptions.UseSameProjectFileName(o1,o2) module CompileHelpers = let mkCompilationErorHandlers() = @@ -2089,7 +2089,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let scriptClosureCache = MruCache(projectCacheSize, areSame=FSharpProjectOptions.AreSameForChecking, - areSameForSubsumption=FSharpProjectOptions.AreSubsumable) + areSimilar=FSharpProjectOptions.UseSameProjectFileName) let scriptClosureCacheLock = Lock() let frameworkTcImportsCache = FrameworkImportsCache(frameworkTcImportsCacheStrongSize) @@ -2114,7 +2114,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let loadClosure = scriptClosureCacheLock.AcquireLock (fun ltok -> scriptClosureCache.TryGet (ltok, options)) let! builderOpt, diagnostics = IncrementalBuilder.TryCreateBackgroundBuilderForProjectOptions - (ctok, referenceResolver, defaultFSharpBinariesDir, frameworkTcImportsCache, loadClosure, Array.toList options.ProjectFileNames, + (ctok, referenceResolver, defaultFSharpBinariesDir, frameworkTcImportsCache, loadClosure, Array.toList options.SourceFiles, Array.toList options.OtherOptions, projectReferences, options.ProjectDirectory, options.UseScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds) @@ -2152,7 +2152,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent MruCache (keepStrongly=projectCacheSize, keepMax=projectCacheSize, areSame = FSharpProjectOptions.AreSameForChecking, - areSameForSubsumption = FSharpProjectOptions.AreSubsumable, + areSimilar = FSharpProjectOptions.UseSameProjectFileName, requiredToKeep=(fun (builderOpt,_,_) -> match builderOpt with None -> false | Some (b:IncrementalBuilder) -> b.IsBeingKeptAliveApartFromCacheEntry), onDiscard = (fun (_, _, decrement:IDisposable) -> decrement.Dispose())) @@ -2174,7 +2174,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let parseFileInProjectCache = MruCache(parseFileInProjectCacheSize, areSame=AreSameForParsing3, - areSameForSubsumption=AreSubsumable3) + areSimilar=AreSubsumable3) // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseAndCheckFileInProjectCachePossiblyStale // STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.parseAndCheckFileInProjectCache @@ -2188,14 +2188,14 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent MruCache (keepStrongly=incrementalTypeCheckCacheSize, areSame=AreSameForChecking2, - areSameForSubsumption=AreSubsumable2) + areSimilar=AreSubsumable2) // Also keyed on source. This can only be out of date if the antecedent is out of date let parseAndCheckFileInProjectCache = MruCache (keepStrongly=incrementalTypeCheckCacheSize, areSame=AreSameForChecking3, - areSameForSubsumption=AreSubsumable3) + areSimilar=AreSubsumable3) /// Holds keys for files being currently checked. It's used to prevent checking same file in parallel (interleaving chunck queued to Reactor). let beingCheckedFileTable = @@ -2269,7 +2269,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent | Some builder -> // Do the parsing. let parseErrors, _matchPairs, inputOpt, anyErrors = - Parser.ParseOneFile (ctok, source, false, true, filename, builder.ProjectFileNames, builder.TcConfig) + Parser.ParseOneFile (ctok, source, false, true, filename, builder.SourceFiles, builder.TcConfig) let res = FSharpParseFileResults(parseErrors, inputOpt, anyErrors, builder.AllDependenciesDeprecated ) parseCacheLock.AcquireLock (fun ctok -> parseFileInProjectCache.Set (ctok, (filename, source, options), res)) @@ -2301,7 +2301,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent | None -> return [| |] | Some builder -> let _parseErrors, matchPairs, _inputOpt, _anyErrors = - Parser.ParseOneFile (ctok, source, true, false, filename, builder.ProjectFileNames, builder.TcConfig) + Parser.ParseOneFile (ctok, source, true, false, filename, builder.SourceFiles, builder.TcConfig) return matchPairs } @@ -2315,7 +2315,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // | Some (parseResults, checkResults, _, _) when builder.AreCheckResultsBeforeFileInProjectReady(filename) -> | Some (parseResults, checkResults,_,priorTimeStamp) when - (match builder.GetCheckResultsBeforeFileInProjectIfReady filename with + (match builder.GetCheckResultsBeforeFileInProjectEvenIfStale filename with | None -> false | Some(tcPrior) -> tcPrior.TimeStamp = priorTimeStamp && @@ -2383,8 +2383,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent } /// Type-check the result obtained by parsing, but only if the antecedent type checking context is available. - member bc.CheckFileInProjectIfReady(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo: obj option) = - let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("CheckFileInProjectIfReady " + filename, action >> cancellable.Return) + member bc.CheckFileInProjectAllowingStaleCachedResults(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo: obj option) = + let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("CheckFileInProjectAllowingStaleCachedResults " + filename, action >> cancellable.Return) async { try let! cachedResults = @@ -2403,7 +2403,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let! tcPrior = execWithReactorAsync <| fun ctok -> DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok - builder.GetCheckResultsBeforeFileInProjectIfReady filename + builder.GetCheckResultsBeforeFileInProjectEvenIfStale filename match tcPrior with | Some tcPrior -> let! checkResults = bc.CheckOneFile(parseResults, source, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors) @@ -2458,7 +2458,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // Do the parsing. let! parseErrors, _matchPairs, inputOpt, anyErrors = execWithReactorAsync <| fun ctok -> - Parser.ParseOneFile (ctok, source, false, true, filename, builder.ProjectFileNames, builder.TcConfig) |> cancellable.Return + Parser.ParseOneFile (ctok, source, false, true, filename, builder.SourceFiles, builder.TcConfig) |> cancellable.Return let parseResults = FSharpParseFileResults(parseErrors, inputOpt, anyErrors, builder.AllDependenciesDeprecated) let! checkResults = bc.CheckOneFile(parseResults, source, filename, options, textSnapshotInfo, fileVersion, builder, tcPrior, creationErrors) @@ -2573,7 +2573,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let options = { ProjectFileName = filename + ".fsproj" // Make a name that is unique in this directory. - ProjectFileNames = loadClosure.SourceFiles |> List.map fst |> List.toArray + SourceFiles = loadClosure.SourceFiles |> List.map fst |> List.toArray OtherOptions = otherFlags ReferencedProjects= [| |] IsIncompleteTypeCheckEnvironment = false @@ -2589,31 +2589,37 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent }) member bc.InvalidateConfiguration(options : FSharpProjectOptions) = + // This operation can't currently be cancelled nor awaited reactor.EnqueueOp("InvalidateConfiguration", fun ctok -> - // This operation can't currently be cancelled and is not async - match incrementalBuildersCache.TryGetAny (ctok, options) with + // If there was a similar entry then re-establish an empty builder . This is a somewhat arbitrary choice - it + // will have the effect of releasing memory associated with the previous builder, but costs some time. + match incrementalBuildersCache.TryGetAnySimilar (ctok, options) with | None -> () - | Some (_oldBuilder, _, _) -> - // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, - // including by incrementalBuildersCache.Set. - let builderB, errorsB, decrementB = CreateOneIncrementalBuilder (ctok, options) |> Cancellable.runWithoutCancellation - incrementalBuildersCache.Set(ctok, options, (builderB, errorsB, decrementB)) + | Some (_similarOptions, (_oldBuilder, _, _)) -> + + // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, + // including by incrementalBuildersCache.Set. + let builderB, errorsB, decrementB = CreateOneIncrementalBuilder (ctok, options) |> Cancellable.runWithoutCancellation + incrementalBuildersCache.Set(ctok, options, (builderB, errorsB, decrementB)) + + // Start working on the project. Also a somewhat arbitrary choice if implicitlyStartBackgroundWork then bc.CheckProjectInBackground(options)) member bc.NotifyProjectCleaned (options : FSharpProjectOptions) = reactor.EnqueueAndAwaitOpAsync("NotifyProjectCleaned", fun ctok -> - cancellable { -#if EXTENSIONTYPING - match incrementalBuildersCache.TryGetAny (ctok, options) with + cancellable { + // If there was a similar entry (as there normally will have been) then re-establish an empty builder . This + // is a somewhat arbitrary choice - it will have the effect of releasing memory associated with the previous + // builder, but costs some time. + match incrementalBuildersCache.TryGetAnySimilar (ctok, options) with | None -> return () - | Some (builderOpt, _, _) -> - builderOpt |> Option.iter (fun builder -> - if builder.ThereAreLiveTypeProviders then - bc.InvalidateConfiguration(options)) -#endif - return () - }) + | Some (_similarOptions, (_oldBuilder, _, _)) -> + // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, + // including by incrementalBuildersCache.Set. + let! builderB, errorsB, decrementB = CreateOneIncrementalBuilder (ctok, options) + incrementalBuildersCache.Set(ctok, options, (builderB, errorsB, decrementB)) + }) member bc.CheckProjectInBackground (options) = reactor.SetBackgroundOp (Some (fun ctok -> @@ -2671,6 +2677,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent static member GlobalForegroundParseCountStatistic = foregroundParseCount static member GlobalForegroundTypeCheckCountStatistic = foregroundTypeCheckCount + //---------------------------------------------------------------------------- // FSharpChecker // @@ -2695,7 +2702,7 @@ type FSharpChecker(referenceResolver, projectCacheSize, keepAssemblyContents, ke let braceMatchCache = MruCache(braceMatchCacheSize, areSame=AreSameForParsing3, - areSameForSubsumption=AreSubsumable3) + areSimilar=AreSubsumable3) let mutable maxMemoryReached = false let mutable maxMB = maxMBDefault @@ -2863,8 +2870,8 @@ type FSharpChecker(referenceResolver, projectCacheSize, keepAssemblyContents, ke /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. - member ic.CheckFileInProjectIfReady(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj) = - backgroundCompiler.CheckFileInProjectIfReady(parseResults,filename,fileVersion,source,options,textSnapshotInfo) + member ic.CheckFileInProjectAllowingStaleCachedResults(parseResults:FSharpParseFileResults, filename:string, fileVersion:int, source:string, options:FSharpProjectOptions, ?textSnapshotInfo:obj) = + backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults(parseResults,filename,fileVersion,source,options,textSnapshotInfo) /// Typecheck a source code file, returning a handle to the results of the /// parse including the reconstructed types in the file. @@ -2892,7 +2899,7 @@ type FSharpChecker(referenceResolver, projectCacheSize, keepAssemblyContents, ke member ic.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?extraProjectInfo: obj) = let loadedTimeStamp = defaultArg loadedTimeStamp DateTime.MaxValue // Not 'now', we don't want to force reloading { ProjectFileName = projectFileName - ProjectFileNames = [| |] // the project file names will be inferred from the ProjectOptions + SourceFiles = [| |] // the project file names will be inferred from the ProjectOptions OtherOptions = argv ReferencedProjects= [| |] IsIncompleteTypeCheckEnvironment = false diff --git a/src/fsharp/vs/service.fsi b/src/fsharp/vs/service.fsi index 961c3d30c9f..34b5f525d94 100755 --- a/src/fsharp/vs/service.fsi +++ b/src/fsharp/vs/service.fsi @@ -301,27 +301,36 @@ type internal FSharpProjectOptions = { // Note that this may not reduce to just the project directory, because there may be two projects in the same directory. ProjectFileName: string + /// The files in the project - ProjectFileNames: string[] + SourceFiles: string[] + /// Additional command line argument options for the project. These can include additional files and references. OtherOptions: string[] + /// The command line arguments for the other projects referenced by this project, indexed by the /// exact text used in the "-r:" reference in FSharpProjectOptions. ReferencedProjects: (string * FSharpProjectOptions)[] + /// When true, the typechecking environment is known a priori to be incomplete, for /// example when a .fs file is opened outside of a project. In this case, the number of error /// messages reported is reduced. IsIncompleteTypeCheckEnvironment : bool + /// When true, use the reference resolution rules for scripts rather than the rules for compiler. UseScriptResolutionRules : bool + /// Timestamp of project/script load, used to differentiate between different instances of a project load. /// This ensures that a complete reload of the project or script type checking /// context occurs on project or script unload/reload. LoadTime : DateTime + /// Unused in this API and should be 'None' when used as user-specified input UnresolvedReferences : UnresolvedReferencesSet option + /// Unused in this API and should be '[]' when used as user-specified input OriginalLoadReferences: (range * string) list + /// Extra information passed back on event trigger ExtraProjectInfo : obj option @@ -401,7 +410,7 @@ type internal FSharpChecker = /// can be used to marginally increase accuracy of intellisense results in some situations. /// /// - member CheckFileInProjectIfReady : parsed: FSharpParseFileResults * filename: string * fileversion: int * source: string * options: FSharpProjectOptions * ?textSnapshotInfo: obj -> Async + member CheckFileInProjectAllowingStaleCachedResults : parsed: FSharpParseFileResults * filename: string * fileversion: int * source: string * options: FSharpProjectOptions * ?textSnapshotInfo: obj -> Async /// /// @@ -629,8 +638,7 @@ type internal FSharpChecker = /// Tokenize an entire file, line by line member TokenizeFile: source:string -> FSharpTokenInfo [] [] - - + // An object to typecheck source in a given typechecking environment. // Used internally to provide intellisense over F# Interactive. diff --git a/tests/service/FileSystemTests.fs b/tests/service/FileSystemTests.fs index 2dc2c1fb1ad..dee67a9969c 100644 --- a/tests/service/FileSystemTests.fs +++ b/tests/service/FileSystemTests.fs @@ -95,7 +95,7 @@ let ``FileSystem compilation test``() = yield "-r:" + r |] { ProjectFileName = @"c:\mycode\compilation.fsproj" // Make a name that is unique in this directory. - ProjectFileNames = [| fileName1; fileName2 |] + SourceFiles = [| fileName1; fileName2 |] OtherOptions = allFlags ReferencedProjects = [| |]; IsIncompleteTypeCheckEnvironment = false diff --git a/tests/service/ProjectOptionsTests.fs b/tests/service/ProjectOptionsTests.fs index e641bcbc9a5..1069789fef7 100644 --- a/tests/service/ProjectOptionsTests.fs +++ b/tests/service/ProjectOptionsTests.fs @@ -50,7 +50,7 @@ let ``Project file parsing example 1 Default Configuration`` () = let projectFile = __SOURCE_DIRECTORY__ + @"/FSharp.Compiler.Service.Tests.fsproj" let options = ProjectCracker.GetProjectOptionsFromProjectFile(projectFile) - checkOption options.ProjectFileNames "FileSystemTests.fs" + checkOption options.SourceFiles "FileSystemTests.fs" checkOption options.OtherOptions "FSharp.Compiler.Service.dll" checkOption options.OtherOptions "--define:TRACE" @@ -65,7 +65,7 @@ let ``Project file parsing example 1 Release Configuration`` () = // Check with Configuration = Release let options = ProjectCracker.GetProjectOptionsFromProjectFile(projectFile, [("Configuration", "Release")]) - checkOption options.ProjectFileNames "FileSystemTests.fs" + checkOption options.SourceFiles "FileSystemTests.fs" checkOption options.OtherOptions "FSharp.Compiler.Service.dll" checkOption options.OtherOptions "--define:TRACE" @@ -78,7 +78,7 @@ let ``Project file parsing example 1 Default configuration relative path`` () = Directory.SetCurrentDirectory(__SOURCE_DIRECTORY__) let options = ProjectCracker.GetProjectOptionsFromProjectFile(projectFile) - checkOption options.ProjectFileNames "FileSystemTests.fs" + checkOption options.SourceFiles "FileSystemTests.fs" checkOption options.OtherOptions "FSharp.Compiler.Service.dll" checkOption options.OtherOptions "--define:TRACE" @@ -123,14 +123,14 @@ let ``Project file parsing Sample_VS2013_FSharp_Portable_Library_net451_adjusted [] let ``Project file parsing -- compile files 1``() = let opts = ProjectCracker.GetProjectOptionsFromProjectFile(__SOURCE_DIRECTORY__ + @"/data/Test1.fsproj") - CollectionAssert.AreEqual (["Test1File2.fs"; "Test1File1.fs"], opts.ProjectFileNames |> Array.map Path.GetFileName) + CollectionAssert.AreEqual (["Test1File2.fs"; "Test1File1.fs"], opts.SourceFiles |> Array.map Path.GetFileName) CollectionAssert.IsEmpty (getCompiledFilenames opts.OtherOptions) [] let ``Project file parsing -- compile files 2``() = let opts = ProjectCracker.GetProjectOptionsFromProjectFile(__SOURCE_DIRECTORY__ + @"/data/Test2.fsproj") - CollectionAssert.AreEqual (["Test2File2.fs"; "Test2File1.fs"], opts.ProjectFileNames |> Array.map Path.GetFileName) + CollectionAssert.AreEqual (["Test2File2.fs"; "Test2File1.fs"], opts.SourceFiles |> Array.map Path.GetFileName) CollectionAssert.IsEmpty (getCompiledFilenames opts.OtherOptions) [] @@ -413,7 +413,7 @@ let ``Project file parsing -- project file contains project reference to out-of- [] let ``Project file parsing -- space in file name``() = let opts = ProjectCracker.GetProjectOptionsFromProjectFile(__SOURCE_DIRECTORY__ + @"/data/Space in name.fsproj") - CollectionAssert.AreEqual (["Test2File2.fs"; "Test2File1.fs"], opts.ProjectFileNames |> Array.map Path.GetFileName) + CollectionAssert.AreEqual (["Test2File2.fs"; "Test2File1.fs"], opts.SourceFiles |> Array.map Path.GetFileName) CollectionAssert.IsEmpty (getCompiledFilenames opts.OtherOptions) [] @@ -461,14 +461,14 @@ let ``Test OtherOptions order for GetProjectOptionsFromScript`` () = #endif [] -let ``Test ProjectFileNames order for GetProjectOptionsFromScript`` () = // See #594 +let ``Test SourceFiles order for GetProjectOptionsFromScript`` () = // See #594 let test scriptName expected = let scriptPath = __SOURCE_DIRECTORY__ + @"/data/ScriptProject/" + scriptName + ".fsx" let scriptSource = File.ReadAllText scriptPath let projOpts, _diagnostics = checker.GetProjectOptionsFromScript(scriptPath, scriptSource) |> Async.RunSynchronously - projOpts.ProjectFileNames + projOpts.SourceFiles |> Array.map Path.GetFileNameWithoutExtension |> shouldEqual expected test "Main1" [|"BaseLib1"; "Lib1"; "Lib2"; "Main1"|] diff --git a/vsintegration/Utils/LanguageServiceProfiling/Options.fs b/vsintegration/Utils/LanguageServiceProfiling/Options.fs index 35ce0f86883..8738893333b 100644 --- a/vsintegration/Utils/LanguageServiceProfiling/Options.fs +++ b/vsintegration/Utils/LanguageServiceProfiling/Options.fs @@ -196,7 +196,7 @@ let FCS (repositoryDir: string) : Options = { Options = {ProjectFileName = repositoryDir @"src\fsharp\FSharp.Compiler.Service\FSharp.Compiler.Service.fsproj" - ProjectFileNames = files |> Array.map (fun x -> repositoryDir x) + SourceFiles = files |> Array.map (fun x -> repositoryDir x) OtherOptions = [|@"-o:obj\Release\FSharp.Compiler.Service.dll"; "-g"; "--noframework"; @"--baseaddress:0x06800000"; "--define:DEBUG"; @@ -304,7 +304,7 @@ let FCS (repositoryDir: string) : Options = let VFPT (repositoryDir: string) : Options = { Options = {ProjectFileName = repositoryDir @"src\FSharp.Editing\FSharp.Editing.fsproj" - ProjectFileNames = + SourceFiles = [|@"src\FSharp.Editing\AssemblyInfo.fs"; @"src\FSharp.Editing\Common\Utils.fs"; @"src\FSharp.Editing\Common\CompilerLocationUtils.fs"; diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 878013a095e..32f7b81bdd7 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -64,6 +64,8 @@ type internal FSharpCheckerProvider member this.Checker = checker.Value +type Refreshable<'T> = 'T * (unit -> 'T) + // Exposes project information as MEF component [); Composition.Shared>] type internal ProjectInfoManager @@ -73,21 +75,34 @@ type internal ProjectInfoManager [)>] serviceProvider: System.IServiceProvider ) = // A table of information about projects, excluding single-file projects. - let projectTable = ConcurrentDictionary() + let projectTable = ConcurrentDictionary>() // A table of information about single-file projects. Currently we only need the load time of each such file, plus // the original options for editing let singleFileProjectTable = ConcurrentDictionary() - member this.AddSingleFileProject(projectId, timeStampAndOptions) = - singleFileProjectTable.TryAdd(projectId, timeStampAndOptions) |> ignore + /// Clear a project from the project table + member this.ClearInfoForProject(projectId: ProjectId) = + projectTable.TryRemove(projectId) |> ignore + this.RefreshInfoForProjectsThatReferenceThisProject(projectId) - member this.RemoveSingleFileProject(projectId) = + member this.ClearInfoForSingleFileProject(projectId) = singleFileProjectTable.TryRemove(projectId) |> ignore - /// Clear a project from the project table - member this.ClearProjectInfo(projectId: ProjectId) = - projectTable.TryRemove(projectId) |> ignore + member this.RefreshInfoForProjectsThatReferenceThisProject(projectId: ProjectId) = + + // Search the projectTable for things to refresh + for KeyValue(otherProjectId, ((referencedProjectIds, _options), refresh)) in projectTable.ToArray() do + for referencedProjectId in referencedProjectIds do + if referencedProjectId = projectId then + projectTable.[otherProjectId] <- (refresh(), refresh) + + member this.AddOrUpdateProject(projectId, refresh) = + projectTable.[projectId] <- (refresh(), refresh) + this.RefreshInfoForProjectsThatReferenceThisProject(projectId) + + member this.AddOrUpdateSingleFileProject(projectId, data) = + singleFileProjectTable.[projectId] <- data /// Get the exact options for a single-file script member this.ComputeSingleFileOptions (tryGetOrCreateProjectId, fileName, loadTime, fileContents, workspace: Workspace) = async { @@ -96,7 +111,8 @@ type internal ProjectInfoManager if SourceFile.MustBeSingleFileProject(fileName) then let optionsStamp = None // TODO: can we use a unique stamp? let! options, _diagnostics = checkerProvider.Checker.GetProjectOptionsFromScript(fileName, fileContents, loadTime, [| |], ?extraProjectInfo=extraProjectInfo, ?optionsStamp=optionsStamp) - let site = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, options) + let referencedProjectFileNames = [| |] // TODO: can we find the referenced project file names + let site = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, referencedProjectFileNames, options) return ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject,site,fileName,options.ExtraProjectInfo,serviceProvider, true) else let site = ProjectSitesAndFiles.ProjectSiteOfSingleFile(fileName) @@ -105,11 +121,13 @@ type internal ProjectInfoManager /// Update the info for a project in the project table member this.UpdateProjectInfo(tryGetOrCreateProjectId, projectId: ProjectId, site: IProjectSite, workspace: Workspace) = - let extraProjectInfo = Some(box workspace) - let tryGetOptionsForReferencedProject f = f |> tryGetOrCreateProjectId |> Option.bind this.TryGetOptionsForProject - let options = ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, site, site.ProjectFileName(), extraProjectInfo, serviceProvider, true) - checkerProvider.Checker.InvalidateConfiguration(options) - projectTable.[projectId] <- options + this.AddOrUpdateProject(projectId, (fun () -> + let extraProjectInfo = Some(box workspace) + let tryGetOptionsForReferencedProject f = f |> tryGetOrCreateProjectId |> Option.bind this.TryGetOptionsForProject + let referencedProjects, options = ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, site, site.ProjectFileName(), extraProjectInfo, serviceProvider, true) + let referencedProjectIds = referencedProjects |> Array.choose tryGetOrCreateProjectId + checkerProvider.Checker.InvalidateConfiguration(options) + referencedProjectIds, options)) /// Get compilation defines relevant for syntax processing. /// Quicker then TryGetOptionsForDocumentOrProject as it doesn't need to recompute the exact project @@ -125,7 +143,7 @@ type internal ProjectInfoManager /// Get the options for a project member this.TryGetOptionsForProject(projectId: ProjectId) = match projectTable.TryGetValue(projectId) with - | true, options -> Some options + | true, ((_referencedProjects, options), _) -> Some options | _ -> None /// Get the exact options for a document or project @@ -136,13 +154,14 @@ type internal ProjectInfoManager // single-file project may contain #load and #r references which are changing as the user edits, and we may need to re-analyze // to determine the latest settings. FCS keeps a cache to help ensure these are up-to-date. match singleFileProjectTable.TryGetValue(projectId) with - | true, (loadTime,_) -> + | true, (loadTime, _) -> try let fileName = document.FilePath let! cancellationToken = Async.CancellationToken let! sourceText = document.GetTextAsync(cancellationToken) - let! options = this.ComputeSingleFileOptions ((fun _ -> None), fileName, loadTime, sourceText.ToString(), document.Project.Solution.Workspace) - singleFileProjectTable.[projectId] <- (loadTime, options) + let tryGetOrCreateProjectId _ = None // TODO: can we get proper project references for scripts + let! _referencedProjectFileNames, options = this.ComputeSingleFileOptions (tryGetOrCreateProjectId, fileName, loadTime, sourceText.ToString(), document.Project.Solution.Workspace) + this.AddOrUpdateSingleFileProject(projectId, (loadTime, options)) return Some options with ex -> Assert.Exception(ex) @@ -260,13 +279,17 @@ and let tryRemoveSingleFileProject projectId = match singleFileProjects.TryRemove(projectId) with | true, project -> - projectInfoManager.RemoveSingleFileProject(projectId) + projectInfoManager.ClearInfoForSingleFileProject(projectId) project.Disconnect() | _ -> () let invalidPathChars = set (Path.GetInvalidPathChars()) let isPathWellFormed (path: string) = not (String.IsNullOrWhiteSpace path) && path |> Seq.forall (fun c -> not (Set.contains c invalidPathChars)) + let tryGetOrCreateProjectId (workspace: VisualStudioWorkspaceImpl) (projectFileName: string) = + let projectDisplayName = projectDisplayNameOf projectFileName + Some (workspace.ProjectTracker.GetOrCreateProjectIdForPath(projectFileName, projectDisplayName)) + override this.Initialize() = base.Initialize() @@ -340,7 +363,7 @@ and // update the cached options if updated then - projectInfoManager.UpdateProjectInfo(this.GetProjectIdForReferencedProject workspace, project.Id, site, project.Workspace) + projectInfoManager.UpdateProjectInfo(tryGetOrCreateProjectId workspace, project.Id, site, project.Workspace) member this.SetupProjectFile(siteProvider: IProvideProjectSite, workspace: VisualStudioWorkspaceImpl) = let rec setup (site: IProjectSite) = @@ -350,7 +373,7 @@ and let projectId = workspace.ProjectTracker.GetOrCreateProjectIdForPath(projectFileName, projectDisplayName) if isNull (workspace.ProjectTracker.GetProject projectId) then - projectInfoManager.UpdateProjectInfo(this.GetProjectIdForReferencedProject workspace, projectId, site, workspace) + projectInfoManager.UpdateProjectInfo(tryGetOrCreateProjectId workspace, projectId, site, workspace) let projectContextFactory = package.ComponentModel.GetService(); let errorReporter = ProjectExternalErrorReporter(projectId, "FS", this.SystemServiceProvider) @@ -375,7 +398,7 @@ and AdviseProjectSiteChanges(fun () -> this.SyncProject(project, projectContext, site, workspace, forceUpdate=true))) site.AdviseProjectSiteClosed(FSharpConstants.FSharpLanguageServiceCallbackName, AdviseProjectSiteChanges(fun () -> - projectInfoManager.ClearProjectInfo(project.Id) + projectInfoManager.ClearInfoForProject(project.Id) project.Disconnect())) for referencedSite in ProjectSitesAndFiles.GetReferencedProjectSites (site, this.SystemServiceProvider) do let referencedProjectId = setup referencedSite @@ -383,20 +406,15 @@ and projectId setup (siteProvider.GetProjectSite()) |> ignore - member this.GetProjectIdForReferencedProject (workspace: VisualStudioWorkspaceImpl) (projectFileName: string) = - let projectDisplayName = projectDisplayNameOf projectFileName - Some (workspace.ProjectTracker.GetOrCreateProjectIdForPath(projectFileName, projectDisplayName)) - member this.SetupStandAloneFile(fileName: string, fileContents: string, workspace: VisualStudioWorkspaceImpl, hier: IVsHierarchy) = let loadTime = DateTime.Now - let options = projectInfoManager.ComputeSingleFileOptions (this.GetProjectIdForReferencedProject workspace, fileName, loadTime, fileContents, workspace) |> Async.RunSynchronously - let projectFileName = fileName let projectDisplayName = projectDisplayNameOf projectFileName let projectId = workspace.ProjectTracker.GetOrCreateProjectIdForPath(projectFileName, projectDisplayName) - projectInfoManager.AddSingleFileProject(projectId, (loadTime, options)) + let _referencedProjectFileNames, options = projectInfoManager.ComputeSingleFileOptions (tryGetOrCreateProjectId workspace, fileName, loadTime, fileContents, workspace) |> Async.RunSynchronously + projectInfoManager.AddOrUpdateSingleFileProject(projectId, (loadTime, options)) if isNull (workspace.ProjectTracker.GetProject projectId) then let projectContextFactory = package.ComponentModel.GetService(); diff --git a/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs b/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs index 94e36166b78..cb7f6fdfa8e 100644 --- a/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs +++ b/vsintegration/src/FSharp.LanguageService/BackgroundRequests.fs @@ -71,7 +71,8 @@ type internal FSharpLanguageServiceBackgroundRequests let timestamp = if source=null then System.DateTime(2000,1,1) else source.OpenedTime // source is null in unit tests let checker = getInteractiveChecker() let checkOptions, _diagnostics = checker.GetProjectOptionsFromScript(fileName, sourceText, timestamp, [| |]) |> Async.RunSynchronously - let projectSite = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, checkOptions) + let referencedProjectFileNames = [| |] + let projectSite = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, referencedProjectFileNames, checkOptions) { ProjectSite = projectSite CheckOptions = checkOptions ProjectFileName = projectSite.ProjectFileName() @@ -82,7 +83,7 @@ type internal FSharpLanguageServiceBackgroundRequests // This portion is executed on the UI thread. let rdt = getServiceProvider().RunningDocumentTable let projectSite = getProjectSitesAndFiles().FindOwningProject(rdt,fileName) - let checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, fileName, None, getServiceProvider(), false) + let _, checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, fileName, None, getServiceProvider(), false) let projectFileName = projectSite.ProjectFileName() let data = { ProjectSite = projectSite @@ -168,7 +169,7 @@ type internal FSharpLanguageServiceBackgroundRequests // Type-checking let typedResults,aborted = - match interactiveChecker.CheckFileInProjectIfReady(parseResults,req.FileName,req.Timestamp,req.Text,checkOptions,req.Snapshot) |> Async.RunSynchronously with + match interactiveChecker.CheckFileInProjectAllowingStaleCachedResults(parseResults,req.FileName,req.Timestamp,req.Text,checkOptions,req.Snapshot) |> Async.RunSynchronously with | None -> None,false | Some FSharpCheckFileAnswer.Aborted -> // isResultObsolete returned true during the type check. diff --git a/vsintegration/src/FSharp.LanguageService/FSharpSource.fs b/vsintegration/src/FSharp.LanguageService/FSharpSource.fs index 08980eb1309..2faac7745bf 100644 --- a/vsintegration/src/FSharp.LanguageService/FSharpSource.fs +++ b/vsintegration/src/FSharp.LanguageService/FSharpSource.fs @@ -322,7 +322,7 @@ type internal FSharpSource(service:LanguageService, textLines, colorizer, vsFile // get a sync parse of the file let co = { ProjectFileName = fileName + ".dummy.fsproj" - ProjectFileNames = [| fileName |] + SourceFiles = [| fileName |] OtherOptions = flags ReferencedProjects = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs b/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs index 0596c9f0a80..f5898e58b1f 100644 --- a/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs +++ b/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs @@ -15,12 +15,12 @@ open Microsoft.FSharp.Compiler.SourceCodeServices /// An additional interface that an IProjectSite object can implement to indicate it has an FSharpProjectOptions /// already available, so we don't have to recreate it type private IHaveCheckOptions = - abstract OriginalCheckOptions : unit -> FSharpProjectOptions + abstract OriginalCheckOptions : unit -> string[] * FSharpProjectOptions /// Convert from FSharpProjectOptions into IProjectSite. -type private ProjectSiteOfScriptFile(filename:string, checkOptions : FSharpProjectOptions) = +type private ProjectSiteOfScriptFile(filename:string, referencedProjectFileNames, checkOptions : FSharpProjectOptions) = interface IProjectSite with - override this.SourceFilesOnDisk() = checkOptions.ProjectFileNames + override this.SourceFilesOnDisk() = checkOptions.SourceFiles override this.DescriptionOfProject() = sprintf "Script Closure at Root %s" filename override this.CompilerFlags() = checkOptions.OtherOptions override this.ProjectFileName() = checkOptions.ProjectFileName @@ -37,7 +37,7 @@ type private ProjectSiteOfScriptFile(filename:string, checkOptions : FSharpProje override this.AssemblyReferences() = [||] interface IHaveCheckOptions with - override this.OriginalCheckOptions() = checkOptions + override this.OriginalCheckOptions() = (referencedProjectFileNames, checkOptions) /// An orphan file project is a .fs, .ml, .fsi, .mli that is not associated with a .fsproj. @@ -110,45 +110,49 @@ type internal ProjectSitesAndFiles() = | Some _ -> Seq.empty static let rec referencedProvideProjectSites (projectSite:IProjectSite, serviceProvider:System.IServiceProvider) = - let solutionService = - try Some (serviceProvider.GetService(typeof) :?> IVsSolution) with _ -> None - match solutionService with - | Some solutionService -> - referencedProjects projectSite - |> Seq.choose (fun p -> - match solutionService.GetProjectOfUniqueName(p.UniqueName) with - | VSConstants.S_OK, (:? IProvideProjectSite as ps) -> - Some (p, ps) - | _ -> None) - | None -> Seq.empty + seq { + let solutionService = try Some (serviceProvider.GetService(typeof) :?> IVsSolution) with _ -> None + match solutionService with + | Some solutionService -> + for p in referencedProjects projectSite do + match solutionService.GetProjectOfUniqueName(p.UniqueName) with + | VSConstants.S_OK, (:? IProvideProjectSite as ps) -> + yield (p, ps) + | _ -> () + | None -> () + } - static let rec referencedProjectsOf (tryGetOptionsForReferencedProject, projectSite:IProjectSite, fileName, extraProjectInfo, serviceProvider:System.IServiceProvider, useUniqueStamp) = - referencedProvideProjectSites (projectSite, serviceProvider) - |> Seq.choose (fun (p, ps) -> - fullOutputAssemblyPath p - |> Option.map (fun path -> - let referencedProjectOptions = - // Lookup may not succeed if the project has not been established yet - // In this case we go and compute the options recursively. - match tryGetOptionsForReferencedProject p.FileName with - | None -> getProjectOptionsForProjectSite (tryGetOptionsForReferencedProject, ps.GetProjectSite(), fileName, extraProjectInfo, serviceProvider, useUniqueStamp) - | Some options -> options - path, referencedProjectOptions) - ) - |> Seq.toArray + static let rec referencedProjectsOf (tryGetOptionsForReferencedProject, projectSite:IProjectSite, extraProjectInfo, serviceProvider:System.IServiceProvider, useUniqueStamp) = + [| for (p,ps) in referencedProvideProjectSites (projectSite, serviceProvider) do + match fullOutputAssemblyPath p with + | None -> () + | Some path -> + let referencedProjectOptions = + // Lookup may not succeed if the project has not been established yet + // In this case we go and compute the options recursively. + match tryGetOptionsForReferencedProject p.FileName with + | None -> getProjectOptionsForProjectSite (tryGetOptionsForReferencedProject, ps.GetProjectSite(), p.FileName, extraProjectInfo, serviceProvider, useUniqueStamp) |> snd + | Some options -> options + yield (p.FileName, (path, referencedProjectOptions)) |] and getProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, projectSite:IProjectSite, fileName, extraProjectInfo, serviceProvider, useUniqueStamp) = - {ProjectFileName = projectSite.ProjectFileName() - ProjectFileNames = projectSite.SourceFilesOnDisk() - OtherOptions = projectSite.CompilerFlags() - ReferencedProjects = referencedProjectsOf(tryGetOptionsForReferencedProject, projectSite, fileName, extraProjectInfo, serviceProvider, useUniqueStamp) - IsIncompleteTypeCheckEnvironment = projectSite.IsIncompleteTypeCheckEnvironment - UseScriptResolutionRules = SourceFile.MustBeSingleFileProject fileName - LoadTime = projectSite.LoadTime - UnresolvedReferences = None - OriginalLoadReferences = [] - ExtraProjectInfo=extraProjectInfo - Stamp = (if useUniqueStamp then (stamp <- stamp + 1L; Some stamp) else None) } + let referencedProjectFileNames, referencedProjectOptions = + referencedProjectsOf(tryGetOptionsForReferencedProject, projectSite, extraProjectInfo, serviceProvider, useUniqueStamp) + |> Array.unzip + + let options = + {ProjectFileName = projectSite.ProjectFileName() + SourceFiles = projectSite.SourceFilesOnDisk() + OtherOptions = projectSite.CompilerFlags() + ReferencedProjects = referencedProjectOptions + IsIncompleteTypeCheckEnvironment = projectSite.IsIncompleteTypeCheckEnvironment + UseScriptResolutionRules = SourceFile.MustBeSingleFileProject fileName + LoadTime = projectSite.LoadTime + UnresolvedReferences = None + OriginalLoadReferences = [] + ExtraProjectInfo=extraProjectInfo + Stamp = (if useUniqueStamp then (stamp <- stamp + 1L; Some stamp) else None) } + referencedProjectFileNames, options /// Construct a project site for a single file. May be a single file project (for scripts) or an orphan project site (for everything else). static member ProjectSiteOfSingleFile(filename:string) : IProjectSite = @@ -240,5 +244,6 @@ type internal ProjectSitesAndFiles() = getProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, projectSite, filename, extraProjectInfo, serviceProvider, useUniqueStamp) /// Create project site for these project options - static member CreateProjectSiteForScript (filename, checkOptions) = ProjectSiteOfScriptFile (filename, checkOptions) :> IProjectSite + static member CreateProjectSiteForScript (filename, referencedProjectFileNames, checkOptions) = + ProjectSiteOfScriptFile (filename, referencedProjectFileNames, checkOptions) :> IProjectSite diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index 1f373f44dba..2735b0c8c3a 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1362,9 +1362,7 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem override x.ComputeSourcesAndFlags() = - if x.IsInBatchUpdate || box x.BuildProject = null then () - else - if not(inMidstOfReloading) && not(VsBuildManagerAccessorExtensionMethods.IsInProgress(accessor)) then + if not x.IsInBatchUpdate && box x.BuildProject <> null && not inMidstOfReloading && not (VsBuildManagerAccessorExtensionMethods.IsInProgress(accessor)) then use waitDialog = { @@ -1697,6 +1695,12 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem null : System.String let OnActiveProjectCfgChange(pIVsHierarchy) = + if pIVsHierarchy = null then + let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) + MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) + MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) + projNode.UpdateMSBuildState() + if GetCaption(pIVsHierarchy) = GetCaption(projNode.InteropSafeIVsHierarchy) && batchState <> BatchDone then projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) projNode.ComputeSourcesAndFlags() diff --git a/vsintegration/tests/Salsa/FSharpLanguageServiceTestable.fs b/vsintegration/tests/Salsa/FSharpLanguageServiceTestable.fs index 8e820697b75..eebd9e5c31e 100644 --- a/vsintegration/tests/Salsa/FSharpLanguageServiceTestable.fs +++ b/vsintegration/tests/Salsa/FSharpLanguageServiceTestable.fs @@ -126,7 +126,7 @@ type internal FSharpLanguageServiceTestable() as this = /// Respond to project being cleaned/rebuilt (any live type providers in the project should be refreshed) member this.OnProjectCleaned(projectSite:IProjectSite) = - let checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, "" ,None, serviceProvider.Value, false) + let _, checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, "" ,None, serviceProvider.Value, false) this.FSharpChecker.NotifyProjectCleaned(checkOptions) |> Async.RunSynchronously member this.OnActiveViewChanged(textView) = @@ -168,7 +168,7 @@ type internal FSharpLanguageServiceTestable() as this = interface IDependencyFileChangeNotify with member this.DependencyFileCreated projectSite = // Invalidate the configuration if we notice any add for any DependencyFiles - let checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, "", None, this.ServiceProvider, false) + let _, checkOptions = ProjectSitesAndFiles.GetProjectOptionsForProjectSite((fun _ -> None), projectSite, "", None, this.ServiceProvider, false) this.FSharpChecker.InvalidateConfiguration(checkOptions) member this.DependencyFileChanged (filename) = diff --git a/vsintegration/tests/unittests/BraceMatchingServiceTests.fs b/vsintegration/tests/unittests/BraceMatchingServiceTests.fs index 4db16665231..180224985db 100644 --- a/vsintegration/tests/unittests/BraceMatchingServiceTests.fs +++ b/vsintegration/tests/unittests/BraceMatchingServiceTests.fs @@ -19,7 +19,7 @@ type BraceMatchingServiceTests() = let fileName = "C:\\test.fs" let options: FSharpProjectOptions = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| fileName |] + SourceFiles = [| fileName |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/BreakpointResolutionService.fs b/vsintegration/tests/unittests/BreakpointResolutionService.fs index e25aea1b9e2..11f2879369f 100644 --- a/vsintegration/tests/unittests/BreakpointResolutionService.fs +++ b/vsintegration/tests/unittests/BreakpointResolutionService.fs @@ -24,7 +24,7 @@ type BreakpointResolutionServiceTests() = let fileName = "C:\\test.fs" let options: FSharpProjectOptions = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| fileName |] + SourceFiles = [| fileName |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/CompletionProviderTests.fs b/vsintegration/tests/unittests/CompletionProviderTests.fs index 23b638cd891..c5fef8253b6 100644 --- a/vsintegration/tests/unittests/CompletionProviderTests.fs +++ b/vsintegration/tests/unittests/CompletionProviderTests.fs @@ -37,7 +37,7 @@ open UnitTests.TestLib.LanguageService let filePath = "C:\\test.fs" let internal options = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/DocumentDiagnosticAnalyzerTests.fs b/vsintegration/tests/unittests/DocumentDiagnosticAnalyzerTests.fs index d6576406f88..7fc0ecfcdad 100644 --- a/vsintegration/tests/unittests/DocumentDiagnosticAnalyzerTests.fs +++ b/vsintegration/tests/unittests/DocumentDiagnosticAnalyzerTests.fs @@ -26,7 +26,7 @@ type DocumentDiagnosticAnalyzerTests() = let endMarker = "(*end*)" let options: FSharpProjectOptions = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/DocumentHighlightsServiceTests.fs b/vsintegration/tests/unittests/DocumentHighlightsServiceTests.fs index 568af25a273..433a93df02a 100644 --- a/vsintegration/tests/unittests/DocumentHighlightsServiceTests.fs +++ b/vsintegration/tests/unittests/DocumentHighlightsServiceTests.fs @@ -39,7 +39,7 @@ let filePath = "C:\\test.fs" let internal options = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/GoToDefinitionServiceTests.fs b/vsintegration/tests/unittests/GoToDefinitionServiceTests.fs index 1c23588a572..6ea2c0dc516 100644 --- a/vsintegration/tests/unittests/GoToDefinitionServiceTests.fs +++ b/vsintegration/tests/unittests/GoToDefinitionServiceTests.fs @@ -105,7 +105,7 @@ let _ = Module1.foo 1 let filePath = Path.GetTempFileName() + ".fs" let options: FSharpProjectOptions = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/HelpContextServiceTests.fs b/vsintegration/tests/unittests/HelpContextServiceTests.fs index ba5ddd86f1d..24c2ca9e651 100644 --- a/vsintegration/tests/unittests/HelpContextServiceTests.fs +++ b/vsintegration/tests/unittests/HelpContextServiceTests.fs @@ -22,7 +22,7 @@ type HelpContextServiceTests() = let fileName = "C:\\test.fs" let options: FSharpProjectOptions = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| fileName |] + SourceFiles = [| fileName |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/QuickInfoProviderTests.fs b/vsintegration/tests/unittests/QuickInfoProviderTests.fs index 0d6c0456019..cc9280f43a4 100644 --- a/vsintegration/tests/unittests/QuickInfoProviderTests.fs +++ b/vsintegration/tests/unittests/QuickInfoProviderTests.fs @@ -36,7 +36,7 @@ let filePath = "C:\\test.fs" let internal options = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/SignatureHelpProviderTests.fs b/vsintegration/tests/unittests/SignatureHelpProviderTests.fs index a83891eb5a7..524b580461b 100644 --- a/vsintegration/tests/unittests/SignatureHelpProviderTests.fs +++ b/vsintegration/tests/unittests/SignatureHelpProviderTests.fs @@ -36,7 +36,7 @@ let PathRelativeToTestAssembly p = Path.Combine(Path.GetDirectoryName(Uri( Syste let internal options = { ProjectFileName = "C:\\test.fsproj" - ProjectFileNames = [| filePath |] + SourceFiles = [| filePath |] ReferencedProjects = [| |] OtherOptions = [| "-r:" + PathRelativeToTestAssembly(@"UnitTests\MockTypeProviders\DummyProviderForLanguageServiceTesting.dll") |] IsIncompleteTypeCheckEnvironment = true diff --git a/vsintegration/tests/unittests/Tests.InternalCollections.fs b/vsintegration/tests/unittests/Tests.InternalCollections.fs index 0aca1861a8b..1ad0088761c 100644 --- a/vsintegration/tests/unittests/Tests.InternalCollections.fs +++ b/vsintegration/tests/unittests/Tests.InternalCollections.fs @@ -77,7 +77,7 @@ type MruCache = let PairToString (s,n) = rb.NumToString n let AreSameForSubsumption((s1,n1),(s2,n2)) = n1=n2 - let m = new MruCache(3, PairToString, (fun (x,y) -> x = y), areSameForSubsumption=AreSameForSubsumption) + let m = new MruCache(3, PairToString, (fun (x,y) -> x = y), areSimilar=AreSameForSubsumption) m.SetAlternate(("x",2),"Banana") let s = m.Get (("x",2)) Assert.IsTrue("Banana"=s, "Check1") @@ -92,7 +92,7 @@ type MruCache = let AreSameForSubsumption((s1,n1),(s2,n2)) = s1=s2 let discarded = ref [] - let m = new MruCache(compute=fst, areSame=(fun (x,y) -> x = y), areSameForSubsumption=AreSameForSubsumption, keepStrongly=2, keepMax=2, onDiscard=(fun s -> discarded := s :: !discarded)) + let m = new MruCache(compute=fst, areSame=(fun (x,y) -> x = y), areSimilar=AreSameForSubsumption, keepStrongly=2, keepMax=2, onDiscard=(fun s -> discarded := s :: !discarded)) m.SetAlternate(("x",1),"Banana") // no discard printfn "discarded = %A" discarded.Value Assert.IsTrue(discarded.Value = [], "Check1") diff --git a/vsintegration/tests/unittests/Tests.LanguageService.Script.fs b/vsintegration/tests/unittests/Tests.LanguageService.Script.fs index b29287fc801..bce0b1696a2 100644 --- a/vsintegration/tests/unittests/Tests.LanguageService.Script.fs +++ b/vsintegration/tests/unittests/Tests.LanguageService.Script.fs @@ -1199,8 +1199,8 @@ type UsingMSBuild() as this = AssertArrayContainsPartialMatchOf(fas.OtherOptions, "System.Runtime.Remoting.dll") AssertArrayContainsPartialMatchOf(fas.OtherOptions, "System.Transactions.dll") AssertArrayContainsPartialMatchOf(fas.OtherOptions, "FSharp.Compiler.Interactive.Settings.dll") - Assert.AreEqual(Path.Combine(projectFolder,"File1.fsx"), fas.ProjectFileNames.[0]) - Assert.AreEqual(1, fas.ProjectFileNames.Length) + Assert.AreEqual(Path.Combine(projectFolder,"File1.fsx"), fas.SourceFiles.[0]) + Assert.AreEqual(1, fas.SourceFiles.Length) /// FEATURE: #reference against a strong name should work. From fe086b3b2508177426f1f8ba8e89ae8f72cf1c2b Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 00:25:26 +0100 Subject: [PATCH 02/19] Fix configuration changes --- src/fsharp/CompileOps.fs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 2c13503dca4..6c31ba89ddb 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2702,8 +2702,6 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = | Some(fslibFilename) -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename try - use ilReader = OpenILBinary(filename,data.optimizeForMemory,data.openBinariesInMemory,None,None, data.shadowCopyReferences) - checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) fslibRoot (* , sprintf "v%d.%d" v1 v2 *) with e -> From 2dbbfd8f85326e31fd8b623a951c2720f5ae3251 Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 01:16:27 +0100 Subject: [PATCH 03/19] Fix colorization cache for changing defines --- .../LanguageService/Tokenizer.fs | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs b/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs index 01e52c13b80..f811f783888 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/Tokenizer.fs @@ -2,6 +2,7 @@ open System open System.Collections.Generic +open System.Collections.Concurrent open System.Threading open System.Threading.Tasks open System.Runtime.CompilerServices @@ -267,7 +268,7 @@ module internal Tokenizer = data.[i] <- None i <- i + 1 - let private dataCache = ConditionalWeakTable() + let private dataCache = ConditionalWeakTable>() let compilerTokenToRoslynToken(colorKind: FSharpTokenColorKind) : string = match colorKind with @@ -346,13 +347,23 @@ module internal Tokenizer = SourceLineData(textLine.Start, lexState, previousLexState.Value, lineContents.GetHashCode(), classifiedSpans, List.ofSeq tokens) + + // We keep incremental data per-document. When text changes we correlate text line-by-line (by hash codes of lines) + // We index the data by the active defines in the document. + let private getSourceTextData(documentKey: DocumentId, defines: string list, linesCount) = + let dict = dataCache.GetValue(documentKey, fun key -> new ConcurrentDictionary<_,_>(1,1,HashIdentity.Structural)) + if dict.ContainsKey(defines) then dict.[defines] + else + let data = SourceTextData(linesCount) + dict.TryAdd(defines, data) |> ignore + data + let getColorizationData(documentKey: DocumentId, sourceText: SourceText, textSpan: TextSpan, fileName: string option, defines: string list, - cancellationToken: CancellationToken) : List = + cancellationToken: CancellationToken) : List = try let sourceTokenizer = FSharpSourceTokenizer(defines, fileName) let lines = sourceText.Lines - // We keep incremental data per-document. When text changes we correlate text line-by-line (by hash codes of lines) - let sourceTextData = dataCache.GetValue(documentKey, fun key -> SourceTextData(lines.Count)) + let sourceTextData = getSourceTextData(documentKey, defines, lines.Count) let startLine = lines.GetLineFromPosition(textSpan.Start).LineNumber let endLine = lines.GetLineFromPosition(textSpan.End).LineNumber @@ -539,7 +550,7 @@ module internal Tokenizer = let sourceTokenizer = FSharpSourceTokenizer(defines, Some fileName) let lines = sourceText.Lines // We keep incremental data per-document. When text changes we correlate text line-by-line (by hash codes of lines) - let sourceTextData = dataCache.GetValue(documentKey, fun key -> SourceTextData(lines.Count)) + let sourceTextData = getSourceTextData(documentKey, defines, lines.Count) // Go backwards to find the last cached scanned line that is valid let scanStartLine = let mutable i = min (lines.Count - 1) lineNumber From 9bd99c0f1ec686e965f437f6562516a9bf5cb3ca Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 15:19:18 +0100 Subject: [PATCH 04/19] fix config switching --- .../LanguageService/LanguageService.fs | 36 +++++-- .../Project/Utilities.cs | 24 +++++ .../FSharp.ProjectSystem.FSharp/Project.fs | 96 +++++++++---------- 3 files changed, 101 insertions(+), 55 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 32f7b81bdd7..3fcca9719d1 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -8,6 +8,7 @@ open System open System.Collections.Concurrent open System.Collections.Generic open System.ComponentModel.Composition +open System.Runtime.CompilerServices open System.Runtime.InteropServices open System.IO open System.Diagnostics @@ -290,6 +291,8 @@ and let projectDisplayName = projectDisplayNameOf projectFileName Some (workspace.ProjectTracker.GetOrCreateProjectIdForPath(projectFileName, projectDisplayName)) + let optionsAssociation = ConditionalWeakTable() + override this.Initialize() = base.Initialize() @@ -331,36 +334,55 @@ and /// Sync the information for the project member this.SyncProject(project: AbstractProject, projectContext: IWorkspaceProjectContext, site: IProjectSite, workspace, forceUpdate) = let wellFormedFilePathSetIgnoreCase (paths: seq) = - HashSet(paths |> Seq.filter isPathWellFormed, StringComparer.OrdinalIgnoreCase) + HashSet(paths |> Seq.filter isPathWellFormed |> Seq.map (fun s -> try System.IO.Path.GetFullPath(s) with _ -> s), StringComparer.OrdinalIgnoreCase) let updatedFiles = site.SourceFilesOnDisk() |> wellFormedFilePathSetIgnoreCase - let workspaceFiles = project.GetCurrentDocuments() |> Seq.map (fun file -> file.FilePath) |> wellFormedFilePathSetIgnoreCase + let originalFiles = project.GetCurrentDocuments() |> Seq.map (fun file -> file.FilePath) |> wellFormedFilePathSetIgnoreCase let mutable updated = forceUpdate for file in updatedFiles do - if not(workspaceFiles.Contains(file)) then + if not(originalFiles.Contains(file)) then projectContext.AddSourceFile(file) updated <- true - for file in workspaceFiles do + for file in originalFiles do if not(updatedFiles.Contains(file)) then projectContext.RemoveSourceFile(file) updated <- true let updatedRefs = site.AssemblyReferences() |> wellFormedFilePathSetIgnoreCase - let workspaceRefs = project.GetCurrentMetadataReferences() |> Seq.map (fun ref -> ref.FilePath) |> wellFormedFilePathSetIgnoreCase + let originalRefs = project.GetCurrentMetadataReferences() |> Seq.map (fun ref -> ref.FilePath) |> wellFormedFilePathSetIgnoreCase for ref in updatedRefs do - if not(workspaceRefs.Contains(ref)) then + if not(originalRefs.Contains(ref)) then projectContext.AddMetadataReference(ref, MetadataReferenceProperties.Assembly) updated <- true - for ref in workspaceRefs do + for ref in originalRefs do if not(updatedRefs.Contains(ref)) then projectContext.RemoveMetadataReference(ref) updated <- true + let ok,originalOptions = optionsAssociation.TryGetValue(projectContext) + let updatedOptions = site.CompilerFlags() + if not ok || originalOptions <> updatedOptions then + let updatedFiles = site.SourceFilesOnDisk() |> wellFormedFilePathSetIgnoreCase + + // OK, project options have changed, try to fake out Roslyn to convince it to reparse things + // Calling SetOptions fails because the CPS project system being used by the F# project system + // imlpementation at the moment has no command line parser installed. + //projectContext.SetOptions(String.concat " " updatedOptions) + for file in updatedFiles do + projectContext.RemoveSourceFile(file) + projectContext.AddSourceFile(file) + + // Record the last seen options as an associated value + if ok then optionsAssociation.Remove(projectContext) |> ignore + optionsAssociation.Add(projectContext, updatedOptions) + + updated <- true + // update the cached options if updated then projectInfoManager.UpdateProjectInfo(tryGetOrCreateProjectId workspace, project.Id, site, project.Workspace) diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/Utilities.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/Utilities.cs index 78fd100ed4f..516ff22a11b 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/Utilities.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/Utilities.cs @@ -997,6 +997,30 @@ public static bool TryGetActiveConfigurationAndPlatform(System.IServiceProvider return true; } + /// + /// Retrives the configuration and the platform using the IVsSolutionBuildManager2 interface. + /// + /// A service provider. + /// The hierrachy whose configuration is requested. + /// true if successfull. + public static bool TryGetConfigurationAndPlatform(IVsCfg config, out ConfigCanonicalName configCanonicalName) + { + + string configName = null; + config.get_DisplayName(out configName); + + if (configName == null) + { + configCanonicalName = new ConfigCanonicalName(); + return false; + } + + configCanonicalName = new ConfigCanonicalName(configName); + + return true; + } + + /// /// Determines whether the shell is in command line mode. /// diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index 2735b0c8c3a..4107b100784 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1364,7 +1364,7 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem if not x.IsInBatchUpdate && box x.BuildProject <> null && not inMidstOfReloading && not (VsBuildManagerAccessorExtensionMethods.IsInProgress(accessor)) then - use waitDialog = + use sourcesAndFlagsWaitDialog = { WaitCaption = FSharpSR.GetString FSharpSR.ProductName WaitMessage = FSharpSR.GetString FSharpSR.ComputingSourcesAndFlags @@ -1672,7 +1672,7 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // "double CCW-wrapping" of the same object. type internal SolutionEventsListener(projNode) = - let mutable waitDialog : IDisposable option = None + static let mutable waitDialog : IDisposable option = None // During batch active project configuration changes, make sure we only run CSAF once // per batch. Before this change, OnActiveProjectCfgChange was being called twice per @@ -1683,44 +1683,26 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // two IVsHierarchy objects are equal by comparing their captions. (It's ok if this // occasionally yields false positives, as this just means we may do a little extra // background work.) - let GetCaption(hier : IVsHierarchy) = + let GetCaption(hier : IVsHierarchy) : string = if hier = null then - null : System.String + null else - let mutable o : obj = null - let r = hier.GetProperty(VSConstants.VSITEMID_ROOT, int(__VSHPROPID.VSHPROPID_Caption), &o) - if r = VSConstants.S_OK then - o :?> System.String + let mutable o = null + let hr = hier.GetProperty(VSConstants.VSITEMID_ROOT, int(__VSHPROPID.VSHPROPID_Caption), &o) + if hr = VSConstants.S_OK then + o :?> string else - null : System.String - - let OnActiveProjectCfgChange(pIVsHierarchy) = - if pIVsHierarchy = null then - let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) - MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) - MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) - projNode.UpdateMSBuildState() - - if GetCaption(pIVsHierarchy) = GetCaption(projNode.InteropSafeIVsHierarchy) && batchState <> BatchDone then - projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - projNode.ComputeSourcesAndFlags() - - if batchState = BatchWaiting then - batchState <- BatchDone - VSConstants.S_OK + null let UpdateConfig(pHierProj) = - // By default, the F# project system keeps its own internal Configuration and Platform in sync with the current active - // Configuration and Platform by listening for OnActiveProjectCfgChange events. However there is one case where the - // active cfg changes without an event, and this is during 'Batch Build'. So we listen for the start and end of - // Batch Build, and manually update the project to the active cfg before/after to set/reset the config. - if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) then + if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) && batchState <> BatchDone then // This code matches what ProjectNode.SetConfiguration would do; that method cannot be called during a build, but at this // current moment in time, it is 'safe' to do this update. let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) - projNode.UpdateMSBuildState() + if batchState = BatchWaiting then + batchState <- BatchDone interface IVsUpdateSolutionEvents with member x.UpdateSolution_Begin(pfCancelUpdate) = @@ -1731,8 +1713,9 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem VSConstants.S_OK member x.UpdateSolution_Cancel() = VSConstants.S_OK - member x.OnActiveProjectCfgChange(pIVsHierarchy) = - OnActiveProjectCfgChange(pIVsHierarchy) + member x.OnActiveProjectCfgChange(pHierProj) = + UpdateConfig(pHierProj) + VSConstants.S_OK interface IVsUpdateSolutionEvents2 with member x.UpdateSolution_Begin(pfCancelUpdate) = @@ -1743,49 +1726,66 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem VSConstants.S_OK member x.UpdateSolution_Cancel() = VSConstants.S_OK - member x.OnActiveProjectCfgChange(pIVsHierarchy) = - OnActiveProjectCfgChange(pIVsHierarchy) + member x.OnActiveProjectCfgChange(pHierProj) = + UpdateConfig(pHierProj) + VSConstants.S_OK member x.UpdateProjectCfg_Begin(pHierProj, _pCfgProj, _pCfgSln, _dwAction, pfCancel) = UpdateConfig(pHierProj) VSConstants.S_OK member x.UpdateProjectCfg_Done(pHierProj, _pCfgProj, _pCfgSln, _dwAction, _fSuccess, _fCancel) = UpdateConfig(pHierProj) + // We wait until allproject configurations have been updated before updating our MSBuild state + projNode.UpdateMSBuildState() + projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + projNode.ComputeSourcesAndFlags() VSConstants.S_OK interface IVsUpdateSolutionEvents3 with + member x.OnBeforeActiveSolutionCfgChange(_oldCfg, _newCfg) = + // this will be called for each project, but wait dialogs cannot 'stack' // i.e. if a wait dialog is already open, subsequent calls to StartWaitDialog // will not override the current open dialog - waitDialog <- - { - WaitCaption = FSharpSR.GetString FSharpSR.ProductName - WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration - ProgressText = None - StatusBmpAnim = null - StatusBarText = None - DelayToShowDialogSecs = 1 - IsCancelable = false - ShowMarqueeProgress = true - } - |> WaitDialog.start projNode.Site - |> Some + if waitDialog.IsNone then + waitDialog <- + { + WaitCaption = FSharpSR.GetString FSharpSR.ProductName + WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration + ProgressText = None + StatusBmpAnim = null + StatusBarText = None + DelayToShowDialogSecs = 1 + IsCancelable = false + ShowMarqueeProgress = true + } + |> WaitDialog.start projNode.Site + |> Some VSConstants.S_OK member x.OnAfterActiveSolutionCfgChange(_oldCfg, _newCfg) = + // We wait until allproject configurations have been updated before updating our MSBuild state + projNode.UpdateMSBuildState() + projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + projNode.ComputeSourcesAndFlags() + match waitDialog with | Some x -> x.Dispose() waitDialog <- None - | None -> () + | _ -> () VSConstants.S_OK interface IVsUpdateSolutionEvents4 with member x.OnActiveProjectCfgChangeBatchBegin() = batchState <- BatchWaiting + member x.OnActiveProjectCfgChangeBatchEnd() = + projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + projNode.ComputeSourcesAndFlags() batchState <- NonBatch + member x.UpdateSolution_BeginFirstUpdateAction() = () member x.UpdateSolution_BeginUpdateAction(_dwAction) = From 6f593bb1b2ab0c83589effef75d6539b03619a1d Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 15:31:34 +0100 Subject: [PATCH 05/19] add manual test cases --- .../AssemblyInfo.fs | 41 ++++++++ .../Class.fs | 11 +++ ...brary1AlwaysInMatchingConfiguration.fsproj | 77 +++++++++++++++ .../fff.config | 4 + .../AssemblyInfo.fs | 41 ++++++++ .../Class.fs | 10 ++ .../Library2AlwaysInDebugConfiguration.fsproj | 78 +++++++++++++++ .../packages.config | 4 + .../TestProjectChanges/TestProjectChanges.sln | 34 +++++++ .../TestProjectChanges/App.config | 6 ++ .../TestProjectChanges/AssemblyInfo.fs | 41 ++++++++ .../TestProjectChanges/Program.fs | 18 ++++ .../TestProjectChanges.fsproj | 95 +++++++++++++++++++ .../LanguageService/LanguageService.fs | 1 + 14 files changed, 461 insertions(+) create mode 100644 tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/AssemblyInfo.fs create mode 100644 tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Class.fs create mode 100644 tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Library1AlwaysInMatchingConfiguration.fsproj create mode 100644 tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/fff.config create mode 100644 tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/AssemblyInfo.fs create mode 100644 tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Class.fs create mode 100644 tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Library2AlwaysInDebugConfiguration.fsproj create mode 100644 tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/packages.config create mode 100644 tests/projects/misc/TestProjectChanges/TestProjectChanges.sln create mode 100644 tests/projects/misc/TestProjectChanges/TestProjectChanges/App.config create mode 100644 tests/projects/misc/TestProjectChanges/TestProjectChanges/AssemblyInfo.fs create mode 100644 tests/projects/misc/TestProjectChanges/TestProjectChanges/Program.fs create mode 100644 tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj diff --git a/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/AssemblyInfo.fs b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/AssemblyInfo.fs new file mode 100644 index 00000000000..6d9185a23ff --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace Library1AlwaysInMatchingConfiguration.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Class.fs b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Class.fs new file mode 100644 index 00000000000..4c07dc31062 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Class.fs @@ -0,0 +1,11 @@ + +namespace Library1AlwaysInMatchingConfiguration + +type Class() = + static member PropertyAlwaysAvailable = "F#" +#if DEBUG + static member PropertyAvailableInProject1DebugConfiguration = "F#" +#endif +#if RELEASE + static member PropertyAvailableInProject1ReleaseConfiguration = "F#" +#endif diff --git a/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Library1AlwaysInMatchingConfiguration.fsproj b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Library1AlwaysInMatchingConfiguration.fsproj new file mode 100644 index 00000000000..41a5d2167c2 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/Library1AlwaysInMatchingConfiguration.fsproj @@ -0,0 +1,77 @@ + + + + + Debug + AnyCPU + 2.0 + 9f36577a-657b-4117-a118-f69ab182aa31 + Library + Library1AlwaysInMatchingConfiguration + Library1AlwaysInMatchingConfiguration + v4.5.2 + 4.4.1.0 + true + Library1AlwaysInMatchingConfiguration + + + true + full + false + false + bin\$(Configuration)\ + DEBUG;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + pdbonly + true + true + bin\$(Configuration)\ + RELEASE;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + 11 + + + + + $(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets + + + + + + + + + + + + FSharp.Core + FSharp.Core.dll + $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\$(TargetFSharpCoreVersion)\FSharp.Core.dll + + + + + + ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + + + + \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/fff.config b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/fff.config new file mode 100644 index 00000000000..7d629041bc5 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library1AlwaysInMatchingConfiguration/fff.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/AssemblyInfo.fs b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/AssemblyInfo.fs new file mode 100644 index 00000000000..2060387a9b4 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace Library2AlwaysInDebugConfiguration.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Class.fs b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Class.fs new file mode 100644 index 00000000000..a2c57eefb35 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Class.fs @@ -0,0 +1,10 @@ +namespace Library2AlwaysInDebugConfiguration + +type Class() = + static member PropertyAlwaysAvailable = "F#" +#if DEBUG + static member PropertyAvailableInProject2DebugConfiguration = "F#" +#endif +#if RELEASE + static member PropertyAvailableInProject2ReleaseConfiguration = "F#" +#endif diff --git a/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Library2AlwaysInDebugConfiguration.fsproj b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Library2AlwaysInDebugConfiguration.fsproj new file mode 100644 index 00000000000..2d4ffb6f889 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/Library2AlwaysInDebugConfiguration.fsproj @@ -0,0 +1,78 @@ + + + + + Debug + AnyCPU + 2.0 + e72ee9de-323e-4f99-8d7e-1a1ed8a3477c + Library + Library2AlwaysInDebugConfiguration + Library2AlwaysInDebugConfiguration + v4.5.2 + 4.4.1.0 + true + Library2AlwaysInDebugConfiguration + + + true + full + false + false + bin\$(Configuration)\ + DEBUG;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + pdbonly + true + true + bin\$(Configuration)\ + RELEASE;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + 11 + + + + + $(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets + + + + + + + + + + + + + FSharp.Core + FSharp.Core.dll + $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\$(TargetFSharpCoreVersion)\FSharp.Core.dll + + + + + + ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + + + + \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/packages.config b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/packages.config new file mode 100644 index 00000000000..7d629041bc5 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/Library2AlwaysInDebugConfiguration/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges.sln b/tests/projects/misc/TestProjectChanges/TestProjectChanges.sln new file mode 100644 index 00000000000..5a19cafa3e8 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.4 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "TestProjectChanges", "TestProjectChanges\TestProjectChanges.fsproj", "{DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Library1AlwaysInMatchingConfiguration", "Library1AlwaysInMatchingConfiguration\Library1AlwaysInMatchingConfiguration.fsproj", "{9F36577A-657B-4117-A118-F69AB182AA31}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Library2AlwaysInDebugConfiguration", "Library2AlwaysInDebugConfiguration\Library2AlwaysInDebugConfiguration.fsproj", "{E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Release|Any CPU.Build.0 = Release|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Release|Any CPU.Build.0 = Release|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Release|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges/App.config b/tests/projects/misc/TestProjectChanges/TestProjectChanges/App.config new file mode 100644 index 00000000000..88fa4027bda --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges/AssemblyInfo.fs b/tests/projects/misc/TestProjectChanges/TestProjectChanges/AssemblyInfo.fs new file mode 100644 index 00000000000..973e1b5c8a2 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace ConsoleApplication1.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges/Program.fs b/tests/projects/misc/TestProjectChanges/TestProjectChanges/Program.fs new file mode 100644 index 00000000000..97fad1e1a71 --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges/Program.fs @@ -0,0 +1,18 @@ +// Learn more about F# at http://fsharp.org +// See the 'F# Tutorial' project for more help. + +[] +let main argv = + printfn "%A" argv + let c1 = Library1AlwaysInMatchingConfiguration.Class.PropertyAlwaysAvailable + let c1 = Library2AlwaysInDebugConfiguration.Class.PropertyAlwaysAvailable +#if DEBUG + let c1 = Library1AlwaysInMatchingConfiguration.Class.PropertyAvailableInProject1DebugConfiguration + let c2 = Library2AlwaysInDebugConfiguration.Class.PropertyAvailableInProject2DebugConfiguration +#else + let c1 = Library1AlwaysInMatchingConfiguration.Class.PropertyAvailableInProject1ReleaseConfiguration + let c2 = Library2AlwaysInDebugConfiguration.Class.PropertyAvailableInProject2DebugConfiguration +#endif + + + 0 // return an integer exit code diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj b/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj new file mode 100644 index 00000000000..4ace4388b7a --- /dev/null +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj @@ -0,0 +1,95 @@ + + + + + Debug + AnyCPU + 2.0 + df29450f-abd7-49fb-96c5-c9cae9a54f40 + Exe + ConsoleApplication1 + ConsoleApplication1 + v4.5.2 + true + 4.4.1.0 + TestProjectChanges + + + true + full + false + false + bin\$(Configuration)\ + DEBUG;TRACE + 3 + AnyCPU + bin\$(Configuration)\$(AssemblyName).XML + true + + + pdbonly + true + true + bin\$(Configuration)\ + TRACE + 3 + AnyCPU + bin\$(Configuration)\$(AssemblyName).XML + true + + + + + FSharp.Core + FSharp.Core.dll + $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\$(TargetFSharpCoreVersion)\FSharp.Core.dll + + + ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + True + + + + + + + + + + + + + Library1AlwaysInMatchingConfiguration + {9f36577a-657b-4117-a118-f69ab182aa31} + True + + + Library2AlwaysInDebugConfiguration + {e72ee9de-323e-4f99-8d7e-1a1ed8a3477c} + True + + + + 11 + + + + + $(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets + + + + + + \ No newline at end of file diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 3fcca9719d1..77c7f18bfb7 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -421,6 +421,7 @@ and site.AdviseProjectSiteClosed(FSharpConstants.FSharpLanguageServiceCallbackName, AdviseProjectSiteChanges(fun () -> projectInfoManager.ClearInfoForProject(project.Id) + optionsAssociation.Remove(projectContext) |> ignore project.Disconnect())) for referencedSite in ProjectSitesAndFiles.GetReferencedProjectSites (site, this.SystemServiceProvider) do let referencedProjectId = setup referencedSite From 1e840615985fd6ddd4aa6cf290c9fcd3c7134449 Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 15:35:45 +0100 Subject: [PATCH 06/19] Fix test --- src/fsharp/CompileOps.fs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 6c31ba89ddb..b503384b58f 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2702,6 +2702,10 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = | Some(fslibFilename) -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename try + if validate && fslibReference.ProjectReference.IsNone then + use ilReader = OpenILBinary(filename,data.optimizeForMemory,data.openBinariesInMemory,None,None, data.shadowCopyReferences) + checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; + let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) fslibRoot (* , sprintf "v%d.%d" v1 v2 *) with e -> From ccc9e47415b3d96ce087a034cd22516c8afe8be1 Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 15:36:35 +0100 Subject: [PATCH 07/19] minor nit --- src/fsharp/CompileOps.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index b503384b58f..02e0bcc1570 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2707,7 +2707,7 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) - fslibRoot (* , sprintf "v%d.%d" v1 v2 *) + fslibRoot with e -> error(Error(FSComp.SR.buildErrorOpeningBinaryFile(filename, e.Message), rangeStartup)) | _ -> From 4b62d41efd67a722548edb7670a5f1473d3f4802 Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 16:18:35 +0100 Subject: [PATCH 08/19] use correct reference count --- src/fsharp/vs/service.fs | 32 +++++++++---------- src/fsharp/vs/service.fsi | 3 +- .../LanguageService/LanguageService.fs | 31 ++++++++++++------ 3 files changed, 38 insertions(+), 28 deletions(-) diff --git a/src/fsharp/vs/service.fs b/src/fsharp/vs/service.fs index 8bbfc5c196a..68979e44aed 100644 --- a/src/fsharp/vs/service.fs +++ b/src/fsharp/vs/service.fs @@ -1727,11 +1727,11 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo // This may be None initially, or may be set to None when the object is disposed or finalized let mutable details = match scopeOptX with None -> None | Some scopeX -> Some (scopeX, builderX, reactorOpsX) + // Increment the usage count on the IncrementalBuilder. We want to keep the IncrementalBuilder and all associated + // resources and type providers alive for the duration of the lifetime of this object. let decrementer = match details with | Some (_,Some builder,_) -> - // Increment the usage count on the IncrementalBuilder. We want to keep the IncrementalBuilder and all associated - // resources and type providers alive for the duration of the lifetime of this object. builder.IncrementUsageCount() | _ -> { new System.IDisposable with member x.Dispose() = () } @@ -1749,7 +1749,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo decrementer.Dispose()) | _ -> () - // Run an operation that needs to be run in the reactor thread + // Run an operation that needs to access a builder and be run in the reactor thread let reactorOp desc dflt f = async { match details with @@ -1759,7 +1759,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo System.Diagnostics.Debug.Assert(false,"unexpected dead builder") return dflt | Some (scope, builderOpt, reactor) -> - // Ensure the builder doesn't get released while running operations asynchronously. + // Increment the usage count to ensure the builder doesn't get released while running operations asynchronously. use _unwind = match builderOpt with Some builder -> builder.IncrementUsageCount() | None -> { new System.IDisposable with member __.Dispose() = () } let! res = reactor.EnqueueAndAwaitOpAsync(desc, fun ctok -> f ctok scope |> cancellable.Return) return res @@ -2417,7 +2417,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.CheckFileInProject(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("CheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) // Q: Whis it it ok to ignore creationErrors in the build cache? A: These errors will be appended into the typecheck results + let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt match builderOpt with | None -> return FSharpCheckFileAnswer.Succeeded (MakeCheckFileResultsEmpty(creationErrors)) @@ -2438,7 +2438,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.ParseAndCheckFileInProject(filename:string, fileVersion, source, options:FSharpProjectOptions,textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("ParseAndCheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) // Q: Whis it it ok to ignore creationErrors in the build cache? A: These errors will be appended into the typecheck results + let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt match builderOpt with | None -> @@ -2588,7 +2588,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent return options, errors.Diagnostics }) - member bc.InvalidateConfiguration(options : FSharpProjectOptions) = + member bc.InvalidateConfiguration(options : FSharpProjectOptions, ?startBackgroundCompile) = + let startBackgroundCompile = defaultArg startBackgroundCompile implicitlyStartBackgroundWork // This operation can't currently be cancelled nor awaited reactor.EnqueueOp("InvalidateConfiguration", fun ctok -> // If there was a similar entry then re-establish an empty builder . This is a somewhat arbitrary choice - it @@ -2599,11 +2600,11 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, // including by incrementalBuildersCache.Set. - let builderB, errorsB, decrementB = CreateOneIncrementalBuilder (ctok, options) |> Cancellable.runWithoutCancellation - incrementalBuildersCache.Set(ctok, options, (builderB, errorsB, decrementB)) + let newBuilderInfo = CreateOneIncrementalBuilder (ctok, options) |> Cancellable.runWithoutCancellation + incrementalBuildersCache.Set(ctok, options, newBuilderInfo) // Start working on the project. Also a somewhat arbitrary choice - if implicitlyStartBackgroundWork then + if startBackgroundCompile then bc.CheckProjectInBackground(options)) member bc.NotifyProjectCleaned (options : FSharpProjectOptions) = @@ -2617,8 +2618,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent | Some (_similarOptions, (_oldBuilder, _, _)) -> // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, // including by incrementalBuildersCache.Set. - let! builderB, errorsB, decrementB = CreateOneIncrementalBuilder (ctok, options) - incrementalBuildersCache.Set(ctok, options, (builderB, errorsB, decrementB)) + let! newBuilderInfo = CreateOneIncrementalBuilder (ctok, options) + incrementalBuildersCache.Set(ctok, options, newBuilderInfo) }) member bc.CheckProjectInBackground (options) = @@ -2848,9 +2849,6 @@ type FSharpChecker(referenceResolver, projectCacheSize, keepAssemblyContents, ke backgroundCompiler.DownsizeCaches() |> Async.RunSynchronously maxMemEvent.Trigger( () ) - /// This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. - /// For example, the type provider approvals file may have changed. - // // This is for unit testing only member ic.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() = backgroundCompiler.CompleteAllQueuedOps() // flush AsyncOp @@ -2861,8 +2859,8 @@ type FSharpChecker(referenceResolver, projectCacheSize, keepAssemblyContents, ke /// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. /// For example, dependent references may have been deleted or created. - member ic.InvalidateConfiguration(options: FSharpProjectOptions) = - backgroundCompiler.InvalidateConfiguration options + member ic.InvalidateConfiguration(options: FSharpProjectOptions, ?startBackgroundCompile) = + backgroundCompiler.InvalidateConfiguration(options,?startBackgroundCompile=startBackgroundCompile) /// This function is called when a project has been cleaned, and thus type providers should be refreshed. member ic.NotifyProjectCleaned(options: FSharpProjectOptions) = diff --git a/src/fsharp/vs/service.fsi b/src/fsharp/vs/service.fsi index 34b5f525d94..00a0a1af02c 100755 --- a/src/fsharp/vs/service.fsi +++ b/src/fsharp/vs/service.fsi @@ -553,12 +553,11 @@ type internal FSharpChecker = member TryGetRecentCheckResultsForFile : filename: string * options:FSharpProjectOptions * ?source: string -> (FSharpParseFileResults * FSharpCheckFileResults * (*version*)int) option /// This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation. - /// For example, the type provider approvals file may have changed. member InvalidateAll : unit -> unit /// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions. /// For example, dependent references may have been deleted or created. - member InvalidateConfiguration: options: FSharpProjectOptions -> unit + member InvalidateConfiguration: options: FSharpProjectOptions * ?startBackgroundCompile: bool -> unit /// Set the project to be checked in the background. Overrides any previous call to CheckProjectInBackground member CheckProjectInBackground: options: FSharpProjectOptions -> unit diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 77c7f18bfb7..2db51e05432 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -65,7 +65,7 @@ type internal FSharpCheckerProvider member this.Checker = checker.Value -type Refreshable<'T> = 'T * (unit -> 'T) +type Refreshable<'T> = 'T * (bool -> 'T) // Exposes project information as MEF component [); Composition.Shared>] @@ -91,15 +91,14 @@ type internal ProjectInfoManager singleFileProjectTable.TryRemove(projectId) |> ignore member this.RefreshInfoForProjectsThatReferenceThisProject(projectId: ProjectId) = - // Search the projectTable for things to refresh for KeyValue(otherProjectId, ((referencedProjectIds, _options), refresh)) in projectTable.ToArray() do for referencedProjectId in referencedProjectIds do if referencedProjectId = projectId then - projectTable.[otherProjectId] <- (refresh(), refresh) + projectTable.[otherProjectId] <- (refresh true, refresh) member this.AddOrUpdateProject(projectId, refresh) = - projectTable.[projectId] <- (refresh(), refresh) + projectTable.[projectId] <- (refresh false, refresh) this.RefreshInfoForProjectsThatReferenceThisProject(projectId) member this.AddOrUpdateSingleFileProject(projectId, data) = @@ -110,9 +109,13 @@ type internal ProjectInfoManager let extraProjectInfo = Some(box workspace) let tryGetOptionsForReferencedProject f = f |> tryGetOrCreateProjectId |> Option.bind this.TryGetOptionsForProject if SourceFile.MustBeSingleFileProject(fileName) then - let optionsStamp = None // TODO: can we use a unique stamp? + // NOTE: we don't use a unique stamp for single files, instead comparing options structurally. + // This is because we repeatedly recompute the options. + let optionsStamp = None let! options, _diagnostics = checkerProvider.Checker.GetProjectOptionsFromScript(fileName, fileContents, loadTime, [| |], ?extraProjectInfo=extraProjectInfo, ?optionsStamp=optionsStamp) - let referencedProjectFileNames = [| |] // TODO: can we find the referenced project file names + // NOTE: we don't use FCS cross-project references from scripts to projects. THe projects must have been + // compiled and #r will refer to files on disk + let referencedProjectFileNames = [| |] let site = ProjectSitesAndFiles.CreateProjectSiteForScript(fileName, referencedProjectFileNames, options) return ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject,site,fileName,options.ExtraProjectInfo,serviceProvider, true) else @@ -122,12 +125,12 @@ type internal ProjectInfoManager /// Update the info for a project in the project table member this.UpdateProjectInfo(tryGetOrCreateProjectId, projectId: ProjectId, site: IProjectSite, workspace: Workspace) = - this.AddOrUpdateProject(projectId, (fun () -> + this.AddOrUpdateProject(projectId, (fun isRefresh -> let extraProjectInfo = Some(box workspace) let tryGetOptionsForReferencedProject f = f |> tryGetOrCreateProjectId |> Option.bind this.TryGetOptionsForProject let referencedProjects, options = ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, site, site.ProjectFileName(), extraProjectInfo, serviceProvider, true) let referencedProjectIds = referencedProjects |> Array.choose tryGetOrCreateProjectId - checkerProvider.Checker.InvalidateConfiguration(options) + checkerProvider.Checker.InvalidateConfiguration(options, startBackgroundWork = not isRefresh) referencedProjectIds, options)) /// Get compilation defines relevant for syntax processing. @@ -160,7 +163,9 @@ type internal ProjectInfoManager let fileName = document.FilePath let! cancellationToken = Async.CancellationToken let! sourceText = document.GetTextAsync(cancellationToken) - let tryGetOrCreateProjectId _ = None // TODO: can we get proper project references for scripts + // NOTE: we don't use FCS cross-project references from scripts to projects. The projects must have been + // compiled and #r will refer to files on disk. + let tryGetOrCreateProjectId _ = None let! _referencedProjectFileNames, options = this.ComputeSingleFileOptions (tryGetOrCreateProjectId, fileName, loadTime, sourceText.ToString(), document.Project.Solution.Workspace) this.AddOrUpdateSingleFileProject(projectId, (loadTime, options)) return Some options @@ -303,6 +308,14 @@ and tryRemoveSingleFileProject args.Document.Project.Id Events.SolutionEvents.OnAfterCloseSolution.Add <| fun _ -> + checkerProvider.Checker.StopBackgroundCompile() + + // FUTURE: consider enbling some or all of these to flush all caches and stop all background builds. However the operations + // are asynchronous and we need to decide if we stop everything synchronously. + + //checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() + //checkerProvider.Checker.InvalidateAll() + singleFileProjects.Keys |> Seq.iter tryRemoveSingleFileProject let ctx = System.Threading.SynchronizationContext.Current From b9d6ffabd68c285bd2393b926969356b19245227 Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 16:31:20 +0100 Subject: [PATCH 09/19] cleanup decrement logic --- src/fsharp/vs/IncrementalBuild.fsi | 10 +++--- src/fsharp/vs/service.fs | 51 +++++++++++++++--------------- 2 files changed, 31 insertions(+), 30 deletions(-) diff --git a/src/fsharp/vs/IncrementalBuild.fsi b/src/fsharp/vs/IncrementalBuild.fsi index e9eca6905a1..db19694188c 100755 --- a/src/fsharp/vs/IncrementalBuild.fsi +++ b/src/fsharp/vs/IncrementalBuild.fsi @@ -65,10 +65,6 @@ type internal PartialCheckResults = [] type internal IncrementalBuilder = - /// Increment the usage count on the IncrementalBuilder by 1. This initial usage count is 0. The returns an IDisposable which will - /// decrement the usage count on the entire build by 1 and dispose if it is no longer used by anyone. - member IncrementUsageCount : unit -> IDisposable - /// Check if the builder is not disposed member IsAlive : bool @@ -153,7 +149,11 @@ type internal IncrementalBuilder = static member TryCreateBackgroundBuilderForProjectOptions : CompilationThreadToken * ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * FrameworkImportsCache * scriptClosureOptions:LoadClosure option * sourceFiles:string list * commandLineArgs:string list * projectReferences: IProjectReference list * projectDirectory:string * useScriptResolutionRules:bool * keepAssemblyContents: bool * keepAllBackgroundResolutions: bool * maxTimeShareMilliseconds: int64 -> Cancellable - static member KeepBuilderAlive : IncrementalBuilder option -> IDisposable + /// Increment the usage count on the IncrementalBuilder by 1. This initial usage count is 0 so immediately after creation + /// a call to IncrementUsageCount should be made. The returns an IDisposable which will + /// decrement the usage count and dispose if the usage count goes to zero + static member IncrementUsageCount : IncrementalBuilder option -> IDisposable + member IsBeingKeptAliveApartFromCacheEntry : bool /// Generalized Incremental Builder. This is exposed only for unittesting purposes. diff --git a/src/fsharp/vs/service.fs b/src/fsharp/vs/service.fs index 68979e44aed..f9d8dc6da9b 100644 --- a/src/fsharp/vs/service.fs +++ b/src/fsharp/vs/service.fs @@ -1731,8 +1731,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo // resources and type providers alive for the duration of the lifetime of this object. let decrementer = match details with - | Some (_,Some builder,_) -> - builder.IncrementUsageCount() + | Some (_,builderOpt,_) -> IncrementalBuilder.IncrementUsageCount builderOpt | _ -> { new System.IDisposable with member x.Dispose() = () } let mutable disposed = false @@ -1760,7 +1759,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo return dflt | Some (scope, builderOpt, reactor) -> // Increment the usage count to ensure the builder doesn't get released while running operations asynchronously. - use _unwind = match builderOpt with Some builder -> builder.IncrementUsageCount() | None -> { new System.IDisposable with member __.Dispose() = () } + use _unwind = IncrementalBuilder.IncrementUsageCount builderOpt let! res = reactor.EnqueueAndAwaitOpAsync(desc, fun ctok -> f ctok scope |> cancellable.Return) return res } @@ -2119,7 +2118,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent options.UseScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds) // We're putting the builder in the cache, so increment its count. - let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt + let decrement = IncrementalBuilder.IncrementUsageCount builderOpt match builderOpt with | None -> () @@ -2159,12 +2158,15 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent let getOrCreateBuilder (ctok, options) = cancellable { RequireCompilationThread ctok + let! builderOpt,creationErrors,_ = getOrCreateBuilder (ctok, options) match incrementalBuildersCache.TryGet (ctok, options) with | Some b -> return b | None -> let! b = CreateOneIncrementalBuilder (ctok, options) incrementalBuildersCache.Set (ctok, options, b) return b + let decrement = IncrementalBuilder.IncrementUsageCount builderOpt + builderOpt, creationErrors, decrement } let parseCacheLock = Lock() @@ -2262,8 +2264,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent | Some (parseResults, _checkResults,_,_) -> return parseResults | _ -> foregroundParseCount <- foregroundParseCount + 1 - let! builderOpt,creationErrors,_ = getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let builderOpt,creationErrors,decrement = getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> return FSharpParseFileResults(List.toArray creationErrors, None, true, []) | Some builder -> @@ -2281,8 +2283,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.GetBackgroundParseResultsForFileInProject(filename, options) = reactor.EnqueueAndAwaitOpAsync("GetBackgroundParseResultsForFileInProject " + filename, fun ctok -> cancellable { - let! builderOpt, creationErrors, _ = getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt, creationErrors, decrement = getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> return FSharpParseFileResults(List.toArray creationErrors, None, true, []) | Some builder -> @@ -2295,8 +2297,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.MatchBraces(filename:string, source, options)= reactor.EnqueueAndAwaitOpAsync("MatchBraces " + filename, fun ctok -> cancellable { - let! builderOpt,_,_ = getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt,_,decrement = getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> return [| |] | Some builder -> @@ -2417,8 +2419,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.CheckFileInProject(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("CheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt,creationErrors, decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> return FSharpCheckFileAnswer.Succeeded (MakeCheckFileResultsEmpty(creationErrors)) | Some builder -> @@ -2438,8 +2440,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.ParseAndCheckFileInProject(filename:string, fileVersion, source, options:FSharpProjectOptions,textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("ParseAndCheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors,_ = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt,creationErrors,decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> let parseResults = FSharpParseFileResults(List.toArray creationErrors, None, true, []) @@ -2470,8 +2472,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.GetBackgroundCheckResultsForFileInProject(filename,options) = reactor.EnqueueAndAwaitOpAsync("GetBackgroundCheckResultsForFileInProject " + filename, fun ctok -> cancellable { - let! builderOpt, creationErrors, _ = getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt, creationErrors, decrement = getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> let parseResults = FSharpParseFileResults(Array.ofList creationErrors, None, true, []) @@ -2509,8 +2511,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent /// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated) member private bc.ParseAndCheckProjectImpl(options, ctok) : Cancellable = cancellable { - let! builderOpt,creationErrors,_ = getOrCreateBuilder (ctok, options) - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt,creationErrors,decrement = getOrCreateBuilder (ctok, options) + use _unwind = decrement match builderOpt with | None -> return FSharpCheckProjectResults (keepAssemblyContents, Array.ofList creationErrors, None, reactorOps) @@ -2525,8 +2527,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // NOTE: This creation of the background builder is currently run as uncancellable. Creating background builders is generally // cheap though the timestamp computations look suspicious for transitive project references. - let builderOpt,_creationErrors,_ = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let builderOpt,_creationErrors,decrement = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation + use _unwind = decrement match builderOpt with | None -> None | Some builder -> Some (builder.GetLogicalTimeStampForProject(cache, ctok)) @@ -2535,9 +2537,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.KeepProjectAlive(options) = reactor.EnqueueAndAwaitOpAsync("KeepProjectAlive " + options.ProjectFileName, fun ctok -> cancellable { - let! builderOpt,_creationErrors,_ = getOrCreateBuilder (ctok, options) - // This increments, and lets the caller decrement - return IncrementalBuilder.KeepBuilderAlive builderOpt + let! builderOpt,_creationErrors,decrement = getOrCreateBuilder (ctok, options) + return decrement }) /// Parse and typecheck the whole project. @@ -2625,8 +2626,8 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.CheckProjectInBackground (options) = reactor.SetBackgroundOp (Some (fun ctok -> // The creation of the background builder can't currently be cancelled - let builderOpt,_,_ = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation - use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt + let builderOpt,_,decrement = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation + use _unwind = decrement match builderOpt with | None -> false | Some builder -> From c42c2ffc2b9a893401eec7c9a2b3ee62a86ff0da Mon Sep 17 00:00:00 2001 From: dsyme Date: Thu, 11 May 2017 17:50:27 +0100 Subject: [PATCH 10/19] fix build --- src/fsharp/CompileOps.fs | 12 ++--- src/fsharp/vs/IncrementalBuild.fsi | 4 +- src/fsharp/vs/service.fs | 48 +++++++++---------- .../LanguageService/LanguageService.fs | 4 +- 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 02e0bcc1570..2660c07e3a2 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2701,15 +2701,15 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = match fslibExplicitFilenameOpt with | Some(fslibFilename) -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename - try - if validate && fslibReference.ProjectReference.IsNone then + if validate && fslibReference.ProjectReference.IsNone then + try use ilReader = OpenILBinary(filename,data.optimizeForMemory,data.openBinariesInMemory,None,None, data.shadowCopyReferences) checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; + with e -> + error(Error(FSComp.SR.buildErrorOpeningBinaryFile(filename, e.Message), rangeStartup)) - let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) - fslibRoot - with e -> - error(Error(FSComp.SR.buildErrorOpeningBinaryFile(filename, e.Message), rangeStartup)) + let fslibRoot = Path.GetDirectoryName(FileSystem.GetFullPathShim(filename)) + fslibRoot | _ -> data.defaultFSharpBinariesDir #endif diff --git a/src/fsharp/vs/IncrementalBuild.fsi b/src/fsharp/vs/IncrementalBuild.fsi index db19694188c..2af0354aeb7 100755 --- a/src/fsharp/vs/IncrementalBuild.fsi +++ b/src/fsharp/vs/IncrementalBuild.fsi @@ -150,9 +150,9 @@ type internal IncrementalBuilder = static member TryCreateBackgroundBuilderForProjectOptions : CompilationThreadToken * ReferenceResolver.Resolver * defaultFSharpBinariesDir: string * FrameworkImportsCache * scriptClosureOptions:LoadClosure option * sourceFiles:string list * commandLineArgs:string list * projectReferences: IProjectReference list * projectDirectory:string * useScriptResolutionRules:bool * keepAssemblyContents: bool * keepAllBackgroundResolutions: bool * maxTimeShareMilliseconds: int64 -> Cancellable /// Increment the usage count on the IncrementalBuilder by 1. This initial usage count is 0 so immediately after creation - /// a call to IncrementUsageCount should be made. The returns an IDisposable which will + /// a call to KeepBuilderAlive should be made. The returns an IDisposable which will /// decrement the usage count and dispose if the usage count goes to zero - static member IncrementUsageCount : IncrementalBuilder option -> IDisposable + static member KeepBuilderAlive : IncrementalBuilder option -> IDisposable member IsBeingKeptAliveApartFromCacheEntry : bool diff --git a/src/fsharp/vs/service.fs b/src/fsharp/vs/service.fs index f9d8dc6da9b..618624478d1 100644 --- a/src/fsharp/vs/service.fs +++ b/src/fsharp/vs/service.fs @@ -1731,7 +1731,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo // resources and type providers alive for the duration of the lifetime of this object. let decrementer = match details with - | Some (_,builderOpt,_) -> IncrementalBuilder.IncrementUsageCount builderOpt + | Some (_,builderOpt,_) -> IncrementalBuilder.KeepBuilderAlive builderOpt | _ -> { new System.IDisposable with member x.Dispose() = () } let mutable disposed = false @@ -1759,7 +1759,7 @@ type FSharpCheckFileResults(errors: FSharpErrorInfo[], scopeOptX: TypeCheckInfo return dflt | Some (scope, builderOpt, reactor) -> // Increment the usage count to ensure the builder doesn't get released while running operations asynchronously. - use _unwind = IncrementalBuilder.IncrementUsageCount builderOpt + use _unwind = IncrementalBuilder.KeepBuilderAlive builderOpt let! res = reactor.EnqueueAndAwaitOpAsync(desc, fun ctok -> f ctok scope |> cancellable.Return) return res } @@ -2118,7 +2118,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent options.UseScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds) // We're putting the builder in the cache, so increment its count. - let decrement = IncrementalBuilder.IncrementUsageCount builderOpt + let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt match builderOpt with | None -> () @@ -2155,18 +2155,18 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent requiredToKeep=(fun (builderOpt,_,_) -> match builderOpt with None -> false | Some (b:IncrementalBuilder) -> b.IsBeingKeptAliveApartFromCacheEntry), onDiscard = (fun (_, _, decrement:IDisposable) -> decrement.Dispose())) - let getOrCreateBuilder (ctok, options) = + let getOrCreateBuilderAndKeepAlive (ctok, options) = cancellable { - RequireCompilationThread ctok - let! builderOpt,creationErrors,_ = getOrCreateBuilder (ctok, options) - match incrementalBuildersCache.TryGet (ctok, options) with - | Some b -> return b - | None -> - let! b = CreateOneIncrementalBuilder (ctok, options) - incrementalBuildersCache.Set (ctok, options, b) - return b - let decrement = IncrementalBuilder.IncrementUsageCount builderOpt - builderOpt, creationErrors, decrement + RequireCompilationThread ctok + match incrementalBuildersCache.TryGet (ctok, options) with + | Some (builderOpt,creationErrors,_) -> + let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt + return builderOpt,creationErrors, decrement + | None -> + let! (builderOpt,creationErrors,_) as info = CreateOneIncrementalBuilder (ctok, options) + incrementalBuildersCache.Set (ctok, options, info) + let decrement = IncrementalBuilder.KeepBuilderAlive builderOpt + return builderOpt, creationErrors, decrement } let parseCacheLock = Lock() @@ -2264,7 +2264,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent | Some (parseResults, _checkResults,_,_) -> return parseResults | _ -> foregroundParseCount <- foregroundParseCount + 1 - let builderOpt,creationErrors,decrement = getOrCreateBuilder (ctok, options) + let! builderOpt,creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> return FSharpParseFileResults(List.toArray creationErrors, None, true, []) @@ -2283,7 +2283,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.GetBackgroundParseResultsForFileInProject(filename, options) = reactor.EnqueueAndAwaitOpAsync("GetBackgroundParseResultsForFileInProject " + filename, fun ctok -> cancellable { - let! builderOpt, creationErrors, decrement = getOrCreateBuilder (ctok, options) + let! builderOpt, creationErrors, decrement = getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> return FSharpParseFileResults(List.toArray creationErrors, None, true, []) @@ -2297,7 +2297,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.MatchBraces(filename:string, source, options)= reactor.EnqueueAndAwaitOpAsync("MatchBraces " + filename, fun ctok -> cancellable { - let! builderOpt,_,decrement = getOrCreateBuilder (ctok, options) + let! builderOpt,_,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> return [| |] @@ -2419,7 +2419,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.CheckFileInProject(parseResults: FSharpParseFileResults, filename, fileVersion, source, options, textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("CheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors, decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) + let! builderOpt,creationErrors, decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> return FSharpCheckFileAnswer.Succeeded (MakeCheckFileResultsEmpty(creationErrors)) @@ -2440,7 +2440,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.ParseAndCheckFileInProject(filename:string, fileVersion, source, options:FSharpProjectOptions,textSnapshotInfo) = let execWithReactorAsync action = reactor.EnqueueAndAwaitOpAsync("ParseAndCheckFileInProject " + filename, action) async { - let! builderOpt,creationErrors,decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilder (ctok, options) + let! builderOpt,creationErrors,decrement = execWithReactorAsync <| fun ctok -> getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> @@ -2472,7 +2472,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.GetBackgroundCheckResultsForFileInProject(filename,options) = reactor.EnqueueAndAwaitOpAsync("GetBackgroundCheckResultsForFileInProject " + filename, fun ctok -> cancellable { - let! builderOpt, creationErrors, decrement = getOrCreateBuilder (ctok, options) + let! builderOpt, creationErrors, decrement = getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> @@ -2511,7 +2511,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent /// Parse and typecheck the whole project (the implementation, called recursively as project graph is evaluated) member private bc.ParseAndCheckProjectImpl(options, ctok) : Cancellable = cancellable { - let! builderOpt,creationErrors,decrement = getOrCreateBuilder (ctok, options) + let! builderOpt,creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) use _unwind = decrement match builderOpt with | None -> @@ -2527,7 +2527,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // NOTE: This creation of the background builder is currently run as uncancellable. Creating background builders is generally // cheap though the timestamp computations look suspicious for transitive project references. - let builderOpt,_creationErrors,decrement = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation + let builderOpt,_creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) |> Cancellable.runWithoutCancellation use _unwind = decrement match builderOpt with | None -> None @@ -2537,7 +2537,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.KeepProjectAlive(options) = reactor.EnqueueAndAwaitOpAsync("KeepProjectAlive " + options.ProjectFileName, fun ctok -> cancellable { - let! builderOpt,_creationErrors,decrement = getOrCreateBuilder (ctok, options) + let! _builderOpt,_creationErrors,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) return decrement }) @@ -2626,7 +2626,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent member bc.CheckProjectInBackground (options) = reactor.SetBackgroundOp (Some (fun ctok -> // The creation of the background builder can't currently be cancelled - let builderOpt,_,decrement = getOrCreateBuilder (ctok, options) |> Cancellable.runWithoutCancellation + let builderOpt,_,decrement = getOrCreateBuilderAndKeepAlive (ctok, options) |> Cancellable.runWithoutCancellation use _unwind = decrement match builderOpt with | None -> false diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index 2db51e05432..682b5b6944b 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -130,7 +130,7 @@ type internal ProjectInfoManager let tryGetOptionsForReferencedProject f = f |> tryGetOrCreateProjectId |> Option.bind this.TryGetOptionsForProject let referencedProjects, options = ProjectSitesAndFiles.GetProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, site, site.ProjectFileName(), extraProjectInfo, serviceProvider, true) let referencedProjectIds = referencedProjects |> Array.choose tryGetOrCreateProjectId - checkerProvider.Checker.InvalidateConfiguration(options, startBackgroundWork = not isRefresh) + checkerProvider.Checker.InvalidateConfiguration(options, startBackgroundCompile = not isRefresh) referencedProjectIds, options)) /// Get compilation defines relevant for syntax processing. @@ -308,7 +308,7 @@ and tryRemoveSingleFileProject args.Document.Project.Id Events.SolutionEvents.OnAfterCloseSolution.Add <| fun _ -> - checkerProvider.Checker.StopBackgroundCompile() + //checkerProvider.Checker.StopBackgroundCompile() // FUTURE: consider enbling some or all of these to flush all caches and stop all background builds. However the operations // are asynchronous and we need to decide if we stop everything synchronously. From 6285d371d4d293f5352ffe0daa4b33d6fe6c3b47 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 11 May 2017 18:23:21 +0100 Subject: [PATCH 11/19] Update CompileOps.fs --- src/fsharp/CompileOps.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 2660c07e3a2..c134a92c38a 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2701,7 +2701,7 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = match fslibExplicitFilenameOpt with | Some(fslibFilename) -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename - if validate && fslibReference.ProjectReference.IsNone then + if (* validate && *) fslibReference.ProjectReference.IsNone then try use ilReader = OpenILBinary(filename,data.optimizeForMemory,data.openBinariesInMemory,None,None, data.shadowCopyReferences) checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; From 091110d13accbc5083ab40b9ec401234b0e35a38 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 11 May 2017 19:20:24 +0100 Subject: [PATCH 12/19] adjust unit tests mocks --- vsintegration/tests/Salsa/VsMocks.fs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/vsintegration/tests/Salsa/VsMocks.fs b/vsintegration/tests/Salsa/VsMocks.fs index fcddd870fb4..4dc0fe1f183 100644 --- a/vsintegration/tests/Salsa/VsMocks.fs +++ b/vsintegration/tests/Salsa/VsMocks.fs @@ -1522,7 +1522,14 @@ module internal VsMocks = member x.AdviseUpdateSolutionEvents4(pIVsUpdateSolutionEvents, pdwCookie) = pdwCookie <- add4 pIVsUpdateSolutionEvents member x.AdviseUpdateSolutionEventsAsync(a,b) = err(__LINE__) |> ignore - member x.FindActiveProjectCfgName(a,b) = err(__LINE__) + member x.FindActiveProjectCfgName(_projectGuid,outCfgString) = + // For now ignore the _projectGuid and just return the last notified configuration + match configDict |> Seq.tryHead with + | None -> err(__LINE__) |> ignore + | Some (KeyValue(_,v)) -> + outCfgString <- v + 0 + member x.UnadviseUpdateSolutionEventsAsync(a) = err(__LINE__) |> ignore member x.UnadviseUpdateSolutionEvents4(dwCookie) = remove4 dwCookie From fa04449652572c5f2bc78fedbab6da172b531d1e Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 11 May 2017 19:25:59 +0100 Subject: [PATCH 13/19] adjust unit tests mocks --- vsintegration/tests/Salsa/VsMocks.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vsintegration/tests/Salsa/VsMocks.fs b/vsintegration/tests/Salsa/VsMocks.fs index 4dc0fe1f183..f082f7ee10e 100644 --- a/vsintegration/tests/Salsa/VsMocks.fs +++ b/vsintegration/tests/Salsa/VsMocks.fs @@ -1525,7 +1525,7 @@ module internal VsMocks = member x.FindActiveProjectCfgName(_projectGuid,outCfgString) = // For now ignore the _projectGuid and just return the last notified configuration match configDict |> Seq.tryHead with - | None -> err(__LINE__) |> ignore + | None -> err(__LINE__) | Some (KeyValue(_,v)) -> outCfgString <- v 0 From 9af9916cd77d818121832dae5293751037b50d7c Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 11 May 2017 22:22:49 +0100 Subject: [PATCH 14/19] fix test --- .../tests/unittests/Tests.ProjectSystem.Miscellaneous.fs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/vsintegration/tests/unittests/Tests.ProjectSystem.Miscellaneous.fs b/vsintegration/tests/unittests/Tests.ProjectSystem.Miscellaneous.fs index 1531e48c0bf..b17f65a02fe 100644 --- a/vsintegration/tests/unittests/Tests.ProjectSystem.Miscellaneous.fs +++ b/vsintegration/tests/unittests/Tests.ProjectSystem.Miscellaneous.fs @@ -503,12 +503,6 @@ type Miscellaneous() = let expected = [| |] // Ideal behavior is [|"foo.fs";"bar.fs"|], and we could choose to improve this in the future. For now we are just happy to now throw/crash. let actual = ips.SourceFilesOnDisk() Assert.AreEqual(expected, actual, "project site did not report expected set of source files") - // Now let's "fix the error" - configChangeNotifier(project, "Foo|AnyCPU") // switch to Foo mode - should go away, project should start behaving as normal - let expected = [| "foo.fs"; "bar.fs" |] |> Array.map (fun filename -> Path.Combine(project.ProjectFolder, filename)) - let actual = ips.SourceFilesOnDisk() - let actual = if actual.Length > 0 then actual |> Seq.skip 1 |> Seq.toArray else actual // On Dev10, first file will be AssemblyAttributes.fs - Assert.AreEqual(expected, actual, "project site did not report expected set of source files after recovery") ) [] From 7b462e63e235299d3b08a21df3983153d92b21ab Mon Sep 17 00:00:00 2001 From: Don Syme Date: Sat, 13 May 2017 12:23:06 +0100 Subject: [PATCH 15/19] add new misc project test --- .../Library1/AssemblyInfo.fs | 41 +++++++++ .../Library2/AssemblyInfo.fs | 41 +++++++++ .../Library2/Library2.fsproj | 81 +++++++++++++++++ .../Library2/packages.config | 4 + .../SameFileBelongsToMultipleProjects.sln | 34 +++++++ .../App.config | 6 ++ .../AssemblyInfo.fs | 41 +++++++++ .../Program.fs | 9 ++ .../SameFileBelongsToMultipleProjects.fsproj | 90 +++++++++++++++++++ 9 files changed, 347 insertions(+) create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/Library1/AssemblyInfo.fs create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/AssemblyInfo.fs create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/Library2.fsproj create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/packages.config create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.sln create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/App.config create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/AssemblyInfo.fs create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/Program.fs create mode 100644 tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.fsproj diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/Library1/AssemblyInfo.fs b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library1/AssemblyInfo.fs new file mode 100644 index 00000000000..b4d90369ae9 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library1/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace Library1.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/AssemblyInfo.fs b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/AssemblyInfo.fs new file mode 100644 index 00000000000..f5d828440f1 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace Library2.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/Library2.fsproj b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/Library2.fsproj new file mode 100644 index 00000000000..1bc10833d34 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/Library2.fsproj @@ -0,0 +1,81 @@ + + + + + Debug + AnyCPU + 2.0 + e72ee9de-323e-4f99-8d7e-1a1ed8a3477c + Library + Library2 + Library2 + v4.5.2 + 4.4.1.0 + true + Library2 + + + true + full + false + false + bin\$(Configuration)\ + DEBUG;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + pdbonly + true + true + bin\$(Configuration)\ + RELEASE;TRACE + 3 + bin\$(Configuration)\$(AssemblyName).XML + + + 11 + + + + + $(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets + + + + + + + + + Class.fs + + + + + + + FSharp.Core + FSharp.Core.dll + $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\$(TargetFSharpCoreVersion)\FSharp.Core.dll + + + + + + ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + + + + \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/packages.config b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/packages.config new file mode 100644 index 00000000000..7d629041bc5 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/Library2/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.sln b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.sln new file mode 100644 index 00000000000..b4e57f4ea29 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.4 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "SameFileBelongsToMultipleProjects", "SameFileBelongsToMultipleProjects\SameFileBelongsToMultipleProjects.fsproj", "{DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Library1", "Library1\Library1.fsproj", "{9F36577A-657B-4117-A118-F69AB182AA31}" +EndProject +Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Library2", "Library2\Library2.fsproj", "{E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF29450F-ABD7-49FB-96C5-C9CAE9A54F40}.Release|Any CPU.Build.0 = Release|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F36577A-657B-4117-A118-F69AB182AA31}.Release|Any CPU.Build.0 = Release|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {E72EE9DE-323E-4F99-8D7E-1A1ED8A3477C}.Release|Any CPU.Build.0 = Debug|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/App.config b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/App.config new file mode 100644 index 00000000000..88fa4027bda --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/AssemblyInfo.fs b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/AssemblyInfo.fs new file mode 100644 index 00000000000..973e1b5c8a2 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/AssemblyInfo.fs @@ -0,0 +1,41 @@ +namespace ConsoleApplication1.AssemblyInfo + +open System.Reflection +open System.Runtime.CompilerServices +open System.Runtime.InteropServices + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[] +[] +[] +[] +[] +[] +[] +[] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [] +[] +[] + +do + () \ No newline at end of file diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/Program.fs b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/Program.fs new file mode 100644 index 00000000000..55b67799e98 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/Program.fs @@ -0,0 +1,9 @@ +// Learn more about F# at http://fsharp.org +// See the 'F# Tutorial' project for more help. + +[] +let main argv = + printfn "%A" argv + let c1 = Library1.Class.PropertyAlwaysAvailable + let c1 = Library2.Class.PropertyAlwaysAvailable + 0 // return an integer exit code diff --git a/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.fsproj b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.fsproj new file mode 100644 index 00000000000..2a2ea4439a4 --- /dev/null +++ b/tests/projects/misc/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects/SameFileBelongsToMultipleProjects.fsproj @@ -0,0 +1,90 @@ + + + + + Debug + AnyCPU + 2.0 + df29450f-abd7-49fb-96c5-c9cae9a54f40 + Exe + ConsoleApplication1 + ConsoleApplication1 + v4.5.2 + true + 4.4.1.0 + SameFileBelongsToMultipleProjects + + + true + full + false + false + bin\$(Configuration)\ + DEBUG;TRACE + 3 + AnyCPU + bin\$(Configuration)\$(AssemblyName).XML + true + + + pdbonly + true + true + bin\$(Configuration)\ + TRACE + 3 + AnyCPU + bin\$(Configuration)\$(AssemblyName).XML + true + + + + + FSharp.Core + FSharp.Core.dll + $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\$(TargetFSharpCoreVersion)\FSharp.Core.dll + + + ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll + True + + + + + + + + + + + + + Library2 + {e72ee9de-323e-4f99-8d7e-1a1ed8a3477c} + True + + + + 11 + + + + + $(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets + + + + + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\FSharp\Microsoft.FSharp.Targets + + + + + + \ No newline at end of file From e2d7a58298734b12f403be5079708cd4cfb8e434 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Mon, 15 May 2017 12:44:31 +0100 Subject: [PATCH 16/19] do ComputeSourcesAndFlags later --- src/fsharp/CompileOps.fs | 2 +- .../TestProjectChanges.fsproj | 3 +- .../LanguageService/LanguageService.fs | 7 +- .../ProjectSitesAndFiles.fs | 20 +++--- .../FSharp.ProjectSystem.FSharp/Project.fs | 67 +++++++++++++++++-- 5 files changed, 78 insertions(+), 21 deletions(-) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index c134a92c38a..92a528e9157 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -2701,7 +2701,7 @@ type TcConfig private (data : TcConfigBuilder,validate:bool) = match fslibExplicitFilenameOpt with | Some(fslibFilename) -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir fslibFilename - if (* validate && *) fslibReference.ProjectReference.IsNone then + if fslibReference.ProjectReference.IsNone then try use ilReader = OpenILBinary(filename,data.optimizeForMemory,data.openBinariesInMemory,None,None, data.shadowCopyReferences) checkFSharpBinaryCompatWithMscorlib filename ilReader.ILAssemblyRefs ilReader.ILModuleDef.ManifestOfAssembly.Version rangeStartup; diff --git a/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj b/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj index 4ace4388b7a..5775c59f6a8 100644 --- a/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj +++ b/tests/projects/misc/TestProjectChanges/TestProjectChanges/TestProjectChanges.fsproj @@ -92,4 +92,5 @@ --> - \ No newline at end of file + + diff --git a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs index f846e5ef11c..666e288e11e 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/LanguageService.fs @@ -65,6 +65,7 @@ type internal FSharpCheckerProvider member this.Checker = checker.Value +/// A value and a function to recompute/refresh the value. The function is passed a flag indicating if a refresh is happening. type Refreshable<'T> = 'T * (bool -> 'T) // Exposes project information as MEF component @@ -381,11 +382,11 @@ and let ok,originalOptions = optionsAssociation.TryGetValue(projectContext) let updatedOptions = site.CompilerFlags() if not ok || originalOptions <> updatedOptions then - let updatedFiles = site.SourceFilesOnDisk() |> wellFormedFilePathSetIgnoreCase - // OK, project options have changed, try to fake out Roslyn to convince it to reparse things + // OK, project options have changed, try to fake out Roslyn to convince it to reparse things. // Calling SetOptions fails because the CPS project system being used by the F# project system - // imlpementation at the moment has no command line parser installed. + // imlpementation at the moment has no command line parser installed, so we remove/add all the files + // instead. A change of flags doesn't happen very often and the remove/add is fast in any case. //projectContext.SetOptions(String.concat " " updatedOptions) for file in updatedFiles do projectContext.RemoveSourceFile(file) diff --git a/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs b/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs index f5898e58b1f..91d7d6c107f 100644 --- a/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs +++ b/vsintegration/src/FSharp.LanguageService/ProjectSitesAndFiles.fs @@ -124,16 +124,16 @@ type internal ProjectSitesAndFiles() = static let rec referencedProjectsOf (tryGetOptionsForReferencedProject, projectSite:IProjectSite, extraProjectInfo, serviceProvider:System.IServiceProvider, useUniqueStamp) = [| for (p,ps) in referencedProvideProjectSites (projectSite, serviceProvider) do - match fullOutputAssemblyPath p with - | None -> () - | Some path -> - let referencedProjectOptions = - // Lookup may not succeed if the project has not been established yet - // In this case we go and compute the options recursively. - match tryGetOptionsForReferencedProject p.FileName with - | None -> getProjectOptionsForProjectSite (tryGetOptionsForReferencedProject, ps.GetProjectSite(), p.FileName, extraProjectInfo, serviceProvider, useUniqueStamp) |> snd - | Some options -> options - yield (p.FileName, (path, referencedProjectOptions)) |] + match fullOutputAssemblyPath p with + | None -> () + | Some path -> + let referencedProjectOptions = + // Lookup may not succeed if the project has not been established yet + // In this case we go and compute the options recursively. + match tryGetOptionsForReferencedProject p.FileName with + | None -> getProjectOptionsForProjectSite (tryGetOptionsForReferencedProject, ps.GetProjectSite(), p.FileName, extraProjectInfo, serviceProvider, useUniqueStamp) |> snd + | Some options -> options + yield (p.FileName, (path, referencedProjectOptions)) |] and getProjectOptionsForProjectSite(tryGetOptionsForReferencedProject, projectSite:IProjectSite, fileName, extraProjectInfo, serviceProvider, useUniqueStamp) = let referencedProjectFileNames, referencedProjectOptions = diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index 4107b100784..8e2a6ff0cc0 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1704,15 +1704,65 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem if batchState = BatchWaiting then batchState <- BatchDone + // The following event sequences are observed in Visual Studio 2017, see https://github.com/Microsoft/visualfsharp/pull/3025#pullrequestreview-38005713 + // + // Loading tests\projects\misc\TestProjectChanges.sln: + // + // - OnActiveProjectCfgChangeBatchBegin x 3 (one for each project) + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(null) x 3 + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(not-null) x 6 + // - OnActiveProjectCfgChangeBatchEnd x 3 + // + // Then we get a "duplicate" set of Batch events + // + // - OnActiveProjectCfgChangeBatchBegin x 3 + // - OnActiveProjectCfgChangeBatchEnd x 3 + // + // Switching to "Release" + // - OnBeforeActiveSolutionCfgChange x 3 + // - OnActiveProjectCfgChangeBatchBegin x 3 + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(null) x 3 + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(not-null) x 6 + // - OnActiveProjectCfgChangeBatchEnd x 3 + // - OnAfterActiveSolutionCfgChange x 3 + // + // On prompted solution reload after a project file has been edited + // - OnActiveProjectCfgChangeBatchBegin x 3 + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(null) x 3 + // - IVsUpdateSolutionEvents.OnActiveProjectCfgChange(not-null) x 6 + // - OnActiveProjectCfgChangeBatchEnd x 3 + // + // Then we get a "duplicate" set of Batch events + // + // - OnActiveProjectCfgChangeBatchBegin x 3 + // - OnActiveProjectCfgChangeBatchEnd x 3 + // + // On individual project reload: + // - OnActiveProjectCfgChange + // + // We never see these being called in the scenarios I've tested - if you know a sequence that triggers them please let us know + // - IVsUpdateSolutionEvents2.OnActiveProjectCfgChange + // - IVsUpdateSolutionEvents2.UpdateProjectCfg_Begin + // - IVsUpdateSolutionEvents2.UpdateProjectCfg_Done + // + // Placing the call to ComputeSourcesAndFlags in OnAfterActiveSolutionCfgChange appears to be + // sufficient to ensure consistent update. Note that we can only call ComputeSourcesAndFlags + // after UpdateMSBuildState has been called for each project. + + interface IVsUpdateSolutionEvents with member x.UpdateSolution_Begin(pfCancelUpdate) = VSConstants.S_OK + member x.UpdateSolution_Done(_fSucceeded, _fModified, _fCancelCommand) = VSConstants.S_OK + member x.UpdateSolution_StartUpdate(pfCancelUpdate) = VSConstants.S_OK + member x.UpdateSolution_Cancel() = VSConstants.S_OK + member x.OnActiveProjectCfgChange(pHierProj) = UpdateConfig(pHierProj) VSConstants.S_OK @@ -1720,21 +1770,28 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem interface IVsUpdateSolutionEvents2 with member x.UpdateSolution_Begin(pfCancelUpdate) = VSConstants.S_OK + member x.UpdateSolution_Done(_fSucceeded, _fModified, _fCancelCommand) = VSConstants.S_OK + member x.UpdateSolution_StartUpdate(pfCancelUpdate) = VSConstants.S_OK + member x.UpdateSolution_Cancel() = VSConstants.S_OK + member x.OnActiveProjectCfgChange(pHierProj) = UpdateConfig(pHierProj) VSConstants.S_OK + + // NOTE: we don't see this being called, at least in common scenarios member x.UpdateProjectCfg_Begin(pHierProj, _pCfgProj, _pCfgSln, _dwAction, pfCancel) = UpdateConfig(pHierProj) VSConstants.S_OK + + // NOTE: we don't see this being called, at least in common scenarios member x.UpdateProjectCfg_Done(pHierProj, _pCfgProj, _pCfgSln, _dwAction, _fSuccess, _fCancel) = UpdateConfig(pHierProj) - // We wait until allproject configurations have been updated before updating our MSBuild state projNode.UpdateMSBuildState() projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) projNode.ComputeSourcesAndFlags() @@ -1765,11 +1822,9 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem VSConstants.S_OK member x.OnAfterActiveSolutionCfgChange(_oldCfg, _newCfg) = - // We wait until allproject configurations have been updated before updating our MSBuild state - projNode.UpdateMSBuildState() - projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - projNode.ComputeSourcesAndFlags() + // We have updated the MSBuild state of each project. Now we can call ComputeSourcesAndFlags + projNode.ComputeSourcesAndFlags() match waitDialog with | Some x -> x.Dispose() @@ -1782,8 +1837,8 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem batchState <- BatchWaiting member x.OnActiveProjectCfgChangeBatchEnd() = + projNode.UpdateMSBuildState() projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - projNode.ComputeSourcesAndFlags() batchState <- NonBatch member x.UpdateSolution_BeginFirstUpdateAction() = From c3c1ac01ae806ec6a3fc14b5e981655736edc9ff Mon Sep 17 00:00:00 2001 From: Don Syme Date: Mon, 15 May 2017 13:05:51 +0100 Subject: [PATCH 17/19] do ComputeSourcesAndFlags once --- .../src/FSharp.ProjectSystem.FSharp/Project.fs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index 8e2a6ff0cc0..fac4d0ab614 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1674,11 +1674,6 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem static let mutable waitDialog : IDisposable option = None - // During batch active project configuration changes, make sure we only run CSAF once - // per batch. Before this change, OnActiveProjectCfgChange was being called twice per - // batch per project. - let mutable batchState = NonBatch - // The CCW wrapper seems to prevent an object-identity test, so we determine whether // two IVsHierarchy objects are equal by comparing their captions. (It's ok if this // occasionally yields false positives, as this just means we may do a little extra @@ -1695,14 +1690,12 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem null let UpdateConfig(pHierProj) = - if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) && batchState <> BatchDone then + if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) then // This code matches what ProjectNode.SetConfiguration would do; that method cannot be called during a build, but at this // current moment in time, it is 'safe' to do this update. let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) - if batchState = BatchWaiting then - batchState <- BatchDone // The following event sequences are observed in Visual Studio 2017, see https://github.com/Microsoft/visualfsharp/pull/3025#pullrequestreview-38005713 // @@ -1834,12 +1827,11 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem interface IVsUpdateSolutionEvents4 with member x.OnActiveProjectCfgChangeBatchBegin() = - batchState <- BatchWaiting + () member x.OnActiveProjectCfgChangeBatchEnd() = projNode.UpdateMSBuildState() projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - batchState <- NonBatch member x.UpdateSolution_BeginFirstUpdateAction() = () From a98032824b0e82970c2a2f007144bcb2a02caa46 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Mon, 15 May 2017 18:01:27 +0100 Subject: [PATCH 18/19] variations --- src/absil/ilread.fs | 2 +- src/fsharp/InternalCollections.fs | 6 +- src/fsharp/InternalCollections.fsi | 10 ++- src/fsharp/vs/IncrementalBuild.fs | 2 +- src/fsharp/vs/service.fs | 10 +-- .../DocComments/XMLDocumentation.fs | 2 +- .../XmlDocumentation.fs | 2 +- .../FSharp.ProjectSystem.FSharp/Project.fs | 83 +++++++++++-------- .../unittests/Tests.InternalCollections.fs | 2 +- 9 files changed, 68 insertions(+), 51 deletions(-) diff --git a/src/absil/ilread.fs b/src/absil/ilread.fs index c0a2c0be973..24779e32821 100644 --- a/src/absil/ilread.fs +++ b/src/absil/ilread.fs @@ -3967,7 +3967,7 @@ let OpenILModuleReader infile opts = // ++GLOBAL MUTABLE STATE (concurrency safe via locking) type ILModuleReaderCacheLockToken() = interface LockToken -let ilModuleReaderCache = new AgedLookup(0, areSame=(fun (x,y) -> x = y)) +let ilModuleReaderCache = new AgedLookup(0, areSimilar=(fun (x,y) -> x = y)) let ilModuleReaderCacheLock = Lock() let OpenILModuleReaderAfterReadingAllBytes infile opts = diff --git a/src/fsharp/InternalCollections.fs b/src/fsharp/InternalCollections.fs index da9f838c9cc..64b746af018 100755 --- a/src/fsharp/InternalCollections.fs +++ b/src/fsharp/InternalCollections.fs @@ -167,10 +167,10 @@ type internal MruCache<'Token, 'Key,'Value when 'Value : not struct>(keepStrongl /// Whether or not this result value is still valid. let isStillValid = defaultArg isStillValid (fun _ -> true) - member bc.TryGetAnySimilar(tok, key) = + member bc.ContainsSimilarKey(tok, key) = match cache.TryPeekKeyValue(tok, key) with - | Some(similarKey, value)-> Some(similarKey, value) - | None -> None + | Some(_similarKey, _value)-> true + | None -> false member bc.TryGetAny(tok, key) = match cache.TryPeekKeyValue(tok, key) with diff --git a/src/fsharp/InternalCollections.fsi b/src/fsharp/InternalCollections.fsi index a9fa058680d..1bd77dd9e81 100755 --- a/src/fsharp/InternalCollections.fsi +++ b/src/fsharp/InternalCollections.fsi @@ -4,10 +4,12 @@ namespace Internal.Utilities.Collections /// Simple aging lookup table. When a member is accessed it's /// moved to the top of the list and when there are too many elements - /// the least-recently-accessed element falls of the end. + /// the least-recently-accessed element falls of the end. + /// + /// - areSimilar: Keep at most once association for two similar keys (as given by areSimilar) type internal AgedLookup<'Token, 'Key, 'Value when 'Value : not struct> = new : keepStrongly:int - * areSame:('Key * 'Key -> bool) + * areSimilar:('Key * 'Key -> bool) * ?requiredToKeep:('Value -> bool) * ?onStrongDiscard : ('Value -> unit) // this may only be set if keepTotal=keepStrongly, i.e. not weak entries * ?keepMax: int @@ -40,6 +42,8 @@ namespace Internal.Utilities.Collections /// threads seeing different live sets of cached items, and may result in the onDiscard action /// being called multiple times. In practice this means the collection is only safe for concurrent /// access if there is no discard action to execute. + /// + /// - areSimilar: Keep at most once association for two similar keys (as given by areSimilar) type internal MruCache<'Token, 'Key,'Value when 'Value : not struct> = new : keepStrongly:int * areSame:('Key * 'Key -> bool) @@ -54,7 +58,7 @@ namespace Internal.Utilities.Collections member Clear : 'Token -> unit /// Get the similar (subsumable) value for the given key or None if not already available. - member TryGetAnySimilar : 'Token * key:'Key -> ('Key * 'Value) option + member ContainsSimilarKey : 'Token * key:'Key -> bool /// Get the value for the given key or None if not still valid. member TryGetAny : 'Token * key:'Key -> 'Value option diff --git a/src/fsharp/vs/IncrementalBuild.fs b/src/fsharp/vs/IncrementalBuild.fs index 35e576e75d3..3b74a7e1896 100755 --- a/src/fsharp/vs/IncrementalBuild.fs +++ b/src/fsharp/vs/IncrementalBuild.fs @@ -1037,7 +1037,7 @@ type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetF type FrameworkImportsCache(keepStrongly) = // Mutable collection protected via CompilationThreadToken - let frameworkTcImportsCache = AgedLookup(keepStrongly, areSame=(fun (x,y) -> x = y)) + let frameworkTcImportsCache = AgedLookup(keepStrongly, areSimilar=(fun (x,y) -> x = y)) member __.Downsize(ctok) = frameworkTcImportsCache.Resize(ctok, keepStrongly=0) member __.Clear(ctok) = frameworkTcImportsCache.Clear(ctok) diff --git a/src/fsharp/vs/service.fs b/src/fsharp/vs/service.fs index 618624478d1..a86127392f5 100644 --- a/src/fsharp/vs/service.fs +++ b/src/fsharp/vs/service.fs @@ -166,7 +166,7 @@ type TypeCheckInfo // Is not keyed on 'Names' collection because this is invariant for the current position in // this unchanged file. Keyed on lineStr though to prevent a change to the currently line // being available against a stale scope. - let getToolTipTextCache = AgedLookup>(getToolTipTextSize,areSame=(fun (x,y) -> x = y)) + let getToolTipTextCache = AgedLookup>(getToolTipTextSize,areSimilar=(fun (x,y) -> x = y)) let amap = tcImports.GetImportMap() let infoReader = new InfoReader(g,amap) @@ -2595,9 +2595,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent reactor.EnqueueOp("InvalidateConfiguration", fun ctok -> // If there was a similar entry then re-establish an empty builder . This is a somewhat arbitrary choice - it // will have the effect of releasing memory associated with the previous builder, but costs some time. - match incrementalBuildersCache.TryGetAnySimilar (ctok, options) with - | None -> () - | Some (_similarOptions, (_oldBuilder, _, _)) -> + if incrementalBuildersCache.ContainsSimilarKey (ctok, options) then // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, // including by incrementalBuildersCache.Set. @@ -2614,9 +2612,7 @@ type BackgroundCompiler(referenceResolver, projectCacheSize, keepAssemblyContent // If there was a similar entry (as there normally will have been) then re-establish an empty builder . This // is a somewhat arbitrary choice - it will have the effect of releasing memory associated with the previous // builder, but costs some time. - match incrementalBuildersCache.TryGetAnySimilar (ctok, options) with - | None -> return () - | Some (_similarOptions, (_oldBuilder, _, _)) -> + if incrementalBuildersCache.ContainsSimilarKey (ctok, options) then // We do not need to decrement here - the onDiscard function is called each time an entry is pushed out of the build cache, // including by incrementalBuildersCache.Set. let! newBuilderInfo = CreateOneIncrementalBuilder (ctok, options) diff --git a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs index 072729234b2..717466c380e 100644 --- a/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs +++ b/vsintegration/src/FSharp.Editor/DocComments/XMLDocumentation.fs @@ -214,7 +214,7 @@ module internal XmlDocumentation = /// Provide Xml Documentation type Provider(xmlIndexService:IVsXMLMemberIndexService, dte: DTE) = /// Index of assembly name to xml member index. - let mutable xmlCache = new AgedLookup(10,areSame=(fun (x,y) -> x = y)) + let mutable xmlCache = new AgedLookup(10,areSimilar=(fun (x,y) -> x = y)) let events = dte.Events :?> Events2 let solutionEvents = events.SolutionEvents diff --git a/vsintegration/src/FSharp.LanguageService/XmlDocumentation.fs b/vsintegration/src/FSharp.LanguageService/XmlDocumentation.fs index cd20c4b43ff..c40b07a90cc 100644 --- a/vsintegration/src/FSharp.LanguageService/XmlDocumentation.fs +++ b/vsintegration/src/FSharp.LanguageService/XmlDocumentation.fs @@ -219,7 +219,7 @@ module internal XmlDocumentation = /// Provide Xml Documentation type Provider(xmlIndexService:IVsXMLMemberIndexService, dte: DTE) = /// Index of assembly name to xml member index. - let mutable xmlCache = new AgedLookup(10,areSame=(fun (x,y) -> x = y)) + let mutable xmlCache = new AgedLookup(10,areSimilar=(fun (x,y) -> x = y)) let events = dte.Events :?> Events2 let solutionEvents = events.SolutionEvents diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index fac4d0ab614..fabc9c02e94 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1672,30 +1672,48 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // "double CCW-wrapping" of the same object. type internal SolutionEventsListener(projNode) = - static let mutable waitDialog : IDisposable option = None + let mutable waitDialog : IDisposable option = None + // During batch active project configuration changes, make sure we only run CSAF once + // per batch. Before this change, OnActiveProjectCfgChange was being called twice per + // batch per project. + let mutable batchState = NonBatch + // The CCW wrapper seems to prevent an object-identity test, so we determine whether // two IVsHierarchy objects are equal by comparing their captions. (It's ok if this // occasionally yields false positives, as this just means we may do a little extra // background work.) - let GetCaption(hier : IVsHierarchy) : string = + let GetCaption(hier : IVsHierarchy) = if hier = null then - null + null : System.String else - let mutable o = null - let hr = hier.GetProperty(VSConstants.VSITEMID_ROOT, int(__VSHPROPID.VSHPROPID_Caption), &o) - if hr = VSConstants.S_OK then - o :?> string + let mutable o : obj = null + let r = hier.GetProperty(VSConstants.VSITEMID_ROOT, int(__VSHPROPID.VSHPROPID_Caption), &o) + if r = VSConstants.S_OK then + o :?> System.String else - null + null : System.String + + let OnActiveProjectCfgChangeAndAllProjectsUpdated() = + if batchState <> BatchDone then + projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + projNode.ComputeSourcesAndFlags() + + if batchState = BatchWaiting then + batchState <- BatchDone let UpdateConfig(pHierProj) = + // By default, the F# project system keeps its own internal Configuration and Platform in sync with the current active + // Configuration and Platform by listening for OnActiveProjectCfgChange events. However there is one case where the + // active cfg changes without an event, and this is during 'Batch Build'. So we listen for the start and end of + // Batch Build, and manually update the project to the active cfg before/after to set/reset the config. if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) then // This code matches what ProjectNode.SetConfiguration would do; that method cannot be called during a build, but at this // current moment in time, it is 'safe' to do this update. let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) + projNode.UpdateMSBuildState() // The following event sequences are observed in Visual Studio 2017, see https://github.com/Microsoft/visualfsharp/pull/3025#pullrequestreview-38005713 // @@ -1773,21 +1791,19 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem member x.UpdateSolution_Cancel() = VSConstants.S_OK + // NOTE: we don't see this being called in any known scenarios member x.OnActiveProjectCfgChange(pHierProj) = UpdateConfig(pHierProj) VSConstants.S_OK - // NOTE: we don't see this being called, at least in common scenarios + // NOTE: we don't see this being called in any known scenarios member x.UpdateProjectCfg_Begin(pHierProj, _pCfgProj, _pCfgSln, _dwAction, pfCancel) = UpdateConfig(pHierProj) VSConstants.S_OK - // NOTE: we don't see this being called, at least in common scenarios + // NOTE: we don't see this being called in any known scenarios member x.UpdateProjectCfg_Done(pHierProj, _pCfgProj, _pCfgSln, _dwAction, _fSuccess, _fCancel) = UpdateConfig(pHierProj) - projNode.UpdateMSBuildState() - projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - projNode.ComputeSourcesAndFlags() VSConstants.S_OK interface IVsUpdateSolutionEvents3 with @@ -1797,41 +1813,42 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // this will be called for each project, but wait dialogs cannot 'stack' // i.e. if a wait dialog is already open, subsequent calls to StartWaitDialog // will not override the current open dialog - if waitDialog.IsNone then - waitDialog <- - { - WaitCaption = FSharpSR.GetString FSharpSR.ProductName - WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration - ProgressText = None - StatusBmpAnim = null - StatusBarText = None - DelayToShowDialogSecs = 1 - IsCancelable = false - ShowMarqueeProgress = true - } - |> WaitDialog.start projNode.Site - |> Some + waitDialog <- + { + WaitCaption = FSharpSR.GetString FSharpSR.ProductName + WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration + ProgressText = None + StatusBmpAnim = null + StatusBarText = None + DelayToShowDialogSecs = 1 + IsCancelable = false + ShowMarqueeProgress = true + } + |> WaitDialog.start projNode.Site + |> Some VSConstants.S_OK member x.OnAfterActiveSolutionCfgChange(_oldCfg, _newCfg) = - // We have updated the MSBuild state of each project. Now we can call ComputeSourcesAndFlags - projNode.ComputeSourcesAndFlags() match waitDialog with | Some x -> x.Dispose() waitDialog <- None - | _ -> () + | None -> () VSConstants.S_OK interface IVsUpdateSolutionEvents4 with member x.OnActiveProjectCfgChangeBatchBegin() = - () + batchState <- BatchWaiting member x.OnActiveProjectCfgChangeBatchEnd() = - projNode.UpdateMSBuildState() - projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + try + OnActiveProjectCfgChangeAndAllProjectsUpdated() + with e -> + Debug.Assert(false, sprintf "unexpected exception in ComputeSourcesAndFlags: %s" (e.ToString())) + + batchState <- NonBatch member x.UpdateSolution_BeginFirstUpdateAction() = () diff --git a/vsintegration/tests/unittests/Tests.InternalCollections.fs b/vsintegration/tests/unittests/Tests.InternalCollections.fs index 1ad0088761c..3fb1e769454 100644 --- a/vsintegration/tests/unittests/Tests.InternalCollections.fs +++ b/vsintegration/tests/unittests/Tests.InternalCollections.fs @@ -92,7 +92,7 @@ type MruCache = let AreSameForSubsumption((s1,n1),(s2,n2)) = s1=s2 let discarded = ref [] - let m = new MruCache(compute=fst, areSame=(fun (x,y) -> x = y), areSimilar=AreSameForSubsumption, keepStrongly=2, keepMax=2, onDiscard=(fun s -> discarded := s :: !discarded)) + let m = new MruCache(compute=fst, areSimilar=(fun (x,y) -> x = y), areSimilar=AreSameForSubsumption, keepStrongly=2, keepMax=2, onDiscard=(fun s -> discarded := s :: !discarded)) m.SetAlternate(("x",1),"Banana") // no discard printfn "discarded = %A" discarded.Value Assert.IsTrue(discarded.Value = [], "Check1") From f475386ff402dec37f5bc828646f1fd812680923 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Mon, 15 May 2017 18:40:55 +0100 Subject: [PATCH 19/19] keep dialog open --- .../FSharp.ProjectSystem.FSharp/Project.fs | 82 +++++++++---------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs index fabc9c02e94..07665cf040e 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/Project.fs @@ -1672,7 +1672,8 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // "double CCW-wrapping" of the same object. type internal SolutionEventsListener(projNode) = - let mutable waitDialog : IDisposable option = None + static let mutable waitDialog : IDisposable option = None + static let mutable waitCount = 0 // During batch active project configuration changes, make sure we only run CSAF once // per batch. Before this change, OnActiveProjectCfgChange was being called twice per @@ -1694,22 +1695,10 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem else null : System.String - let OnActiveProjectCfgChangeAndAllProjectsUpdated() = - if batchState <> BatchDone then - projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) - projNode.ComputeSourcesAndFlags() - - if batchState = BatchWaiting then - batchState <- BatchDone - let UpdateConfig(pHierProj) = - // By default, the F# project system keeps its own internal Configuration and Platform in sync with the current active - // Configuration and Platform by listening for OnActiveProjectCfgChange events. However there is one case where the - // active cfg changes without an event, and this is during 'Batch Build'. So we listen for the start and end of - // Batch Build, and manually update the project to the active cfg before/after to set/reset the config. + // Check we're referring to the current project if GetCaption(pHierProj) = GetCaption(projNode.InteropSafeIVsHierarchy) then - // This code matches what ProjectNode.SetConfiguration would do; that method cannot be called during a build, but at this - // current moment in time, it is 'safe' to do this update. + // This code matches what ProjectNode.SetConfiguration would do. let _,currentConfigName = Utilities.TryGetActiveConfigurationAndPlatform(projNode.Site, projNode.ProjectIDGuid) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Configuration, currentConfigName.ConfigName) MSBuildProject.SetGlobalProperty(projNode.BuildProject, ProjectFileConstants.Platform, currentConfigName.MSBuildPlatform) @@ -1751,6 +1740,10 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // On individual project reload: // - OnActiveProjectCfgChange // + // On batch build: + // - UpdateProjectCfg_Begin x 6 (twice for each project!) + // - UpdateProjectCfg_Done x 6 (twice for each project!) + // // We never see these being called in the scenarios I've tested - if you know a sequence that triggers them please let us know // - IVsUpdateSolutionEvents2.OnActiveProjectCfgChange // - IVsUpdateSolutionEvents2.UpdateProjectCfg_Begin @@ -1796,12 +1789,12 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem UpdateConfig(pHierProj) VSConstants.S_OK - // NOTE: we don't see this being called in any known scenarios + // NOTE: this is called for batch build (Build --> Batch Build) member x.UpdateProjectCfg_Begin(pHierProj, _pCfgProj, _pCfgSln, _dwAction, pfCancel) = UpdateConfig(pHierProj) VSConstants.S_OK - // NOTE: we don't see this being called in any known scenarios + // NOTE: this is called for batch build (Build --> Batch Build) member x.UpdateProjectCfg_Done(pHierProj, _pCfgProj, _pCfgSln, _dwAction, _fSuccess, _fCancel) = UpdateConfig(pHierProj) VSConstants.S_OK @@ -1813,41 +1806,48 @@ namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem // this will be called for each project, but wait dialogs cannot 'stack' // i.e. if a wait dialog is already open, subsequent calls to StartWaitDialog // will not override the current open dialog - waitDialog <- - { - WaitCaption = FSharpSR.GetString FSharpSR.ProductName - WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration - ProgressText = None - StatusBmpAnim = null - StatusBarText = None - DelayToShowDialogSecs = 1 - IsCancelable = false - ShowMarqueeProgress = true - } - |> WaitDialog.start projNode.Site - |> Some - + if waitCount = 0 then + waitDialog <- + { + WaitCaption = FSharpSR.GetString FSharpSR.ProductName + WaitMessage = FSharpSR.GetString FSharpSR.UpdatingSolutionConfiguration + ProgressText = None + StatusBmpAnim = null + StatusBarText = None + DelayToShowDialogSecs = 1 + IsCancelable = false + ShowMarqueeProgress = true + } + |> WaitDialog.start projNode.Site + |> Some + waitCount <- waitCount + 1 VSConstants.S_OK member x.OnAfterActiveSolutionCfgChange(_oldCfg, _newCfg) = - match waitDialog with - | Some x -> - x.Dispose() - waitDialog <- None - | None -> () + try + Debug.Assert((batchState = NonBatch), "We expect the group of project config updates to be over by the time we update the flags") // We only update flags after all the batch updates are done + projNode.SetProjectFileDirty(projNode.IsProjectFileDirty) + projNode.ComputeSourcesAndFlags() + with e -> + Debug.Assert(false, sprintf "unexpected exception in ComputeSourcesAndFlags: %s" (e.ToString())) + + waitCount <- max 0 (waitCount - 1) + if waitCount = 0 then + match waitDialog with + | Some x -> + x.Dispose() + waitDialog <- None + | None -> () VSConstants.S_OK interface IVsUpdateSolutionEvents4 with + + // Note, this use of the word "batch" is not the same as a "batch build" - it means "update a number of project configurations as a group" member x.OnActiveProjectCfgChangeBatchBegin() = batchState <- BatchWaiting member x.OnActiveProjectCfgChangeBatchEnd() = - try - OnActiveProjectCfgChangeAndAllProjectsUpdated() - with e -> - Debug.Assert(false, sprintf "unexpected exception in ComputeSourcesAndFlags: %s" (e.ToString())) - batchState <- NonBatch member x.UpdateSolution_BeginFirstUpdateAction() =