internal static bool ResetRenameTrackingStateWorker(Workspace workspace, DocumentId documentId, bool visible)
        {
            if (workspace.IsDocumentOpen(documentId))
            {
                var         document = workspace.CurrentSolution.GetDocument(documentId);
                ITextBuffer textBuffer;
                if (document != null &&
                    document.TryGetText(out var text))
                {
                    textBuffer = text.Container.TryGetTextBuffer();
                    if (textBuffer == null)
                    {
                        FailFast.Fail(string.Format("document with name {0} is open but textBuffer is null. Textcontainer is of type {1}. SourceText is: {2}",
                                                    document.Name, text.Container.GetType().FullName, text.ToString()));
                    }

                    if (textBuffer.Properties.TryGetProperty(typeof(StateMachine), out StateMachine stateMachine))
                    {
                        if (visible)
                        {
                            return(stateMachine.ClearVisibleTrackingSession());
                        }
                        else
                        {
                            return(stateMachine.ClearTrackingSession());
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 2
0
        public VisualStudioDiagnosticAnalyzerProvider(
            [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
        {
            var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));

            // Microsoft.VisualStudio.ExtensionManager is non-versioned, so we need to dynamically load it, depending on the version of VS we are running on
            // this will allow us to build once and deploy on different versions of VS SxS.
            var vsDteVersion = Version.Parse(dte.Version.Split(' ')[0]); // DTE.Version is in the format of D[D[.D[D]]][ (?+)], so we need to split out the version part and check for uninitialized Major/Minor below
            var assembly     = Assembly.Load($"Microsoft.VisualStudio.ExtensionManager, Version={(vsDteVersion.Major == -1 ? 0 : vsDteVersion.Major)}.{(vsDteVersion.Minor == -1 ? 0 : vsDteVersion.Minor)}.0.0, PublicKeyToken=b03f5f7f11d50a3a");

            if (assembly == null)
            {
                // extension manager can't be null. if it is null, then VS is seriously broken.
                // fail fast right away
                FailFast.OnFatalException(new Exception("extension manager can't be null"));
            }

            // Get the analyzer assets for installed VSIX extensions through the VSIX extension manager.
            var extensionManager = serviceProvider.GetService(assembly.GetType("Microsoft.VisualStudio.ExtensionManager.SVsExtensionManager"));

            Assumes.Present(extensionManager);

            _hostDiagnosticAnalyzerInfo = new Lazy <ImmutableArray <HostDiagnosticAnalyzerPackage> >(
                () => GetHostAnalyzerPackagesWithName(extensionManager, assembly.GetType("Microsoft.VisualStudio.ExtensionManager.IExtensionContent")), isThreadSafe: true);
        }
 internal void WaitUntilCompletion_ForTestingPurposesOnly()
 {
     // this shouldn't happen. would like to get some diagnostic
     while (_workItemQueue.HasAnyWork)
     {
         FailFast.Fail("How?");
     }
 }
 internal void WaitUntilCompletion()
 {
     // this shouldn't happen. would like to get some diagnostic
     while (_lowPriorityProcessor._workItemQueue.HasAnyWork)
     {
         FailFast.Fail("How?");
     }
 }
            /// <summary>
            /// Return <see cref="StateSet"/>s that are added as the given <see cref="Project"/>'s AnalyzerReferences.
            /// This will never create new <see cref="StateSet"/> but will return ones already created.
            /// </summary>
            public ImmutableArray <StateSet> CreateBuildOnlyProjectStateSet(Project project)
            {
                // create project analyzer reference identity map
                var referenceIdentities = project.AnalyzerReferences.Select(r => _analyzerManager.GetAnalyzerReferenceIdentity(r)).ToSet();

                // now create analyzer to host stateset map
                var hostStateSetMap = _hostStates.GetOrCreateStateSets(project.Language).ToDictionary(s => s.Analyzer, s => s);

                // create build only stateSet array
                var stateSets = ImmutableArray.CreateBuilder <StateSet>();

                // we always include compiler analyzer in build only state
                var compilerAnalyzer = _analyzerManager.GetCompilerDiagnosticAnalyzer(project.Language);

                if (compilerAnalyzer == null)
                {
                    // only way to get here is if MEF is corrupted.
                    FailFast.OnFatalException(new Exception("How can this happen?"));
                }

                StateSet compilerStateSet;

                if (hostStateSetMap.TryGetValue(compilerAnalyzer, out compilerStateSet))
                {
                    stateSets.Add(compilerStateSet);
                }

                // now add all project analyzers
                stateSets.AddRange(_projectStates.GetOrUpdateStateSets(project));

                // now add analyzers that exist in both host and project
                var analyzerMap = _analyzerManager.GetHostDiagnosticAnalyzersPerReference(project.Language);

                foreach (var kv in analyzerMap)
                {
                    var identity = kv.Key;
                    if (!referenceIdentities.Contains(identity))
                    {
                        // it is from host analyzer package rather than project analyzer reference
                        // which build doesn't have
                        continue;
                    }

                    // if same analyzer exists both in host (vsix) and in analyzer reference,
                    // we include it in build only analyzer.
                    foreach (var analyzer in kv.Value)
                    {
                        StateSet stateSet;
                        if (hostStateSetMap.TryGetValue(analyzer, out stateSet) && stateSet != compilerStateSet)
                        {
                            stateSets.Add(stateSet);
                        }
                    }
                }

                return(stateSets.ToImmutable());
            }
Ejemplo n.º 6
0
 public void UnregisterSnapshot(PinnedRemotableDataScope scope)
 {
     // calling it multiple times for same snapshot is not allowed.
     if (!_storages.TryRemove(scope.SolutionInfo.ScopeId, out var dummy))
     {
         // this should make failure more explicit
         FailFast.OnFatalException(new Exception("who is removing same snapshot?"));
     }
 }
Ejemplo n.º 7
0
 public void UnregisterSnapshot(int scopeId)
 {
     // calling it multiple times for same snapshot is not allowed.
     if (!_storages.TryRemove(scopeId, out _))
     {
         // this should make failure more explicit
         FailFast.OnFatalException(new Exception("who is removing same snapshot?"));
     }
 }
Ejemplo n.º 8
0
        public bool WaitIfBlocked(TimeSpan timeout)
        {
            if (_disposed)
            {
                FailFast.Fail("Badness");
            }

            return(_waitHandle.WaitOne(timeout));
        }
Ejemplo n.º 9
0
 public void RegisterSnapshot(int scopeId, AssetStorages.Storage storage)
 {
     // duplicates are not allowed, there can be multiple snapshots to same solution, so no ref counting.
     if (!_storages.TryAdd(scopeId, storage))
     {
         // this should make failure more explicit
         FailFast.OnFatalException(new Exception("who is adding same snapshot?"));
     }
 }
Ejemplo n.º 10
0
        public static bool Crash(Exception e)
        {
            if (!IsFailFastSuppressed())
            {
                FailFast.OnFatalException(e);
            }

            return(false);
        }
            private bool ReportUnlessCanceled(Exception ex, CancellationToken cancellationToken)
            {
                if (!cancellationToken.IsCancellationRequested && _owner.IsDisposed)
                {
                    // kill OOP if snapshot service got disconnected due to this exception.
                    FailFast.OnFatalException(ex);
                }

                return(false);
            }
            private bool ReportUnlessCanceled(Exception ex)
            {
                // TODO: check !cancellationToken.IsCancellationRequeste instead (https://github.com/dotnet/roslyn/issues/39723)
                if (!(ex is OperationCanceledException) && !(ex is TaskCanceledException) && _owner.IsDisposed)
                {
                    // kill OOP if snapshot service got disconnected due to this exception.
                    FailFast.OnFatalException(ex);
                }

                return(false);
            }
Ejemplo n.º 13
0
        public static void ReportNonFatal(Exception exception)
        {
            if (exception is OutOfMemoryException)
            {
                FailFast.OnFatalException(exception);
            }

            if (!s_report)
            {
                return;
            }

            var emptyCallstack = exception.SetCallstackIfEmpty();
            var currentProcess = Process.GetCurrentProcess();

            // write the exception to a log file:
            s_logger?.TraceEvent(TraceEventType.Error, 1, $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}");

            var session = s_telemetrySession;

            if (session == null)
            {
                return;
            }

            var logFilePaths = CaptureLogFiles();

            var faultEvent = new FaultEvent(
                eventName: FunctionId.NonFatalWatson.GetEventName(),
                description: "Roslyn NonFatal Watson",
                FaultSeverity.Diagnostic,
                exceptionObject: exception,
                gatherEventDetails: faultUtility =>
            {
                // add current process dump
                faultUtility.AddProcessDump(currentProcess.Id);

                // add ServiceHub log files:
                foreach (var path in logFilePaths)
                {
                    faultUtility.AddFile(path);
                }

                // Returning "0" signals that we should send data to Watson; any other value will cancel the Watson report.
                return(0);
            });

            // add extra bucket parameters to bucket better in NFW
            // we do it here so that it gets bucketted better in both
            // watson and telemetry.
            faultEvent.SetExtraParameters(exception, emptyCallstack);

            session.PostEvent(faultEvent);
        }
Ejemplo n.º 14
0
        public static bool CrashUnlessCanceled(Exception e)
        {
            if (e is OperationCanceledException ||
                e is ThreadAbortException ||
                IsFailFastSuppressed())
            {
                return(false);
            }

            FailFast.OnFatalException(e);
            return(false);
        }
Ejemplo n.º 15
0
        public override int GetHashCode()
        {
            unchecked {
                int hash = 17;
                if (Recipient != default(string))
                {
                    hash = hash * 23 + Recipient.GetHashCode();
                }
                if (BankAccount != default(BankAccount))
                {
                    hash = hash * 23 + BankAccount.GetHashCode();
                }
                if (Sent != default(bool))
                {
                    hash = hash * 23 + Sent.GetHashCode();
                }
                if (Paid != default(bool))
                {
                    hash = hash * 23 + Paid.GetHashCode();
                }
                if (Fee != default(long))
                {
                    hash = hash * 23 + Fee.GetHashCode();
                }
                if (Amount != default(long))
                {
                    hash = hash * 23 + Amount.GetHashCode();
                }
                if (Currency != default(string))
                {
                    hash = hash * 23 + Currency.GetHashCode();
                }
                if (FailFast != default(bool))
                {
                    hash = hash * 23 + FailFast.GetHashCode();
                }
                if (FailureCode != default(string))
                {
                    hash = hash * 23 + FailureCode.GetHashCode();
                }
                if (FailureMessage != default(string))
                {
                    hash = hash * 23 + FailureMessage.GetHashCode();
                }
                if (Transaction != default(string))
                {
                    hash = hash * 23 + Transaction.GetHashCode();
                }

                return(hash);
            }
        }
Ejemplo n.º 16
0
        private static void EnsureMandatoryAnalyzers(ImmutableArray <HostDiagnosticAnalyzerPackage> packages)
        {
            foreach (var package in packages)
            {
                if (package.Assemblies.Any(a => a?.EndsWith(MicrosoftCodeAnalysisCSharp, StringComparison.OrdinalIgnoreCase) == true) &&
                    package.Assemblies.Any(a => a?.EndsWith(MicrosoftCodeAnalysisVisualBasic, StringComparison.OrdinalIgnoreCase) == true))
                {
                    return;
                }
            }

            FailFast.OnFatalException(new Exception("Mandatory analyzers are missing"));
        }
Ejemplo n.º 17
0
        public static bool Crash(Exception e)
        {
            if (!IsFailFastSuppressed())
            {
                // hold onto last exception to make investigation easier
                lastException        = e;
                lastExceptionMessage = e.ToString();

                FailFast.OnFatalException(e);
            }

            return(false);
        }
Ejemplo n.º 18
0
        public static void ReportFatal(Exception exception)
        {
            try
            {
                CaptureFilesInMemory(CollectServiceHubLogFilePaths());
            }
            catch
            {
                // ignore any exceptions (e.g. OOM)
            }

            FailFast.OnFatalException(exception);
        }
Ejemplo n.º 19
0
        public static bool CrashUnlessCanceled(Exception e)
        {
            if (e is OperationCanceledException ||
                e is ThreadAbortException ||
                IsFailFastSuppressed())
            {
                return(false);
            }

            // hold onto last exception to make investigation easier
            lastException        = e;
            lastExceptionMessage = e.ToString();

            FailFast.OnFatalException(e);
            return(false);
        }
Ejemplo n.º 20
0
        public static void ReportNonFatal(Exception exception)
        {
            if (exception is OutOfMemoryException)
            {
                FailFast.OnFatalException(exception);
            }

            var emptyCallstack = exception.SetCallstackIfEmpty();
            var currentProcess = Process.GetCurrentProcess();

            // write the exception to a log file:
            s_logger?.TraceEvent(TraceEventType.Error, 1, $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}");

            var session = s_telemetrySession;

            if (session == null)
            {
                return;
            }

            var faultEvent = new FaultEvent(
                eventName: FunctionId.NonFatalWatson.GetEventName(),
                description: GetDescription(exception),
                FaultSeverity.Diagnostic,
                exceptionObject: exception,
                gatherEventDetails: faultUtility =>
            {
                if (faultUtility is FaultEvent {
                    IsIncludedInWatsonSample: true
                })
                {
                    // add ServiceHub log files:
                    foreach (var path in CollectServiceHubLogFilePaths())
                    {
                        faultUtility.AddFile(path);
                    }
                }

                // Returning "0" signals that, if sampled, we should send data to Watson.
                // Any other value will cancel the Watson report. We never want to trigger a process dump manually,
                // we'll let TargetedNotifications determine if a dump should be collected.
                // See https://aka.ms/roslynnfwdocs for more details
                return(0);
            });
Ejemplo n.º 21
0
        public VisualStudioWorkspaceDiagnosticAnalyzerProviderService(VisualStudioWorkspaceImpl workspace)
        {
            // Microsoft.VisualStudio.ExtensionManager is non-versioned, so we need to dynamically load it, depending on the version of VS we are running on
            // this will allow us to build once and deploy on different versions of VS SxS.
            var vsDteVersion = Version.Parse(workspace.GetVsDte().Version.Split(' ')[0]); // DTE.Version is in the format of D[D[.D[D]]][ (?+)], so we need to split out the version part and check for uninitialized Major/Minor below
            var assembly     = Assembly.Load($"Microsoft.VisualStudio.ExtensionManager, Version={(vsDteVersion.Major == -1 ? 0 : vsDteVersion.Major)}.{(vsDteVersion.Minor == -1 ? 0 : vsDteVersion.Minor)}.0.0, PublicKeyToken=b03f5f7f11d50a3a");

            // Get the analyzer assets for installed VSIX extensions through the VSIX extension manager.
            var extensionManager = workspace.GetVsService(assembly.GetType("Microsoft.VisualStudio.ExtensionManager.SVsExtensionManager"));

            if (extensionManager == null)
            {
                // extension manager can't be null. if it is null, then VS is seriously broken.
                // fail fast right away
                FailFast.OnFatalException(new Exception("extension manager can't be null"));
            }

            _hostDiagnosticAnalyzerInfo = GetHostAnalyzerPackagesWithName(extensionManager, assembly.GetType("Microsoft.VisualStudio.ExtensionManager.IExtensionContent"));
        }
Ejemplo n.º 22
0
 public void WhenOneValidatorFails_ThenFail() =>
 FailFast(List(Success, Failure))(1).Match(
     Valid: (_) => Assert.Fail(),
     Invalid: (errs) => Assert.AreEqual(1, errs.Count()));
Ejemplo n.º 23
0
 public void WhenAllValidatorsSucceed_ThenSucceed() => Assert.AreEqual(
     actual: FailFast(List(Success, Success))(1),
     expected: Valid(1)
     );
Ejemplo n.º 24
0
 public void WhenNoValidators_ThenSucceed() => Assert.AreEqual(
     actual: FailFast(List <Validator <int> >())(1),
     expected: Valid(1)
     );
Ejemplo n.º 25
0
 public void WhenSeveralValidatorsFail_ThenFail() =>
 FailFast(List(Success, Failure, Failure, Success))(1).Match(
     Valid: (_) => Assert.Fail(),
     Invalid: (errs) => Assert.AreEqual(1, errs.Count())); // only the first error is returned
Ejemplo n.º 26
0
 public static void ReportFatal(Exception exception)
 {
     _ = CaptureLogFiles();
     FailFast.OnFatalException(exception);
 }
Ejemplo n.º 27
0
            public ImmutableArray <StateSet> CreateBuildOnlyProjectStateSet(Project project)
            {
                var hostStateSets = GetOrCreateHostStateSets(project.Language).OrderedStateSets;

                if (!project.SupportsCompilation)
                {
                    // languages which don't use our compilation model but diagnostic framework,
                    // all their analyzer should be host analyzers. return all host analyzers
                    // for the language
                    return(hostStateSets);
                }

                // now create analyzer to host stateset map
                var hostStateSetMap = hostStateSets.ToDictionary(s => s.Analyzer, s => s);

                // create project analyzer reference identity map
                var referenceIdentities = project.AnalyzerReferences.Select(r => _analyzerInfoCache.GetAnalyzerReferenceIdentity(r)).ToSet();

                // create build only stateSet array
                var stateSets = ImmutableArray.CreateBuilder <StateSet>();

                // we always include compiler analyzer in build only state
                var compilerAnalyzer = _analyzerInfoCache.GetCompilerDiagnosticAnalyzer(project.Language);

                if (compilerAnalyzer == null)
                {
                    // only way to get here is if MEF is corrupted.
                    FailFast.OnFatalException(new Exception("How can this happen?"));
                }

                if (hostStateSetMap.TryGetValue(compilerAnalyzer, out var compilerStateSet))
                {
                    stateSets.Add(compilerStateSet);
                }

                // now add all project analyzers
                stateSets.AddRange(GetOrUpdateProjectAnalyzerMap(project).Values);

                // now add analyzers that exist in both host and project
                var analyzerMap = _analyzerInfoCache.GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language);

                foreach (var(identity, analyzers) in analyzerMap)
                {
                    if (!referenceIdentities.Contains(identity))
                    {
                        // it is from host analyzer package rather than project analyzer reference
                        // which build doesn't have
                        continue;
                    }

                    // if same analyzer exists both in host (vsix) and in analyzer reference,
                    // we include it in build only analyzer.
                    foreach (var analyzer in analyzers)
                    {
                        if (hostStateSetMap.TryGetValue(analyzer, out var stateSet) && stateSet != compilerStateSet)
                        {
                            stateSets.Add(stateSet);
                        }
                    }
                }

                return(stateSets.ToImmutable());
            }
            /// <summary>
            /// Walks the bound tree and adds all non compiler generated bound nodes whose syntax matches the given one
            /// to the cache.
            /// </summary>
            /// <param name="root">The root of the bound tree.</param>
            /// <param name="map">The cache.</param>
            /// <param name="node">The syntax node where to add bound nodes for.</param>
            public static void AddToMap(BoundNode root, Dictionary <CSharpSyntaxNode, ImmutableArray <BoundNode> > map, CSharpSyntaxNode node = null)
            {
                Debug.Assert(node == null || root == null || !(root.Syntax is StatementSyntax), "individually added nodes are not supposed to be statements.");

                if (root == null || map.ContainsKey(root.Syntax))
                {
                    // root node is already in the map, children must be in the map too.
                    return;
                }

                var additionMap = OrderPreservingMultiDictionary <CSharpSyntaxNode, BoundNode> .GetInstance();

                var builder = new NodeMapBuilder(additionMap, node);

                builder.Visit(root);

                foreach (CSharpSyntaxNode key in additionMap.Keys)
                {
                    if (map.ContainsKey(key))
                    {
#if DEBUG
                        // It's possible that AddToMap was previously called with a subtree of root.  If this is the case,
                        // then we'll see an entry in the map.  Since the incremental binder should also have seen the
                        // pre-existing map entry, the entry in addition map should be identical.
                        // Another, more unfortunate, possibility is that we've had to re-bind the syntax and the new bound
                        // nodes are equivalent, but not identical, to the existing ones.  In such cases, we prefer the
                        // existing nodes so that the cache will always return the same bound node for a given syntax node.

                        // EXAMPLE: Suppose we have the statement P.M(1);
                        // First, we ask for semantic info about "P".  We'll walk up to the statement level and bind that.
                        // We'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);".
                        // Next, we ask for semantic info about "P.M".  That isn't in our map, so we walk up to the statement
                        // level - again - and bind that - again.
                        // Once again, we'll end up with map entries for "1", "P", "P.M(1)", and "P.M(1);".  They will
                        // have the same structure as the original map entries, but will not be ReferenceEquals.

                        var existing = map[key];
                        var added    = additionMap[key];
                        FailFast.Assert(existing.Length == added.Length, "existing.Length == added.Length");
                        for (int i = 0; i < existing.Length; i++)
                        {
                            // TODO: it would be great if we could check !ReferenceEquals(existing[i], added[i]) (DevDiv #11584).
                            // Known impediments include:
                            //   1) Field initializers aren't cached because they're not in statements.
                            //   2) Single local declarations (e.g. "int x = 1;" vs "int x = 1, y = 2;") aren't found in the cache
                            //      since nothing is cached for the statement syntax.
                            if (existing[i].Kind != added[i].Kind)
                            {
                                FailFast.Assert(!(key is StatementSyntax), "!(key is StatementSyntax)");

                                // This also seems to be happening when we get equivalent BoundTypeExpression and BoundTypeOrValueExpression nodes.
                                if (existing[i].Kind == BoundKind.TypeExpression && added[i].Kind == BoundKind.TypeOrValueExpression)
                                {
                                    FailFast.Assert(
                                        ((BoundTypeExpression)existing[i]).Type == ((BoundTypeOrValueExpression)added[i]).Type,
                                        string.Format(
                                            CultureInfo.InvariantCulture,
                                            "((BoundTypeExpression)existing[{0}]).Type == ((BoundTypeOrValueExpression)added[{0}]).Type", i));
                                }
                                else if (existing[i].Kind == BoundKind.TypeOrValueExpression && added[i].Kind == BoundKind.TypeExpression)
                                {
                                    FailFast.Assert(
                                        ((BoundTypeOrValueExpression)existing[i]).Type == ((BoundTypeExpression)added[i]).Type,
                                        string.Format(
                                            CultureInfo.InvariantCulture,
                                            "((BoundTypeOrValueExpression)existing[{0}]).Type == ((BoundTypeExpression)added[{0}]).Type", i));
                                }
                                else
                                {
                                    FailFast.Assert(false, "New bound node does not match existing bound node");
                                }
                            }
                            else
                            {
                                // The following assert is commented out because of Bug 985811.
                                // When the bug is resolved, please remove it completely or uncomment (depending on resolution).

                                ////FailFast.Assert(
                                ////    (object)existing[i] == added[i] || !(key is StatementSyntax),
                                ////    string.Format(
                                ////        CultureInfo.InvariantCulture,
                                ////        "(object)existing[{0}] == added[{0}] || !(key is StatementSyntax)", i));
                            }
                        }
#endif
                    }
                    else
                    {
                        map[key] = additionMap[key];
                    }
                }

                additionMap.Free();
            }