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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using MonoDevelop.Core;
using Microsoft.CodeAnalysis;
using ICSharpCode.NRefactory6.CSharp;
using RefactoringEssentials;
namespace MonoDevelop.CSharp.Diagnostics.RemoveUnnecessaryCast
{
internal abstract class RemoveUnnecessaryCastDiagnosticAnalyzerBase<TLanguageKindEnum> : DiagnosticAnalyzer where TLanguageKindEnum : struct
{
private static string s_localizableTitle = GettextCatalog.GetString ("Remove Unnecessary Cast");
private static string s_localizableMessage = GettextCatalog.GetString ("Cast is redundant.");
private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId,
s_localizableTitle,
s_localizableMessage,
DiagnosticAnalyzerCategories.RedundanciesInCode,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: DiagnosticCustomTags.Unnecessary);
#region Interface methods
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(s_descriptor);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(
(nodeContext) =>
{
Diagnostic diagnostic;
if (TryRemoveCastExpression(nodeContext.SemanticModel, nodeContext.Node, out diagnostic, nodeContext.CancellationToken))
{
nodeContext.ReportDiagnostic(diagnostic);
}
},
this.SyntaxKindsOfInterest.ToArray());
}
public abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; }
#endregion
protected abstract bool IsUnnecessaryCast(SemanticModel model, SyntaxNode node, CancellationToken cancellationToken);
protected abstract TextSpan GetDiagnosticSpan(SyntaxNode node);
private bool TryRemoveCastExpression(
SemanticModel model, SyntaxNode node, out Diagnostic diagnostic, CancellationToken cancellationToken)
{
diagnostic = default(Diagnostic);
if (model.IsFromGeneratedCode (cancellationToken))
return false;
if (!IsUnnecessaryCast(model, node, cancellationToken))
{
return false;
}
var tree = model.SyntaxTree;
var span = GetDiagnosticSpan(node);
if (tree.OverlapsHiddenPosition(span, cancellationToken))
{
return false;
}
diagnostic = Diagnostic.Create(s_descriptor, tree.GetLocation(span));
return true;
}
}
}
|