Skip to content

Commit 03b4790

Browse files
committed
Improve test helpers
1 parent fbc2c2e commit 03b4790

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

Tsarev.Analyzer.Helpers/TypeHelpers.cs

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Microsoft.CodeAnalysis;
1+
using JetBrains.Annotations;
2+
using Microsoft.CodeAnalysis;
23
using Microsoft.CodeAnalysis.CSharp.Syntax;
34
using Microsoft.CodeAnalysis.Diagnostics;
45

@@ -36,11 +37,47 @@ public static bool IsExpressionOfType<T>(this ExpressionSyntax createNode, Synta
3637
}
3738

3839
/// <summary>
39-
/// Gets matching type in context
40+
/// Determines if some expression is actually of type T or of type derived from T
4041
/// </summary>
41-
public static INamedTypeSymbol GetType<T>(this SyntaxNodeAnalysisContext context)
42+
public static bool IsExpressionOfTypeOrDerived<T>(this ExpressionSyntax createNode, SyntaxNodeAnalysisContext context)
4243
{
43-
return context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(T).FullName);
44+
var targetType = GetType<T>(context);
45+
return createNode.IsExpressionOfTypeOrDerived(context, targetType);
4446
}
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);
4582
}
4683
}

0 commit comments

Comments
 (0)