Skip to content

Commit

Permalink
Use collection expressions (#76534)
Browse files Browse the repository at this point in the history
  • Loading branch information
CyrusNajmabadi authored Jan 2, 2025
2 parents 98ea496 + 7052f5a commit 7d33556
Show file tree
Hide file tree
Showing 558 changed files with 1,808 additions and 1,929 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ public static ImmutableArray<ImmutableArray<StatementSyntax>> GetSubsequentUnrea
switch (firstUnreachableStatement.Parent)
{
case BlockSyntax block:
siblingStatements = ImmutableArray.CreateRange(block.Statements);
siblingStatements = [.. block.Statements];
break;

case SwitchSectionSyntax switchSection:
siblingStatements = ImmutableArray.CreateRange(switchSection.Statements);
siblingStatements = [.. switchSection.Statements];
break;

case GlobalStatementSyntax globalStatement:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal sealed class CSharpAddDocCommentNodesCodeFixProvider()
protected override string NodeName { get; } = "param";

protected override List<XmlNameAttributeSyntax> GetNameAttributes(XmlElementSyntax node)
=> node.StartTag.Attributes.OfType<XmlNameAttributeSyntax>().ToList();
=> [.. node.StartTag.Attributes.OfType<XmlNameAttributeSyntax>()];

protected override string GetValueFromNameAttribute(XmlNameAttributeSyntax attribute)
=> attribute.Identifier.Identifier.ValueText;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,16 @@ private ITypeParameterSymbol GetMethodTypeParameter(TypeSyntax type, Cancellatio
}

protected override ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken)
=> _invocationExpression.ArgumentList.Arguments.Select(a => a.GetRefKind()).ToImmutableArray();
=> [.. _invocationExpression.ArgumentList.Arguments.Select(a => a.GetRefKind())];

protected override ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken)
=> _invocationExpression.ArgumentList.Arguments.Select(a => DetermineParameterType(a, cancellationToken)).ToImmutableArray();
=> [.. _invocationExpression.ArgumentList.Arguments.Select(a => DetermineParameterType(a, cancellationToken))];

private ITypeSymbol DetermineParameterType(ArgumentSyntax argument, CancellationToken cancellationToken)
=> argument.DetermineParameterType(Document.SemanticModel, cancellationToken);

protected override ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken)
=> _invocationExpression.ArgumentList.Arguments.Select(a => false).ToImmutableArray();
=> [.. _invocationExpression.ArgumentList.Arguments.Select(a => false)];

protected override bool IsIdentifierName()
=> State.SimpleNameOpt.Kind() == SyntaxKind.IdentifierName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ private static ImmutableArray<StatementSyntax> GetStatements(SyntaxNode pseudoBl
return [.. switchSection.Statements];

if (pseudoBlock is CompilationUnitSyntax compilationUnit)
return compilationUnit.Members.OfType<GlobalStatementSyntax>().Select(g => g.Statement).ToImmutableArray();
return [.. compilationUnit.Members.OfType<GlobalStatementSyntax>().Select(g => g.Statement)];

return [];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ private static CompilationUnitSyntax MoveUsingsOutsideNamespaces(CompilationUnit
var usingsToAdd = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace)
.Select(directive => directive.WithAdditionalAnnotations(Formatter.Annotation, s_warningAnnotation));

var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, usingsToAdd.ToImmutableArray());
var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, [.. usingsToAdd]);

// Update the compilation unit with the usings from the namespace declaration.
var newUsings = compilationUnitWithReplacedNamespaces.Usings.AddRange(deduplicatedUsings);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ protected override async Task FixAllAsync(
currentRoot = ReplaceReferences(
document, currentRoot,
delegateType, parameterList,
references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray());
[.. references.Select(node => currentRoot.GetCurrentNode(node))]);
}

editor.ReplaceNode(root, currentRoot);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,13 @@ private class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
#pragma warning disable RS0030 // Do not used banned APIs
=> ImmutableArray.Create(new DiagnosticDescriptor(
=> [new DiagnosticDescriptor(
"CS8865",
"Only records may inherit from records.",
"Only records may inherit from records.",
"Compiler error",
DiagnosticSeverity.Error,
isEnabledByDefault: true));
isEnabledByDefault: true)];
#pragma warning restore RS0030 // Do not used banned APIs

public override void Initialize(AnalysisContext context)
Expand Down
4 changes: 2 additions & 2 deletions src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ class C
{
{{camelCaseSymbol}}
}
""", new TestParameters(options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(alternateAccessibility))));
""", new TestParameters(options: s_options.AccessibilitiesArePascalCase([alternateAccessibility])));

await TestInRegularAndScriptAsync(
$$"""
Expand All @@ -286,7 +286,7 @@ class C
{
{{pascalCaseSymbol}}
}
""", options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(accessibility)));
""", options: s_options.AccessibilitiesArePascalCase([accessibility]));
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,15 +351,15 @@ private static (ImmutableArray<string> userIdExclusions, ImmutableArray<string>
{
case "":
case null:
return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false);
return (userIdExclusions: [], userCategoryExclusions: [], analyzerDisabled: false);

case "all":
return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: true);
return (userIdExclusions: [], userCategoryExclusions: [], analyzerDisabled: true);

default:
// Default string representation for unconfigured option value should be treated as no exclusions.
if (userExclusions == CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions.DefaultValue)
return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false);
return (userIdExclusions: [], userCategoryExclusions: [], analyzerDisabled: false);

break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ private CompilationAnalyzer(
_eventArgsType = compilation.EventArgsType();
_iNotifyCompletionType = compilation.GetBestTypeByMetadataName(typeof(INotifyCompletion).FullName!);
_deserializationConstructorCheck = new DeserializationConstructorCheck(compilation);
_attributeSetForMethodsToIgnore = ImmutableHashSet.CreateRange<INamedTypeSymbol?>(GetAttributesForMethodsToIgnore(compilation));
_attributeSetForMethodsToIgnore = [.. GetAttributesForMethodsToIgnore(compilation)];
}

private static Location GetDiagnosticLocation(ISymbol symbol)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ private AccessedFields GetGetterFields(
using var _ = PooledHashSet<IFieldSymbol>.GetInstance(out var set);
AddAccessedFields(semanticModel, getMethod, fieldNames, set, cancellationToken);

return new(TrivialField: null, set.ToImmutableArray());
return new(TrivialField: null, [.. set]);
}

private AccessedFields GetSetterFields(
Expand All @@ -291,7 +291,7 @@ private AccessedFields GetSetterFields(
using var _ = PooledHashSet<IFieldSymbol>.GetInstance(out var set);
AddAccessedFields(semanticModel, setMethod, fieldNames, set, cancellationToken);

return new(TrivialField: null, set.ToImmutableArray());
return new(TrivialField: null, [.. set]);
}

private IFieldSymbol? CheckFieldAccessExpression(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,9 @@ private static async Task<ImmutableArray<IMethodSymbol>> FindMethodDeclarationRe
var referencedSymbols = await SymbolFinder.FindReferencesAsync(
method, invocationDocument.Project.Solution, cancellationToken).ConfigureAwait(false);

return referencedSymbols.Select(referencedSymbol => referencedSymbol.Definition)
return [.. referencedSymbols.Select(referencedSymbol => referencedSymbol.Definition)
.OfType<IMethodSymbol>()
.Distinct()
.ToImmutableArray();
.Distinct()];
}

private static IParameterSymbol CreateParameterSymbol(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,9 @@ private List<TXmlElementSyntax> GetElementNodes(SyntaxNode docComment, string no
// If we don't find any, then fallback to the first element node at any depth with the requested name.
if (!nodes.Any())
{
nodes = docComment.DescendantNodes(descendIntoChildren: _ => true)
nodes = [.. docComment.DescendantNodes(descendIntoChildren: _ => true)
.OfType<TXmlElementSyntax>()
.Where(w => GetXmlElementLocalName(w) == nodeName)
.ToList();
.Where(w => GetXmlElementLocalName(w) == nodeName)];
}

return nodes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ private async Task<bool> TryInitializeDelegatedConstructorAsync(CancellationToke
var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray();
var remainingParameterNames = _service.GenerateParameterNames(
_document, remainingArguments,
delegatedConstructor.Parameters.Select(p => p.Name).ToList(),
[.. delegatedConstructor.Parameters.Select(p => p.Name)],
_parameterNamingRule,
cancellationToken);

Expand Down Expand Up @@ -287,7 +287,7 @@ internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancell
var semanticModel = _document.SemanticModel;
var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken));

return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray();
return [.. allTypes.Select(t => FixType(t, semanticModel, allTypeParameters))];
}

private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@ private ImmutableArray<ParameterName> GenerateParameterNames(

var syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var comparer = syntaxFacts.StringComparer;
return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n)))
return [.. NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n)))
.Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule))
.Skip(reservedNames.Count).ToImmutableArray();
.Skip(reservedNames.Count)];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,10 @@ private ImmutableArray<ISymbol> GenerateMembers(
ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
CancellationToken cancellationToken)
{
return _unimplementedMembers
return [.. _unimplementedMembers
.SelectMany(t => t.members)
.Select(m => GenerateMember(compilation, m, throughMember, propertyGenerationBehavior, cancellationToken))
.WhereNotNull()
.ToImmutableArray();
.WhereNotNull()];
}

private ISymbol? GenerateMember(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ protected SyntaxTriviaList CreateCommentTrivia(
trivia.Add(this.SyntaxGeneratorInternal.ElasticCarriageReturnLineFeed);
}

return new SyntaxTriviaList(trivia);
return [.. trivia];
}

public async Task<Document> ImplementInterfaceAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private static async Task<Solution> RemoveAwaitFromCallersAsync(
if (referencedSymbol != null)
{
return await RemoveAwaitFromCallersAsync(
document.Project.Solution, referencedSymbol.Locations.ToImmutableArray(), cancellationToken).ConfigureAwait(false);
document.Project.Solution, [.. referencedSymbol.Locations], cancellationToken).ConfigureAwait(false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ private static SyntaxTriviaList UpdateLeadingTrivia(ISyntaxKindsService syntaxKi
currentStart++;
}

return new SyntaxTriviaList(builder.ToImmutable());
return [.. builder.ToImmutable()];
}

private static bool IsEndOfLine(ISyntaxKindsService syntaxKinds, SyntaxTriviaList triviaList, int index)
Expand Down
2 changes: 1 addition & 1 deletion src/CodeStyle/Tools/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public static int Main(string[] args)
var language = args[0];
var outputDir = args[1];
var targetsFileName = args[2];
var assemblyList = args[3].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray();
var assemblyList = args[3].Split([';'], StringSplitOptions.RemoveEmptyEntries).ToImmutableArray();

CreateGlobalConfigFiles(language, outputDir, assemblyList);
CreateTargetsFile(language, outputDir, targetsFileName);
Expand Down
Loading

0 comments on commit 7d33556

Please sign in to comment.