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

Formatter options refactoring - step 1 #58807

Merged
merged 13 commits into from
Jan 15, 2022
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 @@ -10,9 +10,11 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues;

Expand All @@ -31,6 +33,11 @@ public CSharpRemoveUnusedValuesCodeFixProvider()
{
}

#if CODE_STYLE
protected override ISyntaxFormattingService GetSyntaxFormattingService()
=> CSharpSyntaxFormattingService.Instance;
#endif

protected override BlockSyntax WrapWithBlockIfNecessary(IEnumerable<StatementSyntax> statements)
=> SyntaxFactory.Block(statements);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.MoveDeclarationNearReference;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplaceDiscardDeclarationsWithAssignments;
using Microsoft.CodeAnalysis.Shared.Extensions;
Expand Down Expand Up @@ -66,6 +67,9 @@ public sealed override ImmutableArray<string> FixableDiagnosticIds

internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;

#if CODE_STYLE
protected abstract ISyntaxFormattingService GetSyntaxFormattingService();
#endif
/// <summary>
/// Method to update the identifier token for the local/parameter declaration or reference
/// that was flagged as an unused value write by the analyzer.
Expand Down Expand Up @@ -268,14 +272,21 @@ private static async Task<Document> PreprocessDocumentAsync(Document document, I

protected sealed override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var newRoot = await GetNewRootAsync(
await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false),
diagnostics, cancellationToken).ConfigureAwait(false);
#if CODE_STYLE
var provider = GetSyntaxFormattingService();
var options = SyntaxFormattingOptions.Create(document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken));
#else
var provider = document.Project.Solution.Workspace.Services;
var options = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false);
#endif
var preprocessedDocument = await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false);
var newRoot = await GetNewRootAsync(preprocessedDocument, options, diagnostics, cancellationToken).ConfigureAwait(false);
editor.ReplaceNode(editor.OriginalRoot, newRoot);
}

private async Task<SyntaxNode> GetNewRootAsync(
Document document,
SyntaxFormattingOptions options,
ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
Expand Down Expand Up @@ -314,7 +325,7 @@ await FixAllAsync(diagnosticId, diagnosticsToFix.Select(d => d), document, seman

// Second pass to post process the document.
var currentRoot = editor.GetChangedRoot();
var newRoot = await PostProcessDocumentAsync(document, currentRoot,
var newRoot = await PostProcessDocumentAsync(document, options, currentRoot,
diagnosticId, preference, cancellationToken).ConfigureAwait(false);

if (currentRoot != newRoot)
Expand Down Expand Up @@ -719,6 +730,7 @@ bool ShouldRemoveStatement(TLocalDeclarationStatementSyntax localDeclarationStat

private async Task<SyntaxNode> PostProcessDocumentAsync(
Document document,
SyntaxFormattingOptions options,
SyntaxNode currentRoot,
string diagnosticId,
UnusedValuePreference preference,
Expand All @@ -731,24 +743,25 @@ private async Task<SyntaxNode> PostProcessDocumentAsync(
if (preference == UnusedValuePreference.DiscardVariable)
{
currentRoot = await PostProcessDocumentCoreAsync(
ReplaceDiscardDeclarationsWithAssignmentsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
ReplaceDiscardDeclarationsWithAssignmentsAsync, currentRoot, document, options, cancellationToken).ConfigureAwait(false);
}

// If we added new variable declaration statements, move these as close as possible to their
// first reference site.
if (NeedsToMoveNewLocalDeclarationsNearReference(diagnosticId))
{
currentRoot = await PostProcessDocumentCoreAsync(
AdjustLocalDeclarationsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
AdjustLocalDeclarationsAsync, currentRoot, document, options, cancellationToken).ConfigureAwait(false);
}

return currentRoot;
}

private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(
Func<SyntaxNode, Document, CancellationToken, Task<SyntaxNode>> processMemberDeclarationAsync,
Func<SyntaxNode, Document, SyntaxFormattingOptions, CancellationToken, Task<SyntaxNode>> processMemberDeclarationAsync,
SyntaxNode currentRoot,
Document document,
SyntaxFormattingOptions options,
CancellationToken cancellationToken)
{
// Process each member declaration which had at least one diagnostic reported in the original tree and hence
Expand All @@ -760,7 +773,7 @@ private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(

foreach (var memberDecl in newRoot.DescendantNodes().Where(n => n.HasAnnotation(s_memberAnnotation)))
{
var newMemberDecl = await processMemberDeclarationAsync(memberDecl, newDocument, cancellationToken).ConfigureAwait(false);
var newMemberDecl = await processMemberDeclarationAsync(memberDecl, newDocument, options, cancellationToken).ConfigureAwait(false);
memberDeclReplacementsMap.Add(memberDecl, newMemberDecl);
}

Expand All @@ -776,7 +789,7 @@ private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(
/// This is needed to prevent the code fix/FixAll from generating code with
/// multiple local variables named '_', which is a compiler error.
/// </summary>
private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(SyntaxNode memberDeclaration, Document document, CancellationToken cancellationToken)
private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(SyntaxNode memberDeclaration, Document document, SyntaxFormattingOptions options, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IReplaceDiscardDeclarationsWithAssignmentsService>();
if (service == null)
Expand All @@ -798,6 +811,7 @@ private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(Sy
private async Task<SyntaxNode> AdjustLocalDeclarationsAsync(
SyntaxNode memberDeclaration,
Document document,
SyntaxFormattingOptions options,
CancellationToken cancellationToken)
{
var moveDeclarationService = document.GetRequiredLanguageService<IMoveDeclarationNearReferenceService>();
Expand All @@ -821,7 +835,13 @@ private async Task<SyntaxNode> AdjustLocalDeclarationsAsync(
var rootWithTrackedNodes = root.TrackNodes(originalDeclStatementsToMoveOrRemove);

// Run formatter prior to invoking IMoveDeclarationNearReferenceService.
rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), document.Project.Solution.Workspace, cancellationToken: cancellationToken);
#if CODE_STYLE
var provider = GetSyntaxFormattingService();
rootWithTrackedNodes = FormatterHelper.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), provider, options, rules: null, cancellationToken);
#else
var provider = document.Project.Solution.Workspace.Services;
rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), provider, options, rules: null, cancellationToken);
#endif

document = document.WithSyntaxRoot(rootWithTrackedNodes);
await OnDocumentUpdatedAsync().ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
using Microsoft.CodeAnalysis.Simplification;
using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers;

#if CODE_STYLE
using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper;
#else
using Formatter = Microsoft.CodeAnalysis.Formatting.Formatter;
#endif

namespace Microsoft.CodeAnalysis.UseConditionalExpression
{
internal abstract class AbstractUseConditionalExpressionCodeFixProvider<
Expand Down Expand Up @@ -70,21 +76,15 @@ await FixOneAsync(
// annotation on it.
var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() };

var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);

#if CODE_STYLE
var formattedRoot = FormatterHelper.Format(changedRoot,
GetSyntaxFormattingService(),
SpecializedFormattingAnnotation,
options,
rules, cancellationToken);
var provider = GetSyntaxFormattingService();
var options = SyntaxFormattingOptions.Create(document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken));
#else
var formattedRoot = Formatter.Format(changedRoot,
SpecializedFormattingAnnotation,
document.Project.Solution.Workspace,
options,
rules, cancellationToken);
var provider = document.Project.Solution.Workspace.Services;
var options = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false);
#endif
var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, provider, options, rules, cancellationToken);

changedRoot = formattedRoot;

editor.ReplaceNode(root, changedRoot);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues
Imports Microsoft.CodeAnalysis.VisualBasic.Formatting
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues
Expand All @@ -23,6 +25,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues
Public Sub New()
End Sub

#If CODE_STYLE Then
Protected Overrides Function GetSyntaxFormattingService() As ISyntaxFormattingService
Return VisualBasicSyntaxFormattingService.Instance
End Function
#End If

Protected Overrides Function WrapWithBlockIfNecessary(statements As IEnumerable(Of StatementSyntax)) As StatementSyntax
' Unreachable code path as VB statements don't need to be wrapped in special BlockSyntax.
Throw ExceptionUtilities.Unreachable
Expand Down
6 changes: 2 additions & 4 deletions src/CodeStyle/Core/Analyzers/AbstractFormattingAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
Expand Down Expand Up @@ -36,8 +34,8 @@ protected sealed override void InitializeWorker(AnalysisContext context)

private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var analyzerConfigOptions = context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree);
FormattingAnalyzerHelper.AnalyzeSyntaxTree(context, SyntaxFormattingService, Descriptor, analyzerConfigOptions);
var options = SyntaxFormattingOptions.Create(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree));
FormattingAnalyzerHelper.AnalyzeSyntaxTree(context, SyntaxFormattingService, Descriptor, options);
}
}
}
Loading