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 S2328: "GetHashCode should not reference mutable fields" should report once per method #414

Merged
merged 3 commits into from
Jun 9, 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
Expand Up @@ -2,8 +2,18 @@
"issues": [
{
"id": "S2328",
"message": "Remove this use of '_hashCode' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"message": " Refactor 'GetHashCode' to not reference mutable fields.",
"location": [
{
"uri": "Nancy\src\Nancy\TinyIoc\TinyIoC.cs",
"region": {
"startLine": 3055,
"startColumn": 33,
"endLine": 3055,
"endColumn": 44
}
},
{
"uri": "Nancy\src\Nancy\TinyIoc\TinyIoC.cs",
"region": {
"startLine": 3057,
Expand All @@ -12,6 +22,7 @@
"endColumn": 33
}
}
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@
"issues": [
{
"id": "S2328",
"message": "Remove this use of 'Data' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"message": " Refactor 'GetHashCode' to not reference mutable fields.",
"location": [
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestConverterType.cs",
"region": {
"startLine": 22,
"startColumn": 23,
"endLine": 22,
"endColumn": 34
}
},
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestConverterType.cs",
"region": {
"startLine": 24,
Expand All @@ -12,24 +22,31 @@
"endColumn": 20
}
}
]
},
{
"id": "S2328",
"message": "Remove this use of 'ConverterData' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"message": " Refactor 'GetHashCode' to not reference mutable fields.",
"location": [
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestData.cs",
"region": {
"startLine": 31,
"startColumn": 23,
"endLine": 31,
"endColumn": 34
}
},
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestData.cs",
"region": {
"startLine": 33,
"startColumn": 11,
"endLine": 33,
"endColumn": 24
}
}
},
{
"id": "S2328",
"message": "Remove this use of 'PrimitiveConverterData' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestData.cs",
"region": {
"startLine": 33,
Expand All @@ -38,11 +55,22 @@
"endColumn": 63
}
}
]
},
{
"id": "S2328",
"message": "Remove this use of 'Data' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"message": " Refactor 'GetHashCode' to not reference mutable fields.",
"location": [
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestPrimitiveConverterType.cs",
"region": {
"startLine": 22,
"startColumn": 23,
"endLine": 22,
"endColumn": 34
}
},
{
"uri": "Nancy\src\Nancy.Tests\Unit\Json\TestPrimitiveConverterType.cs",
"region": {
"startLine": 24,
Expand All @@ -51,6 +79,7 @@
"endColumn": 20
}
}
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@
"issues": [
{
"id": "S2328",
"message": "Remove this use of 'inputType' from the 'GetHashCode' declaration, or make it 'readonly'.",
"location": {
"message": " Refactor 'GetHashCode' to not reference mutable fields.",
"location": [
{
"uri": "akka.net\src\core\Akka\Actor\Props.cs",
"region": {
"startLine": 111,
"startColumn": 29,
"endLine": 111,
"endColumn": 40
}
},
{
"uri": "akka.net\src\core\Akka\Actor\Props.cs",
"region": {
"startLine": 118,
Expand All @@ -12,6 +22,7 @@
"endColumn": 55
}
}
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public static bool IsObjectEquals(this IMethodSymbol methodSymbol)

public static bool IsObjectGetHashCode(this IMethodSymbol methodSymbol)
{
return methodSymbol.IsOverride &&
return methodSymbol != null &&
Copy link
Contributor

Choose a reason for hiding this comment

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

Good idea. We should do it for all other methods in this class.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@michalb-sonar Yes I think so too but this refactoring doesn't belong to this PR that's why I haven't done it yet.

methodSymbol.IsOverride &&
methodSymbol.MethodKind == MethodKind.Ordinary &&
methodSymbol.Name == nameof(object.GetHashCode) &&
methodSymbol.Parameters.Length == 0 &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
Expand All @@ -26,7 +27,6 @@
using Microsoft.CodeAnalysis.Diagnostics;
using SonarAnalyzer.Common;
using SonarAnalyzer.Helpers;
using System.Collections.Generic;

namespace SonarAnalyzer.Rules.CSharp
{
Expand All @@ -35,10 +35,11 @@ namespace SonarAnalyzer.Rules.CSharp
public class GetHashCodeMutable : SonarDiagnosticAnalyzer
{
internal const string DiagnosticId = "S2328";
private const string MessageFormat = "Remove this use of '{0}' from the 'GetHashCode' declaration, or make it 'readonly'.";
private const string IssueMessage = " Refactor 'GetHashCode' to not reference mutable fields.";
private const string SecondaryMessageFormat = "Remove this use of '{0}' or make it 'readonly'.";

private static readonly DiagnosticDescriptor rule =
DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager);
DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, IssueMessage, RspecStrings.ResourceManager);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(rule);

Expand All @@ -50,9 +51,7 @@ protected sealed override void Initialize(SonarAnalysisContext context)
var methodSyntax = (MethodDeclarationSyntax)c.Node;
var methodSymbol = c.SemanticModel.GetDeclaredSymbol(methodSyntax);

if (methodSymbol == null ||
methodSyntax.Identifier.Text != "GetHashCode" ||
!methodSyntax.Modifiers.Any(SyntaxKind.OverrideKeyword))
if (!methodSymbol.IsObjectGetHashCode())
{
return;
}
Expand All @@ -74,15 +73,25 @@ protected sealed override void Initialize(SonarAnalysisContext context)
.Where(symbol => symbol != null)
.ToImmutableHashSet();

var identifiers = methodSyntax.DescendantNodes()
.OfType<IdentifierNameSyntax>();
var identifiers = methodSyntax.DescendantNodes().OfType<IdentifierNameSyntax>();

var secondaryLocations = GetAllFirstMutableFieldsUsed(c, fieldsOfClass, identifiers)
.Select(identifierSyntax => new SecondaryLocation(identifierSyntax.GetLocation(),
string.Format(SecondaryMessageFormat, identifierSyntax.Identifier.Text)))
Copy link
Contributor

Choose a reason for hiding this comment

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

This Select is a bit ugly and could be extracted into a method...

.ToList();
if (secondaryLocations.Count == 0)
{
return;
}

ReportOnFirstReferences(c, fieldsOfClass, identifiers);
c.ReportDiagnostic(Diagnostic.Create(rule, methodSyntax.Identifier.GetLocation(),
additionalLocations: secondaryLocations.ToAdditionalLocations(),
properties: secondaryLocations.ToProperties()));
},
SyntaxKind.MethodDeclaration);
}

private static void ReportOnFirstReferences(SyntaxNodeAnalysisContext context,
private static IEnumerable<IdentifierNameSyntax> GetAllFirstMutableFieldsUsed(SyntaxNodeAnalysisContext context,
ImmutableHashSet<IFieldSymbol> fieldsOfClass, IEnumerable<IdentifierNameSyntax> identifiers)
{
var syntaxNodes = new Dictionary<IFieldSymbol, List<IdentifierNameSyntax>>();
Expand All @@ -108,12 +117,9 @@ private static void ReportOnFirstReferences(SyntaxNodeAnalysisContext context,
syntaxNodes[identifierSymbol].Add(identifier);
}

foreach (var identifierReferences in syntaxNodes.Values)
{
var firstPosition = identifierReferences.Select(id => id.SpanStart).Min();
var identifier = identifierReferences.First(id => id.SpanStart == firstPosition);
context.ReportDiagnostic(Diagnostic.Create(rule, identifier.GetLocation(), identifier.Identifier.Text));
}
return syntaxNodes.Values
.Select(identifierReferences => identifierReferences.OrderBy(id => id.SpanStart).FirstOrDefault())
.Where(identifierSyntax => identifierSyntax != null);
}

private static bool IsFieldRelevant(IFieldSymbol fieldSymbol, ImmutableHashSet<IFieldSymbol> fieldsOfClass)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,17 @@
* 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.CodeFixes;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using SonarAnalyzer.Helpers;

namespace SonarAnalyzer.Rules.CSharp
Expand All @@ -49,41 +52,70 @@ public sealed override FixAllProvider GetFixAllProvider()
protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var identifierName = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as IdentifierNameSyntax;
if (identifierName == null)

var identifiersToFix = diagnostic.AdditionalLocations
.Select(location => location.SourceSpan)
.Select(diagnosticSpan => root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as IdentifierNameSyntax)
.Where(idenfitierName => idenfitierName != null)
.ToList();

if (identifiersToFix.Count == 0)
{
return;
}

var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var semanticModel = await context.Document
.GetSemanticModelAsync(context.CancellationToken)
.ConfigureAwait(false);
var allFieldDeclarationTasks = identifiersToFix.Select(identifier =>
GetFieldDeclarationSyntax(semanticModel, identifier, context.CancellationToken));
var allFieldDeclarations = await Task.WhenAll(allFieldDeclarationTasks).ConfigureAwait(false);
allFieldDeclarations = allFieldDeclarations.Where(fieldDeclaration => fieldDeclaration != null).ToArray();

context.RegisterCodeFix(
CodeAction.Create(
Title,
token => AddReadonlyToFieldDeclarations(context.Document, token, allFieldDeclarations)),
context.Diagnostics);
}

private async Task<FieldDeclarationSyntax> GetFieldDeclarationSyntax(SemanticModel semanticModel,
IdentifierNameSyntax identifierName, CancellationToken cancellationToken)
{
var fieldSymbol = semanticModel.GetSymbolInfo(identifierName).Symbol as IFieldSymbol;

if (fieldSymbol == null ||
!fieldSymbol.DeclaringSyntaxReferences.Any())
{
return;
return null;
}

var reference = await fieldSymbol.DeclaringSyntaxReferences.First().GetSyntaxAsync(context.CancellationToken).ConfigureAwait(false);
var reference = await fieldSymbol.DeclaringSyntaxReferences.First()
.GetSyntaxAsync(cancellationToken)
.ConfigureAwait(false);
var fieldDeclaration = (FieldDeclarationSyntax)reference.Parent.Parent;

if (fieldDeclaration.Declaration.Variables.Count != 1)
{
return;
return null;
}

context.RegisterCodeFix(
CodeAction.Create(
Title,
c =>
{
var newFieldDeclaration = fieldDeclaration.AddModifiers(
SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
var newRoot = root.ReplaceNode(fieldDeclaration, newFieldDeclaration);
return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
}),
context.Diagnostics);
return fieldDeclaration;
}

private async Task<Document> AddReadonlyToFieldDeclarations(Document document, CancellationToken cancellationToken,
IEnumerable<FieldDeclarationSyntax> fieldDeclarations)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken);

foreach (var fieldDeclaration in fieldDeclarations)
{
var readonlyToken = SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword).WithTrailingTrivia(SyntaxFactory.Space);
var newFieldDeclaration = fieldDeclaration.AddModifiers(readonlyToken);
editor.ReplaceNode(fieldDeclaration, newFieldDeclaration);
}

return editor.GetChangedDocument();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ public GetHashCodeMutable()
{
}

public override int GetHashCode()
public override int GetHashCode() // Fixed
{
int hash = Zero;
hash += foo.GetHashCode(); // Fixed
hash += age.GetHashCode(); // Fixed
hash += this.name.GetHashCode(); // Fixed
hash += foo.GetHashCode();
hash += age.GetHashCode();
hash += this.name.GetHashCode();
hash += name.GetHashCode(); // Compliant, we already reported on this symbol
hash += this.birthday.GetHashCode();
hash += SomeMethod(Field); // Fixed
hash += SomeMethod(Field);
return hash;
}
public int SomeMethod(int value)
Expand All @@ -48,4 +48,4 @@ public override int GetHashCode()
return i; // we don't report on this
}
}
}
}
Loading