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

Add file-scoped namespace support to SA1208 #3438

Merged
merged 2 commits into from Jan 28, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace StyleCop.Analyzers.OrderingRules
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Lightup;

/// <summary>
/// Implements a code fix for all misaligned using statements.
Expand Down Expand Up @@ -123,12 +124,12 @@ internal TreeTextSpan GetContainingSpan(SyntaxNode node)

private static void ProcessNodeMembers(TreeTextSpan.Builder builder, SyntaxList<MemberDeclarationSyntax> members)
{
foreach (var namespaceDeclaration in members.OfType<NamespaceDeclarationSyntax>())
foreach (var namespaceDeclaration in members.Where(member => BaseNamespaceDeclarationSyntaxWrapper.IsInstance(member)))
{
var childBuilder = builder.AddChild(namespaceDeclaration.FullSpan.Start);
childBuilder.SetEnd(namespaceDeclaration.FullSpan.End);

ProcessNodeMembers(childBuilder, namespaceDeclaration.Members);
ProcessNodeMembers(childBuilder, ((BaseNamespaceDeclarationSyntaxWrapper)namespaceDeclaration).Members);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -467,10 +467,10 @@ private bool StartsWithSystemUsingDirectiveIdentifier(NameSyntax name)

private void ProcessMembers(SyntaxList<MemberDeclarationSyntax> members)
{
foreach (var namespaceDeclaration in members.OfType<NamespaceDeclarationSyntax>())
foreach (var namespaceDeclaration in members.Where(member => BaseNamespaceDeclarationSyntaxWrapper.IsInstance(member)))
{
this.ProcessUsingDirectives(namespaceDeclaration.Usings);
this.ProcessMembers(namespaceDeclaration.Members);
this.ProcessUsingDirectives(((BaseNamespaceDeclarationSyntaxWrapper)namespaceDeclaration).Usings);
this.ProcessMembers(((BaseNamespaceDeclarationSyntaxWrapper)namespaceDeclaration).Members);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace StyleCop.Analyzers.OrderingRules
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Lightup;
using StyleCop.Analyzers.Settings.ObjectModel;

/// <summary>
Expand Down Expand Up @@ -134,7 +135,7 @@ private static string DetermineIndentation(CompilationUnitSyntax compilationUnit

if (usingDirectivesPlacement == UsingDirectivesPlacement.InsideNamespace)
{
var rootNamespace = compilationUnit.Members.OfType<NamespaceDeclarationSyntax>().First();
var rootNamespace = compilationUnit.Members.First(member => BaseNamespaceDeclarationSyntaxWrapper.IsInstance(member));
var indentationLevel = IndentationHelper.GetIndentationSteps(indentationSettings, rootNamespace);
usingsIndentation = IndentationHelper.GenerateIndentationString(indentationSettings, indentationLevel + 1);
}
Expand Down Expand Up @@ -185,9 +186,9 @@ private static int CountNamespaces(SyntaxList<MemberDeclarationSyntax> members)
{
var result = 0;

foreach (var namespaceDeclaration in members.OfType<NamespaceDeclarationSyntax>())
foreach (var namespaceDeclaration in members.Where(member => BaseNamespaceDeclarationSyntaxWrapper.IsInstance(member)))
{
result += 1 + CountNamespaces(namespaceDeclaration.Members);
result += 1 + CountNamespaces(((BaseNamespaceDeclarationSyntaxWrapper)namespaceDeclaration).Members);
}

return result;
Expand Down Expand Up @@ -267,7 +268,7 @@ private static int CompareSpanStart(UsingDirectiveSyntax left, UsingDirectiveSyn

private static SyntaxNode AddUsingsToNamespace(SyntaxNode newSyntaxRoot, UsingsSorter usingsHelper, string usingsIndentation, bool hasConditionalDirectives)
{
var rootNamespace = ((CompilationUnitSyntax)newSyntaxRoot).Members.OfType<NamespaceDeclarationSyntax>().First();
var rootNamespace = (BaseNamespaceDeclarationSyntaxWrapper)((CompilationUnitSyntax)newSyntaxRoot).Members.First(member => BaseNamespaceDeclarationSyntaxWrapper.IsInstance(member));
var withTrailingBlankLine = hasConditionalDirectives || rootNamespace.Members.Any() || rootNamespace.Externs.Any();

var groupedUsings = usingsHelper.GenerateGroupedUsings(TreeTextSpan.Empty, usingsIndentation, withTrailingBlankLine, qualifyNames: false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,62 @@

namespace StyleCop.Analyzers.Test.CSharp10.OrderingRules
{
using System.Threading;
using System.Threading.Tasks;
using StyleCop.Analyzers.Test.CSharp9.OrderingRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.OrderingRules.SA1208SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives,
StyleCop.Analyzers.OrderingRules.UsingCodeFixProvider>;

public class SA1208CSharp10UnitTests : SA1208CSharp9UnitTests
{
[Fact]
sharwell marked this conversation as resolved.
Show resolved Hide resolved
[WorkItem(3437, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3437")]
public async Task TestWhenSystemUsingDirectivesAreNotOnTopInFileScopedNamespaceAsync()
sharwell marked this conversation as resolved.
Show resolved Hide resolved
{
await new CSharpTest
{
TestSources =
{
"namespace Xyz {}",
"namespace AnotherNamespace {}",
@"
namespace Test;

using Xyz;
{|#0:using System;|}
{|#1:using System.IO;|}
using AnotherNamespace;
{|#2:using System.Threading.Tasks;|}

class A
{
}",
},
FixedSources =
{
"namespace Xyz {}",
"namespace AnotherNamespace {}",
@"
namespace Test;
using System;
using System.IO;
using System.Threading.Tasks;
using AnotherNamespace;
using Xyz;

class A
{
}",
},
ExpectedDiagnostics =
{
Diagnostic().WithLocation(0).WithArguments("System", "Xyz"),
Diagnostic().WithLocation(1).WithArguments("System.IO", "Xyz"),
Diagnostic().WithLocation(2).WithArguments("System.Threading.Tasks", "Xyz"),
},
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace StyleCop.Analyzers.OrderingRules
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Lightup;
using StyleCop.Analyzers.Settings.ObjectModel;

/// <summary>
Expand Down Expand Up @@ -40,6 +41,7 @@ internal class SA1208SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives

private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> CompilationUnitAction = HandleCompilationUnit;
private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> NamespaceDeclarationAction = HandleNamespaceDeclaration;
private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> FileScopedNamespaceDeclarationAction = HandleFileScopedNamespaceDeclaration;

/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
Expand All @@ -53,6 +55,7 @@ public override void Initialize(AnalysisContext context)

context.RegisterSyntaxNodeAction(CompilationUnitAction, SyntaxKind.CompilationUnit);
context.RegisterSyntaxNodeAction(NamespaceDeclarationAction, SyntaxKind.NamespaceDeclaration);
context.RegisterSyntaxNodeAction(FileScopedNamespaceDeclarationAction, SyntaxKindEx.FileScopedNamespaceDeclaration);
}

private static void HandleCompilationUnit(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
Expand All @@ -77,9 +80,19 @@ private static void HandleNamespaceDeclaration(SyntaxNodeAnalysisContext context
}

var namespaceDeclaration = (NamespaceDeclarationSyntax)context.Node;

var usings = namespaceDeclaration.Usings;
ProcessUsingsAndReportDiagnostic(usings, context);
}

private static void HandleFileScopedNamespaceDeclaration(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
{
if (!settings.OrderingRules.SystemUsingDirectivesFirst)
{
return;
}

var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntaxWrapper)context.Node;
var usings = namespaceDeclaration.Usings;
ProcessUsingsAndReportDiagnostic(usings, context);
}

Expand Down