forked from CommunityToolkit/Maui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBindablePropertyAttributeSourceGenerator.cs
More file actions
634 lines (536 loc) · 23.5 KB
/
BindablePropertyAttributeSourceGenerator.cs
File metadata and controls
634 lines (536 loc) · 23.5 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using CommunityToolkit.Maui.SourceGenerators.Helpers;
using CommunityToolkit.Maui.SourceGenerators.Internal.Helpers;
using CommunityToolkit.Maui.SourceGenerators.Internal.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace CommunityToolkit.Maui.SourceGenerators.Internal;
[Generator]
public class BindablePropertyAttributeSourceGenerator : IIncrementalGenerator
{
public const string BindablePropertyAttributeExperimentalDiagnosticId = "MCTEXP001";
static readonly SemanticValues emptySemanticValues = new(default, []);
const string bpFullName = "global::Microsoft.Maui.Controls.BindableProperty";
const string bpAttribute =
/* language=C#-test */
//lang=csharp
$$"""
// <auto-generated>
// See: CommunityToolkit.Maui.SourceGenerators.Internal.BindablePropertyAttributeSourceGenerator
#pragma warning disable
#nullable enable
namespace CommunityToolkit.Maui;
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.AttributeUsage(global::System.AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
[global::System.Diagnostics.CodeAnalysis.Experimental("{{BindablePropertyAttributeExperimentalDiagnosticId}}")]
sealed partial class BindablePropertyAttribute : global::System.Attribute
{
public string? PropertyName { get; }
public global::System.Type? DeclaringType { get; set; }
public global::Microsoft.Maui.Controls.BindingMode DefaultBindingMode { get; set; }
public string ValidateValueMethodName { get; set; } = string.Empty;
public string PropertyChangedMethodName { get; set; } = string.Empty;
public string PropertyChangingMethodName { get; set; } = string.Empty;
public string CoerceValueMethodName { get; set; } = string.Empty;
public string DefaultValueCreatorMethodName { get; set; } = string.Empty;
}
""";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
#if DEBUG
if (!Debugger.IsAttached)
{
// To debug this SG, uncomment the line below and rebuild the SourceGenerator project.
//Debugger.Launch();
}
#endif
context.RegisterPostInitializationOutput(static ctx => ctx.AddSource("BindablePropertyAttribute.g.cs", SourceText.From(bpAttribute, Encoding.UTF8)));
var provider = context.SyntaxProvider.ForAttributeWithMetadataName("CommunityToolkit.Maui.BindablePropertyAttribute",
IsNonEmptyPropertyDeclarationSyntax, SemanticTransform)
.Where(static x => x.ClassInformation != default || !x.BindableProperties.IsEmpty)
.Collect();
context.RegisterSourceOutput(provider, ExecuteAllValues);
}
static void ExecuteAllValues(SourceProductionContext context, ImmutableArray<SemanticValues> semanticValues)
{
// Pre-allocate dictionary with expected capacity
var groupedValues = new Dictionary<(string, string, string, string), List<SemanticValues>>(semanticValues.Length);
// Single-pass grouping without LINQ
foreach (var sv in semanticValues)
{
var key = (sv.ClassInformation.ClassName, sv.ClassInformation.ContainingNamespace, sv.ClassInformation.ContainingTypes, sv.ClassInformation.GenericTypeParameters);
if (!groupedValues.TryGetValue(key, out var list))
{
list = [];
groupedValues[key] = list;
}
list.Add(sv);
}
// Use ArrayPool for temporary storage
var bindablePropertiesBuffer = System.Buffers.ArrayPool<BindablePropertyModel>.Shared.Rent(32);
try
{
foreach (var keyValuePair in groupedValues)
{
var (className, containingNamespace, containingTypes, genericTypeParameters) = keyValuePair.Key;
var values = keyValuePair.Value;
if (values.Count is 0 || string.IsNullOrEmpty(className) || string.IsNullOrEmpty(containingNamespace))
{
continue;
}
// Flatten bindable properties without SelectMany allocation
var bindablePropertiesCount = 0;
foreach (var value in values)
{
foreach (var bp in value.BindableProperties)
{
if (bindablePropertiesCount >= bindablePropertiesBuffer.Length)
{
var newBuffer = System.Buffers.ArrayPool<BindablePropertyModel>.Shared.Rent(bindablePropertiesBuffer.Length * 2);
Array.Copy(bindablePropertiesBuffer, newBuffer, bindablePropertiesBuffer.Length);
System.Buffers.ArrayPool<BindablePropertyModel>.Shared.Return(bindablePropertiesBuffer);
bindablePropertiesBuffer = newBuffer;
}
bindablePropertiesBuffer[bindablePropertiesCount++] = bp;
}
}
var bindableProperties = ImmutableArray.Create(bindablePropertiesBuffer, 0, bindablePropertiesCount);
var classAccessibility = values[0].ClassInformation.DeclaredAccessibility;
var combinedClassInfo = new ClassInformation(className, classAccessibility, containingNamespace, containingTypes, genericTypeParameters);
var combinedValues = new SemanticValues(combinedClassInfo, bindableProperties);
var fileNameSuffix = string.IsNullOrEmpty(containingTypes) ? className : string.Concat(containingTypes, ".", className);
var source = GenerateSource(combinedValues);
SourceStringService.FormatText(ref source);
context.AddSource($"{fileNameSuffix}.g.cs", SourceText.From(source, Encoding.UTF8));
}
}
finally
{
System.Buffers.ArrayPool<BindablePropertyModel>.Shared.Return(bindablePropertiesBuffer);
}
}
static string GenerateSource(SemanticValues value)
{
// Pre-calculate StringBuilder capacity to avoid resizing
var estimatedCapacity = 500 + (value.BindableProperties.Count() * 400);
var sb = new StringBuilder(estimatedCapacity);
// Use string concatenation for simple cases
sb.Append("// <auto-generated>\n// See: CommunityToolkit.Maui.SourceGenerators.Internal.BindablePropertyAttributeSourceGenerator\n\n#pragma warning disable\n#nullable enable\n\n");
if (!IsGlobalNamespace(value.ClassInformation))
{
sb.Append("namespace ").Append(value.ClassInformation.ContainingNamespace).Append(";\n\n");
}
// Generate nested class hierarchy
if (!string.IsNullOrEmpty(value.ClassInformation.ContainingTypes))
{
var containingTypeNames = value.ClassInformation.ContainingTypes.Split('.');
foreach (var typeName in containingTypeNames)
{
sb.Append(value.ClassInformation.DeclaredAccessibility).Append(" partial class ").Append(typeName).Append("\n{\n\n");
}
}
// Get the class name with generic parameters
var classNameWithGenerics = value.ClassInformation.ClassName;
if (!string.IsNullOrEmpty(value.ClassInformation.GenericTypeParameters))
{
classNameWithGenerics = string.Concat(value.ClassInformation.ClassName, "<", value.ClassInformation.GenericTypeParameters, ">");
}
sb.Append(value.ClassInformation.DeclaredAccessibility).Append(" partial class ").Append(classNameWithGenerics).Append("\n{\n\n");
// Prepare helper builder for file-static class members (static flags + default creators)
var fileStaticClassStringBuilder = new StringBuilder(256);
var helperNames = new HashSet<string>();
// Build fully-qualified declaring type name for helper method casts (include containing types)
var fullDeclaringType = string.IsNullOrEmpty(value.ClassInformation.ContainingTypes)
? classNameWithGenerics
: string.Concat(value.ClassInformation.ContainingTypes, ".", classNameWithGenerics);
var fileStaticClassName = $"__{value.ClassInformation.ClassName}BindablePropertyInitHelpers";
foreach (var info in value.BindableProperties)
{
if (info.IsReadOnlyBindableProperty)
{
GenerateReadOnlyBindableProperty(sb, in info, fileStaticClassName);
}
else
{
GenerateBindableProperty(sb, in info, fileStaticClassName);
}
if (info.ShouldUsePropertyInitializer)
{
// Generate only references within the class; actual static field and creator method
// will be placed inside the file static helper class below.
if (helperNames.Add(info.InitializingPropertyName))
{
AppendHelperInitializingField(fileStaticClassStringBuilder, in info);
}
if (helperNames.Add(info.EffectiveDefaultValueCreatorMethodName))
{
AppendHelperDefaultValueMethod(fileStaticClassStringBuilder, in info, fullDeclaringType);
}
}
GenerateProperty(sb, in info, fileStaticClassName);
}
sb.Append('}');
// Close nested class hierarchy
if (!string.IsNullOrEmpty(value.ClassInformation.ContainingTypes))
{
var containingTypeNames = value.ClassInformation.ContainingTypes.Split('.');
for (int i = 0; i < containingTypeNames.Length; i++)
{
sb.Append("\n}");
}
}
// If we generated any helper members, emit a file static class with them.
if (fileStaticClassStringBuilder.Length > 0)
{
sb.Append("\n\nfile static class ").Append(fileStaticClassName).Append("\n{\n");
sb.Append(fileStaticClassStringBuilder.ToString());
sb.Append("}\n");
}
return sb.ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void GenerateReadOnlyBindableProperty(StringBuilder sb, in BindablePropertyModel info, in string fileStaticClassName)
{
// Sanitize the Return Type because Nullable Reference Types cannot be used in the `typeof()` operator
var nonNullableReturnType = ConvertToNonNullableTypeSymbol(info.ReturnType);
var sanitizedPropertyName = IsDotnetKeyword(info.PropertyName) ? string.Concat("@", info.PropertyName) : info.PropertyName;
sb.Append("/// <summary>\r\n/// Backing BindableProperty for the <see cref=\"")
.Append(sanitizedPropertyName)
.Append("\"/> property.\r\n/// </summary>\r\n");
// Generate BindablePropertyKey for read-only properties
sb.Append("static readonly global::Microsoft.Maui.Controls.BindablePropertyKey ")
.Append(info.BindablePropertyKeyName)
.Append(" = \n")
.Append(bpFullName)
.Append(".CreateReadOnly(\"")
.Append(sanitizedPropertyName)
.Append("\", typeof(")
.Append(GetFormattedReturnType(nonNullableReturnType))
.Append("), typeof(")
.Append(info.DeclaringType)
.Append("), null, ")
.Append(info.DefaultBindingMode)
.Append(", ")
.Append(info.ValidateValueMethodName)
.Append(", ")
.Append(info.PropertyChangedMethodName)
.Append(", ")
.Append(info.PropertyChangingMethodName)
.Append(", ")
.Append(info.CoerceValueMethodName)
.Append(", ");
if (info.ShouldUsePropertyInitializer)
{
sb.Append(fileStaticClassName)
.Append('.');
}
sb.Append(info.EffectiveDefaultValueCreatorMethodName)
.Append(");\n");
// Generate public BindableProperty from the key
sb.Append("public ")
.Append(info.NewKeywordText)
.Append("static readonly ")
.Append(bpFullName)
.Append(' ')
.Append(info.BindablePropertyName)
.Append(" = ")
.Append(info.BindablePropertyKeyName)
.Append(".BindableProperty;\n");
sb.Append('\n');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void GenerateBindableProperty(StringBuilder sb, in BindablePropertyModel info, in string helperClassName)
{
// Sanitize the Return Type because Nullable Reference Types cannot be used in the `typeof()` operator
var nonNullableReturnType = ConvertToNonNullableTypeSymbol(info.ReturnType);
var sanitizedPropertyName = IsDotnetKeyword(info.PropertyName) ? string.Concat("@", info.PropertyName) : info.PropertyName;
sb.Append("/// <summary>\r\n/// Backing BindableProperty for the <see cref=\"")
.Append(sanitizedPropertyName)
.Append("\"/> property.\r\n/// </summary>\r\n");
// Generate regular BindableProperty
sb.Append("public ")
.Append(info.NewKeywordText)
.Append("static readonly ")
.Append(bpFullName)
.Append(' ')
.Append(info.BindablePropertyName)
.Append(" = \n")
.Append(bpFullName)
.Append(".Create(\"")
.Append(sanitizedPropertyName)
.Append("\", typeof(")
.Append(GetFormattedReturnType(nonNullableReturnType))
.Append("), typeof(")
.Append(info.DeclaringType)
.Append("), null, ")
.Append(info.DefaultBindingMode)
.Append(", ")
.Append(info.ValidateValueMethodName)
.Append(", ")
.Append(info.PropertyChangedMethodName)
.Append(", ")
.Append(info.PropertyChangingMethodName)
.Append(", ")
.Append(info.CoerceValueMethodName)
.Append(", ");
if (info.ShouldUsePropertyInitializer)
{
sb.Append(helperClassName)
.Append('.');
}
sb.Append(info.EffectiveDefaultValueCreatorMethodName)
.Append(");\n")
.Append('\n');
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void GenerateProperty(StringBuilder sb, in BindablePropertyModel info, in string fileStaticClassName)
{
var sanitizedPropertyName = IsDotnetKeyword(info.PropertyName) ? string.Concat("@", info.PropertyName) : info.PropertyName;
var formattedReturnType = GetFormattedReturnType(info.ReturnType);
sb.Append("public ")
.Append(info.NewKeywordText)
.Append("partial ")
.Append(formattedReturnType)
.Append(' ')
.Append(sanitizedPropertyName)
.Append("\n{\nget => ");
if (info.HasInitializer)
{
if (info.ShouldUsePropertyInitializer)
{
// Now reference the static flag on the file static helper class
sb.Append(fileStaticClassName).Append(".").Append(info.InitializingPropertyName);
}
else
{
sb.Append("false");
}
sb.Append(" ? field : ");
}
sb.Append("(")
.Append(formattedReturnType)
.Append(")GetValue(")
.Append(info.BindablePropertyName)
.Append(");\n");
if (info.SetterAccessibility is not null)
{
sb.Append(info.SetterAccessibility)
.Append("set => SetValue(")
.Append(info.IsReadOnlyBindableProperty ? info.BindablePropertyKeyName : info.BindablePropertyName)
.Append(", value);\n");
}
// else Do not create a Setter because the property is read-only
sb.Append("}\n");
}
static SemanticValues SemanticTransform(GeneratorAttributeSyntaxContext context, CancellationToken cancellationToken)
{
var propertyDeclarationSyntax = Unsafe.As<PropertyDeclarationSyntax>(context.TargetNode);
var semanticModel = context.SemanticModel;
var propertySymbol = (IPropertySymbol?)ModelExtensions.GetDeclaredSymbol(semanticModel, propertyDeclarationSyntax, cancellationToken);
var hasInitializer = propertyDeclarationSyntax.Initializer is not null;
if (propertySymbol is null)
{
return emptySemanticValues;
}
var @namespace = propertySymbol.ContainingNamespace.ToDisplayString();
var className = propertySymbol.ContainingType.Name;
var classAccessibility = propertySymbol.ContainingSymbol.DeclaredAccessibility.ToString().ToLower();
var returnType = propertySymbol.Type;
// Build containing types hierarchy
var containingTypes = GetContainingTypes(propertySymbol.ContainingType);
// Extract generic type parameters
var genericTypeParameters = GetGenericTypeParameters(propertySymbol.ContainingType);
var propertyInfo = new ClassInformation(className, classAccessibility, @namespace, containingTypes, genericTypeParameters);
// Use array instead of List to avoid resizing
var bindablePropertyModels = new BindablePropertyModel[context.Attributes.Length];
var doesContainNewKeyword = HasNewKeyword(propertyDeclarationSyntax);
var (isReadOnlyBindableProperty, setterAccessibility) = GetPropertyAccessibility(propertySymbol, propertyDeclarationSyntax);
var attributeData = context.Attributes[0];
bindablePropertyModels[0] = CreateBindablePropertyModel(attributeData, propertySymbol.ContainingType, propertySymbol.Name, returnType, doesContainNewKeyword, isReadOnlyBindableProperty, setterAccessibility, hasInitializer);
return new(propertyInfo, ImmutableArray.Create(bindablePropertyModels));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool HasNewKeyword(PropertyDeclarationSyntax syntax)
{
foreach (var modifier in syntax.Modifiers)
{
if (modifier.IsKind(SyntaxKind.NewKeyword))
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static (bool IsReadOnlyBindableProperty, string? SetterAccessibility) GetPropertyAccessibility(IPropertySymbol propertySymbol, PropertyDeclarationSyntax syntax)
{
// Check if property is get-only (no setter)
if (propertySymbol.SetMethod is null)
{
return (true, null);
}
return propertySymbol.SetMethod.DeclaredAccessibility switch
{
Accessibility.NotApplicable => throw new NotSupportedException($"The setter type for {propertySymbol.Name} is not yet supported"),
Accessibility.Private => (true, "private "),
Accessibility.ProtectedAndInternal => (true, "private protected "),
Accessibility.Protected => (true, "protected "),
Accessibility.Internal => (false, "internal "),
Accessibility.ProtectedOrInternal => (false, "protected internal "),
Accessibility.Public => (false, " "), // Keep the SetterAccessibility empty because the Property is public and the setter will inherit that accessbility modified, e.g. `public string Test { get; set; }`
_ => throw new NotSupportedException($"The setter type for {propertySymbol.Name} is not yet supported"),
};
}
static string GetContainingTypes(INamedTypeSymbol typeSymbol)
{
var current = typeSymbol.ContainingType;
if (current is null)
{
return string.Empty;
}
var sb = new StringBuilder(100);
var stack = new Stack<string>(4);
while (current is not null)
{
stack.Push(current.Name);
current = current.ContainingType;
}
var first = true;
while (stack.Count > 0)
{
if (!first)
{
sb.Append('.');
}
sb.Append(stack.Pop());
first = false;
}
return sb.ToString();
}
static string GetGenericTypeParameters(INamedTypeSymbol typeSymbol)
{
if (!typeSymbol.IsGenericType || typeSymbol.TypeParameters.IsEmpty)
{
return string.Empty;
}
var typeParams = typeSymbol.TypeParameters;
if (typeParams.Length == 1)
{
return typeParams[0].Name;
}
var sb = new StringBuilder(typeParams.Length * 10);
for (int i = 0; i < typeParams.Length; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(typeParams[i].Name);
}
return sb.ToString();
}
static BindablePropertyModel CreateBindablePropertyModel(in AttributeData attributeData, in INamedTypeSymbol declaringType, in string propertyName, in ITypeSymbol returnType, in bool doesContainNewKeyword, in bool isReadOnly, in string? setterAccessibility, in bool hasInitializer)
{
if (attributeData.AttributeClass is null)
{
throw new ArgumentException($"{nameof(attributeData)}.{nameof(attributeData.AttributeClass)} Cannot Be Null", nameof(attributeData));
}
var coerceValueMethodName = attributeData.GetNamedMethodGroupArgumentsAttributeValueByNameAsString(nameof(BindablePropertyModel.CoerceValueMethodName));
var defaultBindingMode = attributeData.GetNamedTypeArgumentsAttributeValueForDefaultBindingMode(nameof(BindablePropertyModel.DefaultBindingMode), "Microsoft.Maui.Controls.BindingMode.OneWay");
var defaultValueCreatorMethodName = attributeData.GetNamedMethodGroupArgumentsAttributeValueByNameAsString(nameof(BindablePropertyModel.DefaultValueCreatorMethodName));
var propertyChangedMethodName = attributeData.GetNamedMethodGroupArgumentsAttributeValueByNameAsString(nameof(BindablePropertyModel.PropertyChangedMethodName));
var propertyChangingMethodName = attributeData.GetNamedMethodGroupArgumentsAttributeValueByNameAsString(nameof(BindablePropertyModel.PropertyChangingMethodName));
var validateValueMethodName = attributeData.GetNamedMethodGroupArgumentsAttributeValueByNameAsString(nameof(BindablePropertyModel.ValidateValueMethodName));
var newKeywordText = doesContainNewKeyword ? "new " : string.Empty;
return new BindablePropertyModel(propertyName, returnType, declaringType, defaultBindingMode, validateValueMethodName, propertyChangedMethodName, propertyChangingMethodName, coerceValueMethodName, defaultValueCreatorMethodName, newKeywordText, isReadOnly, setterAccessibility, hasInitializer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static ITypeSymbol ConvertToNonNullableTypeSymbol(in ITypeSymbol typeSymbol)
{
// Check for Nullable<T>
if (typeSymbol is INamedTypeSymbol { IsGenericType: true, ConstructedFrom.SpecialType: SpecialType.System_Nullable_T })
{
return typeSymbol;
}
// Check for Nullable Reference Type
if (typeSymbol.NullableAnnotation is NullableAnnotation.Annotated)
{
// For reference types, NullableAnnotation.None indicates non-nullable.
return typeSymbol.WithNullableAnnotation(NullableAnnotation.None);
}
return typeSymbol;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsNonEmptyPropertyDeclarationSyntax(SyntaxNode node, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return node is PropertyDeclarationSyntax { AttributeLists.Count: > 0 };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsDotnetKeyword(in string name) => SyntaxFacts.GetKeywordKind(name) is not SyntaxKind.None;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsGlobalNamespace(in ClassInformation classInformation)
{
return classInformation.ContainingNamespace is "<global namespace>";
}
static string GetFormattedReturnType(ITypeSymbol typeSymbol)
{
if (typeSymbol is IArrayTypeSymbol arrayTypeSymbol)
{
// Get the element type name (e.g., "int")
string elementType = GetFormattedReturnType(arrayTypeSymbol.ElementType);
// Construct the correct rank syntax with commas (e.g., "[,]")
var rank = arrayTypeSymbol.Rank > 1 ? new string(',', arrayTypeSymbol.Rank - 1) : string.Empty;
return string.Concat(elementType, "[", rank, "]");
}
else
{
// Use ToDisplayString with the correct format for the base type (e.g., "int")
return typeSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
}
}
/// <summary>
/// Appends the initializing flag into the file-static helper class.
/// </summary>
/// <param name="fileStaticClassStringBuilder">Helper StringBuilder used to collect helper members.</param>
/// <param name="info">Property model.</param>
static void AppendHelperInitializingField(StringBuilder fileStaticClassStringBuilder, in BindablePropertyModel info)
{
// Make the flag public static so it can be referenced from the generated partial class in the same file.
fileStaticClassStringBuilder.Append("public static bool ")
.Append(info.InitializingPropertyName)
.Append(" = false;\n");
}
/// <summary>
/// Appends a default value creator method into the file-static helper class.
/// The method sets the static initializing flag, reads the property's initializer value by casting the bindable
/// to the declaring type, then clears the flag and returns the value.
/// </summary>
/// <param name="fileStaticClassStringBuilder">Helper StringBuilder used to collect helper members.</param>
/// <param name="info">Property model.</param>
/// <param name="fullDeclaringType">Declaring type including containing types and generic parameters.</param>
static void AppendHelperDefaultValueMethod(StringBuilder fileStaticClassStringBuilder, in BindablePropertyModel info, string fullDeclaringType)
{
var sanitizedPropertyName = IsDotnetKeyword(info.PropertyName) ? string.Concat("@", info.PropertyName) : info.PropertyName;
fileStaticClassStringBuilder.Append("public static object ")
.Append(info.EffectiveDefaultValueCreatorMethodName)
.Append("(global::Microsoft.Maui.Controls.BindableObject bindable)\n")
.Append("{\n")
.Append(info.InitializingPropertyName)
.Append(" = true;\n")
.Append("var defaultValue = ((")
.Append(fullDeclaringType)
.Append(")bindable).")
.Append(sanitizedPropertyName)
.Append(";\n")
.Append(info.InitializingPropertyName)
.Append(" = false;\n")
.Append("return defaultValue;\n")
.Append("}\n\n");
}
}