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


C# SyntaxNodeAnalysisContext类代码示例

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


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

示例1: ProcessUsings

        private static void ProcessUsings(SyntaxNodeAnalysisContext context, SyntaxList<UsingDirectiveSyntax> usings)
        {
            var usingDirectives = new List<UsingDirectiveSyntax>();
            var systemUsingDirectives = new List<UsingDirectiveSyntax>();

            foreach (var usingDirective in usings)
            {
                if (IsAliasOrStaticUsingDirective(usingDirective))
                {
                    continue;
                }

                if (usingDirective.IsPrecededByPreprocessorDirective())
                {
                    CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, usingDirectives);
                    CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, systemUsingDirectives);
                    usingDirectives.Clear();
                    systemUsingDirectives.Clear();
                }

                if (HasNamespaceAliasQualifier(usingDirective) || !usingDirective.IsSystemUsingDirective())
                {
                    usingDirectives.Add(usingDirective);
                }
                else
                {
                    systemUsingDirectives.Add(usingDirective);
                }
            }

            CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, usingDirectives);
            CheckIncorrectlyOrderedUsingsAndReportDiagnostic(context, systemUsingDirectives);
        }
开发者ID:nvincent,项目名称:StyleCopAnalyzers,代码行数:33,代码来源:SA1210UsingDirectivesMustBeOrderedAlphabeticallyByNamespace.cs

示例2: AnalyzeNode

        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGenerated()) return;
            var objectCreationExpression = (ObjectCreationExpressionSyntax)context.Node;

            var type = objectCreationExpression.Type;
            var typeSymbol = context.SemanticModel.GetSymbolInfo(type).Symbol as ITypeSymbol;
            if (!typeSymbol?.ToString().EndsWith("System.ArgumentException") ?? true) return;

            var argumentList = objectCreationExpression.ArgumentList as ArgumentListSyntax;
            if ((argumentList?.Arguments.Count ?? 0) < 2) return;

            var paramNameLiteral = argumentList.Arguments[1].Expression as LiteralExpressionSyntax;
            if (paramNameLiteral == null) return;

            var paramNameOpt = context.SemanticModel.GetConstantValue(paramNameLiteral);
            if (!paramNameOpt.HasValue) return;

            var paramName = paramNameOpt.Value as string;

            IList<string> parameters;
            if (IsParamNameCompatibleWithCreatingContext(objectCreationExpression, paramName, out parameters)) return;
            var props = parameters.ToImmutableDictionary(p => $"param{p}", p => p);
            var diagnostic = Diagnostic.Create(Rule, paramNameLiteral.GetLocation(), props.ToImmutableDictionary(), paramName);
            context.ReportDiagnostic(diagnostic);
        }
开发者ID:JeanLLopes,项目名称:code-cracker,代码行数:26,代码来源:ArgumentExceptionAnalyzer.cs

示例3: HandleDocumentation

        private static void HandleDocumentation(SyntaxNodeAnalysisContext context)
        {
            var documentationTrivia = context.Node as DocumentationCommentTriviaSyntax;

            if (documentationTrivia != null)
            {
                var summaryElement = documentationTrivia.Content.GetFirstXmlElement(XmlCommentHelper.SummaryXmlTag) as XmlElementSyntax;

                if (summaryElement != null)
                {
                    var textElement = summaryElement.Content.FirstOrDefault() as XmlTextSyntax;

                    if (textElement != null)
                    {
                        string text = XmlCommentHelper.GetText(textElement, true);

                        if (!string.IsNullOrEmpty(text))
                        {
                            if (text.TrimStart().StartsWith(DefaultText, StringComparison.Ordinal))
                            {
                                context.ReportDiagnostic(Diagnostic.Create(Descriptor, summaryElement.GetLocation()));
                            }
                        }
                    }
                }
            }
        }
开发者ID:endjin,项目名称:StyleCopAnalyzers,代码行数:27,代码来源:SA1608ElementDocumentationMustNotHaveDefaultSummary.cs

示例4: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var anyInvoke = nodeContext.Node as InvocationExpressionSyntax;

            var info = nodeContext.SemanticModel.GetSymbolInfo(anyInvoke);

            IMethodSymbol anyResolve = info.Symbol as IMethodSymbol;
            if (anyResolve == null)
            {
                anyResolve = info.CandidateSymbols.OfType<IMethodSymbol>().FirstOrDefault(candidate => HasPredicateVersion(candidate));
            }

            if (anyResolve == null || !HasPredicateVersion(anyResolve))
                return false;

            ExpressionSyntax target, followUp;
            TypeSyntax type;
            ParameterSyntax param;
            if (ReplaceWithOfTypeAnyAnalyzer.MatchSelect(anyInvoke, out target, out type, out param, out followUp))
            {
                // if (member == "Where" && followUp == null) return;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    anyInvoke.GetLocation()
                );
                return true;
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:30,代码来源:ReplaceWithOfTypeFirstAnalyzer.cs

示例5: TryGetDiagnostic

        private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            var localDeclarationUnused = nodeContext.Node as LocalDeclarationStatementSyntax;
            var body = localDeclarationUnused?.Parent as BlockSyntax;
            if (body == null)
                return false;

            var dataFlow = nodeContext.SemanticModel.AnalyzeDataFlow(body);
            var variablesDeclared = dataFlow.VariablesDeclared;
            var variablesRead = dataFlow.ReadInside.Union(dataFlow.ReadOutside);
            var unused = variablesDeclared.Except(variablesRead).ToArray();
            if (unused == null)
                return false;

            if (localDeclarationUnused.Declaration == null || !localDeclarationUnused.Declaration.Variables.Any())
                return false; 

            var localDeclarationSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(localDeclarationUnused.Declaration.Variables.FirstOrDefault());
            if (unused.Any())
            {
                if (unused.Contains(localDeclarationSymbol))
                {
                    diagnostic = Diagnostic.Create(descriptor, localDeclarationUnused.Declaration.GetLocation());
                    return true;
                }
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:30,代码来源:LocalVariableNotUsedAnalyzer.cs

示例6: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            var node = nodeContext.Node as ConditionalExpressionSyntax;

            bool? trueBranch = SimplifyConditionalTernaryExpressionCodeFixProvider.GetBool(node.WhenTrue.SkipParens());
            bool? falseBranch = SimplifyConditionalTernaryExpressionCodeFixProvider.GetBool(node.WhenFalse.SkipParens());

            if (trueBranch == falseBranch ||
                trueBranch == true && falseBranch == false) // Handled by RedundantTernaryExpressionIssue
                return false;

            var typeTrue = nodeContext.SemanticModel.GetTypeInfo(node.WhenTrue);
            var typeFalse = nodeContext.SemanticModel.GetTypeInfo(node.WhenFalse);
            if (typeTrue.Type == null || typeTrue.Type.SpecialType != SpecialType.System_Boolean ||
                typeFalse.Type == null || typeFalse.Type.SpecialType != SpecialType.System_Boolean)
                return false;


            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
开发者ID:pgrefviau,项目名称:RefactoringEssentials,代码行数:27,代码来源:SimplifyConditionalTernaryExpressionAnalyzer.cs

示例7: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            var node = nodeContext.Node as InvocationExpressionSyntax;
            MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax;
            if (mre == null)
                return false;
            if (mre.Name.Identifier.ValueText != "StartsWith")
                return false;

            var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken);
            if (rr.Symbol == null)
                return false;
            var symbol = rr.Symbol;
            if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String))
                return false;
            var parameters = symbol.GetParameters();
            var firstParameter = parameters.FirstOrDefault();
            if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String)
                return false;   // First parameter not a string
            var lastParameter = parameters.Last();
            if (lastParameter.Type.Name == "StringComparison")
                return false;   // already specifying a string comparison
            diagnostic = Diagnostic.Create(
                descriptor,
                node.GetLocation()
            );
            return true;
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:29,代码来源:StringStartsWithIsCultureSpecificAnalyzer.cs

示例8: AnalyzeRegexCreation

        private void AnalyzeRegexCreation(SyntaxNodeAnalysisContext context)
        {
            var objectCreation = (ObjectCreationExpressionSyntax) context.Node;

            var type = context.SemanticModel.GetSymbolInfo(objectCreation.Type).Symbol as ITypeSymbol;
            if (type == null || !type.Equals(context.SemanticModel.GetClrType(typeof(Regex))))
            {
                return;
            }

            var pattern = objectCreation.ArgumentList.Arguments[0].Expression.GetLiteral(context.SemanticModel);
            if (pattern == null)
            {
                return;
            }

            try
            {
                var regex = new Regex(pattern, RegexOptions.None, Timeout);
            }
            catch (ArgumentException e)
            {
                context.ReportDiagnostic(Diagnostic.Create(InvalidRegexRule, objectCreation.ArgumentList.Arguments[0].GetLocation(), e.Message));
            }
        }
开发者ID:SergeyTeplyakov,项目名称:ErrorProne.NET,代码行数:25,代码来源:RegexPatternAnalyzer.cs

示例9: CheckOverridableCallInConstructor

        private static void CheckOverridableCallInConstructor(SyntaxNodeAnalysisContext c)
        {
            var invocationExpression = (InvocationExpressionSyntax)c.Node;

            var calledOn = (invocationExpression.Expression as MemberAccessExpressionSyntax)?.Expression;
            var isCalledOnThis = calledOn == null || calledOn is ThisExpressionSyntax;
            if (!isCalledOnThis)
            {
                return;
            }

            var enclosingSymbol = c.SemanticModel.GetEnclosingSymbol(invocationExpression.SpanStart) as IMethodSymbol;
            if (!IsMethodConstructor(enclosingSymbol))
            {
                return;
            }

            var methodSymbol = c.SemanticModel.GetSymbolInfo(invocationExpression.Expression).Symbol as IMethodSymbol;

            if (methodSymbol != null &&
                IsMethodOverridable(methodSymbol) &&
                enclosingSymbol.IsInType(methodSymbol.ContainingType))
            {
                c.ReportDiagnostic(Diagnostic.Create(Rule, invocationExpression.Expression.GetLocation(),
                    methodSymbol.Name));
            }
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:27,代码来源:ConstructorOverridableCall.cs

示例10: AnalyzeTell

        private static void AnalyzeTell(SyntaxNodeAnalysisContext context)
        {
            var invocationExpr = (InvocationExpressionSyntax)context.Node;

            // technically this should be a MemberAccessExpression, since it's invoked as a method off of IActorRef / ICanTell
            var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;
            if (memberAccessExpr?.Name.ToString() != TargetMethodName) return;

            // need to verify that this `Tell` method is actually `ICanTell.Tell`
            var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol;

            var memberIsICanTell = (memberSymbol?.ToString().StartsWith(ICanTellMethodFQN) ?? false) || (memberSymbol?.ToString().StartsWith(IActorRefTellMethodFQN) ?? false);
            var memberIsActorRefExtension = memberSymbol?.ToString().StartsWith(ActorRefImplicitSenderTellFQN) ?? false;
            if (!memberIsICanTell && !memberIsActorRefExtension) return;

            // need to get the first argument being passed to the `Tell` method
            var argumentList = invocationExpr.ArgumentList as ArgumentListSyntax;
            if ((argumentList?.Arguments.Count ?? 0) < 1) return;

            // ReSharper disable once PossibleNullReferenceException //already validated as not null above
            var messageArgument =
                context.SemanticModel.GetSymbolInfo(memberIsICanTell ? argumentList.Arguments[0].Expression : argumentList.Arguments[1].Expression).Symbol;
            var allInterfaces = ((messageArgument as INamedTypeSymbol)?.Interfaces ?? ImmutableArray<INamedTypeSymbol>.Empty).Concat(messageArgument?.ContainingType.Interfaces ?? ImmutableArray<INamedTypeSymbol>.Empty).ToImmutableArray();
            if (allInterfaces.Any(y => y.ToString().StartsWith(ISystemMsgFQN)))
            {
                // found an ISystemMessage being passed into a Tell method
                var diagnostic = Diagnostic.Create(Rule, argumentList.GetLocation(), messageArgument.ToString(), DiagnosticSeverity.Error);
                context.ReportDiagnostic(diagnostic);
            }
        }
开发者ID:akkadotnet,项目名称:AkkaAnalyzer,代码行数:30,代码来源:SysMsgAnalyzer.cs

示例11: AnalyzeInvocation

 private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, Compilation compilation)
 {
     if (context.IsGenerated()) return;
     var methodInvokeSyntax = context.Node as InvocationExpressionSyntax;
     var childNodes = methodInvokeSyntax.ChildNodes();
     var methodCaller = childNodes.OfType<MemberAccessExpressionSyntax>().FirstOrDefault();
     if (methodCaller == null) return;
     var argumentsCount = CountArguments(childNodes);
     var classSymbol = GetCallerClassSymbol(context.SemanticModel, methodCaller.Expression);
     if (classSymbol == null || !classSymbol.MightContainExtensionMethods) return;
     var methodSymbol = GetCallerMethodSymbol(context.SemanticModel, methodCaller.Name, argumentsCount);
     if (methodSymbol == null || !methodSymbol.IsExtensionMethod) return;
     if (ContainsDynamicArgument(context.SemanticModel, childNodes)) return;
     ExpressionSyntax invocationStatement;
     if (methodInvokeSyntax.Parent.IsNotKind(SyntaxKind.ArrowExpressionClause))
     {
         invocationStatement = (methodInvokeSyntax.FirstAncestorOrSelfThatIsAStatement() as ExpressionStatementSyntax).Expression;
     }
     else
     {
         invocationStatement = methodInvokeSyntax.FirstAncestorOrSelfOfType<ArrowExpressionClauseSyntax>().Expression;
     }
     if (invocationStatement == null) return;
     if (IsSelectingADifferentMethod(childNodes, methodCaller.Name, context.Node.SyntaxTree, methodSymbol, invocationStatement, compilation)) return;
     context.ReportDiagnostic(Diagnostic.Create(Rule, methodCaller.GetLocation(), methodSymbol.Name, classSymbol.Name));
 }
开发者ID:plaurin,项目名称:code-cracker,代码行数:26,代码来源:CallExtensionMethodAsExtensionAnalyzer.cs

示例12: AnalyzePropertyDeclaration

    private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context)
    {
      var propertyNode = (PropertyDeclarationSyntax)context.Node;

      if(!propertyNode.ContainsDiagnostics)
      {
        var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyNode);
        var classSymbol = propertySymbol.ContainingType;

        if (propertySymbol != null && classSymbol != null &&
          classSymbol.IsStereotype() && !propertySymbol.IsAbstract &&
          !propertySymbol.IsStatic)
        {
          if (propertySymbol.GetMethod != null)
          {
            EvaluatePropertiesForSimplicityAnalyzer.AnalyzePropertyGetter(propertyNode, context);
          }

          if (propertySymbol.SetMethod != null)
          {
            EvaluatePropertiesForSimplicityAnalyzer.AnalyzePropertySetter(propertyNode, context);
          }
        }
      }
    }
开发者ID:ronnymgm,项目名称:csla-light,代码行数:25,代码来源:EvaluatePropertiesForSimplicityAnalyzer.cs

示例13: AnalyzeNode

        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGenerated()) return;
            var lambda = context.Node as ExpressionSyntax;

            var invocation = GetInvocationIfAny(lambda);
            if (invocation == null || invocation.ArgumentList.Arguments.Count == 0) return;

            var lambdaParameters = BuildParameters(lambda);
            if (!MatchArguments(lambdaParameters, invocation.ArgumentList)) return;

            var root = lambda.SyntaxTree.GetRoot();
            var newRoot = root.ReplaceNode(lambda, invocation.Expression as ExpressionSyntax);

            var semanticNode = GetNodeRootForAnalysis(lambda);
            var newSemanticNode = newRoot.DescendantNodesAndSelf()
                .Where(x => x.SpanStart == semanticNode.SpanStart && x.Span.OverlapsWith(context.Node.Span))
                .LastOrDefault(x => x.Kind() == semanticNode.Kind());

            if (newSemanticNode == null || ReplacementChangesSemantics(semanticNode, newSemanticNode, context.SemanticModel)) return;

            var diagnostic = Diagnostic.Create(
                Rule,
                context.Node.GetLocation(),
                invocation.Expression.ToString());
            context.ReportDiagnostic(diagnostic);
        }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:27,代码来源:ConvertLambdaExpressionToMethodGroupAnalyzer.cs

示例14: FirstUseOfUntrustedParameterShouldNotBeArgumentToTrustedParameter

 // TODO: Ideally, a load of static code analysis here, but just checking the first use would be a start.
 private void FirstUseOfUntrustedParameterShouldNotBeArgumentToTrustedParameter(SyntaxNodeAnalysisContext context)
 {
     var parameterSyntax = (ParameterSyntax)context.Node;
     var model = context.SemanticModel;
     var parameter = model.GetDeclaredSymbol(parameterSyntax);
     if (parameter.HasAttribute(TrustedAttributeName))
     {
         return;
     }
     var container = parameter.ContainingSymbol;
     if ((container as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction)
     {
         // Be lenient for anonymous functions. Not entirely sure whether this is a good idea,
         // admittedly.
         return;
     }
     var firstUse = container.DeclaringSyntaxReferences
         .SelectMany(syntaxRef => syntaxRef.GetSyntax().DescendantNodes())
         .Select(node => ParameterUsage.ForNode(node, model, parameter))
         .FirstOrDefault(usage => usage != null);
     if (firstUse?.CorrespondingParameter == null)
     {
         return;
     }
     if (firstUse.CorrespondingParameter.HasAttribute(TrustedAttributeName))
     {
         context.ReportDiagnostic(UntrustedParameterIsTrusted, firstUse.UsageNode, parameter.Name, container.Name);
     }
 }
开发者ID:nicklbailey,项目名称:nodatime,代码行数:30,代码来源:TrustedDiagnosticAnalyzer.cs

示例15: TryGetDiagnostic

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            InitializerExpressionSyntax initializer = null;
            var node = nodeContext.Node as ArrayCreationExpressionSyntax;
            if (node != null) initializer = node.Initializer;
            var inode = nodeContext.Node as ImplicitArrayCreationExpressionSyntax;
            if (inode != null) initializer = inode.Initializer;

            if (initializer == null)
                return false;
            var varInitializer = nodeContext.Node.Parent.Parent;
            if (varInitializer == null)
                return false;
            var variableDeclaration = varInitializer.Parent as VariableDeclarationSyntax;
            if (variableDeclaration != null)
            {
                if (!variableDeclaration.Type.IsKind(SyntaxKind.ArrayType))
                    return false;
                diagnostic = Diagnostic.Create(
                    descriptor,
                    Location.Create(nodeContext.SemanticModel.SyntaxTree, TextSpan.FromBounds((node != null ? node.NewKeyword : inode.NewKeyword).Span.Start, initializer.Span.Start))
                );
                return true;
            }
            return false;
        }
开发者ID:ceddlyburge,项目名称:RefactoringEssentials,代码行数:28,代码来源:ArrayCreationCanBeReplacedWithArrayInitializerAnalyzer.cs


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