forked from lofcz/FastCloner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContextCodeGenerator.cs
More file actions
373 lines (321 loc) · 14.1 KB
/
Copy pathContextCodeGenerator.cs
File metadata and controls
373 lines (321 loc) · 14.1 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace FastCloner.SourceGenerator;
internal sealed class ContextCodeGenerator
{
private readonly ContextModel _model;
private readonly StringBuilder _sb = new StringBuilder();
private readonly Dictionary<string, string> _sharedMethodNames = new Dictionary<string, string>();
private readonly HashSet<string> _sharedNeededHelpers = [];
private Dictionary<string, bool> _needsState = new Dictionary<string, bool>();
public ContextCodeGenerator(ContextModel model)
{
_model = model;
}
public string Generate()
{
AnalyzeCircularDependencies();
_sb.AppendLine("// <auto-generated/>");
_sb.AppendLine($"// Generated: {System.DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC");
_sb.AppendLine("#nullable enable");
_sb.AppendLine("#pragma warning disable");
_sb.AppendLine();
_sb.AppendLine("using System;");
_sb.AppendLine("using System.Collections.Generic;");
_sb.AppendLine("using System.Reflection;");
if (_model.IsFastClonerAvailable)
{
_sb.AppendLine("using FastCloner;");
}
_sb.AppendLine();
if (!string.IsNullOrEmpty(_model.Namespace))
{
_sb.AppendLine($"namespace {_model.Namespace}");
_sb.AppendLine("{");
}
_sb.AppendLine($" public partial class {_model.Name}");
_sb.AppendLine(" {");
// Generate methods for each registered type
foreach (TypeModel? typeModel in _model.RegisteredTypes)
{
GenerateTypeCloner(typeModel);
}
// Generate dispatcher
GenerateDispatcher();
GenerateIsHandled();
GenerateTryClone();
// Generate State class (shared)
GenerateStateClass();
_sb.AppendLine(" }");
if (!string.IsNullOrEmpty(_model.Namespace))
{
_sb.AppendLine("}");
}
return _sb.ToString();
}
private void GenerateTypeCloner(TypeModel model)
{
CloneGeneratorContext ctx = new CloneGeneratorContext(model, _sharedMethodNames, _sharedNeededHelpers);
ctx.NeedsStateClass = true; // Use shared state class logic
ctx.UseStaticMethods = false; // Use instance methods for context
// Populate overrides from our analysis
foreach (KeyValuePair<string, bool> kvp in _needsState)
{
ctx.SetCircularReferenceOverride(kvp.Key, kvp.Value);
}
// Pre-register all registered types to map to "Clone" method
foreach (TypeModel? regType in _model.RegisteredTypes)
{
ctx.RegisterExternalMethod(regType.FullyQualifiedName, "Clone");
ctx.RegisterImplicitType(regType);
}
string typeName = model.FullyQualifiedName;
if (model.CircularAnalysisLog.Count > 0)
{
_sb.AppendLine(" // Circular Analysis Log:");
foreach (string? line in model.CircularAnalysisLog)
{
_sb.AppendLine($" // {line}");
}
}
// Determine if we really need state tracking for this type
bool needsState = _needsState.ContainsKey(model.FullyQualifiedName) && _needsState[model.FullyQualifiedName];
// Only generate NotNullIfNotNull attribute if it's available in the runtime (not from polyfill)
string notNullAttr = CloneGeneratorContext.NotNullIfNotNullAttr(_model.CodeAnalysisAvailable);
if (!string.IsNullOrEmpty(notNullAttr))
_sb.AppendLine($" {notNullAttr}");
_sb.AppendLine($" public {typeName}? Clone({typeName}? source)");
_sb.AppendLine(" {");
if (!needsState)
{
_sb.AppendLine(" if (source == null) return null;");
GenerateCloneBody(ctx, typeName, false);
_sb.Append(ctx.Source.ToString());
ctx.Source.Clear();
}
else
{
// Fix: if type needs state, the public method MUST initialize it
_sb.AppendLine($" return Clone(source, new FcGeneratedCloneState());");
}
_sb.AppendLine(" }");
_sb.AppendLine();
if (needsState)
{
_sb.AppendLine($" private {typeName}? Clone({typeName}? source, FcGeneratedCloneState state)");
_sb.AppendLine(" {");
_sb.AppendLine(" if (source == null) return null;");
// Fix: Remove the state ?? new check - state is always passed and managed by caller
if (!model.IsStruct)
{
_sb.AppendLine(" var known = state.GetKnownRef(source);");
_sb.AppendLine($" if (known != null) return ({typeName})known;");
}
GenerateCloneBody(ctx, typeName, true, "state");
_sb.Append(ctx.Source.ToString());
ctx.Source.Clear();
_sb.AppendLine(" }");
_sb.AppendLine();
}
// Generate helpers that were triggered by this type
CollectionHelperGenerator.GenerateHelpers(ctx);
// Append all generated code from context (helpers)
_sb.Append(ctx.Source.ToString());
}
private void GenerateCloneBody(CloneGeneratorContext ctx, string typeName, bool useState, string? stateVarName = null)
{
if (ctx.Model.IsStruct)
{
WriteStructCloneBody(ctx, stateVarName ?? "state");
}
else
{
WriteClassCloneBody(ctx, typeName, useState, stateVarName);
}
}
private void WriteStructCloneBody(CloneGeneratorContext ctx, string stateVarName)
{
StringBuilder sb = ctx.Source;
sb.AppendLine($" var result = source;");
sb.AppendLine();
foreach (MemberModel member in ctx.Model.Members)
{
MemberCloneGenerator.WriteMemberCloning(ctx, member, "result", "source", stateVarName);
}
sb.AppendLine(" return result;");
}
private void WriteClassCloneBody(CloneGeneratorContext ctx, string typeName, bool useState, string? stateVarName)
{
ClassCloneBodyGenerator.WriteClassCloneBody(ctx, typeName, useState, stateVarName, useNullConditional: false);
}
private void GenerateDispatcher()
{
_sb.AppendLine(" public override object Clone(object input)");
_sb.AppendLine(" {");
foreach (TypeModel? type in _model.RegisteredTypes)
{
// Call public Clone method which handles state initialization
_sb.AppendLine($" if (input is {type.FullyQualifiedName} t{type.Name}) return Clone(t{type.Name})!;");
}
// Fallback to reflection-based FastCloner if available, otherwise throw
if (_model.IsFastClonerAvailable)
{
_sb.AppendLine($" return {CloneGeneratorContext.FastClonerDeepCloneCall("input")}!;");
}
else
{
_sb.AppendLine(" throw new System.NotSupportedException(\"Cannot clone unregistered type without FastCloner runtime library.\");");
}
_sb.AppendLine(" }");
_sb.AppendLine();
}
private void GenerateIsHandled()
{
_sb.AppendLine(" public override bool IsHandled(Type type)");
_sb.AppendLine(" {");
foreach (TypeModel? type in _model.RegisteredTypes)
{
_sb.AppendLine($" if (type == typeof({type.FullyQualifiedName})) return true;");
}
_sb.AppendLine(" return false;");
_sb.AppendLine(" }");
_sb.AppendLine();
}
private void GenerateTryClone()
{
// Only generate NotNullWhen attribute if NotNullIfNotNull is available (they're in the same namespace)
if (_model.CodeAnalysisAvailable)
{
_sb.AppendLine(" public override bool TryClone(object input, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out object? clone)");
}
else
{
_sb.AppendLine(" public override bool TryClone(object input, out object? clone)");
}
_sb.AppendLine(" {");
_sb.AppendLine(" if (input == null)");
_sb.AppendLine(" {");
_sb.AppendLine(" clone = null;");
_sb.AppendLine(" return false;");
_sb.AppendLine(" }");
_sb.AppendLine();
foreach (TypeModel? type in _model.RegisteredTypes)
{
_sb.AppendLine($" if (input is {type.FullyQualifiedName} t{type.Name})");
_sb.AppendLine(" {");
_sb.AppendLine($" clone = Clone(t{type.Name});");
_sb.AppendLine(" return true;");
_sb.AppendLine(" }");
}
_sb.AppendLine(" clone = null;");
_sb.AppendLine(" return false;");
_sb.AppendLine(" }");
_sb.AppendLine();
}
private void GenerateStateClass()
{
// Only generate state class if at least one type needs circular reference tracking
if (!_needsState.Any(kvp => kvp.Value))
return;
_sb.AppendLine(" /// <summary>");
_sb.AppendLine(" /// State for tracking circular references during cloning.");
_sb.AppendLine(" /// </summary>");
_sb.AppendLine(" private class FcGeneratedCloneState");
_sb.AppendLine(" {");
_sb.AppendLine(" private readonly Dictionary<object, object> _knownRefs = new Dictionary<object, object>(new ReferenceEqualityComparer());");
_sb.AppendLine();
_sb.AppendLine(" public void AddKnownRef(object original, object clone)");
_sb.AppendLine(" {");
_sb.AppendLine(" if (original != null)");
_sb.AppendLine(" {");
_sb.AppendLine(" _knownRefs[original] = clone;");
_sb.AppendLine(" }");
_sb.AppendLine(" }");
_sb.AppendLine();
_sb.AppendLine(" public object? GetKnownRef(object original)");
_sb.AppendLine(" {");
_sb.AppendLine(" if (original == null) return null;");
_sb.AppendLine(" return _knownRefs.TryGetValue(original, out var clone) ? clone : null;");
_sb.AppendLine(" }");
_sb.AppendLine();
_sb.AppendLine(" private sealed class ReferenceEqualityComparer : IEqualityComparer<object>");
_sb.AppendLine(" {");
_sb.AppendLine(" bool IEqualityComparer<object>.Equals(object? x, object? y) => ReferenceEquals(x, y);");
_sb.AppendLine(" int IEqualityComparer<object>.GetHashCode(object obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);");
_sb.AppendLine(" }");
_sb.AppendLine(" }");
}
private void AnalyzeCircularDependencies()
{
// 1. Build Graph
Dictionary<string, HashSet<string>> adjacency = new Dictionary<string, HashSet<string>>();
Dictionary<string, TypeModel> registeredTypes = _model.RegisteredTypes.ToDictionary(t => t.FullyQualifiedName, t => t);
foreach (TypeModel? type in _model.RegisteredTypes)
{
HashSet<string> deps = [];
adjacency[type.FullyQualifiedName] = deps;
foreach (MemberModel member in type.Members)
{
AddDependency(deps, member.TypeFullName, registeredTypes);
AddDependency(deps, member.ElementTypeName, registeredTypes);
AddDependency(deps, member.KeyTypeName, registeredTypes);
AddDependency(deps, member.ValueTypeName, registeredTypes);
}
}
// 2. Find nodes that reach a cycle
Dictionary<string, VisitStatus> status = new Dictionary<string, VisitStatus>();
Dictionary<string, bool> reachesCycle = new Dictionary<string, bool>();
foreach (TypeModel? type in _model.RegisteredTypes)
{
if (!status.ContainsKey(type.FullyQualifiedName))
{
CheckCycleDFS(type.FullyQualifiedName, adjacency, status, reachesCycle);
}
}
_needsState = reachesCycle;
}
private void AddDependency(HashSet<string> deps, string? typeName, Dictionary<string, TypeModel> registered)
{
if (!string.IsNullOrEmpty(typeName) && registered.ContainsKey(typeName!))
{
deps.Add(typeName!);
}
}
private enum VisitStatus { Unvisited, Visiting, Visited }
private bool CheckCycleDFS(string u, Dictionary<string, HashSet<string>> adj, Dictionary<string, VisitStatus> status, Dictionary<string, bool> reachesCycle)
{
status[u] = VisitStatus.Visiting;
bool cycleFound = false;
if (adj.TryGetValue(u, out HashSet<string>? neighbors))
{
foreach (string? v in neighbors)
{
if (!status.ContainsKey(v)) status[v] = VisitStatus.Unvisited;
if (status[v] == VisitStatus.Visiting)
{
// Back edge found -> Cycle
cycleFound = true;
}
else if (status[v] == VisitStatus.Visited)
{
if (reachesCycle.ContainsKey(v) && reachesCycle[v])
{
cycleFound = true;
}
}
else // Unvisited
{
if (CheckCycleDFS(v, adj, status, reachesCycle))
{
cycleFound = true;
}
}
}
}
status[u] = VisitStatus.Visited;
reachesCycle[u] = cycleFound;
return cycleFound;
}
}