Skip to content

Commit

Permalink
Move a couple of options from IdeCodeStyle to SyntaxFormatting to mak…
Browse files Browse the repository at this point in the history
…e them available to new document formatter
  • Loading branch information
tmat committed Apr 25, 2022
1 parent b4739ac commit e2f0810
Show file tree
Hide file tree
Showing 25 changed files with 205 additions and 121 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
using Microsoft.CodeAnalysis.AddImport;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.Diagnostics;

/// <summary>
/// Provides convenient access to C# editorconfig options with fallback to IDE default values.
/// Provides C# analyzers a convenient access to editorconfig options with fallback to IDE default values.
/// </summary>
internal readonly struct CSharpAnalyzerOptionsProvider
{
Expand Down Expand Up @@ -45,6 +46,11 @@ public CSharpAnalyzerOptionsProvider(AnalyzerConfigOptions options, AnalyzerOpti
public CodeStyleOption2<bool> PreferSimpleDefaultExpression => GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, FallbackSimplifierOptions.PreferSimpleDefaultExpression);
public CodeStyleOption2<PreferBracesPreference> PreferBraces => GetOption(CSharpCodeStyleOptions.PreferBraces, FallbackSimplifierOptions.PreferBraces);

// SyntaxFormattingOptions

public CodeStyleOption2<NamespaceDeclarationPreference> NamespaceDeclarations => GetOption(CSharpCodeStyleOptions.NamespaceDeclarations, FallbackSyntaxFormattingOptions.NamespaceDeclarations);
public CodeStyleOption2<bool> PreferTopLevelStatements => GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements, FallbackSyntaxFormattingOptions.PreferTopLevelStatements);

// CodeStyleOptions

public CodeStyleOption2<bool> ImplicitObjectCreationWhenTypeIsApparent => GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, FallbackCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent);
Expand Down Expand Up @@ -72,13 +78,11 @@ public CSharpAnalyzerOptionsProvider(AnalyzerConfigOptions options, AnalyzerOpti
public CodeStyleOption2<UnusedValuePreference> UnusedValueExpressionStatement => GetOption(CSharpCodeStyleOptions.UnusedValueExpressionStatement, FallbackCodeStyleOptions.UnusedValueExpressionStatement);
public CodeStyleOption2<UnusedValuePreference> UnusedValueAssignment => GetOption(CSharpCodeStyleOptions.UnusedValueAssignment, FallbackCodeStyleOptions.UnusedValueAssignment);
public CodeStyleOption2<bool> PreferMethodGroupConversion => GetOption(CSharpCodeStyleOptions.PreferMethodGroupConversion, FallbackCodeStyleOptions.PreferMethodGroupConversion);
public CodeStyleOption2<bool> PreferTopLevelStatements => GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements, FallbackCodeStyleOptions.PreferTopLevelStatements);

// CodeGenerationOptions

public CodeStyleOption2<ExpressionBodyPreference> PreferExpressionBodiedLambdas => GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, FallbackCodeStyleOptions.PreferExpressionBodiedLambdas);
public CodeStyleOption2<bool> PreferStaticLocalFunction => GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction, FallbackCodeStyleOptions.PreferStaticLocalFunction);
public CodeStyleOption2<NamespaceDeclarationPreference> NamespaceDeclarations => GetOption(CSharpCodeStyleOptions.NamespaceDeclarations, FallbackCodeStyleOptions.NamespaceDeclarations);
public CodeStyleOption2<AddImportPlacement> PreferredUsingDirectivePlacement => GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, FallbackCodeStyleOptions.PreferredUsingDirectivePlacement);

private TValue GetOption<TValue>(Option2<TValue> option, TValue defaultValue)
Expand All @@ -90,6 +94,9 @@ private CSharpIdeCodeStyleOptions FallbackCodeStyleOptions
private CSharpSimplifierOptions FallbackSimplifierOptions
=> (CSharpSimplifierOptions?)_fallbackOptions.CleanupOptions?.SimplifierOptions ?? CSharpSimplifierOptions.Default;

private CSharpSyntaxFormattingOptions FallbackSyntaxFormattingOptions
=> (CSharpSyntaxFormattingOptions?)_fallbackOptions.CleanupOptions?.FormattingOptions ?? CSharpSyntaxFormattingOptions.Default;

public static explicit operator CSharpAnalyzerOptionsProvider(AnalyzerOptionsProvider provider)
=> new(provider.GetAnalyzerConfigOptions(), provider.GetFallbackOptions());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle

Namespace Microsoft.CodeAnalysis.Diagnostics
''' <summary>
''' Provides convenient access to Visual Basic editorconfig options with fallback to IDE default values.
''' Provides Visual Basic analyzers a convenient access to editorconfig options with fallback to IDE default values.
''' </summary>
Friend Structure VisualBasicAnalyzerOptionsProvider
''' <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ public static CSharpIdeCodeStyleOptions GetCSharpCodeStyleOptions(this IGlobalOp
UnusedValueExpressionStatement: globalOptions.GetOption(CSharpCodeStyleOptions.UnusedValueExpressionStatement),
UnusedValueAssignment: globalOptions.GetOption(CSharpCodeStyleOptions.UnusedValueAssignment),
PreferMethodGroupConversion: globalOptions.GetOption(CSharpCodeStyleOptions.PreferMethodGroupConversion),
PreferTopLevelStatements: globalOptions.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements),
PreferExpressionBodiedLambdas: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas),
PreferStaticLocalFunction: globalOptions.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction),
NamespaceDeclarations: globalOptions.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations),
PreferredUsingDirectivePlacement: globalOptions.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement));
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ public SyntaxFormattingOptions GetOptions(IGlobalOptionService globalOptions)

public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(this IGlobalOptionService globalOptions)
=> new(
lineFormatting: globalOptions.GetLineFormattingOptions(LanguageNames.CSharp),
separateImportDirectiveGroups: globalOptions.GetOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp),
globalOptions.GetLineFormattingOptions(LanguageNames.CSharp),
globalOptions.GetOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp),
globalOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, LanguageNames.CSharp).Value,
spacing:
(globalOptions.GetOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration) ? SpacePlacement.IgnoreAroundVariableDeclaration : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName) ? SpacePlacement.AfterMethodDeclarationName : 0) |
Expand All @@ -57,7 +58,7 @@ public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(thi
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceBeforeComma) ? SpacePlacement.BeforeComma : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceAfterDot) ? SpacePlacement.AfterDot : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceBeforeDot) ? SpacePlacement.BeforeDot : 0),
spacingAroundBinaryOperator: globalOptions.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator),
globalOptions.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator),
newLines:
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit) ? NewLinePlacement.BeforeMembersInObjectInitializers : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes) ? NewLinePlacement.BeforeMembersInAnonymousTypes : 0) |
Expand All @@ -74,13 +75,15 @@ public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(thi
(globalOptions.GetOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody) ? NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks) ? NewLinePlacement.BeforeOpenBraceInControlBlocks : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForClausesInQuery) ? NewLinePlacement.BetweenQueryExpressionClauses : 0),
labelPositioning: globalOptions.GetOption(CSharpFormattingOptions2.LabelPositioning),
globalOptions.GetOption(CSharpFormattingOptions2.LabelPositioning),
indentation:
(globalOptions.GetOption(CSharpFormattingOptions2.IndentBraces) ? IndentationPlacement.Braces : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentBlock) ? IndentationPlacement.BlockContents : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSection) ? IndentationPlacement.SwitchCaseContents : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock) ? IndentationPlacement.SwitchCaseContentsWhenBlock : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchSection) ? IndentationPlacement.SwitchSection : 0),
wrappingKeepStatementsOnSingleLine: globalOptions.GetOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine),
wrappingPreserveSingleLine: globalOptions.GetOption(CSharpFormattingOptions2.WrappingPreserveSingleLine));
wrappingPreserveSingleLine: globalOptions.GetOption(CSharpFormattingOptions2.WrappingPreserveSingleLine),
globalOptions.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations),
globalOptions.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements));
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<Extension>
Public Function GetVisualBasicSyntaxFormattingOptions(globalOptions As IGlobalOptionService) As VisualBasicSyntaxFormattingOptions
Return New VisualBasicSyntaxFormattingOptions(
lineFormatting:=globalOptions.GetLineFormattingOptions(LanguageNames.VisualBasic),
separateImportDirectiveGroups:=globalOptions.GetOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic))
globalOptions.GetLineFormattingOptions(LanguageNames.VisualBasic),
globalOptions.GetOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic),
globalOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, LanguageNames.VisualBasic).Value)
End Function
End Module
End Namespace
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,8 @@ public CSharpAccessibilityModifiersNewDocumentFormattingProvider()

public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CodeCleanupOptions options, CancellationToken cancellationToken)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language);
if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never)
var accessibilityPreferences = options.FormattingOptions.AccessibilityModifiersRequired;
if (accessibilityPreferences == AccessibilityModifiersRequired.Never)
{
return document;
}
Expand All @@ -46,7 +45,7 @@ public async Task<Document> FormatNewDocumentAsync(Document document, Document?

foreach (var declaration in typeDeclarations)
{
if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences.Value, out _))
if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences, out _))
continue;

// Since we format each document as they are added to a project we can't assume we know about all
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeCleanup;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ConvertNamespace;
using Microsoft.CodeAnalysis.CSharp.Syntax;
Expand All @@ -31,21 +32,21 @@ public CSharpNamespaceDeclarationNewDocumentFormattingProvider()

public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CodeCleanupOptions options, CancellationToken cancellationToken)
{
var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var root = (CompilationUnitSyntax)await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

var namespaces = GetNamespacesToReplace(document, root, optionSet).ToList();
var formattingOptions = (CSharpSyntaxFormattingOptions)options.FormattingOptions;

var namespaces = GetNamespacesToReplace(document, root, formattingOptions.NamespaceDeclarations).ToList();
if (namespaces.Count != 1)
return document;

return await ConvertNamespaceTransform.ConvertAsync(document, namespaces[0], options.FormattingOptions, cancellationToken).ConfigureAwait(false);
}

private static IEnumerable<BaseNamespaceDeclarationSyntax> GetNamespacesToReplace(Document document, CompilationUnitSyntax root, DocumentOptionSet optionSet)
private static IEnumerable<BaseNamespaceDeclarationSyntax> GetNamespacesToReplace(Document document, CompilationUnitSyntax root, CodeStyleOption2<NamespaceDeclarationPreference> option)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var declarations = root.DescendantNodes().OfType<BaseNamespaceDeclarationSyntax>();
var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations);

foreach (var declaration in declarations)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,13 @@ public CSharpUseProgramMainNewDocumentFormattingProvider()

public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CodeCleanupOptions options, CancellationToken cancellationToken)
{
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

// if the user prefers Program.Main style instead, then attempt to convert a template with
// top-level-statements to that form.
var option = documentOptions.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements);
var option = ((CSharpSyntaxFormattingOptions)options.FormattingOptions).PreferTopLevelStatements;
if (option.Value)
return document;

var accessibilityModifiersRequired = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers).Value;
return await ConvertProgramTransform.ConvertToProgramMainAsync(document, accessibilityModifiersRequired, cancellationToken).ConfigureAwait(false);
return await ConvertProgramTransform.ConvertToProgramMainAsync(document, options.FormattingOptions.AccessibilityModifiersRequired, cancellationToken).ConfigureAwait(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImport;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
Expand Down Expand Up @@ -767,7 +768,8 @@ internal override bool IsGenericName(SimpleNameSyntax simpleName)
internal override bool IsSimpleName(ExpressionSyntax expression)
=> expression is SimpleNameSyntax;

internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(
Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, AddImportPlacementOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
Expand Down Expand Up @@ -803,9 +805,8 @@ internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solut
return updatedSolution;
}

var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
var addImportOptions = await document.GetAddImportPlacementOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, addImportOptions.PlaceSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,9 @@ private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateU
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false);
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(
updatedSolution, modifiedRoot: null, _semanticDocument.Document, _state.SimpleName,
includeUsingsOrImports, _fallbackOptions, cancellationToken).ConfigureAwait(false);
}

// Add reference of the updated project to the triggering Project if they are 2 different projects
Expand Down Expand Up @@ -459,6 +461,7 @@ private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocu
_semanticDocument.Document,
_state.SimpleName,
includeUsingsOrImports,
_fallbackOptions,
_cancellationToken).ConfigureAwait(false);
}

Expand Down
Loading

0 comments on commit e2f0810

Please sign in to comment.