CodeAnalysisExtensions.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using Microsoft.CodeAnalysis;
  9. namespace System.Reactive.Analyzers
  10. {
  11. internal static class CodeAnalysisExtensions
  12. {
  13. public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol? type)
  14. {
  15. var current = type;
  16. while (current != null)
  17. {
  18. yield return current;
  19. current = current.BaseType;
  20. }
  21. }
  22. public static bool InheritsFromOrEquals(
  23. this ITypeSymbol type, ITypeSymbol baseType, bool includeInterfaces)
  24. {
  25. if (!includeInterfaces)
  26. {
  27. return InheritsFromOrEquals(type, baseType);
  28. }
  29. return type.GetBaseTypesAndThis().Concat(type.AllInterfaces).Any(t => SymbolEqualityComparer.Default.Equals(t, baseType));
  30. }
  31. public static bool InheritsFromOrEquals(
  32. this ITypeSymbol type, ITypeSymbol baseType)
  33. {
  34. return type.GetBaseTypesAndThis().Any(t => SymbolEqualityComparer.Default.Equals(t, baseType));
  35. }
  36. public static bool IsIObservable(this ITypeSymbol typeSymbol)
  37. {
  38. return typeSymbol is INamedTypeSymbol { Name: "IObservable", Arity: 1, ContainingNamespace.MetadataName: "System" }
  39. || typeSymbol.AllInterfaces.Any(IsIObservable);
  40. }
  41. }
  42. }