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 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
@@ -0,0 +1,17 @@
{
"issues": [
{
"id": "S4041",
"message": "Change the name of type 'Data' to be different from an existing framework 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,113 @@
/*
* 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 type '{0}' to be different from an existing framework namespace.";

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 =>
{
if (IsDeclaredPublic(c.Node, c.SemanticModel))
{
ReportIfNameClashesWithFrameworkNamespace(GetIdentifier(c.Node), c);
}
},
SyntaxKind.ClassDeclaration,
SyntaxKind.StructDeclaration,
SyntaxKind.InterfaceDeclaration,
SyntaxKind.EnumDeclaration,
SyntaxKind.DelegateDeclaration);
}

private static SyntaxToken? GetIdentifier(SyntaxNode declaration)
{
var baseTypeDeclaration = declaration as BaseTypeDeclarationSyntax;
if (baseTypeDeclaration != null)
{
return baseTypeDeclaration.Identifier;
}

var delegateDeclaration = declaration as DelegateDeclarationSyntax;
if (delegateDeclaration != null)
{
return delegateDeclaration.Identifier;
}

return null;
}

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

bool isNameClash = typeName != null &&
typeNameLocation != null &&
frameworkNamespaces.Contains(typeName.ToLowerInvariant());

if (isNameClash)
{
context.ReportDiagnostic(Diagnostic.Create(rule, typeNameLocation, typeName));
}
}

private static bool IsDeclaredPublic(SyntaxNode declaration, SemanticModel semanticModel)
{
return semanticModel.GetDeclaredSymbol(declaration)?.DeclaredAccessibility == Accessibility.Public;
}
}
}
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,88 @@
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 type 'Web' to be different from an existing framework namespace.}}
// ^^^
public enum IO { x };
// ^^

public delegate void Runtime(); // Noncompliant
// ^^^^^^^

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

public struct Xaml { } // Noncompliant
// ^^^^

interface System { } // Compliant (it's not public)

private interface Data { } // Compliant (it's not public)

namespace Accessibility { } // Compliant (namespace are not checked)

interface { }
}

namespace All_Variants
{
public class Accessibility { } // Noncompliant
public class Activities { } // Noncompliant
public class Addin { } // Noncompliant
public class Build { } // Noncompliant
public class Codedom { } // Noncompliant
public class Collections { } // Noncompliant
public class Componentmodel { } // Noncompliant
public class Configuration { } // Noncompliant
public class Csharp { } // Noncompliant
public class Custommarshalers { } // Noncompliant
public class Data { } // Noncompliant
public class Dataflow { } // Noncompliant
public class Deployment { } // Noncompliant
public class Device { } // Noncompliant
public class Diagnostics { } // Noncompliant
public class Directoryservices { } // Noncompliant
public class Drawing { } // Noncompliant
public class Dynamic { } // Noncompliant
public class Enterpriseservices { } // Noncompliant
public class Globalization { } // Noncompliant
public class Identitymodel { } // Noncompliant
public class Interopservices { } // Noncompliant
public class Io { } // Noncompliant
public class Jscript { } // Noncompliant
public class Linq { } // Noncompliant
public class Location { } // Noncompliant
public class Management { } // Noncompliant
public class Media { } // Noncompliant
public class Messaging { } // Noncompliant
public class Microsoft { } // Noncompliant
public class Net { } // Noncompliant
public class Numerics { } // Noncompliant
public class Printing { } // Noncompliant
public class Reflection { } // Noncompliant
public class Resources { } // Noncompliant
public class Runtime { } // Noncompliant
public class Security { } // Noncompliant
public class Server { } // Noncompliant
public class Servicemodel { } // Noncompliant
public class Serviceprocess { } // Noncompliant
public class Speech { } // Noncompliant
public class Sqlserver { } // Noncompliant
public class System { } // Noncompliant
public class Tasks { } // Noncompliant
public class Text { } // Noncompliant
public class Threading { } // Noncompliant
public class Timers { } // Noncompliant
public class Transactions { } // Noncompliant
public class Uiautomationclientsideproviders { } // Noncompliant
public class Visualbasic { } // Noncompliant
public class Visualc { } // Noncompliant
public class Web { } // Noncompliant
public class Win32 { } // Noncompliant
public class Windows { } // Noncompliant
public class Workflow { } // Noncompliant
public class Xaml { } // Noncompliant
public class Xamlgeneratednamespace { } // Noncompliant
public class Xml { } // Noncompliant
}