ITypeSymbolExtensions.cs 34.9 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 5 6 7 8

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
9
using System.Threading.Tasks;
P
Pilchie 已提交
10
using Microsoft.CodeAnalysis;
11
using Microsoft.CodeAnalysis.FindSymbols;
P
Pilchie 已提交
12
using Microsoft.CodeAnalysis.LanguageServices;
A
Andrew Hall (METAL) 已提交
13
using Microsoft.CodeAnalysis.PooledObjects;
P
Pilchie 已提交
14 15 16 17 18 19 20 21 22 23
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static partial class ITypeSymbolExtensions
    {
        private const string DefaultParameterName = "p";
        private const string DefaultBuiltInParameterName = "v";

24 25 26
        public static bool CanAddNullCheck(this ITypeSymbol type)
            => type != null && (type.IsReferenceType || type.IsNullable());

P
Pilchie 已提交
27 28 29
        public static IList<INamedTypeSymbol> GetAllInterfacesIncludingThis(this ITypeSymbol type)
        {
            var allInterfaces = type.AllInterfaces;
C
CyrusNajmabadi 已提交
30
            if (type is INamedTypeSymbol namedType && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType))
P
Pilchie 已提交
31
            {
32 33 34 35
                var result = new List<INamedTypeSymbol>(allInterfaces.Length + 1);
                result.Add(namedType);
                result.AddRange(allInterfaces);
                return result;
P
Pilchie 已提交
36 37 38 39 40 41 42
            }

            return allInterfaces;
        }

        public static bool IsAbstractClass(this ITypeSymbol symbol)
        {
43
            return symbol?.TypeKind == TypeKind.Class && symbol.IsAbstract;
P
Pilchie 已提交
44 45 46 47
        }

        public static bool IsSystemVoid(this ITypeSymbol symbol)
        {
48 49 50 51
            return symbol?.SpecialType == SpecialType.System_Void;
        }

        public static bool IsNullable(this ITypeSymbol symbol)
52
            => symbol?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        public static bool IsModuleType(this ITypeSymbol symbol)
        {
            return symbol?.TypeKind == TypeKind.Module;
        }

        public static bool IsInterfaceType(this ITypeSymbol symbol)
        {
            return symbol?.TypeKind == TypeKind.Interface;
        }

        public static bool IsDelegateType(this ITypeSymbol symbol)
        {
            return symbol?.TypeKind == TypeKind.Delegate;
        }

69 70 71 72 73
        public static bool IsStructType(this ITypeSymbol symbol)
        {
            return symbol?.TypeKind == TypeKind.Struct;
        }

74 75 76 77 78
        public static bool IsAnonymousType(this INamedTypeSymbol symbol)
        {
            return symbol?.IsAnonymousType == true;
        }

79 80 81 82 83 84 85 86
        public static ITypeSymbol RemoveNullableIfPresent(this ITypeSymbol symbol)
        {
            if (symbol.IsNullable())
            {
                return symbol.GetTypeArguments().Single();
            }

            return symbol;
P
Pilchie 已提交
87 88 89 90 91 92 93 94 95
        }

        /// <summary>
        /// Returns the corresponding symbol in this type or a base type that implements 
        /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
        /// (which might be either because this type doesn't implement the container of
        /// interfaceMember, or this type doesn't supply a member that successfully implements
        /// interfaceMember).
        /// </summary>
96
        public static async Task<ImmutableArray<SymbolAndProjectId>> FindImplementationsForInterfaceMemberAsync(
97
            this SymbolAndProjectId<ITypeSymbol> typeSymbolAndProjectId,
P
Pilchie 已提交
98
            ISymbol interfaceMember,
99
            Solution solution,
P
Pilchie 已提交
100 101 102 103
            CancellationToken cancellationToken)
        {
            // This method can return multiple results.  Consider the case of:
            // 
104
            // interface IGoo<X> { void Goo(X x); }
P
Pilchie 已提交
105
            //
106
            // class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); }
P
Pilchie 已提交
107
            //
108
            // If you're looking for the implementations of IGoo<X>.Goo then you want to find both
P
Pilchie 已提交
109 110
            // results in C.

A
Andrew Hall (METAL) 已提交
111
            var arrBuilder = ArrayBuilder<SymbolAndProjectId>.GetInstance();
112

P
Pilchie 已提交
113 114
            // TODO(cyrusn): Implement this using the actual code for
            // TypeSymbol.FindImplementationForInterfaceMember
115
            var typeSymbol = typeSymbolAndProjectId.Symbol;
P
Pilchie 已提交
116 117
            if (typeSymbol == null || interfaceMember == null)
            {
A
Andrew Hall (METAL) 已提交
118
                return arrBuilder.ToImmutableAndFree();
P
Pilchie 已提交
119 120 121 122 123 124
            }

            if (interfaceMember.Kind != SymbolKind.Event &&
                interfaceMember.Kind != SymbolKind.Method &&
                interfaceMember.Kind != SymbolKind.Property)
            {
A
Andrew Hall (METAL) 已提交
125
                return arrBuilder.ToImmutableAndFree();
P
Pilchie 已提交
126 127 128 129 130 131 132 133 134
            }

            // WorkItem(4843)
            //
            // 'typeSymbol' has to at least implement the interface containing the member.  note:
            // this just means that the interface shows up *somewhere* in the inheritance chain of
            // this type.  However, this type may not actually say that it implements it.  For
            // example:
            //
135
            // interface I { void Goo(); }
P
Pilchie 已提交
136 137 138 139 140 141 142
            //
            // class B { } 
            //
            // class C : B, I { }
            //
            // class D : C { }
            //
143 144
            // D does implement I transitively through C.  However, even if D has a "Goo" method, it
            // won't be an implementation of I.Goo.  The implementation of I.Goo must be from a type
P
Pilchie 已提交
145 146 147 148 149
            // that actually has I in it's direct interface chain, or a type that's a base type of
            // that.  in this case, that means only classes C or B.
            var interfaceType = interfaceMember.ContainingType;
            if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType))
            {
A
Andrew Hall (METAL) 已提交
150
                return arrBuilder.ToImmutableAndFree();
P
Pilchie 已提交
151 152 153 154 155 156 157 158 159
            }

            // We've ascertained that the type T implements some constructed type of the form I<X>.
            // However, we're not precisely sure which constructions of I<X> are being used.  For
            // example, a type C might implement I<int> and I<string>.  If we're searching for a
            // method from I<X> we might need to find several methods that implement different
            // instantiations of that method.
            var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition;
            var originalInterfaceMember = interfaceMember.OriginalDefinition;
160

P
Pilchie 已提交
161 162 163
            var constructedInterfaces = typeSymbol.AllInterfaces.Where(i =>
                SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType));

164
            // Try to get the compilation for the symbol we're searching for, 
A
Andrew Hall (METAL) 已提交
165 166 167 168
            // which can help identify matches with the call to SymbolFinder.OriginalSymbolsMatch.
            // OriginalSymbolMatch allows types to be matched across different assemblies
            // if they are considered to be the same type, which provides a more accurate
            // implementations list for interfaces. 
169
            var typeSymbolProject = solution.GetProject(typeSymbolAndProjectId.ProjectId);
170 171 172
            var typeSymbolCompilation = typeSymbolProject == null ?
                                        null :
                                        await typeSymbolProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
173

P
Pilchie 已提交
174 175 176 177
            foreach (var constructedInterface in constructedInterfaces)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var constructedInterfaceMember = constructedInterface.GetMembers().FirstOrDefault(m =>
A
Andrew Hall (METAL) 已提交
178 179 180 181 182 183 184
                    SymbolFinder.OriginalSymbolsMatch(
                        m,
                        interfaceMember,
                        solution,
                        typeSymbolCompilation,
                        symbolToMatchCompilation: null,
                        cancellationToken));
P
Pilchie 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

                if (constructedInterfaceMember == null)
                {
                    continue;
                }

                // Now we need to walk the base type chain, but we start at the first type that actually
                // has the interface directly in its interface hierarchy.
                var seenTypeDeclaringInterface = false;
                for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType)
                {
                    seenTypeDeclaringInterface = seenTypeDeclaringInterface ||
                                                 currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition);

                    if (seenTypeDeclaringInterface)
                    {
201
                        var result = FindImplementations(solution.Workspace, constructedInterfaceMember, currentType);
P
Pilchie 已提交
202 203 204

                        if (result != null)
                        {
205
                            arrBuilder.Add(typeSymbolAndProjectId.WithSymbol(result));
P
Pilchie 已提交
206 207 208 209 210
                            break;
                        }
                    }
                }
            }
211

A
Andrew Hall (METAL) 已提交
212
            return arrBuilder.ToImmutableAndFree();
P
Pilchie 已提交
213 214
        }

C
CyrusNajmabadi 已提交
215 216 217 218 219 220 221 222 223 224 225 226
        private static ISymbol FindImplementations(Workspace workspace, ISymbol constructedInterfaceMember, ITypeSymbol currentType)
        {
            switch (constructedInterfaceMember)
            {
                case IEventSymbol eventSymbol: return FindImplementations(currentType, eventSymbol, workspace, e => e.ExplicitInterfaceImplementations);
                case IMethodSymbol methodSymbol: return FindImplementations(currentType, methodSymbol, workspace, m => m.ExplicitInterfaceImplementations);
                case IPropertySymbol propertySymbol: return FindImplementations(currentType, propertySymbol, workspace, p => p.ExplicitInterfaceImplementations);
            }

            return null;
        }

P
Pilchie 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        private static HashSet<INamedTypeSymbol> GetOriginalInterfacesAndTheirBaseInterfaces(
            this ITypeSymbol type,
            HashSet<INamedTypeSymbol> symbols = null)
        {
            symbols = symbols ?? new HashSet<INamedTypeSymbol>(SymbolEquivalenceComparer.Instance);

            foreach (var interfaceType in type.Interfaces)
            {
                symbols.Add(interfaceType.OriginalDefinition);
                symbols.AddRange(interfaceType.AllInterfaces.Select(i => i.OriginalDefinition));
            }

            return symbols;
        }

        private static ISymbol FindImplementations<TSymbol>(
            ITypeSymbol typeSymbol,
            TSymbol interfaceSymbol,
245
            Workspace workspace,
P
Pilchie 已提交
246 247 248 249 250 251 252 253 254 255 256
            Func<TSymbol, ImmutableArray<TSymbol>> getExplicitInterfaceImplementations) where TSymbol : class, ISymbol
        {
            // Check the current type for explicit interface matches.  Otherwise, check
            // the current type and base types for implicit matches.
            var explicitMatches =
                from member in typeSymbol.GetMembers().OfType<TSymbol>()
                where getExplicitInterfaceImplementations(member).Length > 0
                from explicitInterfaceMethod in getExplicitInterfaceImplementations(member)
                where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, interfaceSymbol)
                select member;

257
            var provider = workspace.Services.GetLanguageServices(typeSymbol.Language);
P
Pilchie 已提交
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
            var semanticFacts = provider.GetService<ISemanticFactsService>();

            // Even if a language only supports explicit interface implementation, we
            // can't enforce it for types from metadata. For example, a VB symbol
            // representing System.Xml.XmlReader will say it implements IDisposable, but
            // the XmlReader.Dispose() method will not be an explicit implementation of
            // IDisposable.Dispose()
            if (!semanticFacts.SupportsImplicitInterfaceImplementation &&
                typeSymbol.Locations.Any(location => location.IsInSource))
            {
                return explicitMatches.FirstOrDefault();
            }

            var syntaxFacts = provider.GetService<ISyntaxFactsService>();
            var implicitMatches =
                from baseType in typeSymbol.GetBaseTypesAndThis()
                from member in baseType.GetMembers(interfaceSymbol.Name).OfType<TSymbol>()
                where member.DeclaredAccessibility == Accessibility.Public &&
                      !member.IsStatic &&
                      SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, interfaceSymbol, syntaxFacts.IsCaseSensitive)
                select member;

            return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault();
        }

        public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
        {
            var current = type;
            while (current != null)
            {
                yield return current;
                current = current.BaseType;
            }
        }

        public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
        {
            var current = type.BaseType;
            while (current != null)
            {
                yield return current;
                current = current.BaseType;
            }
        }

        public static IEnumerable<ITypeSymbol> GetContainingTypesAndThis(this ITypeSymbol type)
        {
            var current = type;
            while (current != null)
            {
                yield return current;
                current = current.ContainingType;
            }
        }

        public static IEnumerable<INamedTypeSymbol> GetContainingTypes(this ITypeSymbol type)
        {
            var current = type.ContainingType;
            while (current != null)
            {
                yield return current;
                current = current.ContainingType;
            }
        }

323 324 325 326 327 328 329 330 331 332 333 334 335 336
        // Determine if "type" inherits from "baseType", ignoring constructed types, optionally including interfaces,
        // dealing only with original types.
        public static bool InheritsFromOrEquals(
            this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces)
        {
            if (!includeInterfaces)
            {
                return InheritsFromOrEquals(type, baseType);
            }

            return type.GetBaseTypesAndThis().Concat(type.AllInterfaces).Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
        }

        // Determine if "type" inherits from "baseType", ignoring constructed types and interfaces, dealing
P
Pilchie 已提交
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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        // only with original types.
        public static bool InheritsFromOrEquals(
            this ITypeSymbol type, ITypeSymbol baseType)
        {
            return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
        }

        // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
        // only with original types.
        public static bool InheritsFromOrEqualsIgnoringConstruction(
            this ITypeSymbol type, ITypeSymbol baseType)
        {
            var originalBaseType = baseType.OriginalDefinition;
            return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalBaseType));
        }

        // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
        // only with original types.
        public static bool InheritsFromIgnoringConstruction(
            this ITypeSymbol type, ITypeSymbol baseType)
        {
            var originalBaseType = baseType.OriginalDefinition;

            // We could just call GetBaseTypes and foreach over it, but this
            // is a hot path in Find All References. This avoid the allocation
            // of the enumerator type.
            var currentBaseType = type.BaseType;
            while (currentBaseType != null)
            {
                if (SymbolEquivalenceComparer.Instance.Equals(currentBaseType.OriginalDefinition, originalBaseType))
                {
                    return true;
                }

                currentBaseType = currentBaseType.BaseType;
            }

            return false;
        }

        public static bool ImplementsIgnoringConstruction(
            this ITypeSymbol type, ITypeSymbol interfaceType)
        {
            var originalInterfaceType = interfaceType.OriginalDefinition;
            if (type is INamedTypeSymbol && type.TypeKind == TypeKind.Interface)
            {
                // Interfaces don't implement other interfaces. They extend them.
                return false;
            }

            return type.AllInterfaces.Any(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalInterfaceType));
        }

        public static bool Implements(
            this ITypeSymbol type, ITypeSymbol interfaceType)
        {
            return type.AllInterfaces.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, interfaceType));
        }

        public static bool IsAttribute(this ITypeSymbol symbol)
        {
            for (var b = symbol.BaseType; b != null; b = b.BaseType)
            {
                if (b.MetadataName == "Attribute" &&
                    b.ContainingType == null &&
                    b.ContainingNamespace != null &&
                    b.ContainingNamespace.Name == "System" &&
                    b.ContainingNamespace.ContainingNamespace != null &&
                    b.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
                {
                    return true;
                }
            }

            return false;
        }

414 415 416
        public static bool IsFormattableString(this ITypeSymbol symbol)
        {
            return symbol?.MetadataName == "FormattableString"
D
Dustin Campbell 已提交
417
                && symbol.ContainingType == null
418 419 420 421
                && symbol.ContainingNamespace?.Name == "System"
                && symbol.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace == true;
        }

P
Pilchie 已提交
422 423 424 425 426
        public static ITypeSymbol RemoveUnavailableTypeParameters(
            this ITypeSymbol type,
            Compilation compilation,
            IEnumerable<ITypeParameterSymbol> availableTypeParameters)
        {
427
            return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet());
P
Pilchie 已提交
428 429 430 431 432 433 434
        }

        private static ITypeSymbol RemoveUnavailableTypeParameters(
            this ITypeSymbol type,
            Compilation compilation,
            ISet<string> availableTypeParameterNames)
        {
435
            return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames));
P
Pilchie 已提交
436 437 438 439 440 441
        }

        public static ITypeSymbol RemoveAnonymousTypes(
            this ITypeSymbol type,
            Compilation compilation)
        {
442
            return type?.Accept(new AnonymousTypeRemover(compilation));
P
Pilchie 已提交
443 444
        }

B
Basoundr_ms 已提交
445 446 447 448 449 450 451
        public static ITypeSymbol ReplaceTypeParametersBasedOnTypeConstraints(
            this ITypeSymbol type,
            Compilation compilation,
            IEnumerable<ITypeParameterSymbol> availableTypeParameters,
            Solution solution,
            CancellationToken cancellationToken)
        {
452
            return type?.Accept(new ReplaceTypeParameterBasedOnTypeConstraintVisitor(compilation, availableTypeParameters.Select(t => t.Name).ToSet(), solution, cancellationToken));
B
Basoundr_ms 已提交
453 454
        }

P
Pilchie 已提交
455 456 457 458
        public static ITypeSymbol RemoveUnnamedErrorTypes(
            this ITypeSymbol type,
            Compilation compilation)
        {
459
            return type?.Accept(new UnnamedErrorTypeRemover(compilation));
P
Pilchie 已提交
460 461 462 463 464 465
        }

        public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters(
            this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
        {
            result = result ?? new List<ITypeParameterSymbol>();
466
            type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true));
P
Pilchie 已提交
467 468 469 470 471 472 473
            return result;
        }

        public static IList<ITypeParameterSymbol> GetReferencedTypeParameters(
            this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
        {
            result = result ?? new List<ITypeParameterSymbol>();
474
            type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false));
P
Pilchie 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            return result;
        }

        public static ITypeSymbol SubstituteTypes<TType1, TType2>(
            this ITypeSymbol type,
            IDictionary<TType1, TType2> mapping,
            Compilation compilation)
            where TType1 : ITypeSymbol
            where TType2 : ITypeSymbol
        {
            return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation));
        }

        public static ITypeSymbol SubstituteTypes<TType1, TType2>(
            this ITypeSymbol type,
            IDictionary<TType1, TType2> mapping,
            ITypeGenerator typeGenerator)
            where TType1 : ITypeSymbol
            where TType2 : ITypeSymbol
        {
495
            return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator));
P
Pilchie 已提交
496 497
        }

C
Charles Stoner 已提交
498
        public static bool IsUnexpressibleTypeParameterConstraint(this ITypeSymbol typeSymbol)
P
Pilchie 已提交
499
        {
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
            if (typeSymbol.IsSealed || typeSymbol.IsValueType)
            {
                return true;
            }

            switch (typeSymbol.TypeKind)
            {
                case TypeKind.Array:
                case TypeKind.Delegate:
                    return true;
            }

            switch (typeSymbol.SpecialType)
            {
                case SpecialType.System_Array:
                case SpecialType.System_Delegate:
                case SpecialType.System_MulticastDelegate:
                case SpecialType.System_Enum:
                case SpecialType.System_ValueType:
                    return true;
            }

            return false;
P
Pilchie 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
        }

        public static bool IsNumericType(this ITypeSymbol type)
        {
            if (type != null)
            {
                switch (type.SpecialType)
                {
                    case SpecialType.System_Byte:
                    case SpecialType.System_SByte:
                    case SpecialType.System_Int16:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_UInt64:
                    case SpecialType.System_Single:
                    case SpecialType.System_Double:
                    case SpecialType.System_Decimal:
                        return true;
                }
            }

            return false;
        }

        public static Accessibility DetermineMinimalAccessibility(this ITypeSymbol typeSymbol)
        {
            return typeSymbol.Accept(MinimalAccessibilityVisitor.Instance);
        }

        public static bool ContainsAnonymousType(this ITypeSymbol symbol)
        {
C
CyrusNajmabadi 已提交
556 557 558 559 560 561 562
            switch (symbol)
            {
                case IArrayTypeSymbol a: return ContainsAnonymousType(a.ElementType);
                case IPointerTypeSymbol p: return ContainsAnonymousType(p.PointedAtType);
                case INamedTypeSymbol n: return ContainsAnonymousType(n);
                default: return false;
            }
P
Pilchie 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        }

        private static bool ContainsAnonymousType(INamedTypeSymbol type)
        {
            if (type.IsAnonymousType)
            {
                return true;
            }

            foreach (var typeArg in type.GetAllTypeArguments())
            {
                if (ContainsAnonymousType(typeArg))
                {
                    return true;
                }
            }

            return false;
        }

        public static string CreateParameterName(this ITypeSymbol type, bool capitalize = false)
        {
            while (true)
            {
C
CyrusNajmabadi 已提交
587
                switch (type)
P
Pilchie 已提交
588
                {
C
CyrusNajmabadi 已提交
589 590 591 592 593 594
                    case IArrayTypeSymbol arrayType:
                        type = arrayType.ElementType;
                        continue;
                    case IPointerTypeSymbol pointerType:
                        type = pointerType.PointedAtType;
                        continue;
P
Pilchie 已提交
595 596 597 598 599 600 601 602 603 604 605
                }

                break;
            }

            var shortName = GetParameterName(type);
            return capitalize ? shortName.ToPascalCase() : shortName.ToCamelCase();
        }

        private static string GetParameterName(ITypeSymbol type)
        {
606
            if (type == null || type.IsAnonymousType() || type.IsTupleType)
P
Pilchie 已提交
607 608 609 610
            {
                return DefaultParameterName;
            }

611
            if (type.IsSpecialType() || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
P
Pilchie 已提交
612 613 614 615 616 617 618 619 620 621
            {
                return DefaultBuiltInParameterName;
            }

            var shortName = type.GetShortName();
            return shortName.Length == 0
                ? DefaultParameterName
                : shortName;
        }

622
        public static bool IsSpecialType(this ITypeSymbol symbol)
P
Pilchie 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
        {
            if (symbol != null)
            {
                switch (symbol.SpecialType)
                {
                    case SpecialType.System_Object:
                    case SpecialType.System_Void:
                    case SpecialType.System_Boolean:
                    case SpecialType.System_SByte:
                    case SpecialType.System_Byte:
                    case SpecialType.System_Decimal:
                    case SpecialType.System_Single:
                    case SpecialType.System_Double:
                    case SpecialType.System_Int16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_Char:
                    case SpecialType.System_String:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_UInt64:
                        return true;
                }
            }

            return false;
        }

651
        public static bool CanSupportCollectionInitializer(this ITypeSymbol typeSymbol, ISymbol within)
P
Pilchie 已提交
652 653 654
        {
            return
                typeSymbol.AllInterfaces.Any(i => i.SpecialType == SpecialType.System_Collections_IEnumerable) &&
V
Victor Zaytsev 已提交
655 656
                typeSymbol.GetBaseTypesAndThis()
                    .Union(typeSymbol.GetOriginalInterfacesAndTheirBaseInterfaces())
V
Victor Zaytsev 已提交
657
                    .SelectAccessibleMembers<IMethodSymbol>(WellKnownMemberNames.CollectionInitializerAddMethodName, within ?? typeSymbol)
P
Pilchie 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
                    .OfType<IMethodSymbol>()
                    .Any(m => m.Parameters.Any());
        }

        public static INamedTypeSymbol GetDelegateType(this ITypeSymbol typeSymbol, Compilation compilation)
        {
            if (typeSymbol != null)
            {
                var expressionOfT = compilation.ExpressionOfTType();
                if (typeSymbol.OriginalDefinition.Equals(expressionOfT))
                {
                    var typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];
                    return typeArgument as INamedTypeSymbol;
                }

                if (typeSymbol.IsDelegateType())
                {
                    return typeSymbol as INamedTypeSymbol;
                }
            }

            return null;
        }

        public static IEnumerable<T> GetAccessibleMembersInBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
        {
            if (containingType == null)
            {
                return SpecializedCollections.EmptyEnumerable<T>();
            }

            var types = containingType.GetBaseTypes();
            return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
        }

693
        public static ImmutableArray<T> GetAccessibleMembersInThisAndBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
P
Pilchie 已提交
694 695 696
        {
            if (containingType == null)
            {
697
                return ImmutableArray<T>.Empty;
P
Pilchie 已提交
698 699
            }

V
Victor Zaytsev 已提交
700
            return containingType.GetBaseTypesAndThis().SelectAccessibleMembers<T>(within).ToImmutableArray();
P
Pilchie 已提交
701 702 703 704 705 706 707 708 709
        }

        public static bool? AreMoreSpecificThan(this IList<ITypeSymbol> t1, IList<ITypeSymbol> t2)
        {
            if (t1.Count != t2.Count)
            {
                return null;
            }

C
ChuckStoner 已提交
710
            // For t1 to be more specific than t2, it has to be not less specific in every member,
P
Pilchie 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
            // and more specific in at least one.

            bool? result = null;
            for (int i = 0; i < t1.Count; ++i)
            {
                var r = t1[i].IsMoreSpecificThan(t2[i]);
                if (r == null)
                {
                    // We learned nothing. Do nothing.
                }
                else if (result == null)
                {
                    // We have found the first more specific type. See if
                    // all the rest on this side are not less specific.
                    result = r;
                }
                else if (result != r)
                {
                    // We have more specific types on both left and right, so we 
                    // cannot succeed in picking a better type list. Bail out now.
                    return null;
                }
            }

            return result;
        }

V
Victor Zaytsev 已提交
738 739 740 741 742 743 744 745
        private static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol> types, ISymbol within) where T : class, ISymbol
        {
            if (types == null)
            {
                return ImmutableArray<T>.Empty;
            }

            return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
V
Victor Zaytsev 已提交
746 747 748 749 750 751 752 753 754 755
        }

        private static IEnumerable<T> SelectAccessibleMembers<T>(this IEnumerable<ITypeSymbol> types, string memberName, ISymbol within) where T : class, ISymbol
        {
            if (types == null)
            {
                return ImmutableArray<T>.Empty;
            }

            return types.SelectMany(x => x.GetMembers(memberName).OfType<T>().Where(m => m.IsAccessibleWithin(within)));
V
Victor Zaytsev 已提交
756 757
        }

P
Pilchie 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
        private static bool? IsMoreSpecificThan(this ITypeSymbol t1, ITypeSymbol t2)
        {
            // SPEC: A type parameter is less specific than a non-type parameter. 

            var isTypeParameter1 = t1 is ITypeParameterSymbol;
            var isTypeParameter2 = t2 is ITypeParameterSymbol;

            if (isTypeParameter1 && !isTypeParameter2)
            {
                return false;
            }

            if (!isTypeParameter1 && isTypeParameter2)
            {
                return true;
            }

            if (isTypeParameter1)
            {
                Debug.Assert(isTypeParameter2);
                return null;
            }

            if (t1.TypeKind != t2.TypeKind)
            {
                return null;
            }

            // There is an identity conversion between the types and they are both substitutions on type parameters.
            // They had better be the same kind.

            // UNDONE: Strip off the dynamics.

            // SPEC: An array type is more specific than another
            // SPEC: array type (with the same number of dimensions) 
            // SPEC: if the element type of the first is
            // SPEC: more specific than the element type of the second.

            if (t1 is IArrayTypeSymbol)
            {
                var arr1 = (IArrayTypeSymbol)t1;
                var arr2 = (IArrayTypeSymbol)t2;

                // We should not have gotten here unless there were identity conversions
                // between the two types.

                return arr1.ElementType.IsMoreSpecificThan(arr2.ElementType);
            }

            // SPEC EXTENSION: We apply the same rule to pointer types. 

            if (t1 is IPointerTypeSymbol)
            {
                var p1 = (IPointerTypeSymbol)t1;
                var p2 = (IPointerTypeSymbol)t2;
                return p1.PointedAtType.IsMoreSpecificThan(p2.PointedAtType);
            }

            // SPEC: A constructed type is more specific than another
            // SPEC: constructed type (with the same number of type arguments) if at least one type
            // SPEC: argument is more specific and no type argument is less specific than the
            // SPEC: corresponding type argument in the other. 

            var n1 = t1 as INamedTypeSymbol;
            var n2 = t2 as INamedTypeSymbol;

            if (n1 == null)
            {
                return null;
            }

            // We should not have gotten here unless there were identity conversions between the
            // two types.

            var allTypeArgs1 = n1.GetAllTypeArguments().ToList();
            var allTypeArgs2 = n2.GetAllTypeArguments().ToList();

            return allTypeArgs1.AreMoreSpecificThan(allTypeArgs2);
        }

        public static bool IsOrDerivesFromExceptionType(this ITypeSymbol type, Compilation compilation)
        {
            if (type != null)
            {
J
Jared Parsons 已提交
842
                switch (type.Kind)
P
Pilchie 已提交
843
                {
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
                    case SymbolKind.NamedType:
                        foreach (var baseType in type.GetBaseTypesAndThis())
                        {
                            if (baseType.Equals(compilation.ExceptionType()))
                            {
                                return true;
                            }
                        }

                        break;

                    case SymbolKind.TypeParameter:
                        foreach (var constraint in ((ITypeParameterSymbol)type).ConstraintTypes)
                        {
                            if (constraint.IsOrDerivesFromExceptionType(compilation))
                            {
                                return true;
                            }
                        }

                        break;
P
Pilchie 已提交
865 866 867 868 869 870 871 872 873 874
                }
            }

            return false;
        }

        public static bool IsEnumType(this ITypeSymbol type)
        {
            return type.IsValueType && type.TypeKind == TypeKind.Enum;
        }
875

876
        public static bool? IsMutableValueType(this ITypeSymbol type)
877
        {
878 879 880 881 882 883 884
            if (type.IsNullable())
            {
                // Nullable<T> can only be mutable if T is mutable. This case ensures types like 'int?' are treated as
                // immutable.
                type = type.GetTypeArguments()[0];
            }

885 886 887 888 889
            if (type.IsErrorType())
            {
                return null;
            }

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
            if (type.TypeKind != TypeKind.Struct)
            {
                return false;
            }

            foreach (var member in type.GetMembers())
            {
                if (member is IFieldSymbol fieldSymbol &&
                    !(fieldSymbol.IsConst || fieldSymbol.IsReadOnly || fieldSymbol.IsStatic))
                {
                    return true;
                }
            }

            return false;
        }
P
Pilchie 已提交
906
    }
907
}