-
-
Notifications
You must be signed in to change notification settings - Fork 846
Expand file tree
/
Copy pathDelegateRegisterGenerator.cs
More file actions
334 lines (274 loc) · 11.7 KB
/
Copy pathDelegateRegisterGenerator.cs
File metadata and controls
334 lines (274 loc) · 11.7 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Autofac.CodeGen;
/// <summary>
/// Autogenerates generic `Register` delegate resolve methods.
/// </summary>
[Generator]
public class DelegateRegisterGenerator : IIncrementalGenerator
{
/// <summary>
/// Change this number to adjust how many generic arguments we support.
/// </summary>
private const int NumberOfGenericArgs = 10;
private const int SpacesPerIndent = 4;
/// <inheritdoc />
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Set up an incremental generator that regenerates when the 'RegistrationExtensions' class changes.
// Capture the INamedTypeSymbol when it does.
var classDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (s, _) => s is ClassDeclarationSyntax classSyn && classSyn.Modifiers.Any(static m => m.IsKind(SyntaxKind.PartialKeyword)),
transform: static (context, cancelToken) =>
{
var syntax = (ClassDeclarationSyntax)context.Node;
if (context.SemanticModel.GetDeclaredSymbol(syntax, cancelToken) is INamedTypeSymbol symbol)
{
// Looking for the exact name of the class.
if (symbol.ToDisplayString() == "Autofac.RegistrationExtensions")
{
return symbol;
}
}
return null;
})
.Where(static m => m is not null)!;
// Just get our first one (will only be one instance anyway, we just need to convert to a single value provider).
var firstSyntax
= classDeclarations.Collect().Select((all, _) => all.FirstOrDefault());
context.RegisterSourceOutput(
firstSyntax,
static (spc, regExtensionsTypeSymbol) => Execute(spc, regExtensionsTypeSymbol));
}
private static void Execute(SourceProductionContext spc, INamedTypeSymbol? regExtensionClass)
{
if (regExtensionClass is null)
{
return;
}
// Add our holding type for delegate invokers.
GenerateDelegateInvokers(
spc,
holdingTypeName: "DelegateInvokers",
static (int argCount, bool hasComponentContext) => hasComponentContext ? $"DelegateInvoker{argCount}WithComponentContext" : $"DelegateInvoker{argCount}",
NumberOfGenericArgs);
// Add our holding type for registration extensions.
GenerateExtensionMethodClass(
spc,
"RegistrationExtensions",
"Register",
static (int argCount, bool hasComponentContext) => hasComponentContext
? $"DelegateInvokers.DelegateInvoker{argCount}WithComponentContext"
: $"DelegateInvokers.DelegateInvoker{argCount}",
NumberOfGenericArgs);
}
private static void GenerateExtensionMethodClass(
SourceProductionContext spc,
string className,
string extensionMethodName,
Func<int, bool, string> getDelegateInvokerName,
int maxArgs)
{
var sb = new StringBuilder();
sb.Append($@"// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Autofac.Builder;
using Autofac.Core;
using Autofac.Core.Resolving;
namespace Autofac;
/// <summary>
/// Adds registration syntax to the <see cref=""ContainerBuilder""/> type.
/// </summary>
[SuppressMessage(""Microsoft.Maintainability"", ""CA1506:AvoidExcessiveClassCoupling"")]
public static partial class {className}
{{");
for (var argCount = 1; argCount <= maxArgs; argCount++)
{
GenerateExtensionMethod(sb, extensionMethodName, getDelegateInvokerName, argCount, withComponentContext: false);
sb.AppendLine();
GenerateExtensionMethod(sb, extensionMethodName, getDelegateInvokerName, argCount, withComponentContext: true);
sb.AppendLine();
}
sb.AppendLine($@"
}}");
spc.AddSource($"Autofac.{className}.g.cs", sb.ToString());
}
private static void GenerateExtensionMethod(StringBuilder sb, string methodName, Func<int, bool, string> getDelegateInvokerName, int argCount, bool withComponentContext)
{
var delegateGenericTypeList = GetTypeParamList(withComponentContext, argCount);
var methodGenericTypeList = GetTypeParamList(withComponentContext: false, argCount);
sb.AppendLine($@"
/// <summary>
/// Register a delegate as a component.
/// </summary>");
WriteTypeParamDocs(sb, argCount, 1);
sb.AppendLine($@" /// <typeparam name=""TComponent"">The type of the instance.</typeparam>
/// <param name=""builder"">Container builder.</param>
/// <param name=""delegate"">The delegate to register.</param>
/// <returns>Registration builder allowing the registration to be configured.</returns>
public static IRegistrationBuilder<TComponent, SimpleActivatorData, SingleRegistrationStyle>
{methodName}<{methodGenericTypeList}>(
this ContainerBuilder builder,
Func<{delegateGenericTypeList}> @delegate)");
WriteTypeConstraints(sb, argCount, 2);
sb.Append($@" {{
if (@delegate is null)
{{
throw new ArgumentNullException(nameof(@delegate));
}}
var delegateInvoker = new {getDelegateInvokerName(argCount, withComponentContext)}<{methodGenericTypeList}>(@delegate);
return builder.Register(delegateInvoker.ResolveWithDelegate);
}}");
}
private static void GenerateDelegateInvokers(
SourceProductionContext spc,
string holdingTypeName,
Func<int, bool, string> nameGenerator,
int maxArgs)
{
var sb = new StringBuilder();
sb.Append($@"// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Reflection;
using Autofac.Builder;
using Autofac.Core;
namespace Autofac.Core.Resolving;
/// <summary>
/// Provides delegate invocation holding classes.
/// </summary>
[SuppressMessage(""Microsoft.Maintainability"", ""CA1506:AvoidExcessiveClassCoupling"")]
internal static partial class {holdingTypeName}
{{");
for (var argCount = 1; argCount <= maxArgs; argCount++)
{
GenerateDelegateInvoker(sb, nameGenerator(argCount, false), argCount);
sb.AppendLine();
GenerateDelegateInvokerWithComponentContext(sb, nameGenerator(argCount, true), argCount);
sb.AppendLine();
}
sb.AppendLine($@"
}}");
spc.AddSource($"Autofac.{holdingTypeName}.g.cs", sb.ToString());
}
private static void GenerateDelegateInvokerWithComponentContext(StringBuilder sb, string typeName, int argCount)
{
var delegateGenericTypeList = GetTypeParamList(withComponentContext: true, argCount);
sb.AppendLine($@"
public sealed class {typeName}<{GetTypeParamList(withComponentContext: false, argCount)}> : BaseGenericResolveDelegateInvoker");
WriteTypeConstraints(sb, argCount, 2);
sb.Append($@" {{
private readonly Func<{delegateGenericTypeList}> _delegate;
public {typeName}(Func<{delegateGenericTypeList}> @delegate)
{{
_delegate = @delegate;
}}
protected override ParameterInfo[] GetDelegateParameters() => _delegate.Method.GetParameters();
public TComponent ResolveWithDelegate(IComponentContext context, IEnumerable<Parameter> parameters)
{{
if (AnyParameters(parameters))
{{
return _delegate(
context,");
sb.AppendLine();
WriteResolveWithParametersOrRegistrationCalls(sb, parameterInfoIndexOffset: 1, argCount, indentTimes: 5);
sb.Append(");");
sb.Append($@"
}}
return _delegate(
context,");
sb.AppendLine();
WriteResolveCalls(sb, argCount, indentTimes: 5);
sb.Append($@");
}}
}}");
}
private static void GenerateDelegateInvoker(StringBuilder sb, string typeName, int argCount)
{
var delegateGenericTypeList = GetTypeParamList(withComponentContext: false, argCount);
sb.AppendLine($@"
public sealed class {typeName}<{delegateGenericTypeList}> : BaseGenericResolveDelegateInvoker");
WriteTypeConstraints(sb, argCount, 2);
sb.Append($@" {{
private readonly Func<{delegateGenericTypeList}> _delegate;
public {typeName}(Func<{delegateGenericTypeList}> @delegate)
{{
_delegate = @delegate;
}}
protected override ParameterInfo[] GetDelegateParameters() => _delegate.Method.GetParameters();
public TComponent ResolveWithDelegate(IComponentContext context, IEnumerable<Parameter> parameters)
{{
if (AnyParameters(parameters))
{{
return _delegate(");
sb.AppendLine();
WriteResolveWithParametersOrRegistrationCalls(sb, parameterInfoIndexOffset: 0, argCount, indentTimes: 5);
sb.Append(");");
sb.Append($@"
}}
return _delegate(");
sb.AppendLine();
WriteResolveCalls(sb, argCount, indentTimes: 5);
sb.Append(@$");
}}
}}");
}
private static string GetTypeParamList(bool withComponentContext, int argCount)
{
var sb = new StringBuilder();
if (withComponentContext)
{
sb.Append("IComponentContext, ");
}
for (var argPos = 1; argPos <= argCount; argPos++)
{
sb.Append($"TDependency{argPos}, ");
}
sb.Append("TComponent");
return sb.ToString();
}
private static void WriteTypeConstraints(StringBuilder sb, int argCount, int indentTimes)
{
for (var argPos = 1; argPos <= argCount; argPos++)
{
sb.Append(' ', indentTimes * SpacesPerIndent);
sb.AppendLine($"where TDependency{argPos} : notnull");
}
}
private static void WriteTypeParamDocs(StringBuilder sb, int argCount, int indentTimes)
{
for (var argPos = 1; argPos <= argCount; argPos++)
{
sb.Append(' ', indentTimes * SpacesPerIndent);
sb.AppendLine($"/// <typeparam name=\"TDependency{argPos}\">The type of a dependency to inject into the delegate.</typeparam>");
}
}
private static void WriteResolveWithParametersOrRegistrationCalls(StringBuilder sb, int parameterInfoIndexOffset, int argCount, int indentTimes)
{
for (var argPos = 1; argPos <= argCount; argPos++)
{
sb.Append(' ', indentTimes * SpacesPerIndent);
sb.Append($"ResolveWithParametersOrRegistration<TDependency{argPos}>(context, parameters, {(argPos - 1) + parameterInfoIndexOffset})");
if (argPos < argCount)
{
sb.AppendLine(",");
}
}
}
private static void WriteResolveCalls(StringBuilder sb, int argCount, int indentTimes)
{
for (var argPos = 1; argPos <= argCount; argPos++)
{
sb.Append(' ', indentTimes * SpacesPerIndent);
sb.Append($"context.Resolve<TDependency{argPos}>()");
if (argPos < argCount)
{
sb.AppendLine(",");
}
}
}
}