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

Rule S4041: Type names should not match namespaces #466

Merged
merged 3 commits into from
Jun 23, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
@@ -0,0 +1,17 @@
{
"issues": [
{
"id": "S4041",
"message": "Change the name of that type to be different from an existing namespace.",
"location": {
"uri": "akka.net\src\core\Akka.Remote.TestKit\BarrierCoordinator.cs",
"region": {
"startLine": 51,
"startColumn": 29,
"endLine": 51,
"endColumn": 33
}
}
}
]
}
25 changes: 25 additions & 0 deletions sonaranalyzer-dotnet/rspec/cs/S4041_c#.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<p>When a type name matches the name of a publicly defined namespace, for instance one in the .NET framework class library, it leads to confusion and
makes the library that much harder to use.</p>
<p>This rule raises an issue when a name of a public type matches the name of a .NET Framework namespace, or a namespace of the project assembly, in a
case-insensitive comparison.</p>
<h2>Noncompliant Code Example</h2>
<pre>
using System;

namespace MyLibrary
{
public class Text { // Noncompliant: Collides with System.Text
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
using System;

namespace MyLibrary
{
public class MyText {
}
}
</pre>

13 changes: 13 additions & 0 deletions sonaranalyzer-dotnet/rspec/cs/S4041_c#.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"title": "Type names should not match namespaces",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "2min"
},
"tags": [
"convention"
],
"defaultSeverity": "Minor"
}
27 changes: 27 additions & 0 deletions sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/RspecStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -6930,6 +6930,33 @@
<data name="S4040_Type" xml:space="preserve">
<value>CODE_SMELL</value>
</data>
<data name="S4041_Category" xml:space="preserve">
<value>Sonar Code Smell</value>
</data>
<data name="S4041_Description" xml:space="preserve">
<value>When a type name matches the name of a publicly defined namespace, for instance one in the .NET framework class library, it leads to confusion and makes the library that much harder to use.</value>
</data>
<data name="S4041_IsActivatedByDefault" xml:space="preserve">
<value>False</value>
</data>
<data name="S4041_Remediation" xml:space="preserve">
<value>Constant/Issue</value>
</data>
<data name="S4041_RemediationCost" xml:space="preserve">
<value>2min</value>
</data>
<data name="S4041_Severity" xml:space="preserve">
<value>Minor</value>
</data>
<data name="S4041_Tags" xml:space="preserve">
<value>convention</value>
</data>
<data name="S4041_Title" xml:space="preserve">
<value>Type names should not match namespaces</value>
</data>
<data name="S4041_Type" xml:space="preserve">
<value>CODE_SMELL</value>
</data>
<data name="S818_Category" xml:space="preserve">
<value>Sonar Code Smell</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2017 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using SonarAnalyzer.Common;
using SonarAnalyzer.Helpers;

namespace SonarAnalyzer.Rules.CSharp
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
[Rule(DiagnosticId)]
public sealed class TypeNamesShouldNotMatchNamespaces : SonarDiagnosticAnalyzer
{
internal const string DiagnosticId = "S4041";
private const string MessageFormat = "Change the name of that type to be different from an existing namespace.";
Copy link
Contributor

Choose a reason for hiding this comment

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

I do understand now why they keep the list of namespaces and only split the name after. It is because it allows them to display which namespace conflicts with this name.

I would just add the name of the class/interface... in the message.


private static readonly DiagnosticDescriptor rule =
DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(rule);

// Based on https://msdn.microsoft.com/en-us/library/gg145045%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
private static ISet<string> frameworkNamespaces =
new HashSet<string>
{
"accessibility", "activities", "addin", "build", "codedom", "collections",
"componentmodel", "configuration", "csharp", "custommarshalers", "data",
"dataflow", "deployment", "device", "diagnostics", "directoryservices",
"drawing", "dynamic", "enterpriseservices", "globalization", "identitymodel",
"interopservices", "io", "jscript", "linq", "location", "management", "media",
"messaging", "microsoft", "net", "numerics", "printing", "reflection", "resources",
"runtime", "security", "server", "servicemodel", "serviceprocess", "speech",
"sqlserver", "system", "tasks", "text", "threading", "timers", "transactions",
"uiautomationclientsideproviders", "visualbasic", "visualc", "web", "win32",
"windows", "workflow", "xaml", "xamlgeneratednamespace", "xml"
};

protected override void Initialize(SonarAnalysisContext context)
{
context.RegisterSyntaxNodeActionInNonGenerated(c =>
{
var declaration = (BaseTypeDeclarationSyntax)c.Node;
var symbolDeclaredccess = c.SemanticModel.GetDeclaredSymbol(declaration)?.DeclaredAccessibility;
Copy link
Contributor

Choose a reason for hiding this comment

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

Typo


ReportIfNameClashesWithFrameworkNamespace(declaration?.Identifier, symbolDeclaredccess, c);
},
SyntaxKind.ClassDeclaration,
SyntaxKind.InterfaceDeclaration,
SyntaxKind.EnumDeclaration);
Copy link
Contributor

Choose a reason for hiding this comment

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

What about namespace? What about struct?


context.RegisterSyntaxNodeActionInNonGenerated(c =>
{
var declaration = (DelegateDeclarationSyntax)c.Node;
var symbolDeclaredccess = c.SemanticModel.GetDeclaredSymbol(declaration)?.DeclaredAccessibility;
Copy link
Contributor

Choose a reason for hiding this comment

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

Typo


ReportIfNameClashesWithFrameworkNamespace(declaration?.Identifier, symbolDeclaredccess, c);
},
SyntaxKind.DelegateDeclaration);
Copy link
Contributor

Choose a reason for hiding this comment

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

This block is exactly the same as the previous one except from the cast. I am pretty sure you could use c.SemanticModel.GetDeclaredSymbol(c.Node) directly.

}

private static void ReportIfNameClashesWithFrameworkNamespace(SyntaxToken? identifier,
Accessibility? declaredAccessibility, SyntaxNodeAnalysisContext context)
{
string typeName = identifier?.ValueText;
var typeNameLocation = identifier?.GetLocation();

bool isPublicNameClash = typeName != null &&
typeNameLocation != null &&
declaredAccessibility == Accessibility.Public &&
frameworkNamespaces.Contains(typeName.ToLowerInvariant());

if (isPublicNameClash)
{
context.ReportDiagnostic(Diagnostic.Create(rule, typeNameLocation));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<p>When a type name matches the name of a publicly defined namespace, for instance one in the .NET framework class library, it leads to confusion and
makes the library that much harder to use.</p>
<p>This rule raises an issue when a name of a public type matches the name of a .NET Framework namespace, or a namespace of the project assembly, in a
case-insensitive comparison.</p>
<h2>Noncompliant Code Example</h2>
<pre>
using System;

namespace MyLibrary
{
public class Text { // Noncompliant: Collides with System.Text
}
}
</pre>
<h2>Compliant Solution</h2>
<pre>
using System;

namespace MyLibrary
{
public class MyText {
}
}
</pre>

Original file line number Diff line number Diff line change
Expand Up @@ -4038,7 +4038,7 @@ private static void DetectTypeChanges(ResourceManager resourceManager, IImmutabl
//["4038"],
//["4039"],
["4040"] = "CODE_SMELL",
//["4041"],
["4041"] = "CODE_SMELL",
//["4042"],
//["4043"],
//["4044"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2017 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarAnalyzer.Rules.CSharp;

namespace SonarAnalyzer.UnitTest.Rules
{
[TestClass]
public class TypeNamesShouldNotMatchNamespacesTest
{
[TestMethod]
[TestCategory("Rule")]
public void TypeNamesShouldNotMatchNamespaces()
{
Verifier.VerifyAnalyzer(@"TestCases\TypeNamesShouldNotMatchNamespaces.cs",
new TypeNamesShouldNotMatchNamespaces());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;

namespace Tests.Diagnostics
{
Copy link
Contributor

Choose a reason for hiding this comment

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

This is going to be boring but I would add a test case for every name we handle (avoid regression).

public class Web { } // Noncompliant {{Change the name of that type to be different from an existing namespace.}}
// ^^^
public enum IO { x };
// ^^
public delegate void Runtime(); // Noncompliant
// ^^^^^^^

public interface Linq { } // Noncompliant
// ^^^^

interface System { } // Compliant
Copy link
Contributor

Choose a reason for hiding this comment

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

I would add a comment about why this is compliant.


private interface Data { } // Compliant


interface { }
}