-
-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathParser.cs
More file actions
65 lines (54 loc) · 2.14 KB
/
Parser.cs
File metadata and controls
65 lines (54 loc) · 2.14 KB
1
2
3
4
5
6
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
57
58
59
60
61
62
63
64
65
static class Parser
{
public static ClassToGenerate? Parse(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax typeSyntax, Cancel cancel)
{
var ns = typeSymbol.GetNamespaceOrDefault();
var name = typeSyntax.GetTypeNameWithGenericParameters();
var parents = GetParentClasses(typeSyntax, cancel);
return new ClassToGenerate(
Namespace: ns,
ClassName: name,
OverrideTestContext: BaseClassHasTestContext(typeSymbol),
ParentClasses: parents);
}
static bool BaseClassHasTestContext(INamedTypeSymbol typeSymbol) =>
BaseClassesOf(typeSymbol)
.Any(HasTestContextProperty);
static bool HasTestContextProperty(INamedTypeSymbol typeSymbol) =>
typeSymbol
.GetMembers()
.OfType<IPropertySymbol>()
.Any(property =>
property.Name == "TestContext" &&
property.DeclaredAccessibility == Accessibility.Public);
static IEnumerable<INamedTypeSymbol> BaseClassesOf(INamedTypeSymbol typeSymbol)
{
var baseType = typeSymbol.BaseType;
while (baseType?.TypeKind == TypeKind.Class)
{
yield return baseType;
baseType = baseType.BaseType;
}
}
static ParentClass[] GetParentClasses(TypeDeclarationSyntax typeSyntax, Cancel cancel)
{
// We can only be nested in class/struct/record
static bool IsAllowedKind(SyntaxKind kind) =>
kind is
SyntaxKind.ClassDeclaration or
SyntaxKind.StructDeclaration or
SyntaxKind.RecordDeclaration;
var parents = new Stack<ParentClass>();
var parent = typeSyntax.Parent as TypeDeclarationSyntax;
while (parent is not null &&
IsAllowedKind(parent.Kind()))
{
cancel.ThrowIfCancellationRequested();
parents.Push(new(
Keyword: parent.Keyword.ValueText,
Name: parent.GetTypeNameWithGenericParameters()));
parent = parent.Parent as TypeDeclarationSyntax;
}
return parents.ToArray();
}
}