-
Notifications
You must be signed in to change notification settings - Fork 457
/
OverrideGetHashCodeOnOverridingEquals.Fixer.cs
66 lines (56 loc) · 2.84 KB
/
OverrideGetHashCodeOnOverridingEquals.Fixer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA2218: Override GetHashCode on overriding Equals
/// </summary>
public abstract class OverrideGetHashCodeOnOverridingEqualsFixer : CodeFixProvider
{
public sealed override FixAllProvider GetFixAllProvider()
{
// See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode typeDeclaration = root.FindNode(context.Span);
typeDeclaration = SyntaxGenerator.GetGenerator(context.Document).GetDeclaration(typeDeclaration);
if (typeDeclaration == null)
{
return;
}
// CONSIDER: Do we need to confirm that System.Object.GetHashCode isn't shadowed in a base type?
string title = MicrosoftCodeQualityAnalyzersResources.OverrideGetHashCodeOnOverridingEqualsCodeActionTitle;
context.RegisterCodeFix(
new MyCodeAction(
title,
cancellationToken => OverrideObjectGetHashCode(context.Document, typeDeclaration, cancellationToken),
equivalenceKey: title),
context.Diagnostics);
}
private static async Task<Document> OverrideObjectGetHashCode(Document document, SyntaxNode typeDeclaration, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var methodDeclaration = generator.DefaultGetHashCodeOverrideDeclaration(editor.SemanticModel.Compilation);
editor.AddMember(typeDeclaration, methodDeclaration);
return editor.GetChangedDocument();
}
// Needed for Telemetry (https://github.com/dotnet/roslyn-analyzers/issues/192)
private class MyCodeAction : DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
}
}