public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationAction(AnalyzeCompilation);
        }
 public override void Initialize(AnalysisContext context)
 {
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
     context.RegisterSyntaxNodeAction(
         nodeContext =>
         {
             Diagnostic diagnostic;
             if (TryGetDiagnostic(nodeContext, out diagnostic))
             {
                 nodeContext.ReportDiagnostic(diagnostic);
             }
         },
         new SyntaxKind[] {
             SyntaxKind.EqualsExpression,
             SyntaxKind.NotEqualsExpression,
             SyntaxKind.LessThanExpression,
             SyntaxKind.LessThanOrEqualExpression,
             SyntaxKind.GreaterThanExpression,
             SyntaxKind.GreaterThanOrEqualExpression
         }
     );
     context.RegisterSyntaxNodeAction(
         nodeContext =>
         {
             Diagnostic diagnostic;
             if (TryGetDiagnostic2(nodeContext, out diagnostic))
             {
                 nodeContext.ReportDiagnostic(diagnostic);
             }
         },
         new SyntaxKind[] { SyntaxKind.LogicalNotExpression }
     );
 }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxTreeAction(SyntaxTreeAction);
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            analysisContext.EnableConcurrentExecution();

            analysisContext.RegisterSymbolAction(AnalyzeMethodSymbol, SymbolKind.Method);
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            // this is stateless analyzer, can run concurrently
            analysisContext.EnableConcurrentExecution();

            // this has no meaning on running on generated code which user can't control
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(c =>
            {
                INamedTypeSymbol @string = WellKnownTypes.String(c.Compilation);
                INamedTypeSymbol uri = WellKnownTypes.Uri(c.Compilation);
                if (@string == null || uri == null)
                {
                    // we don't have required types
                    return;
                }

                var analyzer = new Analyzer(c.Compilation, @string, uri, GetInvocationExpression);

                // REVIEW: I need to do this thing because OperationAnalysisContext doesn't give me OwningSymbol
                c.RegisterOperationBlockStartAction(sc =>
                {
                    sc.RegisterOperationAction(oc => analyzer.Analyze(oc, sc.OwningSymbol), OperationKind.InvocationExpression);
                });
            });
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(BinaryExpressionAction, HandledBinaryExpressionKinds);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(compilationStartContext =>
            {
                var immutableArrayType = compilationStartContext.Compilation.GetTypeByMetadataName(ImmutableArrayMetadataName);
                if (immutableArrayType == null)
                {
                    return;
                }

                compilationStartContext.RegisterOperationAction(operationContext =>
                {
                    var invocation = (IInvocationExpression)operationContext.Operation;
                    if (invocation.IsInvalid ||
                        invocation.TargetMethod?.Name != "ToImmutableArray")
                    {
                        return;
                    }

                    var receiverType = invocation.GetReceiverType(operationContext.Compilation, beforeConversion: true, cancellationToken: operationContext.CancellationToken);
                    if (receiverType != null &&
                        receiverType.DerivesFromOrImplementsAnyConstructionOf(immutableArrayType))
                    {
                        operationContext.ReportDiagnostic(Diagnostic.Create(Rule, invocation.Syntax.GetLocation()));
                    }
                }, OperationKind.InvocationExpression);
            });
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(EnumMemberDeclarationAction, SyntaxKind.EnumMemberDeclaration);
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(
                (context) =>
                {
                    INamedTypeSymbol dllImportType = context.Compilation.GetTypeByMetadataName("System.Runtime.InteropServices.DllImportAttribute");
                    if (dllImportType == null)
                    {
                        return;
                    }

                    INamedTypeSymbol marshalAsType = context.Compilation.GetTypeByMetadataName("System.Runtime.InteropServices.MarshalAsAttribute");
                    if (marshalAsType == null)
                    {
                        return;
                    }

                    INamedTypeSymbol stringBuilderType = context.Compilation.GetTypeByMetadataName("System.Text.StringBuilder");
                    if (stringBuilderType == null)
                    {
                        return;
                    }

                    INamedTypeSymbol unmanagedType = context.Compilation.GetTypeByMetadataName("System.Runtime.InteropServices.UnmanagedType");
                    if (unmanagedType == null)
                    {
                        return;
                    }

                    context.RegisterSymbolAction(new SymbolAnalyzer(dllImportType, marshalAsType, stringBuilderType, unmanagedType).AnalyzeSymbol, SymbolKind.Method);
                });
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(
                compilationContext =>
                {
                    Compilation compilation = compilationContext.Compilation;
                    ITypeSymbol argumentExceptionType = compilation.GetTypeByMetadataName("System.ArgumentException");

                    if (argumentExceptionType == null)
                    {
                        return;
                    }

                    compilationContext.RegisterOperationBlockStartAction(
                        operationBlockStartContext =>
                        {
                            operationBlockStartContext.RegisterOperationAction(
                                operationContext => AnalyzeObjectCreation(
                                    operationContext,
                                    operationBlockStartContext.OwningSymbol,
                                    argumentExceptionType),
                                OperationKind.ObjectCreationExpression);
                        });
                });
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(compilationContext =>
            {
                INamedTypeSymbol conditionalAttributeSymbol = WellKnownTypes.ConditionalAttribute(compilationContext.Compilation);

                compilationContext.RegisterOperationBlockAction(context =>
                {
                    var method = context.OwningSymbol as IMethodSymbol;
                    if (method == null)
                    {
                        return;
                    }

                    if (!method.IsFinalizer())
                    {
                        return;
                    }

                    if (IsEmptyFinalizer(context.OperationBlocks, conditionalAttributeSymbol))
                    {
                        context.ReportDiagnostic(context.OwningSymbol.CreateDiagnostic(Rule));
                    }
                });
            });
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterSymbolAction(symbolContext =>
            {
                var method = (IMethodSymbol)symbolContext.Symbol;
                if (!IsEventLikeNameCandidate(method.Name))
                {
                    Debug.Assert(!HasEventLikeName(method), "fast check failed but eventual check succeeds?");
                    return;
                }

                // Bail out for implicitly declared methods, overridden methods, interface implementations, constructors and finalizers (FxCop compat).
                if (method.IsImplicitlyDeclared ||
                    method.IsOverride ||
                    method.IsImplementationOfAnyInterfaceMember() ||
                    method.IsConstructor() ||
                    method.IsFinalizer())
                {
                    return;
                }

                if (HasEventLikeName(method))
                {
                    // Consider making '{0}' an event.
                    var diagnostic = method.CreateDiagnostic(Rule, method.Name);
                    symbolContext.ReportDiagnostic(diagnostic);
                }
            }, SymbolKind.Method);
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(
               (context) =>
               {
                   INamedTypeSymbol iCollectionType = WellKnownTypes.ICollection(context.Compilation);
                   INamedTypeSymbol genericICollectionType = WellKnownTypes.GenericICollection(context.Compilation);
                   INamedTypeSymbol iEnumerableType = WellKnownTypes.IEnumerable(context.Compilation);
                   INamedTypeSymbol genericIEnumerableType = WellKnownTypes.GenericIEnumerable(context.Compilation);
                   INamedTypeSymbol iListType = WellKnownTypes.IList(context.Compilation);
                   INamedTypeSymbol genericIListType = WellKnownTypes.GenericIList(context.Compilation);

                   if (iCollectionType == null && genericICollectionType == null &&
                       iEnumerableType == null && genericIEnumerableType == null &&
                       iListType == null && genericIListType == null)
                   {
                       return;
                   }

                   context.RegisterSymbolAction(c => AnalyzeSymbol(c,
                                                iCollectionType, genericICollectionType,
                                                iEnumerableType, genericIEnumerableType,
                                                iListType, genericIListType),
                                                SymbolKind.NamedType);
               });
        }
 public override void Initialize(AnalysisContext context)
 {
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
     context.RegisterSyntaxNodeAction(
         (nodeContext) =>
         {
             Diagnostic diagnostic;
             if (TryGetDiagnostic(nodeContext, out diagnostic))
             {
                 nodeContext.ReportDiagnostic(diagnostic);
             }
         },
         new SyntaxKind[] {
             SyntaxKind.MethodDeclaration,
                       SyntaxKind.FieldDeclaration,
                       SyntaxKind.PropertyDeclaration,
                       SyntaxKind.IndexerDeclaration,
                       SyntaxKind.EventDeclaration,
                       SyntaxKind.ConstructorDeclaration,
                       SyntaxKind.OperatorDeclaration,
                       SyntaxKind.ClassDeclaration,
                       SyntaxKind.InterfaceDeclaration,
                       SyntaxKind.StructDeclaration,
                       SyntaxKind.EnumDeclaration,
                       SyntaxKind.DelegateDeclaration
         }
     );
 }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(AnonymousMethodExpressionAction, SyntaxKind.AnonymousMethodExpression);
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterCompilationStartAction(
                (context) =>
                {
                    INamedTypeSymbol eventHandler = WellKnownTypes.EventHandler(context.Compilation);
                    if (eventHandler == null)
                    {
                        return;
                    }

                    INamedTypeSymbol genericEventHandler = WellKnownTypes.GenericEventHandler(context.Compilation);
                    if (genericEventHandler == null)
                    {
                        return;
                    }

                    INamedTypeSymbol eventArgs = WellKnownTypes.EventArgs(context.Compilation);
                    if (eventArgs == null)
                    {
                        return;
                    }

                    INamedTypeSymbol comSourceInterfacesAttribute = WellKnownTypes.ComSourceInterfaceAttribute(context.Compilation);
                    if (comSourceInterfacesAttribute == null)
                    {
                        return;
                    }

                    context.RegisterSymbolAction(GetAnalyzer(context.Compilation, eventHandler, genericEventHandler, eventArgs, comSourceInterfacesAttribute).AnalyzeSymbol, SymbolKind.Event);
                });
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(compilationContext =>
            {
                var exportAttribute = compilationContext.Compilation.GetTypeByMetadataName("System.Composition.ExportAttribute");

                if (exportAttribute == null)
                {
                    // We don't need to check assemblies unless they're referencing both MEFv2, so we're done
                    return;
                }

                compilationContext.RegisterSymbolAction(symbolContext =>
                {
                    var namedType = (INamedTypeSymbol)symbolContext.Symbol;
                    var namedTypeAttributes = namedType.GetApplicableAttributes();

                    var exportAttributeApplication = namedTypeAttributes.FirstOrDefault(ad => ad.AttributeClass.DerivesFrom(exportAttribute));

                    if (exportAttributeApplication != null)
                    {
                        if (!namedTypeAttributes.Any(ad => ad.AttributeClass.Name == "SharedAttribute" &&
                                                           ad.AttributeClass.ContainingNamespace.Equals(exportAttribute.ContainingNamespace)))
                        {
                            // '{0}' is exported with MEFv2 and hence must be marked as Shared
                            symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, exportAttributeApplication.ApplicationSyntaxReference.GetSyntax().GetLocation(), namedType.Name));
                        }
                    }
                }, SymbolKind.NamedType);
            });
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            // TODO: Make analyzer thread-safe
            //analysisContext.EnableConcurrentExecution();

            // Security analyzer - analyze and report diagnostics in generated code.
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);

            analysisContext.RegisterCompilationStartAction(
                (context) =>
                {
                    Compilation compilation = context.Compilation;
                    var xmlTypes = new CompilationSecurityTypes(compilation);

                    if (ReferencesAnyTargetType(xmlTypes))
                    {
                        Version version = SecurityDiagnosticHelpers.GetDotNetFrameworkVersion(compilation);

                        if (version != null)
                        {
                            context.RegisterOperationBlockStartAction(
                                (c) =>
                                {
                                    RegisterAnalyzer(c, xmlTypes, version);
                                });
                        }
                    }
                });
        }
 public override void Initialize(AnalysisContext context)
 {
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
     context.RegisterSyntaxNodeAction(
         (nodeContext) =>
         {
             Diagnostic diagnostic;
             if (TryGetDiagnostic(nodeContext, out diagnostic))
             {
                 nodeContext.ReportDiagnostic(diagnostic);
             }
         },
         new SyntaxKind[] { SyntaxKind.LocalDeclarationStatement }
     );
     context.RegisterSyntaxNodeAction(
         (nodeContext) =>
         {
             Diagnostic diagnostic;
             if (TryGetDiagnosticFromForeach(nodeContext, out diagnostic))
             {
                 nodeContext.ReportDiagnostic(diagnostic);
             }
         },
         new SyntaxKind[] { SyntaxKind.ForEachStatement }
     );
 }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterSymbolAction(
                symbolAnalysisContext =>
                {
                    ISymbol symbol = symbolAnalysisContext.Symbol;
                    if (!symbol.ContainingType.IsGenericType ||
                        symbol.DeclaredAccessibility != Accessibility.Public ||
                        !symbol.IsStatic)
                    {
                        return;
                    }

                    var methodSymbol = symbol as IMethodSymbol;
                    if (methodSymbol != null &&
                        (methodSymbol.IsAccessorMethod() ||
                         (methodSymbol.MethodKind == MethodKind.UserDefinedOperator &&
                          (methodSymbol.Name == WellKnownMemberNames.EqualityOperatorName ||
                           methodSymbol.Name == WellKnownMemberNames.InequalityOperatorName))))
                    {
                        return;
                    }

                    symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(Rule, symbol.Name));
                }, SymbolKind.Method, SymbolKind.Property);
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(RegionDirectiveTriviaAction, SyntaxKind.RegionDirectiveTrivia);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(OnCompilationStart);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterSyntaxNodeAction(AnalyzeXmlAttribute, SyntaxKind.XmlTextAttribute);
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(DocumentationTriviaAction, SyntaxKind.SingleLineDocumentationCommentTrivia);
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSymbolAction(Analyzer.HandleFieldDeclaration, SymbolKind.Field);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.RegisterSyntaxNodeAction(
                nodeContext =>
                {
                    GetDiagnostics(nodeContext, ((InvocationExpressionSyntax)nodeContext.Node).ArgumentList?.Arguments);
                },
                new SyntaxKind[] { SyntaxKind.InvocationExpression }
            );
            context.RegisterSyntaxNodeAction(
                nodeContext =>
                {
                    GetDiagnostics(nodeContext, ((ElementAccessExpressionSyntax)nodeContext.Node).ArgumentList?.Arguments);
                },
                new SyntaxKind[] { SyntaxKind.ElementAccessExpression }
            );
            context.RegisterSyntaxNodeAction(
                nodeContext =>
                {
                    GetDiagnostics(nodeContext, ((ObjectCreationExpressionSyntax)nodeContext.Node).ArgumentList?.Arguments);
                },
                new SyntaxKind[] { SyntaxKind.ObjectCreationExpression }
            );

            context.RegisterSyntaxNodeAction(
                nodeContext =>
                {
                    GetDiagnostics(nodeContext, ((AttributeSyntax)nodeContext.Node).ArgumentList?.Arguments);
                },
                new SyntaxKind[] { SyntaxKind.Attribute }
            );
        }
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.RegisterSymbolAction(
                (symbol) =>
                {
                    Diagnostic diagnostic;
                    if (TryGetDiagnostic(symbol, out diagnostic))
                    {
                        symbol.ReportDiagnostic(diagnostic);
                    }
                },
                new SymbolKind[] {
                    SymbolKind.Method
                }
            );

            context.RegisterSyntaxNodeAction(
               (nodeContext) =>
               {
                   Diagnostic diagnostic;
                   if (TryGetDiagnostic(nodeContext, out diagnostic))
                   {
                       nodeContext.ReportDiagnostic(diagnostic);
                   }
               },
               new SyntaxKind[] {
                   SyntaxKind.AnonymousMethodExpression,
                    SyntaxKind.ParenthesizedLambdaExpression,
                    SyntaxKind.SimpleLambdaExpression
               }
           );
        }
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            analysisContext.RegisterSyntaxNodeAction<SyntaxKind>(AnalyzeNode, SyntaxKind.ThrowStatement);
        }
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
        }
        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterSyntaxNodeAction(DoStatementAction, SyntaxKind.DoStatement);
        }
 public override void Initialize(AnalysisContext context)
 {
     context.EnableConcurrentExecution();
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
     context.RegisterOperationAction(AnalyzeInvocation, OperationKind.InvocationExpression);
 }
示例#32
0
        public override void Initialize(AnalysisContext context)
        {
            context.EnableConcurrentExecution();
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

            context.RegisterCompilationStartAction(compilationContext =>
            {
                INamedTypeSymbol localizableStateAttributeSymbol  = WellKnownTypes.LocalizableAttribute(compilationContext.Compilation);
                INamedTypeSymbol conditionalAttributeSymbol       = WellKnownTypes.ConditionalAttribute(compilationContext.Compilation);
                INamedTypeSymbol systemConsoleSymbol              = WellKnownTypes.Console(compilationContext.Compilation);
                ImmutableHashSet <INamedTypeSymbol> typesToIgnore = GetTypesToIgnore(compilationContext.Compilation);

                compilationContext.RegisterOperationBlockStartAction(operationBlockStartContext =>
                {
                    if (!(operationBlockStartContext.OwningSymbol is IMethodSymbol containingMethod) ||
                        containingMethod.IsConfiguredToSkipAnalysis(operationBlockStartContext.Options,
                                                                    Rule, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken))
                    {
                        return;
                    }

                    var lazyValueContentResult = new Lazy <DataFlowAnalysisResult <ValueContentBlockAnalysisResult, ValueContentAbstractValue> >(
                        valueFactory: ComputeValueContentAnalysisResult, isThreadSafe: false);

                    operationBlockStartContext.RegisterOperationAction(operationContext =>
                    {
                        var argument = (IArgumentOperation)operationContext.Operation;
                        IMethodSymbol targetMethod = null;
                        switch (argument.Parent)
                        {
                        case IInvocationOperation invocation:
                            targetMethod = invocation.TargetMethod;
                            break;

                        case IObjectCreationOperation objectCreation:
                            targetMethod = objectCreation.Constructor;
                            break;
                        }

                        if (ShouldAnalyze(targetMethod))
                        {
                            AnalyzeArgument(argument.Parameter, containingPropertySymbolOpt: null, operation: argument, reportDiagnostic: operationContext.ReportDiagnostic);
                        }
                    }, OperationKind.Argument);

                    operationBlockStartContext.RegisterOperationAction(operationContext =>
                    {
                        var propertyReference = (IPropertyReferenceOperation)operationContext.Operation;
                        if (propertyReference.Parent is IAssignmentOperation assignment &&
                            assignment.Target == propertyReference &&
                            !propertyReference.Property.IsIndexer &&
                            propertyReference.Property.SetMethod?.Parameters.Length == 1 &&
                            ShouldAnalyze(propertyReference.Property))
                        {
                            IParameterSymbol valueSetterParam = propertyReference.Property.SetMethod.Parameters[0];
                            AnalyzeArgument(valueSetterParam, propertyReference.Property, assignment, operationContext.ReportDiagnostic);
                        }
                    }, OperationKind.PropertyReference);

                    return;

                    // Local functions
                    bool ShouldAnalyze(ISymbol symbol)
                    => symbol != null && !symbol.IsConfiguredToSkipAnalysis(operationBlockStartContext.Options, Rule, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken);

                    void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol containingPropertySymbolOpt, IOperation operation, Action <Diagnostic> reportDiagnostic)
                    {
                        if (ShouldBeLocalized(parameter.OriginalDefinition, containingPropertySymbolOpt?.OriginalDefinition, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore) &&
                            lazyValueContentResult.Value != null)
                        {
                            ValueContentAbstractValue stringContentValue = lazyValueContentResult.Value[operation.Kind, operation.Syntax];
                            if (stringContentValue.IsLiteralState)
                            {
                                Debug.Assert(stringContentValue.LiteralValues.Count > 0);

                                if (stringContentValue.LiteralValues.Any(l => !(l is string)))
                                {
                                    return;
                                }

                                var stringLiteralValues = stringContentValue.LiteralValues.Select(l => (string)l);

                                // FxCop compat: Do not fire if the literal value came from a default parameter value
                                if (stringContentValue.LiteralValues.Count == 1 &&
                                    parameter.IsOptional &&
                                    parameter.ExplicitDefaultValue is string defaultValue &&
                                    defaultValue == stringLiteralValues.Single())
                                {
                                    return;
                                }

                                // FxCop compat: Do not fire if none of the string literals have any non-control character.
                                if (!LiteralValuesHaveNonControlCharacters(stringLiteralValues))
                                {
                                    return;
                                }

                                // FxCop compat: Filter out xml string literals.
                                var filteredStrings = stringLiteralValues.Where(literal => !LooksLikeXmlTag(literal));
                                if (filteredStrings.Any())
                                {
                                    // Method '{0}' passes a literal string as parameter '{1}' of a call to '{2}'. Retrieve the following string(s) from a resource table instead: "{3}".
                                    var arg1       = containingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                                    var arg2       = parameter.Name;
                                    var arg3       = parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                                    var arg4       = FormatLiteralValues(filteredStrings);
                                    var diagnostic = operation.CreateDiagnostic(Rule, arg1, arg2, arg3, arg4);
                                    reportDiagnostic(diagnostic);
                                }
                            }
                        }
                    }

                    DataFlowAnalysisResult <ValueContentBlockAnalysisResult, ValueContentAbstractValue> ComputeValueContentAnalysisResult()
                    {
                        var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph();
                        if (cfg != null)
                        {
                            var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationBlockStartContext.Compilation);
                            return(ValueContentAnalysis.TryGetOrComputeResult(cfg, containingMethod, wellKnownTypeProvider,
                                                                              operationBlockStartContext.Options, Rule, operationBlockStartContext.CancellationToken));
                        }

                        return(null);
                    }
                });
            });
        }
示例#33
0
        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.EnableConcurrentExecution();

            // We need to analyze generated code, but don't intend to report diagnostics for generated code fields.
            analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);

            analysisContext.RegisterCompilationStartAction(
                (compilationContext) =>
            {
                ConcurrentDictionary <IFieldSymbol, UnusedValue> unreferencedPrivateFields = new ConcurrentDictionary <IFieldSymbol, UnusedValue>();
                ConcurrentDictionary <IFieldSymbol, UnusedValue> referencedPrivateFields   = new ConcurrentDictionary <IFieldSymbol, UnusedValue>();

                ImmutableHashSet <INamedTypeSymbol> specialAttributes = GetSpecialAttributes(compilationContext.Compilation);
                var structLayoutAttribute = WellKnownTypes.StructLayoutAttribute(compilationContext.Compilation);

                compilationContext.RegisterSymbolAction(
                    (symbolContext) =>
                {
                    IFieldSymbol field = (IFieldSymbol)symbolContext.Symbol;

                    // Fields of types marked with StructLayoutAttribute with LayoutKind.Sequential should never be flagged as unused as their removal can change the runtime behavior.
                    if (structLayoutAttribute != null && field.ContainingType != null)
                    {
                        foreach (var attribute in field.ContainingType.GetAttributes())
                        {
                            if (structLayoutAttribute.Equals(attribute.AttributeClass.OriginalDefinition) &&
                                attribute.ConstructorArguments.Length == 1)
                            {
                                var argument = attribute.ConstructorArguments[0];
                                if (argument.Type != null)
                                {
                                    SpecialType specialType = argument.Type.TypeKind == TypeKind.Enum ?
                                                              ((INamedTypeSymbol)argument.Type).EnumUnderlyingType.SpecialType :
                                                              argument.Type.SpecialType;

                                    if (DiagnosticHelpers.TryConvertToUInt64(argument.Value, specialType, out ulong convertedLayoutKindValue) &&
                                        convertedLayoutKindValue == (ulong)System.Runtime.InteropServices.LayoutKind.Sequential)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    if (field.DeclaredAccessibility == Accessibility.Private && !referencedPrivateFields.ContainsKey(field))
                    {
                        // Fields with certain special attributes should never be considered unused.
                        if (!specialAttributes.IsEmpty)
                        {
                            foreach (var attribute in field.GetAttributes())
                            {
                                if (specialAttributes.Contains(attribute.AttributeClass.OriginalDefinition))
                                {
                                    return;
                                }
                            }
                        }

                        unreferencedPrivateFields.TryAdd(field, default);
                    }
                },
                    SymbolKind.Field);

                compilationContext.RegisterOperationAction(
                    (operationContext) =>
                {
                    IFieldSymbol field = ((IFieldReferenceOperation)operationContext.Operation).Field;
                    if (field.DeclaredAccessibility == Accessibility.Private)
                    {
                        referencedPrivateFields.TryAdd(field, default);
                        unreferencedPrivateFields.TryRemove(field, out _);
                    }
                },
                    OperationKind.FieldReference);

                compilationContext.RegisterCompilationEndAction(
                    (compilationEndContext) =>
                {
                    foreach (IFieldSymbol unreferencedPrivateField in unreferencedPrivateFields.Keys)
                    {
                        compilationEndContext.ReportDiagnostic(Diagnostic.Create(Rule, unreferencedPrivateField.Locations[0], unreferencedPrivateField.Name));
                    }
                });
            });
        }
 /// <inheritdoc/>
 public override void Initialize(AnalysisContext context)
 {
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
     context.EnableConcurrentExecution();
     context.RegisterSyntaxNodeAction(x => Handle(x), SyntaxKind.Argument, SyntaxKind.AddAssignmentExpression);
 }
示例#35
0
 /// <inheritdoc/>
 public override void Initialize(AnalysisContext context)
 {
     context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
     context.EnableConcurrentExecution();
     context.RegisterSyntaxNodeAction(HandleDeclaration, SyntaxKind.InvocationExpression);
 }