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


C# SyntaxNodeAnalysisContext.ReportDiagnostic方法代码示例

本文整理汇总了C#中SyntaxNodeAnalysisContext.ReportDiagnostic方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNodeAnalysisContext.ReportDiagnostic方法的具体用法?C# SyntaxNodeAnalysisContext.ReportDiagnostic怎么用?C# SyntaxNodeAnalysisContext.ReportDiagnostic使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SyntaxNodeAnalysisContext的用法示例。


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

示例1: AnalyzeMethod

        private static void AnalyzeMethod(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGenerated()) return;
            var method = (MethodDeclarationSyntax)context.Node;
            if (method.Identifier.ToString().EndsWith("Async")) return;
            if (method.Modifiers.Any(SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword)) return;

            var errorMessage = method.Identifier.ToString() + "Async";
            var diag = Diagnostic.Create(Rule, method.Identifier.GetLocation(), errorMessage);

            if (method.Modifiers.Any(SyntaxKind.AsyncKeyword))
            {
                context.ReportDiagnostic(diag);
                return;
            }
            var returnType = context.SemanticModel.GetSymbolInfo(method.ReturnType).Symbol as INamedTypeSymbol;
            if (returnType == null) return;

            if (returnType.ToString() == "System.Threading.Tasks.Task" ||
                (returnType.IsGenericType && returnType.ConstructedFrom.ToString() == "System.Threading.Tasks.Task<TResult>"))
            {
                context.ReportDiagnostic(diag);
            }

        }
开发者ID:nikolasmagno,项目名称:code-cracker,代码行数:25,代码来源:TaskNameAsyncAnalyzer.cs

示例2: ReportLSPViolatingExceptionIfThrown

 public static void ReportLSPViolatingExceptionIfThrown(SyntaxNodeAnalysisContext context,
                                                        INamedTypeSymbol exceptionType,
                                                        DiagnosticDescriptor rule)
 {
     var throwStatement = context.Node as ThrowStatementSyntax;
     throwStatement.Expression.DescendantNodesAndTokens()
                   .Where(t => t.IsKind(SyntaxKind.IdentifierName) || t.IsKind(SyntaxKind.IdentifierToken))
                   .TryFirst()
                   .Match()
                   .Some().Where(t => t.IsNode).Do(t =>
                   {
                       var identifier = t.AsNode() as IdentifierNameSyntax;
                       var identifierType = context.SemanticModel.GetSymbolInfo(identifier);
                       if (identifierType.Symbol.Equals(exceptionType))
                       {
                           context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
                       }
                   })
                   .Some().Do(t =>
                   {
                       var identifier = t.Parent as IdentifierNameSyntax;
                       var identiferType = context.SemanticModel.GetTypeInfo(identifier).Type;
                       if (identiferType.Equals(exceptionType))
                       {
                           context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation()));
                       }
                   })
                   .None().Do(() => { })
                   .Exec();
 }
开发者ID:DavidArno,项目名称:Arnolyzer,代码行数:30,代码来源:LSPViolatingExceptionReporter.cs

示例3: AnalyzeIfBlock

        private void AnalyzeIfBlock(SyntaxNodeAnalysisContext context)
        {
            var statement = context.Node as IfStatementSyntax;

            var thenClause = statement.Statement;

            if (!(thenClause is BlockSyntax))
            {
                // create the diagnostic:
                var location = thenClause.GetLocation();
                var diagnostic = Diagnostic.Create(Rule, location, "true clause");
                context.ReportDiagnostic(diagnostic);
            }

            // check the else clause:
            var elseStatement = statement.Else;
            if (elseStatement != null)
            {
                if (!(elseStatement.Statement is BlockSyntax))
                {
                    var location = elseStatement.Statement.GetLocation();
                    var diagnostic = Diagnostic.Create(Rule, location, "false (else) clause");
                    context.ReportDiagnostic(diagnostic);
                }
            }
        }
开发者ID:Winsto,项目名称:MVA-Roslyn,代码行数:26,代码来源:IfBraceAnalyzercs.cs

示例4: AnalyzeNode

        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var symbol = context.SemanticModel.GetSymbolInfo(context.Node).Symbol;

            var methodLambda = symbol as IMethodSymbol;

            if (methodLambda != null && methodLambda.IsAsync)
            {
                var type = context.SemanticModel.GetTypeInfo(context.Node);
                if (this.CheckIfVoidReturningDelegateType(type.ConvertedType))
                {
                    // check if the lambda is being assigned to a variable.  This has a code fix.
                    var parent = context.Node.Parent;

                    while (parent != null && !(parent is InvocationExpressionSyntax))
                    {
                        if (parent is VariableDeclarationSyntax)
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Rule2, parent.GetLocation()));
                            return;
                        }

                        parent = parent.Parent;
                    }

                    // if not, add the normal diagnostic
                    context.ReportDiagnostic(Diagnostic.Create(Rule1, context.Node.GetLocation()));
                    return;
                }
            }

            return;
        }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:33,代码来源:AsyncLambdaAnalyzer.cs

示例5: AnalyzeMethodDeclaration

    private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context)
    {
      var methodNode = (MethodDeclarationSyntax)context.Node;
      var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodNode);
      var typeSymbol = methodSymbol.ContainingType;

      if (typeSymbol.IsStereotype() && methodSymbol.IsDataPortalOperation() &&
        methodSymbol.DeclaredAccessibility == Accessibility.Public)
      {
        if(typeSymbol.TypeKind == TypeKind.Interface)
        {
          context.ReportDiagnostic(Diagnostic.Create(
            IsOperationMethodPublicAnalyzer.makeNonPublicForInterfaceRule,
            methodNode.Identifier.GetLocation()));
        }
        else
        {
          var properties = new Dictionary<string, string>()
          {
            [IsOperationMethodPublicAnalyzerConstants.IsSealed] = typeSymbol.IsSealed.ToString()
          }.ToImmutableDictionary();

          context.ReportDiagnostic(Diagnostic.Create(IsOperationMethodPublicAnalyzer.makeNonPublicRule,
            methodNode.Identifier.GetLocation(), properties));
        }
      }
    }
开发者ID:ronnymgm,项目名称:csla-light,代码行数:27,代码来源:IsOperationMethodPublicAnalyzer.cs

示例6: Analyzer

        private static void Analyzer(SyntaxNodeAnalysisContext context)
        {
            var documentationNode = (DocumentationCommentTriviaSyntax)context.Node;
            var method = GetMethodFromXmlDocumentation(documentationNode);
            if (method == null) return;
            var methodParameters = method.ParameterList.Parameters;
            var xElementsWitAttrs = documentationNode.Content.OfType<XmlElementSyntax>()
                                    .Where(xEle => xEle.StartTag?.Name?.LocalName.ValueText == "param")
                                    .SelectMany(xEle => xEle.StartTag.Attributes, (xEle, attr) => attr as XmlNameAttributeSyntax)
                                    .Where(attr => attr != null);

            var keys = methodParameters.Select(parameter => parameter.Identifier.ValueText)
                .Union(xElementsWitAttrs.Select(x => x.Identifier?.Identifier.ValueText))
                .ToImmutableHashSet();

            var parameterWithDocParameter = (from key in keys
                                            where key != null
                                            let Parameter = methodParameters.FirstOrDefault(p => p.Identifier.ValueText == key)
                                            let DocParameter = xElementsWitAttrs.FirstOrDefault(p => p.Identifier?.Identifier.ValueText == key)
                                            select new { Parameter, DocParameter });

            if (parameterWithDocParameter.Any(p => p.Parameter == null))
            {
                var properties = new Dictionary<string, string> {["kind"] = "nonexistentParam" }.ToImmutableDictionary();
                var diagnostic = Diagnostic.Create(Rule, documentationNode.GetLocation(), properties);
                context.ReportDiagnostic(diagnostic);
            }

            if (parameterWithDocParameter.Any(p => p.DocParameter == null))
            {
                var properties = new Dictionary<string, string> { ["kind"] = "missingDoc" }.ToImmutableDictionary();
                var diagnostic = Diagnostic.Create(Rule, documentationNode.GetLocation(), properties);
                context.ReportDiagnostic(diagnostic);
            }
        }
开发者ID:Cadums01,项目名称:code-cracker,代码行数:35,代码来源:XmlDocumentationAnalyzer.cs

示例7: AnalyzeSyntax

		private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
		{
			var classDeclaration = context.Node as ClassDeclarationSyntax;
			
			var dupeExports = classDeclaration.GetAttributes("Export")
				.GroupBy(x => x.ArgumentList.Arguments.First().ToString())
				.Where(x => 1 < x.Count())
				.Select(x => x.Key.ToString())
				.ToArray();

			if (dupeExports.Any())
				context.ReportDiagnostic(Diagnostic.Create(
					DuplicateExportAttributeRule,
					classDeclaration.GetLocation(),
					string.Join(", ", dupeExports)));


			var dupeMetadatas = classDeclaration.GetAttributes("ExportMetadata")
				.GroupBy(x => x.ArgumentList.Arguments.First().ToString())
				.Where(x => 1 < x.Count())
				.Select(x => x.Key.ToString().Replace("\"", ""))
				.ToArray();

			if (dupeMetadatas.Any())
				context.ReportDiagnostic(Diagnostic.Create(
					DuplicateExportMetadataAttributeRule,
					classDeclaration.GetLocation(),
					string.Join(", ", dupeMetadatas)));
		}
开发者ID:NatLee,项目名称:KanColleViewer,代码行数:29,代码来源:DuplicateAttributeAnalyzer.cs

示例8: AnalyzeNode

 public void AnalyzeNode(SyntaxNodeAnalysisContext context)
 {
     var classDecl = (ClassDeclarationSyntax)context.Node;
     var location = classDecl.Identifier.GetLocation();
     context.ReportDiagnostic(Diagnostic.Create(Decsciptor1, location));
     context.ReportDiagnostic(Diagnostic.Create(Decsciptor2, location));
 }
开发者ID:nicro950,项目名称:roslyn,代码行数:7,代码来源:SuppressionTest_FixMultipleTests.cs

示例9: AnalyzeField

        static void AnalyzeField(SyntaxNodeAnalysisContext nodeContext)
        {
            var node = nodeContext.Node as FieldDeclarationSyntax;
            if (node?.Declaration?.Variables == null)
                return;
            if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ConstKeyword)))
                return;
            var type = nodeContext.SemanticModel.GetTypeInfo(node.Declaration.Type).Type;
            if (type == null)
                return;
            foreach (var v in node.Declaration.Variables)
            {
                var initializer = v.Initializer?.Value;
                if (initializer == null)
                    continue;

                if (initializer.IsKind(SyntaxKind.DefaultExpression))
                {
                    //var defaultExpr = (DefaultExpressionSyntax)initializer;
                    //var defaultType = nodeContext.SemanticModel.GetTypeInfo(defaultExpr.Type).Type;
                    //if (defaultType == type) {
                    nodeContext.ReportDiagnostic(Diagnostic.Create(descriptor, v.Initializer.GetLocation()));
                    //}
                    continue;
                }

                var constValue = nodeContext.SemanticModel.GetConstantValue(initializer);
                if (!constValue.HasValue)
                    continue;
                if (IsDefaultValue(type, constValue.Value))
                {
                    nodeContext.ReportDiagnostic(Diagnostic.Create(descriptor, v.Initializer.GetLocation()));
                }
            }
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:35,代码来源:RedundantDefaultFieldInitializerAnalyzer.cs

示例10: AnalyzeSyntaxNode

        private static void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context)
        {
            AttributeSyntax attribute = (AttributeSyntax)context.Node;
            var model = context.SemanticModel;
            var attributeSymbol = model.GetSymbolInfo(attribute).Symbol?.ContainingSymbol;
            // TODO: Write a convenience method to do this properly, with namespace as well...
            if (attributeSymbol?.Name != "ReadWriteForEfficiencyAttribute")
            {
                return;
            }
            // ReadWriteForEfficiency can only be applied to fields, so the grandparent node must
            // be a field declaration syntax.
            var fieldDeclaration = (FieldDeclarationSyntax)attribute.Parent.Parent;
            foreach (var individualField in fieldDeclaration.Declaration.Variables)
            {
                var fieldSymbol = model.GetDeclaredSymbol(individualField);
                if (fieldSymbol.DeclaredAccessibility != Accessibility.Private)
                {
                    context.ReportDiagnostic(ReadWriteForEfficiencyNotPrivate, individualField, fieldSymbol.Name);
                }

                var invalidAssignments = fieldSymbol.ContainingType.DeclaringSyntaxReferences
                    .SelectMany(reference => reference.GetSyntax().DescendantNodes())
                    .OfType<AssignmentExpressionSyntax>()
                    .Where(n => IsAssignmentOutsideConstructor(n, fieldSymbol, model));
                foreach (var invalidAssignment in invalidAssignments)
                {
                    context.ReportDiagnostic(ReadWriteForEfficiencyAssignmentOutsideConstructor,
                        invalidAssignment, fieldSymbol.Name);
                }
            }
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:32,代码来源:ReadWriteForEfficiencyDiagnosticAnalyzer.cs

示例11: AnalyzeNode

        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {

            var equalsExpression = (BinaryExpressionSyntax)context.Node;

            var left = context.SemanticModel.GetTypeInfo(equalsExpression.Left);
            var right = context.SemanticModel.GetTypeInfo(equalsExpression.Right);

            if (
                left.IsLite() && right.IsEntity() ||
                left.IsEntity() && right.IsLite())
            {
                context.ReportDiagnostic(Diagnostic.Create(RuleLiteEntity, equalsExpression.GetLocation()));
            }
            else if (
                left.IsLite() && right.IsLite())
            {
                var tLeft = left.GetLiteEntityType();
                var tRight = right.GetLiteEntityType();

                if (tLeft != null && 
                    tRight != null &&
                    !tLeft.IsAbstract &&
                    !tRight.IsAbstract &&
                    !tLeft.GetBaseTypesAndThis().Contains(tRight) &&
                    !tRight.GetBaseTypesAndThis().Contains(tLeft))
                {
                    context.ReportDiagnostic(Diagnostic.Create(RuleEntityTypes, equalsExpression.GetLocation(), tLeft.Name, tRight.Name));
                }
            }
        }
开发者ID:signumsoftware,项目名称:framework,代码行数:31,代码来源:LiteEqualityAnalyzer.cs

示例12: AnalyzeNode

        public void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var ifStatementSyntax = (IfStatementSyntax)context.Node;

            if (ifStatementSyntax.Else != null)
            {
                SyntaxNode ifExpression = GetStatementSingle(ifStatementSyntax.Statement);

                SyntaxNode elseExpression = GetStatementSingle(ifStatementSyntax.Else.Statement);

                if (ifExpression != null && elseExpression != null)
                {
                    if (ifExpression is ReturnStatementSyntax && elseExpression is ReturnStatementSyntax)
                        context.ReportDiagnostic(Diagnostic.Create(Rule, ifStatementSyntax.GetLocation()));
                    else if (ifExpression is ExpressionStatementSyntax && elseExpression is ExpressionStatementSyntax)
                    {
                        ExpressionSyntax ifExpressionStatement = ((ExpressionStatementSyntax)ifExpression).Expression;
                        ExpressionSyntax elseExpressionStatement = ((ExpressionStatementSyntax)elseExpression).Expression;

                        if (ifExpressionStatement.IsKind(SyntaxKind.SimpleAssignmentExpression) &&
                            elseExpressionStatement.IsKind(SyntaxKind.SimpleAssignmentExpression))
                        {
                            var ifAssignmentVariable = ((BinaryExpressionSyntax)ifExpressionStatement).Left as IdentifierNameSyntax;
                            var elseAssignmentVariable = ((BinaryExpressionSyntax)elseExpressionStatement).Left as IdentifierNameSyntax;

                            if (ifAssignmentVariable != null && elseAssignmentVariable != null &&
                               ifAssignmentVariable.Identifier.Text == elseAssignmentVariable.Identifier.Text)
                                context.ReportDiagnostic(Diagnostic.Create(Rule, ifStatementSyntax.GetLocation()));
                        }
                    }
                }
            }
        }
开发者ID:mytinyfast,项目名称:CSharpCodingGuidelines,代码行数:33,代码来源:AV1545.cs

示例13: Analyzer

 private static void Analyzer(SyntaxNodeAnalysisContext context)
 {
     if (context.IsGenerated()) return;
     var ifStatement = context.Node as IfStatementSyntax;
     if (ifStatement == null) return;
     if (ifStatement.Else == null) return;
     var blockIf = ifStatement.Statement as BlockSyntax;
     var blockElse = ifStatement.Else.Statement as BlockSyntax;
     if ((blockIf == null || blockIf.Statements.Count == 1) &&
         (blockElse == null || blockElse.Statements.Count == 1))
     {
         var statementInsideIf = ifStatement.Statement is BlockSyntax ? ((BlockSyntax)ifStatement.Statement).Statements.Single() : ifStatement.Statement;
         var elseStatement = ifStatement.Else;
         var statementInsideElse = elseStatement.Statement is BlockSyntax ? ((BlockSyntax)elseStatement.Statement).Statements.Single() : elseStatement.Statement;
         if (statementInsideIf is ReturnStatementSyntax && statementInsideElse is ReturnStatementSyntax)
         {
             var diagnostic = Diagnostic.Create(RuleForIfWithReturn, ifStatement.IfKeyword.GetLocation(), "You can use a ternary operator.");
             context.ReportDiagnostic(diagnostic);
             return;
         }
         var expressionInsideIf = statementInsideIf as ExpressionStatementSyntax;
         var expressionInsideElse = statementInsideElse as ExpressionStatementSyntax;
         if (expressionInsideIf != null && expressionInsideIf.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression) && expressionInsideElse != null && expressionInsideElse.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression))
         {
             var assignmentExpressionInsideIf = (AssignmentExpressionSyntax)expressionInsideIf.Expression;
             var assignmentExpressionInsideElse = (AssignmentExpressionSyntax)expressionInsideElse.Expression;
             var variableIdentifierInsideIf = assignmentExpressionInsideIf.Left as IdentifierNameSyntax;
             var variableIdentifierInsideElse = assignmentExpressionInsideElse.Left as IdentifierNameSyntax;
             if (variableIdentifierInsideIf == null || variableIdentifierInsideElse == null
                 || variableIdentifierInsideIf.Identifier.Text != variableIdentifierInsideElse.Identifier.Text) return;
             var diagnostic = Diagnostic.Create(RuleForIfWithAssignment, ifStatement.IfKeyword.GetLocation(), "You can use a ternary operator.");
             context.ReportDiagnostic(diagnostic);
         }
     }
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:35,代码来源:TernaryOperatorAnalyzer.cs

示例14: AnalyzeIfOrElseStatement

        private void AnalyzeIfOrElseStatement(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGeneratedOrNonUserCode())
            {
                return;
            }

            IfStatementSyntax ifStatement = context.Node as IfStatementSyntax;

            // Is this an if statement followed directly by a call with no braces?
            if ((ifStatement != null) &&
                (ifStatement.Statement != null) &&
                (ifStatement.Statement.IsKind(SyntaxKind.Block) == false))
            {
                Location loc = ifStatement.GetLocation();
                Diagnostic diagnostic = Diagnostic.Create(Rule, loc, "if");
                context.ReportDiagnostic(diagnostic);
            }

            // Is this an else clause followed by a call with no braces?
            ElseClauseSyntax elseSyntax = context.Node as ElseClauseSyntax;
            if ((elseSyntax != null) &&
                (elseSyntax.Statement != null ) &&
                (elseSyntax.Statement.IsKind(SyntaxKind.IfStatement) == false) &&
                (elseSyntax.Statement.IsKind(SyntaxKind.Block) == false))
            {
                Location loc = elseSyntax.GetLocation();
                Diagnostic diagnostic = Diagnostic.Create(Rule, loc, "else");
                context.ReportDiagnostic(diagnostic);
            }
        }
开发者ID:vuder,项目名称:Wintellect.Analyzers,代码行数:31,代码来源:IfAndElseMustHaveBracesAnalyzer.cs

示例15: Analyze

        private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            var model = context.SemanticModel;

            var classDeclaration = context.Node as ClassDeclarationSyntax;
            if (classDeclaration == null) return;

            var declaredSymbol = model.GetDeclaredSymbol(classDeclaration);
            if (declaredSymbol == null) return;
            if (declaredSymbol.IsAbstract) return;

            var hub = declaredSymbol.FindBaseTargetType("PhotonWire.Server.Hub<T>");
            if (hub == null) return;

            var hubAttribute = declaredSymbol.GetAttributes().FindAttribute("PhotonWire.Server.HubAttribute");
            if (hubAttribute == null)
            {
                // if type == hub, needs attribute
                context.ReportDiagnostic(Diagnostic.Create(HubNeedsHubAttribute, classDeclaration.GetLocation()));
                return;
            }

            var methods = declaredSymbol.GetMembers()
                .OfType<IMethodSymbol>()
                .Where(x => x.MethodKind == MethodKind.Ordinary)
                .Where(x => x.DeclaredAccessibility == Accessibility.Public)
                .Where(x => !x.IsStatic)
                .ToArray();

            // all member needs OperationAttribute
            var attrs = methods.Select(x => x.GetAttributes().FindAttribute("PhotonWire.Server.OperationAttribute")).ToArray();

            var set = new HashSet<byte>();
            for (int i = 0; i < methods.Length; i++)
            {
                var m = methods[i];
                var a = attrs[i];

                if (a == null)
                {
                    // attr needs OperationAttribute;
                    context.ReportDiagnostic(Diagnostic.Create(MethodNeedsOperationAttribute, m.Locations[0]));
                    continue;
                }

                if (a.ConstructorArguments.Length != 1) continue;
                var id = (byte)a.ConstructorArguments[0].Value;
                if (!set.Add(id))
                {
                    // Report Diagnostics
                    var location = Location.Create(a.ApplicationSyntaxReference.SyntaxTree, a.ApplicationSyntaxReference.Span);
                    context.ReportDiagnostic(Diagnostic.Create(OperationIdMustBeUniqueAttribute, location, id));
                }
            }

            var clientType = hub.TypeArguments[0];
            VerifyClient(context, declaredSymbol, clientType);
        }
开发者ID:neuecc,项目名称:PhotonWire,代码行数:58,代码来源:PhotonWireHubAnalyzer.cs


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