IMethodSymbolExtensions.cs 16.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;
6
using System.Diagnostics;
P
Pilchie 已提交
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
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;
            }

C
Use var  
Cyrus Najmabadi 已提交
46
            for (var i = 0; i < method.Parameters.Length; i++)
P
Pilchie 已提交
47 48 49 50 51 52 53 54 55 56
            {
                if (!invoke.Parameters[i].Type.InheritsFromOrEquals(method.Parameters[i].Type))
                {
                    return false;
                }
            }

            return true;
        }

57 58 59 60 61 62 63
        /// <summary>
        /// Returns the methodSymbol and any partial parts.
        /// </summary>
        public static ImmutableArray<IMethodSymbol> GetAllMethodSymbolsOfPartialParts(this IMethodSymbol method)
        {
            if (method.PartialDefinitionPart != null)
            {
64
                Debug.Assert(method.PartialImplementationPart == null && !Equals(method.PartialDefinitionPart, method));
65
                return ImmutableArray.Create(method, method.PartialDefinitionPart);
66
            }
67
            else if (method.PartialImplementationPart != null)
68
            {
69
                Debug.Assert(!Equals(method.PartialImplementationPart, method));
70 71 72 73 74
                return ImmutableArray.Create(method.PartialImplementationPart, method);
            }
            else
            {
                return ImmutableArray.Create(method);
75 76 77
            }
        }

P
Pilchie 已提交
78 79 80 81 82 83 84 85 86 87 88
        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);

89 90
            // The use of AllNullabilityIgnoringSymbolComparer is tracked by https://github.com/dotnet/roslyn/issues/36093
            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>(AllNullabilityIgnoringSymbolComparer.Instance);
C
Use var  
Cyrus Najmabadi 已提交
91
            for (var i = 0; i < method.TypeParameters.Length; i++)
P
Pilchie 已提交
92
            {
93
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
P
Pilchie 已提交
94 95 96 97 98 99 100 101
            }

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
                method.GetAttributes(),
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType.SubstituteTypes(mapping, typeGenerator),
102
                method.RefKind,
103
                method.ExplicitInterfaceImplementations,
P
Pilchie 已提交
104 105
                method.Name,
                updatedTypeParameters,
C
CyrusNajmabadi 已提交
106
                method.Parameters.SelectAsArray(p =>
P
Pilchie 已提交
107
                    CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
C
CyrusNajmabadi 已提交
108
                        p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)));
P
Pilchie 已提交
109 110
        }

111 112
        public static IMethodSymbol RenameParameters(
            this IMethodSymbol method, IList<string> parameterNames)
P
Pilchie 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        {
            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,
128
                method.RefKind,
129
                method.ExplicitInterfaceImplementations,
P
Pilchie 已提交
130 131 132 133 134
                method.Name,
                method.TypeParameters,
                parameters);
        }

C
CyrusNajmabadi 已提交
135
        private static ImmutableArray<ITypeParameterSymbol> RenameTypeParameters(
136
            ImmutableArray<ITypeParameterSymbol> typeParameters,
P
Pilchie 已提交
137 138 139 140 141 142
            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>();
143 144 145

            // The use of AllNullabilityIgnoringSymbolComparer is tracked by https://github.com/dotnet/roslyn/issues/36093
            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>(AllNullabilityIgnoringSymbolComparer.Instance);
C
Use var  
Cyrus Najmabadi 已提交
146
            for (var i = 0; i < typeParameters.Length; i++)
P
Pilchie 已提交
147 148 149 150 151 152 153 154 155 156 157 158
            {
                var typeParameter = typeParameters[i];

                var newTypeParameter = new CodeGenerationTypeParameterSymbol(
                    typeParameter.ContainingType,
                    typeParameter.GetAttributes(),
                    typeParameter.Variance,
                    newNames[i],
                    typeParameter.ConstraintTypes,
                    typeParameter.HasConstructorConstraint,
                    typeParameter.HasReferenceTypeConstraint,
                    typeParameter.HasValueTypeConstraint,
159
                    typeParameter.HasUnmanagedTypeConstraint,
160
                    typeParameter.HasNotNullConstraint,
P
Pilchie 已提交
161 162 163
                    typeParameter.Ordinal);

                newTypeParameters.Add(newTypeParameter);
164
                mapping[typeParameter] = newTypeParameter;
P
Pilchie 已提交
165 166
            }

167
            // Now we update the constraints.
P
Pilchie 已提交
168 169
            foreach (var newTypeParameter in newTypeParameters)
            {
170
                newTypeParameter.ConstraintTypes = ImmutableArray.CreateRange(newTypeParameter.ConstraintTypes, t => t.SubstituteTypes(mapping, typeGenerator));
P
Pilchie 已提交
171 172
            }

C
CyrusNajmabadi 已提交
173
            return newTypeParameters.Cast<ITypeParameterSymbol>().ToImmutableArray();
P
Pilchie 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        }

        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);
        }

201
        public static IMethodSymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
C
CyrusNajmabadi 已提交
202 203
            this IMethodSymbol method, ISymbol accessibleWithin,
            params INamedTypeSymbol[] removeAttributeTypes)
204
        {
C
CyrusNajmabadi 已提交
205
            bool shouldRemoveAttribute(AttributeData a) =>
206 207
                removeAttributeTypes.Any(attr => attr != null && attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);

C
CyrusNajmabadi 已提交
208 209
            return method.RemoveAttributesCore(
                shouldRemoveAttribute,
C
CyrusNajmabadi 已提交
210 211
                statements: default,
                handlesExpressions: default);
212 213 214 215
        }

        private static IMethodSymbol RemoveAttributesCore(
            this IMethodSymbol method, Func<AttributeData, bool> shouldRemoveAttribute,
C
CyrusNajmabadi 已提交
216
            ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions)
217 218
        {
            var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);
219 220

            var someParameterHasAttribute = method.Parameters
221
                .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));
222

223
            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);
224

225
            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
226 227 228 229 230 231
            {
                return method;
            }

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
C
CyrusNajmabadi 已提交
232
                method.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
233 234 235
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType,
236
                method.RefKind,
237
                method.ExplicitInterfaceImplementations,
238 239
                method.Name,
                method.TypeParameters,
C
CyrusNajmabadi 已提交
240
                method.Parameters.SelectAsArray(p =>
241
                    CodeGenerationSymbolFactory.CreateParameterSymbol(
C
CyrusNajmabadi 已提交
242
                        p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
243
                        p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
C
CyrusNajmabadi 已提交
244
                        p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
245 246
                statements,
                handlesExpressions,
C
CyrusNajmabadi 已提交
247
                method.GetReturnTypeAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)));
248 249
        }

P
Pilchie 已提交
250 251 252 253 254 255
        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 已提交
256
            // less specific than method2.
P
Pilchie 已提交
257 258 259 260 261 262
            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 已提交
263
            // be more specific than the other.
P
Pilchie 已提交
264 265 266 267 268 269 270 271 272 273
            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.
            //
274
            // class C<T> { void Goo(T t); void Goo(int t); }
P
Pilchie 已提交
275
            //
276 277
            // THe latter Goo is more specific when comparing "C<int>.Goo(int t)" (method1) vs 
            // "C<int>.Goo(int t)" (method2).
P
Pilchie 已提交
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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
            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;
            }
        }
364 365 366 367 368 369 370 371 372 373 374

        /// <summary>
        /// Returns true for void returning methods with two parameters, where
        /// the first parameter is of <see cref="object"/> type and the second
        /// parameter inherits from or equals <see cref="EventArgs"/> type.
        /// </summary>
        public static bool HasEventHandlerSignature(this IMethodSymbol method, INamedTypeSymbol eventArgsType)
            => eventArgsType != null &&
               method.Parameters.Length == 2 &&
               method.Parameters[0].Type.SpecialType == SpecialType.System_Object &&
               method.Parameters[1].Type.InheritsFromOrEquals(eventArgsType);
P
Pilchie 已提交
375
    }
376
}