LocalCouldBeConstAnalyzer.cs 6.2 KB
Newer Older
C
CyrusNajmabadi 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
J
John Hamby 已提交
2 3 4 5 6 7 8

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;

9
namespace Microsoft.CodeAnalysis.Test.Utilities
J
John Hamby 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
{
    /// <summary>Analyzer used to identify local variables that could be declared Const.</summary>
    public class LocalCouldBeConstAnalyzer : DiagnosticAnalyzer
    {
        private const string SystemCategory = "System";

        public static readonly DiagnosticDescriptor LocalCouldBeConstDescriptor = new DiagnosticDescriptor(
            "LocalCouldBeReadOnly",
            "Local Could Be Const",
            "Local variable is never modified and so could be const.",
            SystemCategory,
            DiagnosticSeverity.Warning,
            isEnabledByDefault: true);

        /// <summary>Gets the set of supported diagnostic descriptors from this analyzer.</summary>
        public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get { return ImmutableArray.Create(LocalCouldBeConstDescriptor); }
        }

        public sealed override void Initialize(AnalysisContext context)
        {
            context.RegisterOperationBlockStartAction(
                (operationBlockContext) =>
                {
                    IMethodSymbol containingMethod = operationBlockContext.OwningSymbol as IMethodSymbol;

                    if (containingMethod != null)
                    {
                        HashSet<ILocalSymbol> mightBecomeConstLocals = new HashSet<ILocalSymbol>();
                        HashSet<ILocalSymbol> assignedToLocals = new HashSet<ILocalSymbol>();

                        operationBlockContext.RegisterOperationAction(
                           (operationContext) =>
                           {
                               IAssignmentExpression assignment = (IAssignmentExpression)operationContext.Operation;
                               AssignTo(assignment.Target, assignedToLocals, mightBecomeConstLocals);
                           },
                           OperationKind.AssignmentExpression,
                           OperationKind.CompoundAssignmentExpression,
                           OperationKind.IncrementExpression);

                        operationBlockContext.RegisterOperationAction(
                            (operationContext) =>
                            {
                                IInvocationExpression invocation = (IInvocationExpression)operationContext.Operation;
                                foreach (IArgument argument in invocation.ArgumentsInParameterOrder)
                                {
                                    if (argument.Parameter.RefKind == RefKind.Out || argument.Parameter.RefKind == RefKind.Ref)
                                    {
                                        AssignTo(argument.Value, assignedToLocals, mightBecomeConstLocals);
                                    }
                                }
                            },
                            OperationKind.InvocationExpression);

                        operationBlockContext.RegisterOperationAction(
                            (operationContext) =>
                            {
                                IVariableDeclarationStatement declaration = (IVariableDeclarationStatement)operationContext.Operation;
70
                                foreach (IVariableDeclaration variable in declaration.Variables)
J
John Hamby 已提交
71 72 73 74 75 76 77
                                {
                                    ILocalSymbol local = variable.Variable;
                                    if (!local.IsConst && !assignedToLocals.Contains(local))
                                    {
                                        var localType = local.Type;
                                        if ((!localType.IsReferenceType || localType.SpecialType == SpecialType.System_String) && localType.SpecialType != SpecialType.None)
                                        {
78
                                            if (variable.InitialValue != null && variable.InitialValue.ConstantValue.HasValue)
J
John Hamby 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
                                            {
                                                mightBecomeConstLocals.Add(local);
                                            }
                                        }
                                    }
                                }
                            },
                            OperationKind.VariableDeclarationStatement);

                        operationBlockContext.RegisterOperationBlockEndAction(
                            (operationBlockEndContext) =>
                            {
                                foreach (ILocalSymbol couldBeConstLocal in mightBecomeConstLocals)
                                {
                                    Report(operationBlockEndContext, couldBeConstLocal, LocalCouldBeConstDescriptor);
                                }
                            });
                    }
                });
        }

J
John Hamby 已提交
100
        private static void AssignTo(IOperation target, HashSet<ILocalSymbol> assignedToLocals, HashSet<ILocalSymbol> mightBecomeConstLocals)
J
John Hamby 已提交
101 102 103 104 105 106 107 108 109 110 111
        {
            if (target.Kind == OperationKind.LocalReferenceExpression)
            {
                ILocalSymbol targetLocal = ((ILocalReferenceExpression)target).Local;

                assignedToLocals.Add(targetLocal);
                mightBecomeConstLocals.Remove(targetLocal);
            }
            else if (target.Kind == OperationKind.FieldReferenceExpression)
            {
                IFieldReferenceExpression fieldReference = (IFieldReferenceExpression)target;
112
                if (fieldReference.Instance != null && fieldReference.Instance.Type.IsValueType)
J
John Hamby 已提交
113 114 115 116 117 118
                {
                    AssignTo(fieldReference.Instance, assignedToLocals, mightBecomeConstLocals);
                }
            }
        }

C
CyrusNajmabadi 已提交
119
        private void Report(OperationBlockAnalysisContext context, ILocalSymbol local, DiagnosticDescriptor descriptor)
J
John Hamby 已提交
120 121 122 123 124
        {
            context.ReportDiagnostic(Diagnostic.Create(descriptor, local.Locations.FirstOrDefault()));
        }
    }
}