|
1 |
| -using Microsoft.CodeAnalysis; |
| 1 | +using JetBrains.Annotations; |
| 2 | +using Microsoft.CodeAnalysis; |
2 | 3 | using Microsoft.CodeAnalysis.CSharp.Syntax;
|
3 | 4 | using Microsoft.CodeAnalysis.Diagnostics;
|
4 | 5 |
|
@@ -36,11 +37,47 @@ public static bool IsExpressionOfType<T>(this ExpressionSyntax createNode, Synta
|
36 | 37 | }
|
37 | 38 |
|
38 | 39 | /// <summary>
|
39 |
| - /// Gets matching type in context |
| 40 | + /// Determines if some expression is actually of type T or of type derived from T |
40 | 41 | /// </summary>
|
41 |
| - public static INamedTypeSymbol GetType<T>(this SyntaxNodeAnalysisContext context) |
| 42 | + public static bool IsExpressionOfTypeOrDerived<T>(this ExpressionSyntax createNode, SyntaxNodeAnalysisContext context) |
42 | 43 | {
|
43 |
| - return context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(T).FullName); |
| 44 | + var targetType = GetType<T>(context); |
| 45 | + return createNode.IsExpressionOfTypeOrDerived(context, targetType); |
44 | 46 | }
|
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Determines if some expression is actually of type T or of type derived from T |
| 50 | + /// </summary> |
| 51 | + public static bool IsExpressionOfTypeOrDerived(this ExpressionSyntax createNode, |
| 52 | + SyntaxNodeAnalysisContext context, INamedTypeSymbol targetType) |
| 53 | + { |
| 54 | + var actualType = context.SemanticModel.GetTypeInfo(createNode).Type as INamedTypeSymbol; |
| 55 | + |
| 56 | + var searchType = actualType; |
| 57 | + |
| 58 | + while (searchType != null) |
| 59 | + { |
| 60 | + if (Equals(searchType, targetType)) |
| 61 | + { |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + searchType = searchType.BaseType; |
| 66 | + } |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + /// <summary> |
| 72 | + /// Gets matching type in context |
| 73 | + /// </summary> |
| 74 | + [CanBeNull] |
| 75 | + public static INamedTypeSymbol GetType<T>(this SyntaxNodeAnalysisContext context) => context.SemanticModel.Compilation.GetType<T>(); |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Gets matching type in context |
| 79 | + /// </summary> |
| 80 | + [CanBeNull] |
| 81 | + public static INamedTypeSymbol GetType<T>(this Compilation semanticModelCompilation) => semanticModelCompilation.GetTypeByMetadataName(typeof(T).FullName); |
45 | 82 | }
|
46 | 83 | }
|
0 commit comments