IMethodSymbolExtensions.cs 14.4 KB
Newer Older
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.
P
Pilchie 已提交
2 3 4

using System;
using System.Collections.Generic;
5
using System.Collections.Immutable;
P
Pilchie 已提交
6 7 8 9 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
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class IMethodSymbolExtensions
    {
        public static bool CompatibleSignatureToDelegate(this IMethodSymbol method, INamedTypeSymbol delegateType)
        {
            Contract.ThrowIfFalse(delegateType.TypeKind == TypeKind.Delegate);

            var invoke = delegateType.DelegateInvokeMethod;
            if (invoke == null)
            {
                // It's possible to get events with no invoke method from metadata.  We will assume
                // that no method can be an event handler for one.
                return false;
            }

            if (method.Parameters.Length != invoke.Parameters.Length)
            {
                return false;
            }

            if (method.ReturnsVoid != invoke.ReturnsVoid)
            {
                return false;
            }

            if (!method.ReturnType.InheritsFromOrEquals(invoke.ReturnType))
            {
                return false;
            }

            for (int i = 0; i < method.Parameters.Length; i++)
            {
                if (!invoke.Parameters[i].Type.InheritsFromOrEquals(method.Parameters[i].Type))
                {
                    return false;
                }
            }

            return true;
        }

        public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList<string> newNames)
        {
            if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
            {
                return method;
            }

            var typeGenerator = new TypeGenerator();
            var updatedTypeParameters = RenameTypeParameters(
                method.TypeParameters, newNames, typeGenerator);

            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
            for (int i = 0; i < method.TypeParameters.Length; i++)
            {
70
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
P
Pilchie 已提交
71 72 73 74 75 76 77 78
            }

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
                method.GetAttributes(),
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType.SubstituteTypes(mapping, typeGenerator),
79
                method.RefKind,
80
                method.ExplicitInterfaceImplementations,
P
Pilchie 已提交
81 82
                method.Name,
                updatedTypeParameters,
C
CyrusNajmabadi 已提交
83
                method.Parameters.SelectAsArray(p =>
P
Pilchie 已提交
84
                    CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
C
CyrusNajmabadi 已提交
85
                        p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)));
P
Pilchie 已提交
86 87
        }

88 89
        public static IMethodSymbol RenameParameters(
            this IMethodSymbol method, IList<string> parameterNames)
P
Pilchie 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        {
            var parameterList = method.Parameters;
            if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
            {
                return method;
            }

            var parameters = parameterList.RenameParameters(parameterNames);

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
                method.GetAttributes(),
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType,
105
                method.RefKind,
106
                method.ExplicitInterfaceImplementations,
P
Pilchie 已提交
107 108 109 110 111
                method.Name,
                method.TypeParameters,
                parameters);
        }

C
CyrusNajmabadi 已提交
112
        private static ImmutableArray<ITypeParameterSymbol> RenameTypeParameters(
113
            ImmutableArray<ITypeParameterSymbol> typeParameters,
P
Pilchie 已提交
114 115 116 117 118 119 120
            IList<string> newNames,
            ITypeGenerator typeGenerator)
        {
            // We generate the type parameter in two passes.  The first creates the new type
            // parameter.  The second updates the constraints to point at this new type parameter.
            var newTypeParameters = new List<CodeGenerationTypeParameterSymbol>();
            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
121
            for (int i = 0; i < typeParameters.Length; i++)
P
Pilchie 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
            {
                var typeParameter = typeParameters[i];

                var newTypeParameter = new CodeGenerationTypeParameterSymbol(
                    typeParameter.ContainingType,
                    typeParameter.GetAttributes(),
                    typeParameter.Variance,
                    newNames[i],
                    typeParameter.ConstraintTypes,
                    typeParameter.HasConstructorConstraint,
                    typeParameter.HasReferenceTypeConstraint,
                    typeParameter.HasValueTypeConstraint,
                    typeParameter.Ordinal);

                newTypeParameters.Add(newTypeParameter);
137
                mapping[typeParameter] = newTypeParameter;
P
Pilchie 已提交
138 139
            }

140
            // Now we update the constraints.
P
Pilchie 已提交
141 142
            foreach (var newTypeParameter in newTypeParameters)
            {
143
                newTypeParameter.ConstraintTypes = ImmutableArray.CreateRange(newTypeParameter.ConstraintTypes, t => t.SubstituteTypes(mapping, typeGenerator));
P
Pilchie 已提交
144 145
            }

C
CyrusNajmabadi 已提交
146
            return newTypeParameters.Cast<ITypeParameterSymbol>().ToImmutableArray();
P
Pilchie 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        }

        public static IMethodSymbol EnsureNonConflictingNames(
            this IMethodSymbol method, INamedTypeSymbol containingType, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
        {
            // The method's type parameters may conflict with the type parameters in the type
            // we're generating into.  In that case, rename them.
            var parameterNames = NameGenerator.EnsureUniqueness(
                method.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);

            var outerTypeParameterNames =
                containingType.GetAllTypeParameters()
                              .Select(tp => tp.Name)
                              .Concat(method.Name)
                              .Concat(containingType.Name);

            var unusableNames = parameterNames.Concat(outerTypeParameterNames).ToSet(
                syntaxFacts.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);

            var newTypeParameterNames = NameGenerator.EnsureUniqueness(
                method.TypeParameters.Select(tp => tp.Name).ToList(),
                n => !unusableNames.Contains(n));

            var updatedMethod = method.RenameTypeParameters(newTypeParameterNames);
            return updatedMethod.RenameParameters(parameterNames);
        }

174
        public static IMethodSymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
C
CyrusNajmabadi 已提交
175 176
            this IMethodSymbol method, ISymbol accessibleWithin,
            params INamedTypeSymbol[] removeAttributeTypes)
177
        {
C
CyrusNajmabadi 已提交
178
            bool shouldRemoveAttribute(AttributeData a) =>
179 180
                removeAttributeTypes.Any(attr => attr != null && attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);

C
CyrusNajmabadi 已提交
181 182
            return method.RemoveAttributesCore(
                shouldRemoveAttribute,
C
CyrusNajmabadi 已提交
183 184
                statements: default,
                handlesExpressions: default);
185 186 187 188
        }

        private static IMethodSymbol RemoveAttributesCore(
            this IMethodSymbol method, Func<AttributeData, bool> shouldRemoveAttribute,
C
CyrusNajmabadi 已提交
189
            ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions)
190 191
        {
            var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);
192 193

            var someParameterHasAttribute = method.Parameters
194
                .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));
195

196
            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);
197

198
            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
199 200 201 202 203 204
            {
                return method;
            }

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
C
CyrusNajmabadi 已提交
205
                method.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
206 207 208
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType,
209
                method.RefKind,
210
                method.ExplicitInterfaceImplementations,
211 212
                method.Name,
                method.TypeParameters,
C
CyrusNajmabadi 已提交
213
                method.Parameters.SelectAsArray(p =>
214
                    CodeGenerationSymbolFactory.CreateParameterSymbol(
C
CyrusNajmabadi 已提交
215
                        p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
216
                        p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
C
CyrusNajmabadi 已提交
217
                        p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
218 219
                statements,
                handlesExpressions,
C
CyrusNajmabadi 已提交
220
                method.GetReturnTypeAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)));
221 222
        }

P
Pilchie 已提交
223 224 225 226 227 228
        public static bool? IsMoreSpecificThan(this IMethodSymbol method1, IMethodSymbol method2)
        {
            var p1 = method1.Parameters;
            var p2 = method2.Parameters;

            // If the methods don't have the same parameter count, then method1 can't be more or 
C
Charles Stoner 已提交
229
            // less specific than method2.
P
Pilchie 已提交
230 231 232 233 234 235
            if (p1.Length != p2.Length)
            {
                return null;
            }

            // If the methods' parameter types differ, or they have different names, then one can't
C
Charles Stoner 已提交
236
            // be more specific than the other.
P
Pilchie 已提交
237 238 239 240 241 242 243 244 245 246
            if (!SignatureComparer.Instance.HaveSameSignature(method1.Parameters, method2.Parameters) ||
                !method1.Parameters.Select(p => p.Name).SequenceEqual(method2.Parameters.Select(p => p.Name)))
            {
                return null;
            }

            // Ok.  We have two methods that look extremely similar to each other.  However, one might
            // be more specific if, for example, it was actually written with concrete types (like 'int') 
            // versus the other which may have been instantiated from a type parameter.   i.e.
            //
247
            // class C<T> { void Goo(T t); void Goo(int t); }
P
Pilchie 已提交
248
            //
249 250
            // THe latter Goo is more specific when comparing "C<int>.Goo(int t)" (method1) vs 
            // "C<int>.Goo(int t)" (method2).
P
Pilchie 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
            p1 = method1.OriginalDefinition.Parameters;
            p2 = method2.OriginalDefinition.Parameters;
            return p1.Select(p => p.Type).ToList().AreMoreSpecificThan(p2.Select(p => p.Type).ToList());
        }

        public static bool TryGetPredefinedComparisonOperator(this IMethodSymbol symbol, out PredefinedOperator op)
        {
            if (symbol.MethodKind == MethodKind.BuiltinOperator)
            {
                op = symbol.GetPredefinedOperator();
                switch (op)
                {
                    case PredefinedOperator.Equality:
                    case PredefinedOperator.Inequality:
                    case PredefinedOperator.GreaterThanOrEqual:
                    case PredefinedOperator.LessThanOrEqual:
                    case PredefinedOperator.GreaterThan:
                    case PredefinedOperator.LessThan:
                        return true;
                }
            }
            else
            {
                op = PredefinedOperator.None;
            }

            return false;
        }

        public static PredefinedOperator GetPredefinedOperator(this IMethodSymbol symbol)
        {
            switch (symbol.Name)
            {
                case "op_Addition":
                case "op_UnaryPlus":
                    return PredefinedOperator.Addition;
                case "op_BitwiseAnd":
                    return PredefinedOperator.BitwiseAnd;
                case "op_BitwiseOr":
                    return PredefinedOperator.BitwiseOr;
                case "op_Concatenate":
                    return PredefinedOperator.Concatenate;
                case "op_Decrement":
                    return PredefinedOperator.Decrement;
                case "op_Division":
                    return PredefinedOperator.Division;
                case "op_Equality":
                    return PredefinedOperator.Equality;
                case "op_ExclusiveOr":
                    return PredefinedOperator.ExclusiveOr;
                case "op_Exponent":
                    return PredefinedOperator.Exponent;
                case "op_GreaterThan":
                    return PredefinedOperator.GreaterThan;
                case "op_GreaterThanOrEqual":
                    return PredefinedOperator.GreaterThanOrEqual;
                case "op_Increment":
                    return PredefinedOperator.Increment;
                case "op_Inequality":
                    return PredefinedOperator.Inequality;
                case "op_IntegerDivision":
                    return PredefinedOperator.IntegerDivision;
                case "op_LeftShift":
                    return PredefinedOperator.LeftShift;
                case "op_LessThan":
                    return PredefinedOperator.LessThan;
                case "op_LessThanOrEqual":
                    return PredefinedOperator.LessThanOrEqual;
                case "op_Like":
                    return PredefinedOperator.Like;
                case "op_LogicalNot":
                case "op_OnesComplement":
                    return PredefinedOperator.Complement;
                case "op_Modulus":
                    return PredefinedOperator.Modulus;
                case "op_Multiply":
                    return PredefinedOperator.Multiplication;
                case "op_RightShift":
                    return PredefinedOperator.RightShift;
                case "op_Subtraction":
                case "op_UnaryNegation":
                    return PredefinedOperator.Subtraction;
                default:
                    return PredefinedOperator.None;
            }
        }
    }
338
}