Skip to content

Commit 1bef046

Browse files
committed
Use ImmutableArrayBuilder<T> in all generators
1 parent 8dd1387 commit 1bef046

11 files changed

+91
-102
lines changed

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/INotifyPropertyChangedGenerator.cs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Collections.Immutable;
66
using System.Linq;
77
using CommunityToolkit.Mvvm.SourceGenerators.Extensions;
8+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
89
using CommunityToolkit.Mvvm.SourceGenerators.Input.Models;
910
using CommunityToolkit.Mvvm.SourceGenerators.Models;
1011
using Microsoft.CodeAnalysis;
@@ -65,9 +66,17 @@ protected override ImmutableArray<MemberDeclarationSyntax> FilterDeclaredMembers
6566
// If requested, only include the event and the basic methods to raise it, but not the additional helpers
6667
if (!info.IncludeAdditionalHelperMethods)
6768
{
68-
return memberDeclarations.Where(static member => member
69-
is EventFieldDeclarationSyntax
70-
or MethodDeclarationSyntax { Identifier.ValueText: "OnPropertyChanged" }).ToImmutableArray();
69+
using ImmutableArrayBuilder<MemberDeclarationSyntax>.Lease selectedMembers = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
70+
71+
foreach (MemberDeclarationSyntax memberDeclaration in memberDeclarations)
72+
{
73+
if (memberDeclaration is EventFieldDeclarationSyntax or MethodDeclarationSyntax { Identifier.ValueText: "OnPropertyChanged" })
74+
{
75+
selectedMembers.Add(memberDeclaration);
76+
}
77+
}
78+
79+
return selectedMembers.ToImmutable();
7180
}
7281

7382
return memberDeclarations;

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/Models/AttributeInfo.cs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,22 +32,25 @@ public static AttributeInfo From(AttributeData attributeData)
3232
{
3333
string typeName = attributeData.AttributeClass!.GetFullyQualifiedName();
3434

35+
using ImmutableArrayBuilder<TypedConstantInfo>.Lease constructorArguments = ImmutableArrayBuilder<TypedConstantInfo>.Rent();
36+
using ImmutableArrayBuilder<(string, TypedConstantInfo)>.Lease namedArguments = ImmutableArrayBuilder<(string, TypedConstantInfo)>.Rent();
37+
3538
// Get the constructor arguments
36-
ImmutableArray<TypedConstantInfo> constructorArguments =
37-
attributeData.ConstructorArguments
38-
.Select(TypedConstantInfo.From)
39-
.ToImmutableArray();
39+
foreach (TypedConstant typedConstant in attributeData.ConstructorArguments)
40+
{
41+
constructorArguments.Add(TypedConstantInfo.From(typedConstant));
42+
}
4043

4144
// Get the named arguments
42-
ImmutableArray<(string, TypedConstantInfo)> namedArguments =
43-
attributeData.NamedArguments
44-
.Select(static arg => (arg.Key, TypedConstantInfo.From(arg.Value)))
45-
.ToImmutableArray();
45+
foreach (KeyValuePair<string, TypedConstant> namedConstant in attributeData.NamedArguments)
46+
{
47+
namedArguments.Add((namedConstant.Key, TypedConstantInfo.From(namedConstant.Value)));
48+
}
4649

4750
return new(
4851
typeName,
49-
constructorArguments,
50-
namedArguments);
52+
constructorArguments.ToImmutable(),
53+
namedArguments.ToImmutable());
5154
}
5255

5356
/// <summary>
@@ -62,8 +65,8 @@ public static AttributeInfo From(INamedTypeSymbol typeSymbol, SemanticModel sema
6265
{
6366
string typeName = typeSymbol.GetFullyQualifiedName();
6467

65-
ImmutableArray<TypedConstantInfo>.Builder constructorArguments = ImmutableArray.CreateBuilder<TypedConstantInfo>();
66-
ImmutableArray<(string, TypedConstantInfo)>.Builder namedArguments = ImmutableArray.CreateBuilder<(string, TypedConstantInfo)>();
68+
using ImmutableArrayBuilder<TypedConstantInfo>.Lease constructorArguments = ImmutableArrayBuilder<TypedConstantInfo>.Rent();
69+
using ImmutableArrayBuilder<(string, TypedConstantInfo)>.Lease namedArguments = ImmutableArrayBuilder<(string, TypedConstantInfo)>.Rent();
6770

6871
foreach (AttributeArgumentSyntax argument in arguments)
6972
{

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/Models/TypedConstantInfo.Factory.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Collections.Immutable;
77
using System.Linq;
88
using System.Threading;
9+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
910
using Microsoft.CodeAnalysis;
1011
using Microsoft.CodeAnalysis.CSharp.Syntax;
1112
using Microsoft.CodeAnalysis.Operations;
@@ -127,7 +128,7 @@ public static TypedConstantInfo From(
127128
return new Array(elementTypeName, ImmutableArray<TypedConstantInfo>.Empty);
128129
}
129130

130-
ImmutableArray<TypedConstantInfo>.Builder items = ImmutableArray.CreateBuilder<TypedConstantInfo>(initializerExpression.Expressions.Count);
131+
using ImmutableArrayBuilder<TypedConstantInfo>.Lease items = ImmutableArrayBuilder<TypedConstantInfo>.Rent();
131132

132133
// Enumerate all array elements and extract serialized info for them
133134
foreach (ExpressionSyntax initializationExpression in initializerExpression.Expressions)
@@ -140,7 +141,7 @@ public static TypedConstantInfo From(
140141
items.Add(From(initializationOperation, semanticModel, initializationExpression, token));
141142
}
142143

143-
return new Array(elementTypeName, items.MoveToImmutable());
144+
return new Array(elementTypeName, items.ToImmutable());
144145
}
145146

146147
throw new ArgumentException("Invalid attribute argument value");

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservablePropertyGenerator.Execute.cs

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using System.Threading;
1111
using CommunityToolkit.Mvvm.SourceGenerators.ComponentModel.Models;
1212
using CommunityToolkit.Mvvm.SourceGenerators.Extensions;
13+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
1314
using CommunityToolkit.Mvvm.SourceGenerators.Models;
1415
using Microsoft.CodeAnalysis;
1516
using Microsoft.CodeAnalysis.CSharp;
@@ -45,7 +46,7 @@ public static bool TryGetInfo(
4546
[NotNullWhen(true)] out PropertyInfo? propertyInfo,
4647
out ImmutableArray<DiagnosticInfo> diagnostics)
4748
{
48-
ImmutableArray<DiagnosticInfo>.Builder builder = ImmutableArray.CreateBuilder<DiagnosticInfo>();
49+
using ImmutableArrayBuilder<DiagnosticInfo>.Lease builder = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
4950

5051
// Validate the target type
5152
if (!IsTargetTypeValid(fieldSymbol, out bool shouldInvokeOnPropertyChanging))
@@ -100,10 +101,11 @@ public static bool TryGetInfo(
100101
return false;
101102
}
102103

103-
ImmutableArray<string>.Builder propertyChangedNames = ImmutableArray.CreateBuilder<string>();
104-
ImmutableArray<string>.Builder propertyChangingNames = ImmutableArray.CreateBuilder<string>();
105-
ImmutableArray<string>.Builder notifiedCommandNames = ImmutableArray.CreateBuilder<string>();
106-
ImmutableArray<AttributeInfo>.Builder forwardedAttributes = ImmutableArray.CreateBuilder<AttributeInfo>();
104+
using ImmutableArrayBuilder<string>.Lease propertyChangedNames = ImmutableArrayBuilder<string>.Rent();
105+
using ImmutableArrayBuilder<string>.Lease propertyChangingNames = ImmutableArrayBuilder<string>.Rent();
106+
using ImmutableArrayBuilder<string>.Lease notifiedCommandNames = ImmutableArrayBuilder<string>.Rent();
107+
using ImmutableArrayBuilder<AttributeInfo>.Lease forwardedAttributes = ImmutableArrayBuilder<AttributeInfo>.Rent();
108+
107109
bool notifyRecipients = false;
108110
bool notifyDataErrorInfo = false;
109111
bool hasOrInheritsClassLevelNotifyPropertyChangedRecipients = false;
@@ -137,22 +139,22 @@ public static bool TryGetInfo(
137139
foreach (AttributeData attributeData in fieldSymbol.GetAttributes())
138140
{
139141
// Gather dependent property and command names
140-
if (TryGatherDependentPropertyChangedNames(fieldSymbol, attributeData, propertyChangedNames, builder) ||
141-
TryGatherDependentCommandNames(fieldSymbol, attributeData, notifiedCommandNames, builder))
142+
if (TryGatherDependentPropertyChangedNames(fieldSymbol, attributeData, in propertyChangedNames, in builder) ||
143+
TryGatherDependentCommandNames(fieldSymbol, attributeData, in notifiedCommandNames, in builder))
142144
{
143145
continue;
144146
}
145147

146148
// Check whether the property should also notify recipients
147-
if (TryGetIsNotifyingRecipients(fieldSymbol, attributeData, builder, hasOrInheritsClassLevelNotifyPropertyChangedRecipients, out isBroadcastTargetValid))
149+
if (TryGetIsNotifyingRecipients(fieldSymbol, attributeData, in builder, hasOrInheritsClassLevelNotifyPropertyChangedRecipients, out isBroadcastTargetValid))
148150
{
149151
notifyRecipients = isBroadcastTargetValid;
150152

151153
continue;
152154
}
153155

154156
// Check whether the property should also be validated
155-
if (TryGetNotifyDataErrorInfo(fieldSymbol, attributeData, builder, hasOrInheritsClassLevelNotifyDataErrorInfo, out isValidationTargetValid))
157+
if (TryGetNotifyDataErrorInfo(fieldSymbol, attributeData, in builder, hasOrInheritsClassLevelNotifyDataErrorInfo, out isValidationTargetValid))
156158
{
157159
notifyDataErrorInfo = isValidationTargetValid;
158160

@@ -266,9 +268,7 @@ public static bool TryGetInfo(
266268
/// <param name="fieldSymbol">The input <see cref="IFieldSymbol"/> instance to process.</param>
267269
/// <param name="shouldInvokeOnPropertyChanging">Whether or not property changing events should also be raised.</param>
268270
/// <returns>Whether or not the containing type for <paramref name="fieldSymbol"/> is valid.</returns>
269-
private static bool IsTargetTypeValid(
270-
IFieldSymbol fieldSymbol,
271-
out bool shouldInvokeOnPropertyChanging)
271+
private static bool IsTargetTypeValid(IFieldSymbol fieldSymbol, out bool shouldInvokeOnPropertyChanging)
272272
{
273273
// The [ObservableProperty] attribute can only be used in types that are known to expose the necessary OnPropertyChanged and OnPropertyChanging methods.
274274
// That means that the containing type for the field needs to match one of the following conditions:
@@ -318,8 +318,8 @@ private static bool IsGeneratedPropertyInvalid(string propertyName, ITypeSymbol
318318
private static bool TryGatherDependentPropertyChangedNames(
319319
IFieldSymbol fieldSymbol,
320320
AttributeData attributeData,
321-
ImmutableArray<string>.Builder propertyChangedNames,
322-
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
321+
in ImmutableArrayBuilder<string>.Lease propertyChangedNames,
322+
in ImmutableArrayBuilder<DiagnosticInfo>.Lease diagnostics)
323323
{
324324
// Validates a property name using existing properties
325325
bool IsPropertyNameValid(string propertyName)
@@ -383,8 +383,8 @@ bool IsPropertyNameValidWithGeneratedMembers(string propertyName)
383383
private static bool TryGatherDependentCommandNames(
384384
IFieldSymbol fieldSymbol,
385385
AttributeData attributeData,
386-
ImmutableArray<string>.Builder notifiedCommandNames,
387-
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
386+
in ImmutableArrayBuilder<string>.Lease notifiedCommandNames,
387+
in ImmutableArrayBuilder<DiagnosticInfo>.Lease diagnostics)
388388
{
389389
// Validates a command name using existing properties
390390
bool IsCommandNameValid(string commandName, out bool shouldLookForGeneratedMembersToo)
@@ -505,7 +505,7 @@ private static bool TryGetIsNotifyingRecipients(IFieldSymbol fieldSymbol, out bo
505505
private static bool TryGetIsNotifyingRecipients(
506506
IFieldSymbol fieldSymbol,
507507
AttributeData attributeData,
508-
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
508+
in ImmutableArrayBuilder<DiagnosticInfo>.Lease diagnostics,
509509
bool hasOrInheritsClassLevelNotifyPropertyChangedRecipients,
510510
out bool isBroadcastTargetValid)
511511
{
@@ -608,7 +608,7 @@ private static bool TryGetNotifyDataErrorInfo(IFieldSymbol fieldSymbol, out bool
608608
private static bool TryGetNotifyDataErrorInfo(
609609
IFieldSymbol fieldSymbol,
610610
AttributeData attributeData,
611-
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
611+
in ImmutableArrayBuilder<DiagnosticInfo>.Lease diagnostics,
612612
bool hasOrInheritsClassLevelNotifyDataErrorInfo,
613613
out bool isValidationTargetValid)
614614
{
@@ -701,7 +701,7 @@ private static bool TryGetNotifyDataErrorInfo(
701701
/// <returns>The generated <see cref="MemberDeclarationSyntax"/> instance for <paramref name="propertyInfo"/>.</returns>
702702
public static MemberDeclarationSyntax GetPropertySyntax(PropertyInfo propertyInfo)
703703
{
704-
ImmutableArray<StatementSyntax>.Builder setterStatements = ImmutableArray.CreateBuilder<StatementSyntax>();
704+
using ImmutableArrayBuilder<StatementSyntax>.Lease setterStatements = ImmutableArrayBuilder<StatementSyntax>.Rent();
705705

706706
// Get the property type syntax
707707
TypeSyntax propertyType = IdentifierName(propertyInfo.TypeNameWithNullabilityAnnotations);
@@ -848,7 +848,7 @@ public static MemberDeclarationSyntax GetPropertySyntax(PropertyInfo propertyInf
848848
.AddArgumentListArguments(
849849
Argument(fieldExpression),
850850
Argument(IdentifierName("value")))),
851-
Block(setterStatements));
851+
Block(setterStatements.ToArray()));
852852

853853
// Prepare the forwarded attributes, if any
854854
ImmutableArray<AttributeListSyntax> forwardedAttributes =

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableRecipientGenerator.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Linq;
77
using CommunityToolkit.Mvvm.SourceGenerators.ComponentModel.Models;
88
using CommunityToolkit.Mvvm.SourceGenerators.Extensions;
9+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
910
using CommunityToolkit.Mvvm.SourceGenerators.Input.Models;
1011
using CommunityToolkit.Mvvm.SourceGenerators.Models;
1112
using Microsoft.CodeAnalysis;
@@ -91,7 +92,7 @@ public ObservableRecipientGenerator()
9192
/// <inheritdoc/>
9293
protected override ImmutableArray<MemberDeclarationSyntax> FilterDeclaredMembers(ObservableRecipientInfo info, ImmutableArray<MemberDeclarationSyntax> memberDeclarations)
9394
{
94-
ImmutableArray<MemberDeclarationSyntax>.Builder builder = ImmutableArray.CreateBuilder<MemberDeclarationSyntax>();
95+
using ImmutableArrayBuilder<MemberDeclarationSyntax>.Lease builder = ImmutableArrayBuilder<MemberDeclarationSyntax>.Rent();
9596

9697
// If the target type has no constructors, generate constructors as well
9798
if (!info.HasExplicitConstructors)

CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableValidatorValidateAllPropertiesGenerator.Execute.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Collections.Immutable;
77
using System.Linq;
88
using CommunityToolkit.Mvvm.SourceGenerators.Extensions;
9+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
910
using CommunityToolkit.Mvvm.SourceGenerators.Input.Models;
1011
using Microsoft.CodeAnalysis;
1112
using Microsoft.CodeAnalysis.CSharp;
@@ -39,7 +40,7 @@ public static bool IsObservableValidator(INamedTypeSymbol typeSymbol)
3940
/// <returns>The resulting <see cref="ValidationInfo"/> instance for <paramref name="typeSymbol"/>.</returns>
4041
public static ValidationInfo GetInfo(INamedTypeSymbol typeSymbol)
4142
{
42-
ImmutableArray<string>.Builder propertyNames = ImmutableArray.CreateBuilder<string>();
43+
using ImmutableArrayBuilder<string>.Lease propertyNames = ImmutableArrayBuilder<string>.Rent();
4344

4445
foreach (ISymbol memberSymbol in typeSymbol.GetMembers())
4546
{
@@ -92,7 +93,7 @@ public static ValidationInfo GetInfo(INamedTypeSymbol typeSymbol)
9293
/// <returns>A <see cref="RecipientInfo"/> instance for the current type being inspected.</returns>
9394
public static RecipientInfo GetInfo(INamedTypeSymbol typeSymbol, ImmutableArray<INamedTypeSymbol> interfaceSymbols)
9495
{
95-
ImmutableArray<string>.Builder names = ImmutableArray.CreateBuilder<string>(interfaceSymbols.Length);
96+
using ImmutableArrayBuilder<string>.Lease names = ImmutableArrayBuilder<string>.Rent();
9697

9798
foreach (INamedTypeSymbol interfaceSymbol in interfaceSymbols)
9899
{
@@ -102,7 +103,7 @@ public static RecipientInfo GetInfo(INamedTypeSymbol typeSymbol, ImmutableArray<
102103
return new(
103104
typeSymbol.GetFullMetadataNameForFileName(),
104105
typeSymbol.GetFullyQualifiedName(),
105-
names.MoveToImmutable());
106+
names.ToImmutable());
106107
}
107108

108109
/// <summary>
@@ -112,8 +113,7 @@ public static RecipientInfo GetInfo(INamedTypeSymbol typeSymbol, ImmutableArray<
112113
/// <returns>The head <see cref="CompilationUnitSyntax"/> instance with the type attributes.</returns>
113114
public static CompilationUnitSyntax GetSyntax(bool isDynamicallyAccessedMembersAttributeAvailable)
114115
{
115-
int numberOfAttributes = 5 + (isDynamicallyAccessedMembersAttributeAvailable ? 1 : 0);
116-
ImmutableArray<AttributeListSyntax>.Builder attributes = ImmutableArray.CreateBuilder<AttributeListSyntax>(numberOfAttributes);
116+
using ImmutableArrayBuilder<AttributeListSyntax>.Lease attributes = ImmutableArrayBuilder<AttributeListSyntax>.Rent();
117117

118118
// Prepare the base attributes with are always present:
119119
//
@@ -171,7 +171,7 @@ public static CompilationUnitSyntax GetSyntax(bool isDynamicallyAccessedMembersA
171171
Token(SyntaxKind.InternalKeyword),
172172
Token(SyntaxKind.StaticKeyword),
173173
Token(SyntaxKind.PartialKeyword))
174-
.AddAttributeLists(attributes.MoveToImmutable().ToArray())))
174+
.AddAttributeLists(attributes.ToArray())))
175175
.NormalizeWhitespace();
176176
}
177177

@@ -261,7 +261,7 @@ public static CompilationUnitSyntax GetSyntax(ValidationInfo validationInfo)
261261
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to validate declared properties.</returns>
262262
private static ImmutableArray<StatementSyntax> EnumerateValidationStatements(ValidationInfo validationInfo)
263263
{
264-
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>(validationInfo.PropertyNames.Length);
264+
using ImmutableArrayBuilder<StatementSyntax>.Lease statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
265265

266266
// This loop produces a sequence of statements as follows:
267267
//
@@ -294,7 +294,7 @@ private static ImmutableArray<StatementSyntax> EnumerateValidationStatements(Val
294294
IdentifierName(propertyName))))))));
295295
}
296296

297-
return statements.MoveToImmutable();
297+
return statements.ToImmutable();
298298
}
299299
}
300300
}

0 commit comments

Comments
 (0)