-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegistrationParser.cs
More file actions
403 lines (350 loc) · 12.3 KB
/
Copy pathRegistrationParser.cs
File metadata and controls
403 lines (350 loc) · 12.3 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using XrmPluginCore.SourceGenerator.CodeGeneration;
using XrmPluginCore.SourceGenerator.Helpers;
using XrmPluginCore.SourceGenerator.Models;
namespace XrmPluginCore.SourceGenerator.Parsers;
/// <summary>
/// Parses plugin class syntax to extract registration metadata
/// </summary>
internal static class RegistrationParser
{
/// <summary>
/// Parses a plugin class and extracts all plugin step metadata
/// </summary>
public static IEnumerable<PluginStepMetadata> ParsePluginClass(
ClassDeclarationSyntax classDeclaration,
SemanticModel semanticModel)
{
// Check if plugin class has a parameterless constructor
var hasParameterlessConstructor = classDeclaration.Members
.OfType<ConstructorDeclarationSyntax>()
.Any(c => c.ParameterList.Parameters.Count == 0);
// Check if class has ANY explicit constructors
var hasExplicitConstructors = classDeclaration.Members
.OfType<ConstructorDeclarationSyntax>()
.Any();
// If class has explicit constructors but no parameterless one, abort generation
// Note: XPC2001 (NoParameterlessConstructor) is handled by a separate analyzer
if (hasExplicitConstructors && !hasParameterlessConstructor)
{
yield break;
}
// Find the parameterless constructor (registration pipeline only supports parameterless)
var constructor = classDeclaration.Members
.OfType<ConstructorDeclarationSyntax>()
.FirstOrDefault(c => c.ParameterList.Parameters.Count == 0);
if (constructor == null)
yield break;
// Find all RegisterStep invocations
foreach (var registerStep in SyntaxHelper.FindRegisterStepInvocations(constructor))
{
var metadata = ParseRegisterStepInvocation(registerStep, semanticModel, classDeclaration);
if (metadata != null)
{
yield return metadata;
}
}
}
/// <summary>
/// Parses a single RegisterStep invocation
/// </summary>
private static PluginStepMetadata ParseRegisterStepInvocation(
InvocationExpressionSyntax registerStepInvocation,
SemanticModel semanticModel,
ClassDeclarationSyntax classDeclaration)
{
// Get the symbol info to extract type arguments
var symbolInfo = semanticModel.GetSymbolInfo(registerStepInvocation);
// Handle both resolved symbols and candidate symbols (when overload resolution is ambiguous)
IMethodSymbol methodSymbol = symbolInfo.Symbol as IMethodSymbol;
if (methodSymbol == null && symbolInfo.CandidateSymbols.Length > 0)
{
methodSymbol = symbolInfo.CandidateSymbols.OfType<IMethodSymbol>().FirstOrDefault();
}
if (methodSymbol == null)
{
return null;
}
// Extract entity type from generic parameter TEntity
if (methodSymbol.TypeArguments.Length == 0)
{
return null;
}
var entityType = methodSymbol.TypeArguments[0];
var metadata = new PluginStepMetadata
{
EntityTypeName = entityType.Name,
EntityTypeFullName = entityType.ToDisplayString(),
Namespace = classDeclaration.GetNamespace(),
PluginClassName = classDeclaration.Identifier.Text
};
// Extract service type from generic parameter TService (if present)
if (methodSymbol.TypeArguments.Length >= 2)
{
var serviceType = methodSymbol.TypeArguments[1];
metadata.ServiceTypeName = serviceType.Name;
metadata.ServiceTypeFullName = serviceType.ToDisplayString();
}
// Extract EventOperation and ExecutionStage from arguments
var arguments = registerStepInvocation.ArgumentList.Arguments;
if (arguments.Count >= 2)
{
metadata.EventOperation = ExtractEnumValue(arguments[0].Expression);
metadata.ExecutionStage = ExtractEnumValue(arguments[1].Expression);
}
// Extract method reference from 3rd argument if present
if (arguments.Count >= 3)
{
metadata.HandlerMethodName = RegisterStepHelper.GetMethodName(arguments[2].Expression);
}
// Find image calls
foreach (var imageCall in SyntaxHelper.FindImageInvocations(registerStepInvocation))
{
var imageMetadata = ParseImageInvocation(imageCall, entityType);
if (imageMetadata != null)
{
metadata.Images.Add(imageMetadata);
}
}
// Return metadata if we have a method reference (for code generation)
// OR if we have diagnostics to report
// Note: XPC3003 (ImageWithoutMethodReference) is handled by a separate analyzer
return !string.IsNullOrEmpty(metadata.HandlerMethodName) || metadata.Diagnostics.Any() ? metadata : null;
}
/// <summary>
/// Parses WithPreImage, WithPostImage, or AddImage call to extract image metadata.
/// </summary>
private static ImageMetadata ParseImageInvocation(
InvocationExpressionSyntax imageInvocation,
ITypeSymbol entityType)
{
if (imageInvocation.Expression is not MemberAccessExpressionSyntax memberAccess)
return null;
// Get method name - handle both generic (AddPreImage<T>) and non-generic (AddPreImage)
string methodName;
bool isGenericMethod = false;
if (memberAccess.Name is GenericNameSyntax genericName)
{
methodName = genericName.Identifier.Text;
isGenericMethod = true;
}
else if (memberAccess.Name is IdentifierNameSyntax identifierName)
{
methodName = identifierName.Identifier.Text;
}
else
{
return null;
}
var imageMetadata = new ImageMetadata();
var arguments = imageInvocation.ArgumentList.Arguments;
int attributeStartIndex = 0;
// Determine image type and starting index for attributes
if (methodName == Constants.AddImageMethodName)
{
// Old API: AddImage(ImageType.PreImage, "name", attr1, attr2, ...)
if (arguments.Count > 0)
{
var imageTypeArg = arguments[0].Expression;
imageMetadata.ImageType = ExtractEnumValue(imageTypeArg);
// Skip first argument (ImageType), process remaining
attributeStartIndex = 1;
}
}
else if (methodName == Constants.WithPreImageMethodName)
{
// New API: WithPreImage(x => x.Name, ...)
imageMetadata.ImageType = Constants.PreImageTypeName;
attributeStartIndex = 0;
}
else if (methodName == Constants.WithPostImageMethodName)
{
// New API: WithPostImage(x => x.Name, ...)
imageMetadata.ImageType = Constants.PostImageTypeName;
attributeStartIndex = 0;
}
// For WithPreImage/WithPostImage, all arguments are attributes
// For AddImage, first string after ImageType might be image name
bool allArgumentsAreAttributes = isGenericMethod ||
methodName == Constants.WithPreImageMethodName || methodName == Constants.WithPostImageMethodName;
// Process arguments starting from attributeStartIndex
for (int i = attributeStartIndex; i < arguments.Count; i++)
{
var argument = arguments[i];
// Try to extract from nameof expression
string value = SyntaxHelper.GetPropertyNameFromNameof(argument.Expression);
// Try to extract from string literal
if (value is null && argument.Expression is LiteralExpressionSyntax literal)
{
value = literal.Token.ValueText;
}
// Try to extract from lambda
if (value is null && argument.Expression is LambdaExpressionSyntax lambda)
{
value = SyntaxHelper.GetPropertyNameFromLambda(lambda);
}
if (value is not null)
{
// Lambdas are always attributes, never image names
// String literals in old AddImage API: first one might be image name
bool isLambda = argument.Expression is LambdaExpressionSyntax;
bool treatAsAttribute = allArgumentsAreAttributes || isLambda || !string.IsNullOrEmpty(imageMetadata.ImageName);
if (treatAsAttribute)
{
// This is an attribute
var attrMetadata = GetAttributeMetadata(value, entityType);
if (attrMetadata != null)
{
imageMetadata.Attributes.Add(attrMetadata);
}
}
else
{
// Old AddImage API: first string literal is image name
imageMetadata.ImageName = value;
}
}
}
// Default image name if not provided
if (string.IsNullOrEmpty(imageMetadata.ImageName))
{
imageMetadata.ImageName = imageMetadata.ImageType;
}
// For WithPreImage/WithPostImage with no attributes specified, capture all entity attributes
if (!imageMetadata.Attributes.Any() &&
(methodName == Constants.WithPreImageMethodName || methodName == Constants.WithPostImageMethodName))
{
imageMetadata.Attributes.AddRange(GetAllEntityAttributes(entityType));
}
return imageMetadata.Attributes.Any() ? imageMetadata : null;
}
/// <summary>
/// Gets all attribute metadata for all entity properties that have an AttributeLogicalName attribute.
/// Used for full entity images where no specific attributes are specified.
/// </summary>
private static IEnumerable<AttributeMetadata> GetAllEntityAttributes(ITypeSymbol entityType)
{
return entityType.GetMembers()
.OfType<IPropertySymbol>()
.Where(p => p.GetAttributes().Any(a => a.AttributeClass?.Name == Constants.LogicalNameAttributeName))
.Select(p => GetAttributeMetadata(p.Name, entityType))
.Where(a => a != null);
}
/// <summary>
/// Gets attribute metadata (property name, logical name, type) for a property
/// </summary>
private static AttributeMetadata GetAttributeMetadata(
string propertyName,
ITypeSymbol entityType)
{
// Find the property in the entity type
var property = entityType.GetMembers(propertyName)
.OfType<IPropertySymbol>()
.FirstOrDefault();
if (property == null)
return null;
// Get the logical name from AttributeLogicalName attribute if present
var logicalName = GetLogicalNameFromAttribute(property) ?? propertyName.ToLowerInvariant();
// Get XML documentation from the property
var xmlDoc = GetFormattedXmlDocumentation(property);
return new AttributeMetadata
{
PropertyName = propertyName,
LogicalName = logicalName,
TypeName = property.Type.ToDisplayString(),
XmlDocumentation = xmlDoc
};
}
/// <summary>
/// Extracts and formats XML documentation from a property symbol into /// comment format.
/// </summary>
private static string GetFormattedXmlDocumentation(IPropertySymbol property)
{
var xmlComment = property.GetDocumentationCommentXml();
if (string.IsNullOrWhiteSpace(xmlComment))
return null;
try
{
var doc = System.Xml.Linq.XDocument.Parse(xmlComment);
var member = doc.Root; // <member> element
if (member == null)
return null;
// Get inner XML (summary, remarks, etc.) and format as /// comments
var innerXml = string.Concat(member.Nodes());
if (string.IsNullOrWhiteSpace(innerXml))
return null;
// Split into lines, trim, and add /// prefix with member-level indentation
var lines = innerXml
.Split(['\r', '\n'], System.StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim())
.Where(line => !string.IsNullOrEmpty(line))
.Select(line => $"{Indent.L2}/// {line}");
var result = string.Join("\n", lines);
return string.IsNullOrWhiteSpace(result) ? null : result;
}
catch
{
return null;
}
}
/// <summary>
/// Extracts the logical name from [AttributeLogicalName("name")] attribute
/// </summary>
private static string GetLogicalNameFromAttribute(IPropertySymbol property)
{
var attribute = property.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.Name == Constants.LogicalNameAttributeName);
if (attribute?.ConstructorArguments.Length > 0)
{
return attribute.ConstructorArguments[0].Value?.ToString();
}
return null;
}
/// <summary>
/// Extracts enum value name from expression
/// </summary>
private static string ExtractEnumValue(ExpressionSyntax expression)
{
// Handle direct enum access like EventOperation.Update
if (expression is MemberAccessExpressionSyntax memberAccess)
{
return memberAccess.Name.Identifier.Text;
}
// Handle string literal for custom messages
if (expression is LiteralExpressionSyntax literal)
{
return literal.Token.ValueText;
}
return "Unknown";
}
}
/// <summary>
/// Extension methods for syntax nodes
/// </summary>
internal static class SyntaxExtensions
{
public static string GetNamespace(this SyntaxNode node)
{
var namespaces = new List<string>();
while (node != null)
{
if (node is NamespaceDeclarationSyntax namespaceDecl)
{
namespaces.Add(namespaceDecl.Name.ToString());
}
else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNs)
{
namespaces.Add(fileScopedNs.Name.ToString());
}
node = node.Parent;
}
if (namespaces.Count == 0)
return "GlobalNamespace";
// Reverse to get outer-to-inner order, then join
namespaces.Reverse();
return string.Join(".", namespaces);
}
}