IMethodSymbolExtensions.cs 16.0 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 46 47 48 49 50 51 52 53 54 55 56
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;
        }

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

            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
            for (int i = 0; i < method.TypeParameters.Length; i++)
            {
92
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
P
Pilchie 已提交
93 94 95 96 97 98 99 100
            }

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

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

C
CyrusNajmabadi 已提交
134
        private static ImmutableArray<ITypeParameterSymbol> RenameTypeParameters(
135
            ImmutableArray<ITypeParameterSymbol> typeParameters,
P
Pilchie 已提交
136 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>();
            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>();
143
            for (int i = 0; i < typeParameters.Length; i++)
P
Pilchie 已提交
144 145 146 147 148 149 150 151 152 153 154 155
            {
                var typeParameter = typeParameters[i];

                var newTypeParameter = new CodeGenerationTypeParameterSymbol(
                    typeParameter.ContainingType,
                    typeParameter.GetAttributes(),
                    typeParameter.Variance,
                    newNames[i],
                    typeParameter.ConstraintTypes,
                    typeParameter.HasConstructorConstraint,
                    typeParameter.HasReferenceTypeConstraint,
                    typeParameter.HasValueTypeConstraint,
156
                    typeParameter.HasUnmanagedTypeConstraint,
P
Pilchie 已提交
157 158 159
                    typeParameter.Ordinal);

                newTypeParameters.Add(newTypeParameter);
160
                mapping[typeParameter] = newTypeParameter;
P
Pilchie 已提交
161 162
            }

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

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

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

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

C
CyrusNajmabadi 已提交
204 205
            return method.RemoveAttributesCore(
                shouldRemoveAttribute,
C
CyrusNajmabadi 已提交
206 207
                statements: default,
                handlesExpressions: default);
208 209 210 211
        }

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

            var someParameterHasAttribute = method.Parameters
217
                .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));
218

219
            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);
220

221
            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
222 223 224 225 226 227
            {
                return method;
            }

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

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

        /// <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 已提交
371
    }
372
}