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

Move few CodeFixProviders to Analyzers layer #60524

Merged
merged 8 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -14,6 +14,7 @@
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
Expand Down Expand Up @@ -80,7 +81,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
if (symbol.IsOverride ||
symbol.ImplicitInterfaceImplementations().Any())
{
context.RegisterCodeFix(new MyCodeAction(FeaturesResources.Explicitly_inherit_documentation,
context.RegisterCodeFix(new MyCodeAction(CSharpCodeFixesResources.Explicitly_inherit_documentation,
c => FixAsync(context.Document, diagnostic, c)), context.Diagnostics);
}
}
Expand All @@ -99,7 +100,12 @@ protected override async Task FixAllAsync(Document document, ImmutableArray<Diag
continue;
}

newLine ??= (await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)).GetOption(FormattingOptions2.NewLine);
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(node.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
newLine ??= options.GetOption(FormattingOptions2.NewLine);
// We can safely assume, that there is no leading doc comment, because that is what CS1591 is telling us.
// So we create a new /// <inheritdoc/> comment.
var xmlSpaceAfterTripleSlash = Token(leading: TriviaList(DocumentationCommentExterior("///")), SyntaxKind.XmlTextLiteralToken, text: " ", valueText: " ", trailing: default);
Expand Down Expand Up @@ -128,10 +134,10 @@ protected override async Task FixAllAsync(Document document, ImmutableArray<Diag
}
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, equivalenceKey: nameof(FeaturesResources.Explicitly_inherit_documentation))
: base(title, createChangedDocument, equivalenceKey: nameof(CSharpCodeFixesResources.Explicitly_inherit_documentation))
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ internal class CSharpAddObsoleteAttributeCodeFixProvider
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpAddObsoleteAttributeCodeFixProvider()
: base(CSharpSyntaxFacts.Instance, CSharpFeaturesResources.Add_Obsolete)
: base(CSharpSyntaxFacts.Instance, CSharpCodeFixesResources.Add_Obsolete)
{
}
}
Expand Down
21 changes: 20 additions & 1 deletion src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,30 @@
<Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiersCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddAccessibilityModifiers\CSharpAddAccessibilityModifiersService.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddBraces\CSharpAddBracesCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddExplicitCast\AddExplicitCastCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddExplicitCast\ArgumentFixer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddExplicitCast\AttributeArgumentFixer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddInheritdoc\AddInheritdocCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AddObsoleteAttribute\CSharpAddObsoleteAttributeCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)AliasAmbiguousType\CSharpAliasAmbiguousTypeCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertNamespaceCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ConvertNamespace\ConvertNamespaceTransform.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ConvertTypeOfToNameOf\CSharpConvertTypeOfToNameOfCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ConvertSwitchStatementToExpression\ConvertSwitchStatementToExpressionCodeFixProvider.Rewriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)DisambiguateSameVariable\CSharpDisambiguateSameVariableCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FixReturnType\CSharpFixReturnTypeCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)HideBase\HideBaseCodeFixProvider.AddNewKeywordAction.cs" />
<Compile Include="$(MSBuildThisFileDirectory)HideBase\HideBaseCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Iterator\CSharpAddYieldCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Iterator\CSharpChangeToIEnumerableCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)MakeMemberStatic\CSharpMakeMemberStaticCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)MakeStatementAsynchronous\CSharpMakeStatementAsynchronousCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)MakeTypeAbstract\CSharpMakeTypeAbstractCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Nullable\CSharpDeclareAsNullableCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UnsealClass\CSharpUnsealClassCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseInterpolatedVerbatimString\CSharpUseInterpolatedVerbatimStringCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseLocalFunction\CSharpUseLocalFunctionCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UsePatternCombinators\CSharpUsePatternCombinatorsCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FileHeaders\CSharpFileHeaderCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)InlineDeclaration\CSharpInlineDeclarationCodeFixProvider.cs" />
Expand Down Expand Up @@ -83,4 +102,4 @@
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
<ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" />
</ItemGroup>
</Project>
</Project>
37 changes: 37 additions & 0 deletions src/Analyzers/CSharp/CodeFixes/CSharpCodeFixesResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,41 @@
<data name="Fix_record_declaration" xml:space="preserve">
<value>Fix_record_declaration</value>
</data>
<data name="Change_return_type_from_0_to_1" xml:space="preserve">
<value>Change return type from {0} to {1}</value>
</data>
<data name="Hide_base_member" xml:space="preserve">
<value>Hide base member</value>
</data>
<data name="Add_Obsolete" xml:space="preserve">
<value>Add [Obsolete]</value>
</data>
<data name="Explicitly_inherit_documentation" xml:space="preserve">
<value>Explicitly inherit documentation</value>
</data>
<data name="Unseal_class_0" xml:space="preserve">
<value>Unseal class '{0}'</value>
</data>
<data name="Use_interpolated_verbatim_string" xml:space="preserve">
<value>Use interpolated verbatim string</value>
</data>
<data name="Add_await" xml:space="preserve">
<value>Add 'await'</value>
<comment>{Locked="await"} "await" is a C# keyword and should not be localized.</comment>
</data>
<data name="Assign_to_0" xml:space="preserve">
<value>Assign to '{0}'</value>
</data>
<data name="Compare_to_0" xml:space="preserve">
<value>Compare to '{0}'</value>
</data>
<data name="Fix_return_type" xml:space="preserve">
<value>Fix return type</value>
</data>
<data name="Replace_return_with_yield_return" xml:space="preserve">
<value>Replace return with yield return</value>
</data>
<data name="Declare_as_nullable" xml:space="preserve">
<value>Declare as nullable</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ private static bool CanFix(
var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
var (left, right, titleFormat) = node switch
{
BinaryExpressionSyntax binary => (binary.Left, binary.Right, CSharpFeaturesResources.Compare_to_0),
AssignmentExpressionSyntax assignment => (assignment.Left, assignment.Right, CSharpFeaturesResources.Assign_to_0),
BinaryExpressionSyntax binary => (binary.Left, binary.Right, CSharpCodeFixesResources.Compare_to_0),
AssignmentExpressionSyntax assignment => (assignment.Left, assignment.Right, CSharpCodeFixesResources.Assign_to_0),
_ => default,
};

Expand Down Expand Up @@ -171,7 +171,7 @@ protected override async Task FixAllAsync(
}
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, nameof(CSharpDisambiguateSameVariableCodeFixProvider))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,10 @@ private static (TypeSyntax type, bool useTask) TryGetDeclarationTypeToFix(Syntax
}
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpFeaturesResources.Fix_return_type, createChangedDocument, nameof(CSharpFeaturesResources.Fix_return_type))
: base(CSharpCodeFixesResources.Fix_return_type, createChangedDocument, nameof(CSharpCodeFixesResources.Fix_return_type))
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
using Microsoft.CodeAnalysis.OrderModifiers;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;

#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
#endif

namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase
{
Expand All @@ -22,7 +29,7 @@ private class AddNewKeywordAction : CodeActions.CodeAction
private readonly Document _document;
private readonly SyntaxNode _node;

public override string Title => CSharpFeaturesResources.Hide_base_member;
public override string Title => CSharpCodeFixesResources.Hide_base_member;

public AddNewKeywordAction(Document document, SyntaxNode node)
{
Expand All @@ -34,19 +41,24 @@ protected override async Task<Document> GetChangedDocumentAsync(CancellationToke
{
var root = await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

var newNode = await GetNewNodeAsync(_node, cancellationToken).ConfigureAwait(false);
#if CODE_STYLE
var options = _document.Project.AnalyzerOptions.GetAnalyzerOptionSet(_node.SyntaxTree, cancellationToken);
#else
var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
Copy link
Member

Choose a reason for hiding this comment

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

man, i would love an extension for this.


var newNode = GetNewNode(_node, options);
var newRoot = root.ReplaceNode(_node, newNode);

return _document.WithSyntaxRoot(newRoot);
}

private async Task<SyntaxNode> GetNewNodeAsync(SyntaxNode node, CancellationToken cancellationToken)
private static SyntaxNode GetNewNode(SyntaxNode node, OptionSet options)
{
var syntaxFacts = CSharpSyntaxFacts.Instance;
var modifiers = syntaxFacts.GetModifiers(node);
var newModifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword));

var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var option = options.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder);
if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder) ||
!AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,10 @@ protected override bool TryGetNode(
return node != null;
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Document newDocument)
: base(CSharpFeaturesResources.Replace_return_with_yield_return, c => Task.FromResult(newDocument), nameof(CSharpFeaturesResources.Replace_return_with_yield_return))
: base(CSharpCodeFixesResources.Replace_return_with_yield_return, c => Task.FromResult(newDocument), nameof(CSharpCodeFixesResources.Replace_return_with_yield_return))
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected override async Task<CodeAction> GetCodeFixAsync(SyntaxNode root, Synta
}

return new MyCodeAction(
string.Format(CSharpFeaturesResources.Change_return_type_from_0_to_1,
string.Format(CSharpCodeFixesResources.Change_return_type_from_0_to_1,
type.ToMinimalDisplayString(model, node.SpanStart),
ienumerableGenericSymbol.ToMinimalDisplayString(model, node.SpanStart)), newDocument);
}
Expand All @@ -130,7 +130,7 @@ private static bool TryGetIEnumerableSymbols(SemanticModel model, out INamedType
return true;
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Document newDocument)
: base(title, c => Task.FromResult(newDocument), title)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,12 @@ private static SyntaxNode TryGetStatementToFix(SyntaxNode node)
return null;
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpFeaturesResources.Add_await,
: base(CSharpCodeFixesResources.Add_await,
createChangedDocument,
CSharpFeaturesResources.Add_await)
CSharpCodeFixesResources.Add_await)
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,10 @@ private static bool IsExpressionSupported(SyntaxNode node)
SyntaxKind.VariableDeclarator);
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(CSharpFeaturesResources.Declare_as_nullable,
: base(CSharpCodeFixesResources.Declare_as_nullable,
createChangedDocument,
equivalenceKey)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ public CSharpUnsealClassCodeFixProvider()
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(CS0509);

protected override string TitleFormat => CSharpFeaturesResources.Unseal_class_0;
protected override string TitleFormat => CSharpCodeFixesResources.Unseal_class_0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ private static void AddEdits(
editor.ReplaceNode(verbatimInterpolated, interpolatedVerbatim);
}

private class MyCodeAction : CodeAction.DocumentChangeAction
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Use_interpolated_verbatim_string, createChangedDocument, nameof(FeaturesResources.Use_interpolated_verbatim_string))
: base(CSharpCodeFixesResources.Use_interpolated_verbatim_string, createChangedDocument, nameof(CSharpCodeFixesResources.Use_interpolated_verbatim_string))
{
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,12 @@ protected override async Task FixAllAsync(
var root = editor.OriginalRoot;
var currentRoot = root.TrackNodes(nodesToTrack);

#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif

var languageVersion = semanticModel.SyntaxTree.Options.LanguageVersion();
var makeStaticIfPossible = languageVersion >= LanguageVersion.CSharp8 &&
options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value;
Expand Down
Loading