-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAutoDisposeSourceGenerator.cs
More file actions
173 lines (147 loc) · 5.64 KB
/
AutoDisposeSourceGenerator.cs
File metadata and controls
173 lines (147 loc) · 5.64 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Platform.Disposables.SourceGenerator
{
[Generator]
public class AutoDisposeSourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new ClassSyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
if (!(context.SyntaxReceiver is ClassSyntaxReceiver receiver))
return;
foreach (var classDeclaration in receiver.CandidateClasses)
{
var semanticModel = context.Compilation.GetSemanticModel(classDeclaration.SyntaxTree);
var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration);
if (classSymbol == null)
continue;
if (!InheritsFromDisposableBase(classSymbol))
continue;
if (HasAutoDisposeAttribute(classSymbol))
{
var sourceCode = GenerateDisposeMethod(classSymbol, classDeclaration);
if (!string.IsNullOrEmpty(sourceCode))
{
context.AddSource($"{classSymbol.Name}.AutoDispose.g.cs", SourceText.From(sourceCode, Encoding.UTF8));
}
}
}
}
private bool InheritsFromDisposableBase(INamedTypeSymbol classSymbol)
{
var baseType = classSymbol.BaseType;
while (baseType != null)
{
if (baseType.Name == "DisposableBase" &&
baseType.ContainingNamespace?.ToDisplayString() == "Platform.Disposables")
{
return true;
}
baseType = baseType.BaseType;
}
return false;
}
private bool HasAutoDisposeAttribute(INamedTypeSymbol classSymbol)
{
return classSymbol.GetAttributes().Any(a =>
a.AttributeClass?.Name == "AutoDisposeAttribute" ||
a.AttributeClass?.Name == "AutoDispose");
}
private string GenerateDisposeMethod(INamedTypeSymbol classSymbol, ClassDeclarationSyntax classDeclaration)
{
var disposableFields = GetDisposableFields(classSymbol);
if (!disposableFields.Any())
return string.Empty;
var namespaceName = classSymbol.ContainingNamespace.ToDisplayString();
var className = classSymbol.Name;
var disposeStatements = GenerateDisposeStatements(disposableFields);
var sourceCode = $@"// <auto-generated />
#nullable enable
using System;
namespace {namespaceName}
{{
partial class {className}
{{
protected override void Dispose(bool manual, bool wasDisposed)
{{
if (!wasDisposed)
{{
{disposeStatements}
}}
}}
}}
}}";
return sourceCode;
}
private List<IFieldSymbol> GetDisposableFields(INamedTypeSymbol classSymbol)
{
var disposableFields = new List<IFieldSymbol>();
foreach (var member in classSymbol.GetMembers())
{
if (member is IFieldSymbol field)
{
if (IsDisposableType(field.Type))
{
disposableFields.Add(field);
}
}
}
return disposableFields;
}
private bool IsDisposableType(ITypeSymbol typeSymbol)
{
// Check for System.IDisposable
if (ImplementsInterface(typeSymbol, "System", "IDisposable"))
return true;
// Check for Platform.Disposables.IDisposable
if (ImplementsInterface(typeSymbol, "Platform.Disposables", "IDisposable"))
return true;
return false;
}
private bool ImplementsInterface(ITypeSymbol typeSymbol, string namespaceName, string interfaceName)
{
return typeSymbol.AllInterfaces.Any(i =>
i.Name == interfaceName &&
i.ContainingNamespace?.ToDisplayString() == namespaceName);
}
private string GenerateDisposeStatements(List<IFieldSymbol> disposableFields)
{
var statements = new StringBuilder();
foreach (var field in disposableFields)
{
statements.AppendLine($" {field.Name}?.Dispose();");
// Only set to null if field is not readonly
if (field.Type.CanBeReferencedByName && !field.IsReadOnly)
{
statements.AppendLine($" {field.Name} = null;");
}
}
return statements.ToString().TrimEnd();
}
}
internal class ClassSyntaxReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> CandidateClasses { get; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax classDeclaration)
{
// Look for classes that might need auto-dispose generation
if (classDeclaration.AttributeLists.Any() ||
classDeclaration.BaseList?.Types.Any() == true)
{
CandidateClasses.Add(classDeclaration);
}
}
}
}
}