IMethodSymbolExtensions.cs 16.5 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
#nullable enable

P
Pilchie 已提交
5 6
using System;
using System.Collections.Generic;
7
using System.Collections.Immutable;
8
using System.Diagnostics;
9
using System.Diagnostics.CodeAnalysis;
P
Pilchie 已提交
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
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 已提交
49
            for (var i = 0; i < method.Parameters.Length; i++)
P
Pilchie 已提交
50 51 52 53 54 55 56 57 58 59
            {
                if (!invoke.Parameters[i].Type.InheritsFromOrEquals(method.Parameters[i].Type))
                {
                    return false;
                }
            }

            return true;
        }

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

P
Pilchie 已提交
81 82 83 84 85 86 87 88 89 90 91
        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);

92 93
            // 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 已提交
94
            for (var i = 0; i < method.TypeParameters.Length; i++)
P
Pilchie 已提交
95
            {
96
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
P
Pilchie 已提交
97 98 99 100 101 102 103 104
            }

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

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

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

            // 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 已提交
149
            for (var i = 0; i < typeParameters.Length; i++)
P
Pilchie 已提交
150 151 152 153 154 155 156 157 158 159 160 161
            {
                var typeParameter = typeParameters[i];

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

                newTypeParameters.Add(newTypeParameter);
167
                mapping[typeParameter] = newTypeParameter;
P
Pilchie 已提交
168 169
            }

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

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

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

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

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

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

            var someParameterHasAttribute = method.Parameters
224
                .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));
225

226
            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);
227

228
            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
229 230 231 232 233 234
            {
                return method;
            }

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

P
Pilchie 已提交
253 254 255 256 257 258
        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 已提交
259
            // less specific than method2.
P
Pilchie 已提交
260 261 262 263 264 265
            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 已提交
266
            // be more specific than the other.
P
Pilchie 已提交
267 268 269 270 271 272 273 274 275 276
            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.
            //
277
            // class C<T> { void Goo(T t); void Goo(int t); }
P
Pilchie 已提交
278
            //
279 280
            // THe latter Goo is more specific when comparing "C<int>.Goo(int t)" (method1) vs 
            // "C<int>.Goo(int t)" (method2).
P
Pilchie 已提交
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 364 365 366
            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;
            }
        }
367 368 369 370 371 372

        /// <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>
373
        public static bool HasEventHandlerSignature(this IMethodSymbol method, [NotNullWhen(returnValue: true)] INamedTypeSymbol? eventArgsType)
374 375 376 377
            => eventArgsType != null &&
               method.Parameters.Length == 2 &&
               method.Parameters[0].Type.SpecialType == SpecialType.System_Object &&
               method.Parameters[1].Type.InheritsFromOrEquals(eventArgsType);
P
Pilchie 已提交
378
    }
379
}