当前位置: 首页>>代码示例>>C#>>正文


C# Diagnostics.DiagnosticAnalyzer类代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer的典型用法代码示例。如果您正苦于以下问题:C# DiagnosticAnalyzer类的具体用法?C# DiagnosticAnalyzer怎么用?C# DiagnosticAnalyzer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DiagnosticAnalyzer类属于Microsoft.CodeAnalysis.Diagnostics命名空间,在下文中一共展示了DiagnosticAnalyzer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetDocumentBodyAnalysisDataAsync

                public async Task<AnalysisData> GetDocumentBodyAnalysisDataAsync(
                    DiagnosticAnalyzer provider, ProviderId providerId, VersionArgument versions, DiagnosticAnalyzerDriver analyzerDriver,
                    SyntaxNode root, SyntaxNode member, int memberId, bool supportsSemanticInSpan, MemberRangeMap.MemberRanges ranges)
                {
                    try
                    {
                        var document = analyzerDriver.Document;
                        var cancellationToken = analyzerDriver.CancellationToken;

                        var state = AnalyzersAndState.GetOrCreateDiagnosticState(StateType.Document, providerId, provider, document.Project.Id, document.Project.Language);
                        var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);

                        ImmutableArray<DiagnosticData> diagnosticData;
                        if (supportsSemanticInSpan && CanUseDocumentState(existingData, ranges.TextVersion, versions.DataVersion))
                        {
                            var memberDxData = await GetSemanticDiagnosticsAsync(providerId, provider, analyzerDriver).ConfigureAwait(false);

                            diagnosticData = _owner.UpdateDocumentDiagnostics(existingData, ranges.Ranges, memberDxData.AsImmutableOrEmpty(), root.SyntaxTree, member, memberId);
                            ValidateMemberDiagnostics(providerId, provider, document, root, diagnosticData);
                        }
                        else
                        {
                            // if we can't re-use existing document state, only option we have is updating whole document state here.
                            var dx = await GetSemanticDiagnosticsAsync(providerId, provider, analyzerDriver).ConfigureAwait(false);
                            diagnosticData = dx.AsImmutableOrEmpty();
                        }

                        return new AnalysisData(versions.TextVersion, versions.DataVersion, GetExistingItems(existingData), diagnosticData);
                    }
                    catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
                    {
                        throw ExceptionUtilities.Unreachable;
                    }
                    }
开发者ID:JinGuoGe,项目名称:roslyn,代码行数:34,代码来源:DiagnosticAnalyzerService.IncrementalAnalyzer.AnalyzerExecutor.cs

示例2: ProcessAnalyzer

        private void ProcessAnalyzer(DiagnosticAnalyzer analyzer, SqaleModel root)
        {
            foreach(DiagnosticDescriptor diagnostic in analyzer.SupportedDiagnostics)
            {
                SqaleDescriptor sqaleDescriptor = new SqaleDescriptor
                {
                    Remediation = new SqaleRemediation
                    {
                        RuleKey = diagnostic.Id
                    },
                    SubCharacteristic = "MAINTAINABILITY_COMPLIANCE"
                };

                sqaleDescriptor.Remediation.Properties.AddRange(new[]
                {
                    new SqaleRemediationProperty
                    {
                        Key = "remediationFunction",
                        Text = "CONSTANT_ISSUE"
                    },
                    new SqaleRemediationProperty
                    {
                        Key = "offset",
                        Value = this.remediationConstantValue,
                        Text = string.Empty
                    }
                });

                root.Sqale.Add(sqaleDescriptor);
            }
        }
开发者ID:SonarSource-VisualStudio,项目名称:sonarqube-roslyn-sdk,代码行数:31,代码来源:HardcodedConstantSqaleGenerator.cs

示例3: GetDiagnostics

 public static Diagnostic[] GetDiagnostics(DiagnosticAnalyzer analyzer, string source)
 {
     var project = CreateProject(source);
     var compilation = project.GetCompilationAsync().Result;
     var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer));
     return compilationWithAnalyzers.GetAllDiagnosticsAsync().Result.ToArray();
 }
开发者ID:FonsDijkstra,项目名称:CConst,代码行数:7,代码来源:DiagnosticHelper.cs

示例4: GetAllDiagnosticsAsync

 public static async Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(DiagnosticAnalyzer workspaceAnalyzerOpt, Document document, TextSpan span, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null, bool logAnalyzerExceptionAsDiagnostics = false, bool includeSuppressedDiagnostics = false)
 {
     using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, workspaceAnalyzerOpt, onAnalyzerException, logAnalyzerExceptionAsDiagnostics, includeSuppressedDiagnostics))
     {
         return await testDriver.GetAllDiagnosticsAsync(workspaceAnalyzerOpt, document, span);
     }
 }
开发者ID:Rickinio,项目名称:roslyn,代码行数:7,代码来源:DiagnosticProviderTestUtilities.cs

示例5: GetCompilationAnalysisScopeAsync

        private async Task<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync(
            DiagnosticAnalyzer analyzer,
            HostSessionStartAnalysisScope sessionScope,
            AnalyzerExecutor analyzerExecutor)
        {
            var analyzerAndOptions = new AnalyzerAndOptions(analyzer, analyzerExecutor.AnalyzerOptions);

            try
            {
                return await GetCompilationAnalysisScopeCoreAsync(analyzerAndOptions, sessionScope, analyzerExecutor).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                // Task to compute the scope was cancelled.
                // Clear the entry in scope map for analyzer, so we can attempt a retry.
                ConditionalWeakTable<Compilation, Task<HostCompilationStartAnalysisScope>> compilationActionsMap;
                if (_compilationScopeMap.TryGetValue(analyzerAndOptions, out compilationActionsMap))
                {
                    compilationActionsMap.Remove(analyzerExecutor.Compilation);
                }

                analyzerExecutor.CancellationToken.ThrowIfCancellationRequested();
                return await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false);
            }
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:roslyn,代码行数:25,代码来源:AnalyzerManager.cs

示例6: ReportAnalyzerDiagnostic

        internal void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Workspace workspace, ProjectId projectId)
        {
            if (workspace != this.Workspace)
            {
                return;
            }

            var project = workspace.CurrentSolution.GetProject(projectId);

            bool raiseDiagnosticsUpdated = true;
            var diagnosticData = project != null ?
                DiagnosticData.Create(project, diagnostic) :
                DiagnosticData.Create(this.Workspace, diagnostic);

            var dxs = ImmutableInterlocked.AddOrUpdate(ref s_analyzerHostDiagnosticsMap,
                analyzer,
                ImmutableHashSet.Create(diagnosticData),
                (a, existing) =>
                {
                    var newDiags = existing.Add(diagnosticData);
                    raiseDiagnosticsUpdated = newDiags.Count > existing.Count;
                    return newDiags;
                });

            if (raiseDiagnosticsUpdated)
            {
                RaiseDiagnosticsUpdated(MakeArgs(analyzer, dxs, project));
            }
        }
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:29,代码来源:AbstractHostDiagnosticUpdateSource.cs

示例7: ProcessCode

        protected Info ProcessCode(DiagnosticAnalyzer analyzer, string sampleProgram,
                                   ImmutableArray<SyntaxKind> expected, bool allowBuildErrors = false)
        {
            var options = new CSharpParseOptions(kind: SourceCodeKind.Script); //, languageVersion: LanguageVersion.CSharp5);
            var tree = CSharpSyntaxTree.ParseText(sampleProgram, options);
            var compilation = CSharpCompilation.Create("Test", new[] { tree }, references);

            var diagnostics = compilation.GetDiagnostics();
            if (diagnostics.Count(d => d.Severity == DiagnosticSeverity.Error) > 0)
            {
                var msg = "There were Errors in the sample code\n";
                if (allowBuildErrors == false)
                    Assert.Fail(msg + string.Join("\n", diagnostics));
                else
                    Console.WriteLine(msg + string.Join("\n", diagnostics));
            }

            var semanticModel = compilation.GetSemanticModel(tree);
            var matches = GetExpectedDescendants(tree.GetRoot().ChildNodes(), expected);

            // Run the code tree through the analyzer and record the allocations it reports
            var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer));
               var allocations = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult().Distinct(DiagnosticEqualityComparer.Instance).ToList();

            return new Info
            {
                Options = options,
                Tree = tree,
                Compilation = compilation,
                Diagnostics = diagnostics,
                SemanticModel = semanticModel,
                Matches = matches,
                Allocations = allocations,
            };
        }
开发者ID:codespare,项目名称:RoslynClrHeapAllocationAnalyzer,代码行数:35,代码来源:AllocationAnalyzerTests.cs

示例8: GetProjectDiagnostics

 public static IEnumerable<Diagnostic> GetProjectDiagnostics(DiagnosticAnalyzer workspaceAnalyzerOpt, Project project, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null, bool logAnalyzerExceptionAsDiagnostics = false)
 {
     using (var testDriver = new TestDiagnosticAnalyzerDriver(project, workspaceAnalyzerOpt, onAnalyzerException, logAnalyzerExceptionAsDiagnostics))
     {
         return testDriver.GetProjectDiagnostics(workspaceAnalyzerOpt, project);
     }
 }
开发者ID:noahstein,项目名称:roslyn,代码行数:7,代码来源:DiagnosticProviderTestUtilities.cs

示例9: GetSortedDiagnosticsFromDocuments

        /// <summary>
        /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
        /// The returned diagnostics are then ordered by location in the source document.
        /// </summary>
        /// <param name="analyzer">The analyzer to run on the documents</param>
        /// <param name="documents">The Documents that the analyzer will be run on</param>
        /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
        protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents)
        {
            var projects = new HashSet<Project>();
            foreach (var document in documents) {
                projects.Add(document.Project);
            }

            var diagnostics = new List<Diagnostic>();
            foreach (var project in projects) {
                var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
                var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
                foreach (var diag in diags) {
                    if (diag.Location == Location.None || diag.Location.IsInMetadata) {
                        diagnostics.Add(diag);
                    }
                    else {
                        for (int i = 0; i < documents.Length; i++) {
                            var document = documents[i];
                            var tree = document.GetSyntaxTreeAsync().Result;
                            if (tree == diag.Location.SourceTree) {
                                diagnostics.Add(diag);
                            }
                        }
                    }
                }
            }

            var results = SortDiagnostics(diagnostics);
            diagnostics.Clear();
            return results;
        }
开发者ID:andrecarlucci,项目名称:tddanalyzer,代码行数:38,代码来源:DiagnosticVerifier.Helper.cs

示例10: GetSessionAnalysisScopeAsync

 private async Task<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync(
     DiagnosticAnalyzer analyzer,
     AnalyzerExecutor analyzerExecutor)
 {
     var analyzerExecutionContext = _analyzerExecutionContextMap.GetOrCreateValue(analyzer);
     return await GetSessionAnalysisScopeCoreAsync(analyzer, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false);
 }
开发者ID:GuilhermeSa,项目名称:roslyn,代码行数:7,代码来源:AnalyzerManager.cs

示例11: GetSortedDiagnosticsFromDocumentsAsync

        /// <summary>
        /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
        /// The returned diagnostics are then ordered by location in the source document.
        /// </summary>
        /// <param name="analyzer">The analyzer to run on the documents</param>
        /// <param name="documents">The Documents that the analyzer will be run on</param>
        /// <returns>An IEnumerable of Diagnostics that surfaced in teh source code, sorted by Location</returns>
        protected async static Task<Diagnostic[]> GetSortedDiagnosticsFromDocumentsAsync(DiagnosticAnalyzer analyzer, Document[] documents)
        {
            var projects = new HashSet<Project>();
            foreach (var document in documents)
                projects.Add(document.Project);

            var diagnostics = new List<Diagnostic>();
            foreach (var project in projects)
            {
                var compilation = await project.GetCompilationAsync().ConfigureAwait(true);
                var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer));
                var diags = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(true);
                CheckIfAnalyzerThrew(await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(true));
                foreach (var diag in diags)
                {
                    if (diag.Location == Location.None || diag.Location.IsInMetadata)
                    {
                        diagnostics.Add(diag);
                    }
                    else
                    {
                        foreach (var document in project.Documents)
                        {
                            var tree = await document.GetSyntaxTreeAsync().ConfigureAwait(true);
                            if (tree == diag.Location.SourceTree) diagnostics.Add(diag);
                        }
                    }
                }
            }
            var results = SortDiagnostics(diagnostics);
            return results;
        }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:39,代码来源:DiagnosticVerifier.Helper.cs

示例12: CreateCompilation

        private static Compilation CreateCompilation(string source, string language, DiagnosticAnalyzer[] analyzers, string rootNamespace)
        {
            string fileName = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb";
            string projectName = "TestProject";

            var syntaxTree = language == LanguageNames.CSharp ?
                CSharpSyntaxTree.ParseText(source, path: fileName) :
                VisualBasicSyntaxTree.ParseText(source, path: fileName);

            if (language == LanguageNames.CSharp)
            {
                return CSharpCompilation.Create(
                    projectName,
                    syntaxTrees: new[] { syntaxTree },
                    references: new[] { TestBase.MscorlibRef });
            }
            else
            {
                return VisualBasicCompilation.Create(
                    projectName,
                    syntaxTrees: new[] { syntaxTree },
                    references: new[] { TestBase.MscorlibRef },
                    options: new VisualBasicCompilationOptions(
                        OutputKind.DynamicallyLinkedLibrary,
                        rootNamespace: rootNamespace));
            }
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:27,代码来源:SuppressMessageAttributeCompilerTests.cs

示例13: VerifyAnalyzer

        public static void VerifyAnalyzer(string path, DiagnosticAnalyzer diagnosticAnalyzer, ParseOptions options = null,
            params MetadataReference[] additionalReferences)
        {
            var file = new FileInfo(path);
            var parseOptions = GetParseOptionsAlternatives(options, file);

            using (var workspace = new AdhocWorkspace())
            {
                var document = GetDocument(file, GeneratedAssemblyName, workspace, additionalReferences);
                var project = document.Project;

                foreach (var parseOption in parseOptions)
                {
                    if (parseOption != null)
                    {
                        project = project.WithParseOptions(parseOption);
                    }

                    var compilation = project.GetCompilationAsync().Result;
                    var diagnostics = GetDiagnostics(compilation, diagnosticAnalyzer);
                    var expected = ExpectedIssues(compilation.SyntaxTrees.First()).ToList();

                    foreach (var diagnostic in diagnostics)
                    {
                        var line = diagnostic.GetLineNumberToReport();
                        expected.Should().Contain(line);
                        expected.Remove(line);
                    }

                    expected.Should().BeEquivalentTo(Enumerable.Empty<int>());
                }
            }
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:33,代码来源:Verifier.cs

示例14: VerifyAsync

 protected override Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null, bool logAnalyzerExceptionAsDiagnostics = false, string rootNamespace = null)
 {
     Assert.True(analyzers != null && analyzers.Length > 0, "Must specify at least one diagnostic analyzer to test suppression");
     var compilation = CreateCompilation(source, language, analyzers, rootNamespace);
     compilation.VerifyAnalyzerDiagnostics(analyzers, onAnalyzerException: onAnalyzerException, logAnalyzerExceptionAsDiagnostics: logAnalyzerExceptionAsDiagnostics, expected: diagnostics);
     return Task.FromResult(false);
 }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:SuppressMessageAttributeCompilerTests.cs

示例15: VerifyFix

        internal void VerifyFix(CodeFixProvider codeFixProvider,
                                DiagnosticAnalyzer diagnosticAnalyzer,
                                string language,
                                string oldSource,
                                string newSource,
                                int? codeFixIndex = null,
                                string[] allowedNewCompilerDiagnosticsId = null)
        {
            CodeFixProvider = codeFixProvider;
            DiagnosticAnalyzer = diagnosticAnalyzer;

            if (allowedNewCompilerDiagnosticsId == null || !allowedNewCompilerDiagnosticsId.Any())
            {
                VerifyFix(language, DiagnosticAnalyzer, CodeFixProvider, oldSource, newSource, codeFixIndex, false);
            }
            else
            {
                var document = DiagnosticVerifier.CreateDocument(oldSource, language);
                var compilerDiagnostics = GetCompilerDiagnostics(document).ToArray();

                VerifyFix(language, DiagnosticAnalyzer, CodeFixProvider, oldSource, newSource, codeFixIndex, true);

                var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)).ToList();

                if (newCompilerDiagnostics.Any(diagnostic => allowedNewCompilerDiagnosticsId.Any(s => s == diagnostic.Id)))
                {
                    Assert.AreEqual(document.GetSyntaxRootAsync().Result.ToFullString(),
                        string.Join(Environment.NewLine, newCompilerDiagnostics.Select(d => d.ToString())),
                        "Fix introduced new compiler diagnostics");
                }
            }
        }
开发者ID:Hosch250,项目名称:RoslynTester,代码行数:32,代码来源:CodeFixVerifier.cs


注:本文中的Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。