Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Special case inlining a collection expr into a spreaded element #76823

Merged
merged 3 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.InlineTemporary;
using Microsoft.CodeAnalysis.Shared.Extensions;
Expand All @@ -24,6 +25,8 @@

namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary;

using static SyntaxFactory;

[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InlineTemporary), Shared]
[method: ImportingConstructor]
[method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
Expand Down Expand Up @@ -159,11 +162,11 @@ private static async Task<Document> InlineTemporaryAsync(Document document, Vari

// Checks to see if inlining the temporary variable may change the code's meaning. This can only apply if the variable has two or more
// references. We later use this heuristic to determine whether or not to display a warning message to the user.
var mayContainSideEffects = allReferences.Count() > 1 &&
var mayContainSideEffects = allReferences.Length > 1 &&
MayContainSideEffects(declarator.Initializer.Value);

var scope = GetScope(declarator);
var newScope = ReferenceRewriter.Visit(scope, conflictReferences, nonConflictReferences, expressionToInline, cancellationToken);
var newScope = RewriteScope(scope);

document = await document.ReplaceNodeAsync(scope, newScope, cancellationToken).ConfigureAwait(false);

Expand Down Expand Up @@ -209,6 +212,72 @@ private static async Task<Document> InlineTemporaryAsync(Document document, Vari
}, cancellationToken).ConfigureAwait(false);

return document;

SyntaxNode RewriteScope(SyntaxNode scope)
{
var editor = new SyntaxEditor(scope, document.Project.Solution.Services);

foreach (var identifier in conflictReferences)
editor.ReplaceNode(identifier, identifier.WithAdditionalAnnotations(CreateConflictAnnotation()));

foreach (var identifier in nonConflictReferences)
{
if (identifier.Parent is AnonymousObjectMemberDeclaratorSyntax { NameEquals: null } anonymousMember)
{
// Special case inlining into anonymous types to ensure that we keep property names:
//
// E.g.
// int x = 42;
// var a = new { x; };
//
// Should become:
// var a = new { x = 42; };
editor.ReplaceNode(
anonymousMember,
anonymousMember.Update(NameEquals(identifier), expressionToInline).WithTriviaFrom(anonymousMember));
}
else if (identifier.Parent is ArgumentSyntax
{
Parent: TupleExpressionSyntax tupleExpression,
NameColon: null,
} argument &&
!SyntaxFacts.IsReservedTupleElementName(identifier.Identifier.ValueText) &&
tupleExpression.Arguments.Count(a => nonConflictReferences.Contains(a.Expression)) == 1)
{
Comment on lines +239 to +246
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indentation seems off here.

Suggested change
else if (identifier.Parent is ArgumentSyntax
{
Parent: TupleExpressionSyntax tupleExpression,
NameColon: null,
} argument &&
!SyntaxFacts.IsReservedTupleElementName(identifier.Identifier.ValueText) &&
tupleExpression.Arguments.Count(a => nonConflictReferences.Contains(a.Expression)) == 1)
{
else if (identifier.Parent is ArgumentSyntax
{
Parent: TupleExpressionSyntax tupleExpression,
NameColon: null,
} argument &&
!SyntaxFacts.IsReservedTupleElementName(identifier.Identifier.ValueText) &&
tupleExpression.Arguments.Count(a => nonConflictReferences.Contains(a.Expression)) == 1)
{

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Formatter doesn't like that, and gives an ide0055 error :+)

// Special case inlining into tuples to ensure that we keep property names:
//
// E.g.
// int x = 42;
// var a = (x, y);
//
// Should become:
// var a = (x: 42, y);
editor.ReplaceNode(
argument,
argument.Update(NameColon(identifier), argument.RefKindKeyword, expressionToInline).WithTriviaFrom(argument));
}
else if (identifier.Parent is SpreadElementSyntax spreadElement &&
declarator.Initializer.Value is CollectionExpressionSyntax collectionToInline)
{
// Special case inlining a collection into a spread element. We can just move the original elements
// into the final collection.
var leadingTrivia = spreadElement.GetLeadingTrivia() is [.., (kind: SyntaxKind.WhitespaceTrivia) space]
? TriviaList(ElasticMarker, space)
: TriviaList(ElasticMarker);

editor.ReplaceNode(
spreadElement,
(_, _) => collectionToInline.Elements.Select(
e => e.WithLeadingTrivia(leadingTrivia)));
}
else
{
editor.ReplaceNode(identifier, expressionToInline.WithTriviaFrom(identifier));
}
}

return editor.GetChangedRoot();
}
}

private static bool MayContainSideEffects(SyntaxNode expression)
Expand Down
38 changes: 38 additions & 0 deletions src/Features/CSharpTest/InlineTemporary/InlineTemporaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5911,4 +5911,42 @@ void M(string[] args)
}
""");
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73148")]
public async Task InlineCollectionIntoSpread()
{
await TestInRegularAndScriptAsync(
"""
using System;
class A
{
void M(string[] args)
{
string[] [||]eStaticSymbols = [
"System.Int32 E.StaticProperty { get; }",
"event System.Action E.StaticEvent",
.. args];

string[] allStaticSymbols = [
.. eStaticSymbols,
"System.Int32 E2.StaticProperty { get; }"];
}
}
""",
"""
using System;
class A
{
void M(string[] args)
{

string[] allStaticSymbols = [
"System.Int32 E.StaticProperty { get; }",
"event System.Action E.StaticEvent",
.. args,
"System.Int32 E2.StaticProperty { get; }"];
}
}
""");
}
}
Loading