Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Update 'use simple using statement' to support global statements #75921

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageService;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement;

Expand Down Expand Up @@ -48,17 +52,14 @@ namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement;
/// semantics will not change.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class UseSimpleUsingStatementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
internal sealed class UseSimpleUsingStatementDiagnosticAnalyzer()
: AbstractBuiltInCodeStyleDiagnosticAnalyzer(
IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId,
EnforceOnBuildValues.UseSimpleUsingStatement,
CSharpCodeStyleOptions.PreferSimpleUsingStatement,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_simple_using_statement), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.using_statement_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
public UseSimpleUsingStatementDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId,
EnforceOnBuildValues.UseSimpleUsingStatement,
CSharpCodeStyleOptions.PreferSimpleUsingStatement,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_simple_using_statement), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.using_statement_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}

public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;

Expand All @@ -83,12 +84,14 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var outermostUsing = (UsingStatementSyntax)context.Node;
var semanticModel = context.SemanticModel;

if (outermostUsing.Parent is not BlockSyntax parentBlock)
{
// Don't offer on a using statement that is parented by another using statement. We'll just offer on the
// topmost using statement.
var parentBlockLike = outermostUsing.Parent;
if (parentBlockLike is GlobalStatementSyntax)
parentBlockLike = parentBlockLike.Parent;

// Don't offer on a using statement that is parented by another using statement. We'll just offer on the
// topmost using statement.
if (parentBlockLike is not BlockSyntax and not CompilationUnitSyntax)
return;
}

var innermostUsing = outermostUsing;

Expand All @@ -102,15 +105,15 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
}

// Verify that changing this using-statement into a using-declaration will not change semantics.
if (!PreservesSemantics(semanticModel, parentBlock, outermostUsing, innermostUsing, cancellationToken))
if (!PreservesSemantics(semanticModel, parentBlockLike, outermostUsing, innermostUsing, cancellationToken))
return;

// Converting a using-statement to a using-variable-declaration will cause the using's variables to now be
// pushed up to the parent block's scope. This is also true for any local variables in the innermost using's
// block. These may then collide with other variables in the block, causing an error. Check for that and
// bail if this happens.
if (CausesVariableCollision(
context.SemanticModel, parentBlock,
context.SemanticModel, parentBlockLike,
outermostUsing, innermostUsing, cancellationToken))
{
return;
Expand All @@ -122,52 +125,69 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
outermostUsing.UsingKeyword.GetLocation(),
option.Notification,
context.Options,
additionalLocations: ImmutableArray.Create(outermostUsing.GetLocation()),
additionalLocations: [outermostUsing.GetLocation()],
properties: null));
}

private static bool CausesVariableCollision(
SemanticModel semanticModel, BlockSyntax parentBlock,
UsingStatementSyntax outermostUsing, UsingStatementSyntax innermostUsing,
SemanticModel semanticModel,
SyntaxNode parentBlockLike,
UsingStatementSyntax outermostUsing,
UsingStatementSyntax innermostUsing,
CancellationToken cancellationToken)
{
var symbolNameToExistingSymbol = semanticModel.GetExistingSymbols(parentBlock, cancellationToken).ToLookup(s => s.Name);
using var _ = PooledDictionary<string, ArrayBuilder<ISymbol>>.GetInstance(out var symbolNameToExistingSymbol);

for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax)
try
{
// Check if the using statement itself contains variables that will collide with other variables in the
// block.
var usingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(current, cancellationToken);
if (DeclaredLocalCausesCollision(symbolNameToExistingSymbol, usingOperation.Locals))
return true;
foreach (var statement in CSharpBlockFacts.Instance.GetExecutableBlockStatements(parentBlockLike))
{
foreach (var symbol in semanticModel.GetExistingSymbols(statement, cancellationToken))
symbolNameToExistingSymbol.MultiAdd(symbol.Name, symbol);
}

for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax)
{
// Check if the using statement itself contains variables that will collide with other variables in the
// block.
var usingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(current, cancellationToken);
if (DeclaredLocalCausesCollision(symbolNameToExistingSymbol, usingOperation.Locals))
return true;
}

var innerUsingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(innermostUsing, cancellationToken);
if (innerUsingOperation.Body is IBlockOperation innerUsingBlock)
return DeclaredLocalCausesCollision(symbolNameToExistingSymbol, innerUsingBlock.Locals);

return false;
}
finally
{
symbolNameToExistingSymbol.FreeValues();
}

var innerUsingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(innermostUsing, cancellationToken);
if (innerUsingOperation.Body is IBlockOperation innerUsingBlock)
return DeclaredLocalCausesCollision(symbolNameToExistingSymbol, innerUsingBlock.Locals);

return false;
}

private static bool DeclaredLocalCausesCollision(ILookup<string, ISymbol> symbolNameToExistingSymbol, ImmutableArray<ILocalSymbol> locals)
=> locals.Any(static (local, symbolNameToExistingSymbol) => symbolNameToExistingSymbol[local.Name].Any(otherLocal => !local.Equals(otherLocal)), symbolNameToExistingSymbol);
private static bool DeclaredLocalCausesCollision(Dictionary<string, ArrayBuilder<ISymbol>> symbolNameToExistingSymbol, ImmutableArray<ILocalSymbol> locals)
=> locals.Any(static (local, symbolNameToExistingSymbol) =>
symbolNameToExistingSymbol.TryGetValue(local.Name, out var symbols) &&
symbols.Any(otherLocal => !local.Equals(otherLocal)), symbolNameToExistingSymbol);

private static bool PreservesSemantics(
SemanticModel semanticModel,
BlockSyntax parentBlock,
SyntaxNode parentBlockLike,
UsingStatementSyntax outermostUsing,
UsingStatementSyntax innermostUsing,
CancellationToken cancellationToken)
{
var statements = parentBlock.Statements;
var statements = (IReadOnlyList<StatementSyntax>)CSharpBlockFacts.Instance.GetExecutableBlockStatements(parentBlockLike);
var index = statements.IndexOf(outermostUsing);

return UsingValueDoesNotLeakToFollowingStatements(semanticModel, statements, index, cancellationToken) &&
UsingStatementDoesNotInvolveJumps(statements, index, innermostUsing);
}

private static bool UsingStatementDoesNotInvolveJumps(
SyntaxList<StatementSyntax> parentStatements, int index, UsingStatementSyntax innermostUsing)
IReadOnlyList<StatementSyntax> parentStatements, int index, UsingStatementSyntax innermostUsing)
{
// Jumps are not allowed to cross a using declaration in the forward direction, and can't go back unless
// there is a curly brace between the using and the label.
Expand Down Expand Up @@ -204,7 +224,7 @@ private static bool IsGotoOrLabeledStatement(StatementSyntax priorStatement)

private static bool UsingValueDoesNotLeakToFollowingStatements(
SemanticModel semanticModel,
SyntaxList<StatementSyntax> statements,
IReadOnlyList<StatementSyntax> statements,
int index,
CancellationToken cancellationToken)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
Expand All @@ -21,6 +20,7 @@
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement;
Expand All @@ -46,41 +46,62 @@ protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var topmostUsingStatements = diagnostics.Select(d => (UsingStatementSyntax)d.AdditionalLocations[0].FindNode(cancellationToken)).ToSet();
var blocks = topmostUsingStatements.Select(u => (BlockSyntax)u.Parent);
var topmostUsingStatements = diagnostics.Select(
d => (UsingStatementSyntax)d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken)).ToSet();
var blockLikes = topmostUsingStatements.Select(u => u.Parent is GlobalStatementSyntax ? u.Parent.GetRequiredParent() : u.GetRequiredParent()).ToSet();

// Process blocks in reverse order so we rewrite from inside-to-outside with nested
// usings.
var root = editor.OriginalRoot;
var updatedRoot = root.ReplaceNodes(
blocks.OrderByDescending(b => b.SpanStart),
blockLikes.OrderByDescending(b => b.SpanStart),
(original, current) => RewriteBlock(original, current, topmostUsingStatements));

editor.ReplaceNode(root, updatedRoot);

return Task.CompletedTask;
}

private static BlockSyntax RewriteBlock(
BlockSyntax originalBlock, BlockSyntax currentBlock,
private static SyntaxNode RewriteBlock(
SyntaxNode originalBlockLike,
SyntaxNode currentBlockLike,
ISet<UsingStatementSyntax> topmostUsingStatements)
{
if (originalBlock.Statements.Count == currentBlock.Statements.Count)
var originalBlockStatements = (IReadOnlyList<StatementSyntax>)CSharpBlockFacts.Instance.GetExecutableBlockStatements(originalBlockLike);
var currentBlockStatements = (IReadOnlyList<StatementSyntax>)CSharpBlockFacts.Instance.GetExecutableBlockStatements(currentBlockLike);

if (originalBlockStatements.Count == currentBlockStatements.Count)
{
var statementToUpdateIndex = originalBlock.Statements.IndexOf(s => topmostUsingStatements.Contains(s));
var statementToUpdate = currentBlock.Statements[statementToUpdateIndex];
var statementToUpdateIndex = originalBlockStatements.IndexOf(s => topmostUsingStatements.Contains(s));
var statementToUpdate = currentBlockStatements[statementToUpdateIndex];

if (statementToUpdate is UsingStatementSyntax usingStatement &&
usingStatement.Declaration != null)
{
var updatedStatements = currentBlock.Statements.ReplaceRange(
statementToUpdate,
Expand(usingStatement));
return currentBlock.WithStatements(updatedStatements);
var expandedUsing = Expand(usingStatement);

return WithStatements(currentBlockLike, usingStatement, expandedUsing);
}
}

return currentBlock;
return currentBlockLike;
}

private static SyntaxNode WithStatements(
SyntaxNode currentBlockLike,
UsingStatementSyntax usingStatement,
ImmutableArray<StatementSyntax> expandedUsingStatements)
{
return currentBlockLike switch
{
BlockSyntax currentBlock => currentBlock.WithStatements(
currentBlock.Statements.ReplaceRange(usingStatement, expandedUsingStatements)),

CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(
compilationUnit.Members.ReplaceRange((GlobalStatementSyntax)usingStatement.GetRequiredParent(), expandedUsingStatements.Select(GlobalStatement))),

_ => throw ExceptionUtilities.UnexpectedValue(currentBlockLike),
};
}

private static ImmutableArray<StatementSyntax> Expand(UsingStatementSyntax usingStatement)
Expand Down Expand Up @@ -163,15 +184,13 @@ private static SyntaxTriviaList Expand(ArrayBuilder<StatementSyntax> result, Usi
}

return default;
}

private static LocalDeclarationStatementSyntax Convert(UsingStatementSyntax usingStatement)
{
return LocalDeclarationStatement(
usingStatement.AwaitKeyword,
usingStatement.UsingKeyword.WithAppendedTrailingTrivia(ElasticMarker),
modifiers: default,
usingStatement.Declaration,
SemicolonToken).WithTrailingTrivia(usingStatement.CloseParenToken.TrailingTrivia);
static LocalDeclarationStatementSyntax Convert(UsingStatementSyntax usingStatement)
=> LocalDeclarationStatement(
usingStatement.AwaitKeyword,
usingStatement.UsingKeyword.WithAppendedTrailingTrivia(ElasticMarker),
modifiers: default,
usingStatement.Declaration!,
SemicolonToken).WithTrailingTrivia(usingStatement.CloseParenToken.TrailingTrivia);
}
}
Loading
Loading