diff --git a/eng/config/BannedSymbols.txt b/eng/config/BannedSymbols.txt index b3f5e5f9afcd1..8a51cac5d9646 100644 --- a/eng/config/BannedSymbols.txt +++ b/eng/config/BannedSymbols.txt @@ -25,3 +25,7 @@ M:Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.Synt M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.Text.TextSpan,Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.Text.TextSpan},Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead +M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions +M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.SyntaxAnnotation,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions +M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.Text.TextSpan,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions +M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.Text.TextSpan},Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions diff --git a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.CustomFixAllProvider.cs b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.CustomFixAllProvider.cs index b7b8c464dcb15..f635a0ad40383 100644 --- a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.CustomFixAllProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.CustomFixAllProvider.cs @@ -46,6 +46,11 @@ private class CustomFixAllProvider : FixAllProvider fixAllContext.Project.Solution, diagnostics, fixAllContext.GetProgressTracker(), +#if CODE_STYLE + options: _ => default, +#else + fixAllContext.State.CodeActionOptionsProvider, +#endif cancellationToken), title); @@ -67,6 +72,7 @@ private static async Task FixAllByDocumentAsync( Solution solution, ImmutableArray diagnostics, IProgressTracker progressTracker, + CodeActionOptionsProvider options, CancellationToken cancellationToken) { // Use documentId instead of tree here because the @@ -89,7 +95,7 @@ private static async Task FixAllByDocumentAsync( var document = newSolution.GetRequiredDocument(documentId); using var _ = progressTracker.ItemCompletedScope(document.Name); - newSolution = await FixAllInDocumentAsync(document, diagnosticsInTree, cancellationToken).ConfigureAwait(false); + newSolution = await FixAllInDocumentAsync(document, diagnosticsInTree, options, cancellationToken).ConfigureAwait(false); } return newSolution; diff --git a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs index 408f4c464f7ef..1155e31fa0f53 100644 --- a/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs @@ -8,12 +8,16 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; +using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.MatchFolderAndNamespace @@ -29,7 +33,13 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix( CodeAction.Create( AnalyzersResources.Change_namespace_to_match_folder_structure, - cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, cancellationToken), + cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, +#if CODE_STYLE + options: _ => default, +#else + context.Options, +#endif + cancellationToken), nameof(AnalyzersResources.Change_namespace_to_match_folder_structure)), context.Diagnostics); } @@ -37,7 +47,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) return Task.CompletedTask; } - private static async Task FixAllInDocumentAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken) + private static async Task FixAllInDocumentAsync(Document document, ImmutableArray diagnostics, CodeActionOptionsProvider options, CancellationToken cancellationToken) { // All the target namespaces should be the same for a given document Debug.Assert(diagnostics.Select(diagnostic => diagnostic.Properties[MatchFolderAndNamespaceConstants.TargetNamespace]).Distinct().Count() == 1); @@ -54,6 +64,9 @@ private static async Task FixAllInDocumentAsync(Document document, Imm var renameActionSet = await Renamer.RenameDocumentAsync( documentWithInvalidFolders, new DocumentRenameOptions(), +#if !CODE_STYLE + ChangeNamespaceOptions.CreateProvider(options), +#endif documentWithInvalidFolders.Name, newDocumentFolders: targetFolders, cancellationToken: cancellationToken).ConfigureAwait(false); diff --git a/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs b/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs index 2323f3ce78a98..3e406ff79ff00 100644 --- a/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Operations; @@ -27,8 +28,9 @@ internal class EncapsulateFieldCommandHandler : AbstractEncapsulateFieldCommandH public EncapsulateFieldCommandHandler( IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, + IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider) - : base(threadingContext, undoManager, listenerProvider) + : base(threadingContext, undoManager, globalOptions, listenerProvider) { } } diff --git a/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs b/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs index 370a3c1f63301..1029a436c209b 100644 --- a/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs +++ b/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs @@ -23,7 +23,7 @@ public Service() { } - public SimplifierOptions GetSimplifierOptions(IGlobalOptionService globalOptions) + public SimplifierOptions GetOptions(IGlobalOptionService globalOptions) => GetCSharpSimplifierOptions(globalOptions); } diff --git a/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs b/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs index 17acdb0203654..4cd54891e3a04 100644 --- a/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs +++ b/src/EditorFeatures/CSharpTest/MoveToNamespace/MoveToNamespaceTests.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; @@ -1124,6 +1125,7 @@ void Method() { } var actions = await testState.MoveToNamespaceService.GetCodeActionsAsync( testState.InvocationDocument, testState.TestInvocationDocument.SelectedSpans.Single(), + language => ChangeNamespaceOptions.GetDefault(testState.InvocationDocument.Project.LanguageServices), CancellationToken.None); Assert.Empty(actions); diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs b/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs index 705445b4258ec..512420104affc 100644 --- a/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs +++ b/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; @@ -30,18 +31,21 @@ internal abstract class AbstractSnippetExpansionClient : IExpansionClient protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; + public readonly IGlobalOptionService GlobalOptions; + protected bool _indentCaretOnCommit; protected int _indentDepth; protected bool _earlyEndExpansionHappened; public IExpansionSession? ExpansionSession { get; private set; } - public AbstractSnippetExpansionClient(IContentType languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IExpansionServiceProvider expansionServiceProvider) + public AbstractSnippetExpansionClient(IContentType languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IExpansionServiceProvider expansionServiceProvider, IGlobalOptionService globalOptions) { - this.LanguageServiceGuid = languageServiceGuid; - this.TextView = textView; - this.SubjectBuffer = subjectBuffer; - this.ExpansionServiceProvider = expansionServiceProvider; + LanguageServiceGuid = languageServiceGuid; + TextView = textView; + SubjectBuffer = subjectBuffer; + ExpansionServiceProvider = expansionServiceProvider; + GlobalOptions = globalOptions; } public abstract IExpansionFunction? GetExpansionFunction(XElement xmlFunctionNode, string fieldName); diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs index 5cc96ccbcfb70..eee35719dac32 100644 --- a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs +++ b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs @@ -84,7 +84,7 @@ protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITex { if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient)) { - expansionClient = new SnippetExpansionClient(subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider); + expansionClient = new SnippetExpansionClient(subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider, GlobalOptions); textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient); } diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetExpansionClient.cs b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetExpansionClient.cs index 5254107f15e7c..6243391dd4f7c 100644 --- a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetExpansionClient.cs +++ b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetExpansionClient.cs @@ -5,6 +5,7 @@ using System; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; @@ -17,8 +18,8 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { internal sealed partial class SnippetExpansionClient : AbstractSnippetExpansionClient { - public SnippetExpansionClient(IContentType languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IExpansionServiceProvider expansionServiceProvider) - : base(languageServiceGuid, textView, subjectBuffer, expansionServiceProvider) + public SnippetExpansionClient(IContentType languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IExpansionServiceProvider expansionServiceProvider, IGlobalOptionService globalOptions) + : base(languageServiceGuid, textView, subjectBuffer, expansionServiceProvider, globalOptions) { } diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs index c1344fe4e68af..d5e5f90bb0df7 100644 --- a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs +++ b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.cs @@ -96,7 +96,8 @@ protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); - var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; + var simplifierOptions = _snippetExpansionClient.GlobalOptions.GetSimplifierOptionsAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); + var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, simplifierOptions, cancellationToken).WaitAndGetResult(cancellationToken); simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs index bfa6bf753cd0e..77919413ba3eb 100644 --- a/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs +++ b/src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs @@ -37,7 +37,8 @@ protected override bool TryGetSimplifiedTypeName(Document documentWithFullyQuali var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithFullyQualifiedTypeName.WithSyntaxRoot(updatedRoot); - var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); + var simplifierOptions = _snippetExpansionClient.GlobalOptions.GetSimplifierOptionsAsync(documentWithAnnotations, cancellationToken).WaitAndGetResult(cancellationToken); + var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, simplifierOptions, cancellationToken).WaitAndGetResult(cancellationToken); simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } diff --git a/src/EditorFeatures/Core.Wpf/Peek/DefinitionPeekableItem.cs b/src/EditorFeatures/Core.Wpf/Peek/DefinitionPeekableItem.cs index 4b398e7df05c7..f3d7a685ac961 100644 --- a/src/EditorFeatures/Core.Wpf/Peek/DefinitionPeekableItem.cs +++ b/src/EditorFeatures/Core.Wpf/Peek/DefinitionPeekableItem.cs @@ -77,7 +77,7 @@ public void FindResults(string relationshipName, IPeekResultCollection resultCol if (!sourceLocations.Any()) { // It's a symbol from metadata, so we want to go produce it from metadata - var options = _peekableItem._globalOptions.GetMetadataAsSourceOptions(); + var options = _peekableItem._globalOptions.GetMetadataAsSourceOptions(project.LanguageServices); var declarationFile = _peekableItem._metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly: true, options, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); var peekDisplayInfo = new PeekResultDisplayInfo(declarationFile.DocumentTitle, declarationFile.DocumentTitle, declarationFile.DocumentTitle, declarationFile.DocumentTitle); var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; diff --git a/src/EditorFeatures/Core/CodeActions/CodeActionOptionsStorage.cs b/src/EditorFeatures/Core/CodeActions/CodeActionOptionsStorage.cs index 2d34c71dce1af..dae5305f10abd 100644 --- a/src/EditorFeatures/Core/CodeActions/CodeActionOptionsStorage.cs +++ b/src/EditorFeatures/Core/CodeActions/CodeActionOptionsStorage.cs @@ -4,12 +4,13 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.Completion; -using Microsoft.CodeAnalysis.ImplementType; -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ExtractMethod; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.ImplementType; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; +using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.CodeActions { @@ -26,7 +27,7 @@ private static CodeActionOptions GetCodeActionOptions(this IGlobalOptionService SearchOptions: globalOptions.GetSymbolSearchOptions(languageServices.Language), ImplementTypeOptions: globalOptions.GetImplementTypeOptions(languageServices.Language), ExtractMethodOptions: globalOptions.GetExtractMethodOptions(languageServices.Language), - FallbackSimplifierOptions: languageServices.GetService()?.GetSimplifierOptions(globalOptions), + SimplifierOptions: globalOptions.GetFallbackSimplifierOptions(languageServices), HideAdvancedMembers: globalOptions.GetOption(CompletionOptionsStorage.HideAdvancedMembers, languageServices.Language), IsBlocking: isBlocking); @@ -39,7 +40,7 @@ internal static CodeActionOptionsProvider GetCodeActionOptionsProvider(this IGlo internal static CodeActionOptionsProvider GetBlockingCodeActionOptionsProvider(this IGlobalOptionService globalOptions) { var cache = ImmutableDictionary.Empty; - return language => ImmutableInterlocked.GetOrAdd(ref cache, language, (language, options) => GetBlockingCodeActionOptions(options, language), globalOptions); + return languageService => ImmutableInterlocked.GetOrAdd(ref cache, languageService.Language, (language, options) => GetBlockingCodeActionOptions(options, languageService), globalOptions); } } } diff --git a/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs b/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs index 02e8b5918d848..d5861917efa69 100644 --- a/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs +++ b/src/EditorFeatures/Core/CodeDefinitionWindow/DefinitionContextTracker.cs @@ -210,7 +210,7 @@ internal async Task> GetContextFrom } else if (_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { - var options = _globalOptions.GetMetadataAsSourceOptions(); + var options = _globalOptions.GetMetadataAsSourceOptions(document.Project.LanguageServices); var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync(document.Project, symbol, signaturesOnly: false, options, cancellationToken).ConfigureAwait(false); var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; return ImmutableArray.Create(new CodeDefinitionWindowLocation(symbol.ToDisplayString(), declarationFile.FilePath, identifierSpan.Start)); diff --git a/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs b/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs index 68847172ebd8b..a356dbaeb5f6c 100644 --- a/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/Core/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs @@ -9,8 +9,10 @@ using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; @@ -23,6 +25,7 @@ internal abstract class AbstractEncapsulateFieldCommandHandler : ICommandHandler { private readonly IThreadingContext _threadingContext; private readonly ITextBufferUndoManagerProvider _undoManager; + private readonly IGlobalOptionService _globalOptions; private readonly IAsynchronousOperationListener _listener; public string DisplayName => EditorFeaturesResources.Encapsulate_Field; @@ -30,10 +33,12 @@ internal abstract class AbstractEncapsulateFieldCommandHandler : ICommandHandler public AbstractEncapsulateFieldCommandHandler( IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, + IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _undoManager = undoManager; + _globalOptions = globalOptions; _listener = listenerProvider.GetListener(FeatureAttribute.EncapsulateField); } @@ -65,7 +70,10 @@ private bool Execute(EncapsulateFieldCommandArgs args, IUIThreadOperationScope w var service = document.GetLanguageService(); - var result = service.EncapsulateFieldsInSpanAsync(document, spans.First().Span.ToTextSpan(), true, cancellationToken).WaitAndGetResult(cancellationToken); + var fallbackOptions = new EncapsulateFieldOptions( + SimplifierOptions: _globalOptions.GetFallbackSimplifierOptions(document.Project.LanguageServices)); + + var result = service.EncapsulateFieldsInSpanAsync(document, spans.First().Span.ToTextSpan(), fallbackOptions, useDefaultBehavior: true, cancellationToken).WaitAndGetResult(cancellationToken); // We are about to show a modal UI dialog so we should take over the command execution // wait context. That means the command system won't attempt to show its own wait dialog diff --git a/src/EditorFeatures/Core/LanguageServer/Handlers/References/FindUsagesLSPContext.cs b/src/EditorFeatures/Core/LanguageServer/Handlers/References/FindUsagesLSPContext.cs index 64787cfc4819c..90912055ea1b1 100644 --- a/src/EditorFeatures/Core/LanguageServer/Handlers/References/FindUsagesLSPContext.cs +++ b/src/EditorFeatures/Core/LanguageServer/Handlers/References/FindUsagesLSPContext.cs @@ -244,7 +244,7 @@ public override async ValueTask OnReferenceFoundAsync(SourceReferenceItem refere return null; } - var options = _globalOptions.GetMetadataAsSourceOptions(); + var options = _globalOptions.GetMetadataAsSourceOptions(_document.Project.LanguageServices); var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync( _document.Project, symbol, signaturesOnly: true, options, cancellationToken).ConfigureAwait(false); diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.cs b/src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.cs index eefb13e9583c9..509a5b87a1122 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; @@ -47,6 +48,7 @@ public async Task TestMoveToNamespaceAsync( var actions = await testState.MoveToNamespaceService.GetCodeActionsAsync( testState.InvocationDocument, testState.TestInvocationDocument.SelectedSpans.Single(), + language => ChangeNamespaceOptions.GetDefault(workspace.Services.GetLanguageServices(GetLanguage())), CancellationToken.None); var operationTasks = actions diff --git a/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs b/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs index 45ff92a6ef52f..096f9d9102285 100644 --- a/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs +++ b/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs @@ -4,6 +4,7 @@ using System; using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; @@ -38,7 +39,8 @@ private static SyntaxNode Simplify( var annotatedDocument = document.WithSyntaxRoot( root.WithAdditionalAnnotations(Simplifier.Annotation)); - var simplifiedDocument = Simplifier.ReduceAsync(annotatedDocument).Result; + var options = document.Project.LanguageServices.GetRequiredService().DefaultOptions; + var simplifiedDocument = Simplifier.ReduceAsync(annotatedDocument, options, CancellationToken.None).Result; var rootNode = simplifiedDocument.GetRequiredSyntaxRootAsync(default).AsTask().Result; diff --git a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb index fc199dd1b1667..5de020bb74c8b 100644 --- a/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb +++ b/src/EditorFeatures/Test2/NavigationBar/TestHelpers.vb @@ -96,7 +96,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar Dim contextLocation = (Await document.GetSyntaxTreeAsync()).GetLocation(New TextSpan(0, 0)) Dim generateCodeItem = DirectCast(rightItem, WrappedNavigationBarItem).UnderlyingItem - Dim newDocument = Await VisualBasicEditorNavigationBarItemService.GetGeneratedDocumentAsync(document, generateCodeItem, CancellationToken.None) + Dim newDocument = Await VisualBasicEditorNavigationBarItemService.GetGeneratedDocumentAsync(document, generateCodeItem, workspace.GlobalOptions, CancellationToken.None) Dim actual = (Await newDocument.GetSyntaxRootAsync()).ToFullString().TrimEnd() Dim expected = expectedText.NormalizedValue.TrimEnd() diff --git a/src/EditorFeatures/Test2/Simplification/ParameterSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/ParameterSimplificationTests.vb index 45bfae7c85aef..0c6aafb34c9e8 100644 --- a/src/EditorFeatures/Test2/Simplification/ParameterSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/ParameterSimplificationTests.vb @@ -2,6 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. +Imports System.Threading +Imports Microsoft.CodeAnalysis.CSharp.Simplification Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text @@ -23,7 +25,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Dim annotatedDocument = document.WithSyntaxRoot( (Await document.GetSyntaxRootAsync()).WithAdditionalAnnotations(Simplifier.Annotation)) - Dim simplifiedDocument = Await Simplifier.ReduceAsync(annotatedDocument) + Dim simplifiedDocument = Await Simplifier.ReduceAsync(annotatedDocument, CSharpSimplifierOptions.Default, CancellationToken.None) Assert.Equal(expected, (Await simplifiedDocument.GetTextAsync()).ToString()) End Using diff --git a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb index 3deca66036fa7..692cfdb2df231 100644 --- a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb @@ -11,6 +11,7 @@ Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities +Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.VisualBasic.EncapsulateField @@ -24,8 +25,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Public Sub New(threadingContext As IThreadingContext, undoManager As ITextBufferUndoManagerProvider, + globalOptions As IGlobalOptionService, listenerProvider As IAsynchronousOperationListenerProvider) - MyBase.New(threadingContext, undoManager, listenerProvider) + MyBase.New(threadingContext, undoManager, globalOptions, listenerProvider) End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb index f5889434f3474..ad29945d5fb42 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb @@ -13,6 +13,7 @@ Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor @@ -88,13 +89,15 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Concat(commitFormattingCleanup) Dim cleanupService = document.GetRequiredLanguageService(Of ICodeCleanerService) + Dim simplifierOptions = _globalOptions.GetSimplifierOptionsAsync(document, cancellationToken).WaitAndGetResult(cancellationToken) + Dim cleanupOptions = New CodeCleanupOptions(formattingOptions, simplifierOptions) Dim finalDocument As Document If useSemantics OrElse isExplicitFormat Then finalDocument = cleanupService.CleanupAsync( document, ImmutableArray.Create(textSpanToFormat), - formattingOptions, + cleanupOptions, codeCleanups, cancellationToken).WaitAndGetResult(cancellationToken) Else diff --git a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService.vb b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService.vb index 370bf1681bc55..29d1e8bb7edf6 100644 --- a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService.vb +++ b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService.vb @@ -9,6 +9,7 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor @@ -23,16 +24,19 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar Private ReadOnly _editorOperationsFactoryService As IEditorOperationsFactoryService Private ReadOnly _textUndoHistoryRegistry As ITextUndoHistoryRegistry + Private ReadOnly _globalOptions As IGlobalOptionService Public Sub New( threadingContext As IThreadingContext, editorOperationsFactoryService As IEditorOperationsFactoryService, - textUndoHistoryRegistry As ITextUndoHistoryRegistry) + textUndoHistoryRegistry As ITextUndoHistoryRegistry, + globalOptions As IGlobalOptionService) MyBase.New(threadingContext) _editorOperationsFactoryService = editorOperationsFactoryService _textUndoHistoryRegistry = textUndoHistoryRegistry + _globalOptions = globalOptions End Sub Friend Overrides Async Function GetNavigationLocationAsync( diff --git a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService_CodeGeneration.vb b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService_CodeGeneration.vb index 15e8944e24f20..e86ba24061d66 100644 --- a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService_CodeGeneration.vb +++ b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicEditorNavigationBarItemService_CodeGeneration.vb @@ -13,6 +13,7 @@ Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.NavigationBar Imports Microsoft.CodeAnalysis.NavigationBar.RoslynNavigationBarItem +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text @@ -24,7 +25,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar Private Async Function GenerateCodeForItemAsync(document As Document, generateCodeItem As AbstractGenerateCodeItem, textView As ITextView, cancellationToken As CancellationToken) As Task ' We'll compute everything up front before we go mutate state Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False) - Dim newDocument = Await GetGeneratedDocumentAsync(document, generateCodeItem, cancellationToken).ConfigureAwait(False) + Dim newDocument = Await GetGeneratedDocumentAsync(document, generateCodeItem, _globalOptions, cancellationToken).ConfigureAwait(False) Dim generatedTree = Await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim generatedNode = generatedTree.GetAnnotatedNodes(GeneratedSymbolAnnotation).Single().FirstAncestorOrSelf(Of MethodBlockBaseSyntax) @@ -48,7 +49,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar End Using End Function - Public Shared Async Function GetGeneratedDocumentAsync(document As Document, generateCodeItem As RoslynNavigationBarItem, cancellationToken As CancellationToken) As Task(Of Document) + Public Shared Async Function GetGeneratedDocumentAsync(document As Document, generateCodeItem As RoslynNavigationBarItem, globalOptions As IGlobalOptionService, cancellationToken As CancellationToken) As Task(Of Document) Dim syntaxTree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False) Dim contextLocation = syntaxTree.GetLocation(New TextSpan(0, 0)) @@ -59,19 +60,20 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar Return document End If - newDocument = Await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).ConfigureAwait(False) + Dim simplifierOptions = Await globalOptions.GetSimplifierOptionsAsync(newDocument, cancellationToken).ConfigureAwait(False) + Dim formattingOptions = Await SyntaxFormattingOptions.FromDocumentAsync(newDocument, cancellationToken).ConfigureAwait(False) + + newDocument = Await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, simplifierOptions, cancellationToken).ConfigureAwait(False) Dim formatterRules = Formatter.GetDefaultFormattingRules(newDocument) If ShouldApplyLineAdjustmentFormattingRule(generateCodeItem) Then formatterRules = ImmutableArray.Create(Of AbstractFormattingRule)(LineAdjustmentFormattingRule.Instance).AddRange(formatterRules) End If - Dim documentOptions = Await document.GetOptionsAsync(cancellationToken).ConfigureAwait(False) - Return Await Formatter.FormatAsync( newDocument, Formatter.Annotation, - options:=documentOptions, + options:=formattingOptions, cancellationToken:=cancellationToken, rules:=formatterRules).ConfigureAwait(False) End Function diff --git a/src/EditorFeatures/VisualBasic/Simplification/VisualBasicSimplifierOptionsStorage.vb b/src/EditorFeatures/VisualBasic/Simplification/VisualBasicSimplifierOptionsStorage.vb index 8ab26843ccf60..3065cbbac3398 100644 --- a/src/EditorFeatures/VisualBasic/Simplification/VisualBasicSimplifierOptionsStorage.vb +++ b/src/EditorFeatures/VisualBasic/Simplification/VisualBasicSimplifierOptionsStorage.vb @@ -22,7 +22,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification End Sub - Public Function GetSimplifierOptions(globalOptions As IGlobalOptionService) As SimplifierOptions Implements ISimplifierOptionsStorage.GetSimplifierOptions + Public Function GetOptions(globalOptions As IGlobalOptionService) As SimplifierOptions Implements ISimplifierOptionsStorage.GetOptions Return GetVisualBasicSimplifierOptions(globalOptions) End Function End Class diff --git a/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb b/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb index d2978febaf77b..c0fc582ef56a0 100644 --- a/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb @@ -171,8 +171,9 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers End If Dim formattingOptions = SyntaxFormattingOptions.FromDocumentAsync(newDocument, cancellationToken).WaitAndGetResult(cancellationToken) + Dim simplifierOptions = _globalOptions.GetSimplifierOptionsAsync(newDocument, cancellationToken).WaitAndGetResult(cancellationToken) - newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, Nothing, cancellationToken).WaitAndGetResult(cancellationToken) + newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, simplifierOptions, cancellationToken).WaitAndGetResult(cancellationToken) newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, formattingOptions, cancellationToken).WaitAndGetResult(cancellationToken) newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken) diff --git a/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb b/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb index 3ef31c1fa05ec..68369fd90e01a 100644 --- a/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CaseCorrecting/CaseCorrectionServiceTests.vb @@ -11,6 +11,7 @@ Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Formatting +Imports Microsoft.CodeAnalysis.Simplification Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CaseCorrecting <[UseExportProvider]> @@ -34,7 +35,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CaseCorrecting Dim buffer = hostDocument.GetTextBuffer() Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim span = (Await document.GetSyntaxRootAsync()).FullSpan - Dim options = Await SyntaxFormattingOptions.FromDocumentAsync(document, CancellationToken.None) + + Dim options = New CodeCleanupOptions( + Await SyntaxFormattingOptions.FromDocumentAsync(document, CancellationToken.None), + Await SimplifierOptions.FromDocumentAsync(document, fallbackOptions:=Nothing, CancellationToken.None)) Dim service = document.GetLanguageService(Of ICodeCleanerService) Dim newDocument = Await service.CleanupAsync( diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb index 30ea8abb4dfaf..25d5a68b0f56b 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb @@ -6,6 +6,7 @@ Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.VisualBasic.EncapsulateField Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands @@ -154,6 +155,7 @@ End Class Dim handler = New EncapsulateFieldCommandHandler( workspace.GetService(Of IThreadingContext), workspace.GetService(Of ITextBufferUndoManagerProvider), + workspace.GlobalOptions, workspace.GetService(Of IAsynchronousOperationListenerProvider)()) Dim state = handler.GetCommandState(New EncapsulateFieldCommandArgs(textView, textView.TextBuffer)) diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb index c5f187fa03b38..386325aca98d5 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb @@ -35,6 +35,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Dim commandHandler = New EncapsulateFieldCommandHandler( Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), Workspace.GetService(Of ITextBufferUndoManagerProvider)(), + Workspace.GlobalOptions, Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub diff --git a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.cs index 4812227cc7116..dcc989931b350 100644 --- a/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.cs @@ -53,7 +53,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte } var configOptions = await document.GetAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); - var simplifierOptions = CSharpSimplifierOptions.Create(configOptions, (CSharpSimplifierOptions)context.Options.FallbackSimplifierOptions); + var simplifierOptions = CSharpSimplifierOptions.Create(configOptions, (CSharpSimplifierOptions)context.Options(document.Project.LanguageServices).SimplifierOptions); var typeStyle = AnalyzeTypeName(declaredType, semanticModel, simplifierOptions, cancellationToken); if (typeStyle.IsStylePreferred && typeStyle.Severity != ReportDiagnostic.Suppress) { diff --git a/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementInterfaceCodeFixProvider.cs b/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementInterfaceCodeFixProvider.cs index 676af4f7ba025..1362d6a7fe76f 100644 --- a/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementInterfaceCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/ImplementInterface/CSharpImplementInterfaceCodeFixProvider.cs @@ -54,7 +54,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) var actions = token.Parent.GetAncestorsOrThis() .Where(_interfaceName) - .Select(n => service.GetCodeActions(document, context.Options(document.Project.Language).ImplementTypeOptions, model, n, cancellationToken)) + .Select(n => service.GetCodeActions(document, context.Options(document.Project.LanguageServices).ImplementTypeOptions, model, n, cancellationToken)) .FirstOrDefault(a => !a.IsEmpty); if (actions.IsDefaultOrEmpty) diff --git a/src/Features/Core/Portable/AddImport/AbstractAddImportCodeFixProvider.cs b/src/Features/Core/Portable/AddImport/AbstractAddImportCodeFixProvider.cs index 2d12603c7e556..44f09038a6057 100644 --- a/src/Features/Core/Portable/AddImport/AbstractAddImportCodeFixProvider.cs +++ b/src/Features/Core/Portable/AddImport/AbstractAddImportCodeFixProvider.cs @@ -55,7 +55,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) var addImportService = document.GetRequiredLanguageService(); var services = document.Project.Solution.Workspace.Services; - var searchOptions = context.Options(document.Project.Language).SearchOptions; + var searchOptions = context.Options(document.Project.LanguageServices).SearchOptions; var symbolSearchService = _symbolSearchService ?? services.GetRequiredService(); @@ -75,7 +75,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) var addImportOptions = new AddImportOptions( searchOptions, - context.Options(document.Project.Language).HideAdvancedMembers, + context.Options(document.Project.LanguageServices).HideAdvancedMembers, placement); var fixesForDiagnostic = await addImportService.GetFixesForDiagnosticsAsync( diff --git a/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs b/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs index 94c8901b70553..9e543e09569ad 100644 --- a/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs +++ b/src/Features/Core/Portable/AddPackage/AbstractAddPackageCodeFixProvider.cs @@ -52,7 +52,7 @@ protected async Task> GetAddPackagesCodeActionsAsync( var codeActions = ArrayBuilder.GetInstance(); if (symbolSearchService != null && installerService != null && - context.Options(document.Project.Language).SearchOptions.SearchNuGetPackages && + context.Options(document.Project.LanguageServices).SearchOptions.SearchNuGetPackages && installerService.IsEnabled(document.Project.Id)) { var packageSources = PackageSourceHelper.GetPackageSources(installerService.TryGetPackageSources()); diff --git a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs index df26d9b289e2b..8060fb3003584 100644 --- a/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs +++ b/src/Features/Core/Portable/CodeRefactorings/AddMissingImports/AbstractAddMissingImportsRefactoringProvider.cs @@ -40,7 +40,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte var addMissingImportsService = document.GetLanguageService(); var placement = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); - var options = new AddMissingImportsOptions(context.Options(document.Project.Language).HideAdvancedMembers, placement); + var options = new AddMissingImportsOptions(context.Options(document.Project.LanguageServices).HideAdvancedMembers, placement); var analysis = await addMissingImportsService.AnalyzeAsync(document, textSpan, options, cancellationToken).ConfigureAwait(false); if (!analysis.CanAddMissingImports) diff --git a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs index aae685a87be61..51aded52f3354 100644 --- a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs @@ -56,7 +56,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte return; } - var options = context.Options(document.Project.Language).ExtractMethodOptions; + var options = context.Options(document.Project.LanguageServices).ExtractMethodOptions; var actions = await GetCodeActionsAsync(document, textSpan, options, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } diff --git a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs index 8e2fa98735110..1997d385a21f7 100644 --- a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractChangeNamespaceService.cs @@ -34,9 +34,9 @@ internal abstract class AbstractChangeNamespaceService : IChangeNamespaceService { public abstract Task CanChangeNamespaceAsync(Document document, SyntaxNode container, CancellationToken cancellationToken); - public abstract Task ChangeNamespaceAsync(Document document, SyntaxNode container, string targetNamespace, CancellationToken cancellationToken); + public abstract Task ChangeNamespaceAsync(Document document, SyntaxNode container, string targetNamespace, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); - public abstract Task TryChangeTopLevelNamespacesAsync(Document document, string targetNamespace, CancellationToken cancellationToken); + public abstract Task TryChangeTopLevelNamespacesAsync(Document document, string targetNamespace, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); /// /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the @@ -110,6 +110,7 @@ public override async Task CanChangeNamespaceAsync(Document document, Synt public override async Task TryChangeTopLevelNamespacesAsync( Document document, string targetNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService(); @@ -151,7 +152,7 @@ public override async Task CanChangeNamespaceAsync(Document document, Synt Debug.Assert(namespaces.Length == originalNamespaceDeclarations.Length); var namespaceToRename = namespaces[i]; - solution = await ChangeNamespaceAsync(document, namespaceToRename, targetNamespace, cancellationToken).ConfigureAwait(false); + solution = await ChangeNamespaceAsync(document, namespaceToRename, targetNamespace, options, cancellationToken).ConfigureAwait(false); document = solution.GetRequiredDocument(document.Id); } @@ -172,6 +173,7 @@ public override async Task ChangeNamespaceAsync( Document document, SyntaxNode container, string targetNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { // Make sure given namespace name is valid, "" means global namespace. @@ -220,7 +222,7 @@ public override async Task ChangeNamespaceAsync( foreach (var documentId in documentIds) { var (newSolution, refDocumentIds) = - await ChangeNamespaceInSingleDocumentAsync(solutionAfterNamespaceChange, documentId, declaredNamespace, targetNamespace, cancellationToken) + await ChangeNamespaceInSingleDocumentAsync(solutionAfterNamespaceChange, documentId, declaredNamespace, targetNamespace, options, cancellationToken) .ConfigureAwait(false); solutionAfterNamespaceChange = newSolution; referenceDocuments.AddRange(refDocumentIds); @@ -426,6 +428,7 @@ private static SyntaxNode CreateImport(SyntaxGenerator syntaxGenerator, string n DocumentId id, string oldNamespace, string newNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { var document = solution.GetRequiredDocument(id); @@ -462,7 +465,7 @@ private static SyntaxNode CreateImport(SyntaxGenerator syntaxGenerator, string n } } - var documentWithNewNamespace = await FixDeclarationDocumentAsync(document, refLocationsInCurrentDocument, oldNamespace, newNamespace, cancellationToken) + var documentWithNewNamespace = await FixDeclarationDocumentAsync(document, refLocationsInCurrentDocument, oldNamespace, newNamespace, options, cancellationToken) .ConfigureAwait(false); var solutionWithChangedNamespace = documentWithNewNamespace.Project.Solution; @@ -474,6 +477,7 @@ private static SyntaxNode CreateImport(SyntaxGenerator syntaxGenerator, string n solutionWithChangedNamespace.GetRequiredDocument(refInOneDocument.Key), refInOneDocument, newNamespace, + options, cancellationToken))).ConfigureAwait(false); var solutionWithFixedReferences = await MergeDocumentChangesAsync(solutionWithChangedNamespace, fixedDocuments, cancellationToken).ConfigureAwait(false); @@ -558,6 +562,7 @@ private async Task FixDeclarationDocumentAsync( IReadOnlyList refLocations, string oldNamespace, string newNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { Debug.Assert(newNamespace != null); @@ -606,15 +611,14 @@ private async Task FixDeclarationDocumentAsync( // references to the type inside it's new namespace var namesToImport = GetAllNamespaceImportsForDeclaringDocument(oldNamespace, newNamespace); - var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); - var addImportsOptions = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var documentOptions = await ChangeNamespaceOptions.FromDocumentAsync(document, options(document.Project.LanguageServices), cancellationToken).ConfigureAwait(false); var documentWithAddedImports = await AddImportsInContainersAsync( document, addImportService, containersToAddImports, namesToImport, - addImportsOptions, + documentOptions.AddImportOptions, cancellationToken).ConfigureAwait(false); var root = await documentWithAddedImports.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); @@ -624,18 +628,18 @@ private async Task FixDeclarationDocumentAsync( // Need to invoke formatter explicitly since we are doing the diff merge ourselves. var services = documentWithAddedImports.Project.Solution.Workspace.Services; - var formattingOptions = SyntaxFormattingOptions.Create(optionSet, services, root.Language); - root = Formatter.Format(root, Formatter.Annotation, services, formattingOptions, cancellationToken); + root = Formatter.Format(root, Formatter.Annotation, services, documentOptions.FormattingOptions, cancellationToken); root = root.WithAdditionalAnnotations(Simplifier.Annotation); var formattedDocument = documentWithAddedImports.WithSyntaxRoot(root); - return await Simplifier.ReduceAsync(formattedDocument, optionSet, cancellationToken).ConfigureAwait(false); + return await Simplifier.ReduceAsync(formattedDocument, documentOptions.SimplifierOptions, cancellationToken).ConfigureAwait(false); } private static async Task FixReferencingDocumentAsync( Document document, IEnumerable refLocations, string newNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { // 1. Fully qualify all simple references (i.e. not via an alias) with new namespace. @@ -651,23 +655,21 @@ private static async Task FixReferencingDocumentAsync( await FixReferencesAsync(document, changeNamespaceService, addImportService, refLocations, newNamespaceParts, cancellationToken) .ConfigureAwait(false); - var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); - var addImportsOptions = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var documentOptions = await ChangeNamespaceOptions.FromDocumentAsync(document, options(document.Project.LanguageServices), cancellationToken).ConfigureAwait(false); var documentWithAdditionalImports = await AddImportsInContainersAsync( documentWithRefFixed, addImportService, containers, ImmutableArray.Create(newNamespace), - addImportsOptions, + documentOptions.AddImportOptions, cancellationToken).ConfigureAwait(false); // Need to invoke formatter explicitly since we are doing the diff merge ourselves. - var formattedDocument = await Formatter.FormatAsync(documentWithAdditionalImports, Formatter.Annotation, formattingOptions, cancellationToken) + var formattedDocument = await Formatter.FormatAsync(documentWithAdditionalImports, Formatter.Annotation, documentOptions.FormattingOptions, cancellationToken) .ConfigureAwait(false); - var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); - return await Simplifier.ReduceAsync(formattedDocument, optionSet, cancellationToken).ConfigureAwait(false); + return await Simplifier.ReduceAsync(formattedDocument, documentOptions.SimplifierOptions, cancellationToken).ConfigureAwait(false); } /// diff --git a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.cs index 95d0fb8d24e5e..678198a141e9c 100644 --- a/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.cs @@ -73,7 +73,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte state.TargetNamespace.Length == 0 ? FeaturesResources.Change_to_global_namespace : string.Format(FeaturesResources.Change_namespace_to_0, state.TargetNamespace), - token => service.ChangeNamespaceAsync(document, state.Container, state.TargetNamespace, token)); + token => service.ChangeNamespaceAsync(document, state.Container, state.TargetNamespace, ChangeNamespaceOptions.CreateProvider(context.Options), token)); context.RegisterRefactoring(solutionChangeAction, textSpan); } diff --git a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs index f7f7226721e08..bed0afe5b7d68 100644 --- a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs +++ b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs @@ -32,7 +32,7 @@ internal abstract partial class AbstractEncapsulateFieldService : ILanguageServi protected abstract Task RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken); protected abstract Task> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken); - public async Task EncapsulateFieldsInSpanAsync(Document document, TextSpan span, bool useDefaultBehavior, CancellationToken cancellationToken) + public async Task EncapsulateFieldsInSpanAsync(Document document, TextSpan span, EncapsulateFieldOptions fallbackOptions, bool useDefaultBehavior, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) @@ -42,10 +42,10 @@ public async Task EncapsulateFieldsInSpanAsync(Document return new EncapsulateFieldResult( firstField.ToDisplayString(), firstField.GetGlyph(), - c => EncapsulateFieldsAsync(document, fields, useDefaultBehavior, c)); + c => EncapsulateFieldsAsync(document, fields, fallbackOptions, useDefaultBehavior, c)); } - public async Task> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken) + public async Task> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, EncapsulateFieldOptions fallbackOptions, CancellationToken cancellationToken) { var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false); if (fields.IsDefaultOrEmpty) @@ -54,7 +54,7 @@ public async Task> GetEncapsulateFieldCodeActionsAsyn if (fields.Length == 1) { // there is only one field - return EncapsulateOneField(document, fields[0]); + return EncapsulateOneField(document, fields[0], fallbackOptions); } // there are multiple fields. @@ -64,38 +64,39 @@ public async Task> GetEncapsulateFieldCodeActionsAsyn { // if there is no selection, get action for each field + all of them. foreach (var field in fields) - builder.AddRange(EncapsulateOneField(document, field)); + builder.AddRange(EncapsulateOneField(document, field, fallbackOptions)); } - builder.AddRange(EncapsulateAllFields(document, fields)); + builder.AddRange(EncapsulateAllFields(document, fields, fallbackOptions)); return builder.ToImmutable(); } - private ImmutableArray EncapsulateAllFields(Document document, ImmutableArray fields) + private ImmutableArray EncapsulateAllFields(Document document, ImmutableArray fields, EncapsulateFieldOptions fallbackOptions) { return ImmutableArray.Create( new MyCodeAction( FeaturesResources.Encapsulate_fields_and_use_property, - c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), + c => EncapsulateFieldsAsync(document, fields, fallbackOptions, updateReferences: true, c)), new MyCodeAction( FeaturesResources.Encapsulate_fields_but_still_use_field, - c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); + c => EncapsulateFieldsAsync(document, fields, fallbackOptions, updateReferences: false, c))); } - private ImmutableArray EncapsulateOneField(Document document, IFieldSymbol field) + private ImmutableArray EncapsulateOneField(Document document, IFieldSymbol field, EncapsulateFieldOptions fallbackOptions) { var fields = ImmutableArray.Create(field); return ImmutableArray.Create( new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_and_use_property, field.Name), - c => EncapsulateFieldsAsync(document, fields, updateReferences: true, c)), + c => EncapsulateFieldsAsync(document, fields, fallbackOptions, updateReferences: true, c)), new MyCodeAction( string.Format(FeaturesResources.Encapsulate_field_colon_0_but_still_use_field, field.Name), - c => EncapsulateFieldsAsync(document, fields, updateReferences: false, c))); + c => EncapsulateFieldsAsync(document, fields, fallbackOptions, updateReferences: false, c))); } public async Task EncapsulateFieldsAsync( Document document, ImmutableArray fields, + EncapsulateFieldOptions fallbackOptions, bool updateReferences, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -124,10 +125,10 @@ public async Task EncapsulateFieldsAsync( } return await EncapsulateFieldsInCurrentProcessAsync( - document, fields, updateReferences, cancellationToken).ConfigureAwait(false); + document, fields, fallbackOptions, updateReferences, cancellationToken).ConfigureAwait(false); } - private async Task EncapsulateFieldsInCurrentProcessAsync(Document document, ImmutableArray fields, bool updateReferences, CancellationToken cancellationToken) + private async Task EncapsulateFieldsInCurrentProcessAsync(Document document, ImmutableArray fields, EncapsulateFieldOptions fallbackOptions, bool updateReferences, CancellationToken cancellationToken) { Contract.ThrowIfTrue(fields.Length == 0); @@ -143,7 +144,7 @@ private async Task EncapsulateFieldsInCurrentProcessAsync(Document doc if (field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol is not IFieldSymbol currentField) continue; - var nextSolution = await EncapsulateFieldAsync(document, currentField, updateReferences, cancellationToken).ConfigureAwait(false); + var nextSolution = await EncapsulateFieldAsync(document, currentField, updateReferences, fallbackOptions, cancellationToken).ConfigureAwait(false); if (nextSolution == null) continue; @@ -154,8 +155,11 @@ private async Task EncapsulateFieldsInCurrentProcessAsync(Document doc } private async Task EncapsulateFieldAsync( - Document document, IFieldSymbol field, - bool updateReferences, CancellationToken cancellationToken) + Document document, + IFieldSymbol field, + bool updateReferences, + EncapsulateFieldOptions fallbackOptions, + CancellationToken cancellationToken) { var originalField = field; var (finalFieldName, generatedPropertyName) = GenerateFieldAndPropertyNames(field); @@ -202,6 +206,7 @@ private async Task EncapsulateFieldAsync( var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, formattingOptions, cancellationToken).ConfigureAwait(false); solution = document.Project.Solution; @@ -231,8 +236,10 @@ private async Task EncapsulateFieldAsync( new SyntaxAnnotation(), document); + var documentSimplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions.SimplifierOptions, cancellationToken).ConfigureAwait(false); + var solutionWithProperty = await AddPropertyAsync( - document, document.Project.Solution, field, generatedProperty, formattingOptions, cancellationToken).ConfigureAwait(false); + document, document.Project.Solution, field, generatedProperty, formattingOptions, documentSimplifierOptions, cancellationToken).ConfigureAwait(false); return solutionWithProperty; } @@ -318,7 +325,14 @@ private ISet GetConstructorLocations(INamedTypeSymbol containingType) internal abstract IEnumerable GetConstructorNodes(INamedTypeSymbol containingType); - protected static async Task AddPropertyAsync(Document document, Solution destinationSolution, IFieldSymbol field, IPropertySymbol property, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken) + protected static async Task AddPropertyAsync( + Document document, + Solution destinationSolution, + IFieldSymbol field, + IPropertySymbol property, + SyntaxFormattingOptions formattingOptions, + SimplifierOptions simplifierOptions, + CancellationToken cancellationToken) { var codeGenerationService = document.GetLanguageService(); @@ -332,7 +346,7 @@ protected static async Task AddPropertyAsync(Document document, Soluti destinationSolution, destination, property, context, cancellationToken).ConfigureAwait(false); updatedDocument = await Formatter.FormatAsync(updatedDocument, Formatter.Annotation, formattingOptions, cancellationToken).ConfigureAwait(false); - updatedDocument = await Simplifier.ReduceAsync(updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); + updatedDocument = await Simplifier.ReduceAsync(updatedDocument, simplifierOptions, cancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } diff --git a/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldOptions.cs b/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldOptions.cs new file mode 100644 index 0000000000000..29070875bebbd --- /dev/null +++ b/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldOptions.cs @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.Simplification; + +namespace Microsoft.CodeAnalysis.EncapsulateField; + +[DataContract] +internal readonly record struct EncapsulateFieldOptions( + [property: DataMember(Order = 0)] SimplifierOptions SimplifierOptions); diff --git a/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldRefactoringProvider.cs b/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldRefactoringProvider.cs index f936e59e6db14..606142d8928d1 100644 --- a/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldRefactoringProvider.cs +++ b/src/Features/Core/Portable/EncapsulateField/EncapsulateFieldRefactoringProvider.cs @@ -26,7 +26,11 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex { var (document, textSpan, cancellationToken) = context; var service = document.GetLanguageService(); - var actions = await service.GetEncapsulateFieldCodeActionsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); + + var fallbackOptions = new EncapsulateFieldOptions( + SimplifierOptions: context.Options(document.Project.LanguageServices).SimplifierOptions); + + var actions = await service.GetEncapsulateFieldCodeActionsAsync(document, textSpan, fallbackOptions, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } diff --git a/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyCodeFixProvider.cs b/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyCodeFixProvider.cs index 6b7f4a4bb3cf6..0d9a624da1027 100644 --- a/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyCodeFixProvider.cs +++ b/src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyCodeFixProvider.cs @@ -63,7 +63,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) return; } - var hideAdvancedMembers = context.Options(document.Project.Language).HideAdvancedMembers; + var hideAdvancedMembers = context.Options(document.Project.LanguageServices).HideAdvancedMembers; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matchingTypes = await GetMatchingTypesAsync(document, semanticModel, node, hideAdvancedMembers, cancellationToken).ConfigureAwait(false); diff --git a/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs b/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs index b15c4fd3d2640..47e275514e026 100644 --- a/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs +++ b/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs @@ -42,7 +42,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) return; var data = await ImplementAbstractClassData.TryGetDataAsync( - document, classNode, GetClassIdentifier(classNode), context.Options(document.Project.Language).ImplementTypeOptions, cancellationToken).ConfigureAwait(false); + document, classNode, GetClassIdentifier(classNode), context.Options(document.Project.LanguageServices).ImplementTypeOptions, cancellationToken).ConfigureAwait(false); if (data == null) return; diff --git a/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.cs b/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.cs index 2f8aea25577e4..19f2619684215 100644 --- a/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.cs +++ b/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.cs @@ -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; using System.Collections.Generic; using System.Collections.Immutable; @@ -24,15 +22,22 @@ namespace Microsoft.CodeAnalysis.MetadataAsSource { internal abstract partial class AbstractMetadataAsSourceService : IMetadataAsSourceService { - public async Task AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken) + public async Task AddSourceToAsync( + Document document, + Compilation symbolCompilation, + ISymbol symbol, + SyntaxFormattingOptions formattingOptions, + SimplifierOptions simplifierOptions, + CancellationToken cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } - var newSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var rootNamespace = newSemanticModel.GetEnclosingNamespace(0, cancellationToken); + var newSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + var rootNamespace = newSemanticModel.GetEnclosingNamespace(position: 0, cancellationToken); + Contract.ThrowIfNull(rootNamespace); var context = new CodeGenerationContext( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), @@ -51,11 +56,11 @@ public async Task AddSourceToAsync(Document document, Compilation symb document = await AddNullableRegionsAsync(document, cancellationToken).ConfigureAwait(false); - var docCommentFormattingService = document.GetLanguageService(); + var docCommentFormattingService = document.GetRequiredLanguageService(); var docWithDocComments = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false); var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbolCompilation, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false); - var node = await docWithAssemblyInfo.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var node = await docWithAssemblyInfo.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync( docWithAssemblyInfo, @@ -65,7 +70,7 @@ public async Task AddSourceToAsync(Document document, Compilation symb cancellationToken).ConfigureAwait(false); var reducers = GetReducers(); - return await Simplifier.ReduceAsync(formattedDoc, reducers, null, cancellationToken).ConfigureAwait(false); + return await Simplifier.ReduceAsync(formattedDoc, reducers, simplifierOptions, cancellationToken).ConfigureAwait(false); } protected abstract Task AddNullableRegionsAsync(Document document, CancellationToken cancellationToken); @@ -99,7 +104,7 @@ private static INamespaceOrTypeSymbol CreateCodeGenerationSymbol(Document docume var topLevelNamespaceSymbol = symbol.ContainingNamespace; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); - var canImplementImplicitly = document.GetLanguageService().SupportsImplicitInterfaceImplementation; + var canImplementImplicitly = document.GetRequiredLanguageService().SupportsImplicitInterfaceImplementation; var docCommentFormattingService = document.GetLanguageService(); INamespaceOrTypeSymbol wrappedType = new WrappedNamedTypeSymbol(topLevelNamedType, canImplementImplicitly, docCommentFormattingService); diff --git a/src/Features/Core/Portable/MetadataAsSource/DecompilationMetadataAsSourceFileProvider.cs b/src/Features/Core/Portable/MetadataAsSource/DecompilationMetadataAsSourceFileProvider.cs index 1387299960d96..79b25b8767313 100644 --- a/src/Features/Core/Portable/MetadataAsSource/DecompilationMetadataAsSourceFileProvider.cs +++ b/src/Features/Core/Portable/MetadataAsSource/DecompilationMetadataAsSourceFileProvider.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -79,6 +80,7 @@ public DecompilationMetadataAsSourceFileProvider() .GetRequiredDocument(temporaryProjectInfoAndDocumentId.Item2); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(temporaryDocument, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(temporaryDocument, options.SimplifierOptions, cancellationToken).ConfigureAwait(false); if (useDecompiler) { @@ -107,7 +109,7 @@ public DecompilationMetadataAsSourceFileProvider() if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService(); - temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, formattingOptions, cancellationToken).ConfigureAwait(false); + temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, formattingOptions, simplifierOptions, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk diff --git a/src/Features/Core/Portable/MetadataAsSource/IMetadataAsSourceService.cs b/src/Features/Core/Portable/MetadataAsSource/IMetadataAsSourceService.cs index 7a032a04a219b..f8689f463c795 100644 --- a/src/Features/Core/Portable/MetadataAsSource/IMetadataAsSourceService.cs +++ b/src/Features/Core/Portable/MetadataAsSource/IMetadataAsSourceService.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.MetadataAsSource { @@ -23,6 +24,6 @@ internal interface IMetadataAsSourceService : ILanguageService /// The symbol to generate source for /// To cancel document operations /// The updated document - Task AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken = default); + Task AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, SyntaxFormattingOptions formattingOptions, SimplifierOptions simplifierOptions, CancellationToken cancellationToken = default); } } diff --git a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceOptions.cs b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceOptions.cs index 2443af58b00c5..9b2f4313f6b15 100644 --- a/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceOptions.cs +++ b/src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceOptions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.Simplification; + namespace Microsoft.CodeAnalysis.MetadataAsSource { /// @@ -12,13 +14,14 @@ namespace Microsoft.CodeAnalysis.MetadataAsSource /// Whether navigation should try to use the default Microsoft and /// Nuget symbol servers regardless of debugger settings internal readonly record struct MetadataAsSourceOptions( + SimplifierOptions? SimplifierOptions = null, bool NavigateToDecompiledSources = true, bool AlwaysUseDefaultSymbolServers = true) { public static readonly MetadataAsSourceOptions Default = new(); public MetadataAsSourceOptions() - : this(NavigateToDecompiledSources: true) + : this(SimplifierOptions: null) { } } diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveItemsToNamespaceCodeAction.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveItemsToNamespaceCodeAction.cs index a052948c87713..eef94890a6c15 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveItemsToNamespaceCodeAction.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveItemsToNamespaceCodeAction.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.ChangeNamespace; + namespace Microsoft.CodeAnalysis.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction @@ -10,8 +12,8 @@ private class MoveItemsToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction { public override string Title => FeaturesResources.Move_contents_to_namespace; - public MoveItemsToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) - : base(changeNamespaceService, analysisResult) + public MoveItemsToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult, ChangeNamespaceOptionsProvider changeNamespaceOptions) + : base(changeNamespaceService, analysisResult, changeNamespaceOptions) { } } diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs index 0c403a550a6cd..090fb8b058346 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.MoveTypeToNamespaceCodeAction.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.CodeAnalysis.ChangeNamespace; + namespace Microsoft.CodeAnalysis.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction @@ -10,8 +12,8 @@ private class MoveTypeToNamespaceCodeAction : AbstractMoveToNamespaceCodeAction { public override string Title => FeaturesResources.Move_to_namespace; - public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) - : base(changeNamespaceService, analysisResult) + public MoveTypeToNamespaceCodeAction(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult, ChangeNamespaceOptionsProvider changeNamespaceOptions) + : base(changeNamespaceService, analysisResult, changeNamespaceOptions) { } } diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.cs index 00534fe23c5bc..253db52b650e8 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Roslyn.Utilities; @@ -17,11 +18,13 @@ internal abstract partial class AbstractMoveToNamespaceCodeAction : CodeActionWi { private readonly IMoveToNamespaceService _moveToNamespaceService; private readonly MoveToNamespaceAnalysisResult _moveToNamespaceAnalysisResult; + private readonly ChangeNamespaceOptionsProvider _changeNamespaceOptions; - public AbstractMoveToNamespaceCodeAction(IMoveToNamespaceService moveToNamespaceService, MoveToNamespaceAnalysisResult analysisResult) + public AbstractMoveToNamespaceCodeAction(IMoveToNamespaceService moveToNamespaceService, MoveToNamespaceAnalysisResult analysisResult, ChangeNamespaceOptionsProvider changeNamespaceOptions) { _moveToNamespaceService = moveToNamespaceService; _moveToNamespaceAnalysisResult = analysisResult; + _changeNamespaceOptions = changeNamespaceOptions; } public override object GetOptions(CancellationToken cancellationToken) @@ -42,6 +45,7 @@ protected override async Task> ComputeOperation var moveToNamespaceResult = await _moveToNamespaceService.MoveToNamespaceAsync( _moveToNamespaceAnalysisResult, moveToNamespaceOptions.Namespace, + _changeNamespaceOptions, cancellationToken).ConfigureAwait(false); if (moveToNamespaceResult.Succeeded) @@ -81,11 +85,11 @@ private static ImmutableArray CreateRenameOperations(MoveTo return operations.ToImmutable(); } - public static AbstractMoveToNamespaceCodeAction Generate(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) + public static AbstractMoveToNamespaceCodeAction Generate(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult, ChangeNamespaceOptionsProvider changeNamespaceOptions) => analysisResult.Container switch { - MoveToNamespaceAnalysisResult.ContainerType.NamedType => new MoveTypeToNamespaceCodeAction(changeNamespaceService, analysisResult), - MoveToNamespaceAnalysisResult.ContainerType.Namespace => new MoveItemsToNamespaceCodeAction(changeNamespaceService, analysisResult), + MoveToNamespaceAnalysisResult.ContainerType.NamedType => new MoveTypeToNamespaceCodeAction(changeNamespaceService, analysisResult, changeNamespaceOptions), + MoveToNamespaceAnalysisResult.ContainerType.Namespace => new MoveItemsToNamespaceCodeAction(changeNamespaceService, analysisResult, changeNamespaceOptions), _ => throw ExceptionUtilities.UnexpectedValue(analysisResult.Container) }; } diff --git a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs index 11e92a4f545f9..c315c056424df 100644 --- a/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs +++ b/src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceService.cs @@ -24,9 +24,9 @@ namespace Microsoft.CodeAnalysis.MoveToNamespace { internal interface IMoveToNamespaceService : ILanguageService { - Task> GetCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken); + Task> GetCodeActionsAsync(Document document, TextSpan span, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); Task AnalyzeTypeAtPositionAsync(Document document, int position, CancellationToken cancellationToken); - Task MoveToNamespaceAsync(MoveToNamespaceAnalysisResult analysisResult, string targetNamespace, CancellationToken cancellationToken); + Task MoveToNamespaceAsync(MoveToNamespaceAnalysisResult analysisResult, string targetNamespace, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); MoveToNamespaceOptionsResult GetChangeNamespaceOptions(Document document, string defaultNamespace, ImmutableArray namespaces); IMoveToNamespaceOptionsService OptionsService { get; } } @@ -49,6 +49,7 @@ protected AbstractMoveToNamespaceService(IMoveToNamespaceOptionsService moveToNa public async Task> GetCodeActionsAsync( Document document, TextSpan span, + ChangeNamespaceOptionsProvider changeNamespaceOptions, CancellationToken cancellationToken) { // Code actions cannot be completed without the options needed @@ -59,7 +60,7 @@ public async Task> GetCodeActi if (typeAnalysisResult.CanPerform) { - return ImmutableArray.Create(AbstractMoveToNamespaceCodeAction.Generate(this, typeAnalysisResult)); + return ImmutableArray.Create(AbstractMoveToNamespaceCodeAction.Generate(this, typeAnalysisResult, changeNamespaceOptions)); } } @@ -166,6 +167,7 @@ private static bool ContainsMultipleTypesInSpine(SyntaxNode node) public Task MoveToNamespaceAsync( MoveToNamespaceAnalysisResult analysisResult, string targetNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { if (!analysisResult.CanPerform) @@ -175,8 +177,8 @@ public Task MoveToNamespaceAsync( return analysisResult.Container switch { - MoveToNamespaceAnalysisResult.ContainerType.Namespace => MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), - MoveToNamespaceAnalysisResult.ContainerType.NamedType => MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, cancellationToken), + MoveToNamespaceAnalysisResult.ContainerType.Namespace => MoveItemsInNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, options, cancellationToken), + MoveToNamespaceAnalysisResult.ContainerType.NamedType => MoveTypeToNamespaceAsync(analysisResult.Document, analysisResult.SyntaxNode, targetNamespace, options, cancellationToken), _ => throw new InvalidOperationException(), }; } @@ -208,6 +210,7 @@ private static async Task MoveItemsInNamespaceAsync( Document document, SyntaxNode container, string targetNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { var memberSymbols = await GetMemberSymbolsAsync(document, container, cancellationToken).ConfigureAwait(false); @@ -226,6 +229,7 @@ private static async Task MoveItemsInNamespaceAsync( document, container, targetNamespace, + options, cancellationToken).ConfigureAwait(false); return new MoveToNamespaceResult(originalSolution, changedSolution, document.Id, newNameOriginalSymbolMapping); @@ -235,6 +239,7 @@ private static async Task MoveTypeToNamespaceAsync( Document document, SyntaxNode container, string targetNamespace, + ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken) { var moveTypeService = document.GetLanguageService(); @@ -272,6 +277,7 @@ private static async Task MoveTypeToNamespaceAsync( mergedDocument, syntaxNode, targetNamespace, + options, cancellationToken).ConfigureAwait(false); } diff --git a/src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.cs b/src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.cs index ad1bcf4f48095..9c0f902d9dfac 100644 --- a/src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.cs +++ b/src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.cs @@ -7,6 +7,7 @@ using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -27,7 +28,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte { var (document, textSpan, cancellationToken) = context; var moveToNamespaceService = document.GetLanguageService(); - var actions = await moveToNamespaceService.GetCodeActionsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); + var actions = await moveToNamespaceService.GetCodeActionsAsync(document, textSpan, ChangeNamespaceOptions.CreateProvider(context.Options), cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } diff --git a/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs b/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs index 0253a7f529e1d..c4048f8c26339 100644 --- a/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs +++ b/src/Features/Core/Portable/SimplifyTypeNames/AbstractSimplifyTypeNamesCodeFixProvider.cs @@ -80,7 +80,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var options = (TSimplifierOptions)await SimplifierOptions.FromDocumentAsync(document, context.Options.FallbackSimplifierOptions, cancellationToken).ConfigureAwait(false); + var options = (TSimplifierOptions)await SimplifierOptions.FromDocumentAsync(document, context.Options(document.Project.LanguageServices).SimplifierOptions, cancellationToken).ConfigureAwait(false); var (node, diagnosticId) = GetNodeToSimplify( root, model, span, options, cancellationToken); @@ -102,7 +102,7 @@ protected override async Task FixAllAsync( { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var simplifierOptions = (TSimplifierOptions)await SimplifierOptions.FromDocumentAsync(document, options(document.Project.LanguageServices).FallbackSimplifierOptions, cancellationToken).ConfigureAwait(false); + var simplifierOptions = (TSimplifierOptions)await SimplifierOptions.FromDocumentAsync(document, options(document.Project.LanguageServices).SimplifierOptions, cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { diff --git a/src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs b/src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs index d2752c63438fc..fb8cf487ab84c 100644 --- a/src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs +++ b/src/Features/Core/Portable/SpellCheck/AbstractSpellCheckCodeFixProvider.cs @@ -118,7 +118,7 @@ private async Task CreateSpellCheckCodeIssueAsync( // - We believe spell-check should only compare what you have typed to what symbol would be offered here. var options = CompletionOptions.Default with { - HideAdvancedMembers = context.Options(document.Project.Language).HideAdvancedMembers, + HideAdvancedMembers = context.Options(document.Project.LanguageServices).HideAdvancedMembers, SnippetsBehavior = SnippetsRule.NeverInclude, ShowItemsFromUnimportedNamespaces = false, TargetTypedCompletionFilter = false, diff --git a/src/Features/Core/Portable/Wrapping/AbstractWrappingCodeRefactoringProvider.cs b/src/Features/Core/Portable/Wrapping/AbstractWrappingCodeRefactoringProvider.cs index f0e74dbfd704b..d54d2493c0e7c 100644 --- a/src/Features/Core/Portable/Wrapping/AbstractWrappingCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/Wrapping/AbstractWrappingCodeRefactoringProvider.cs @@ -45,7 +45,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte var token = root.FindToken(position); var configOptions = await document.GetAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); - var options = GetWrappingOptions(configOptions, context.Options(document.Project.Language)); + var options = GetWrappingOptions(configOptions, context.Options(document.Project.LanguageServices)); foreach (var node in token.GetRequiredParent().AncestorsAndSelf()) { diff --git a/src/Features/LanguageServer/Protocol/Features/Options/ISimplifierOptionsStorage.cs b/src/Features/LanguageServer/Protocol/Features/Options/ISimplifierOptionsStorage.cs deleted file mode 100644 index f50f2a25c2937..0000000000000 --- a/src/Features/LanguageServer/Protocol/Features/Options/ISimplifierOptionsStorage.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Options; - -namespace Microsoft.CodeAnalysis.Simplification; - -internal interface ISimplifierOptionsStorage : ILanguageService -{ - SimplifierOptions GetSimplifierOptions(IGlobalOptionService globalOptions); -} diff --git a/src/Features/LanguageServer/Protocol/Features/Options/MetadataAsSourceOptionsStorage.cs b/src/Features/LanguageServer/Protocol/Features/Options/MetadataAsSourceOptionsStorage.cs index ee8e7e24bcb0c..03278d6efd9e2 100644 --- a/src/Features/LanguageServer/Protocol/Features/Options/MetadataAsSourceOptionsStorage.cs +++ b/src/Features/LanguageServer/Protocol/Features/Options/MetadataAsSourceOptionsStorage.cs @@ -2,19 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Immutable; -using System.Composition; -using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.Options.Providers; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal static class MetadataAsSourceOptionsStorage { - public static MetadataAsSourceOptions GetMetadataAsSourceOptions(this IGlobalOptionService globalOptions) + public static MetadataAsSourceOptions GetMetadataAsSourceOptions(this IGlobalOptionService globalOptions, HostLanguageServices languageServices) => new( + SimplifierOptions: globalOptions.GetFallbackSimplifierOptions(languageServices), NavigateToDecompiledSources: globalOptions.GetOption(NavigateToDecompiledSources), AlwaysUseDefaultSymbolServers: globalOptions.GetOption(AlwaysUseDefaultSymbolServers)); diff --git a/src/Features/LanguageServer/Protocol/Features/Options/SimplifierOptionsStorage.cs b/src/Features/LanguageServer/Protocol/Features/Options/SimplifierOptionsStorage.cs new file mode 100644 index 0000000000000..411fa348e51a6 --- /dev/null +++ b/src/Features/LanguageServer/Protocol/Features/Options/SimplifierOptionsStorage.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Options; + +namespace Microsoft.CodeAnalysis.Simplification; + +internal interface ISimplifierOptionsStorage : ILanguageService +{ + SimplifierOptions GetOptions(IGlobalOptionService globalOptions); +} + +internal static class SimplifierOptionsStorage +{ + public static Task GetSimplifierOptionsAsync(this IGlobalOptionService globalOptions, Document document, CancellationToken cancellationToken) + => SimplifierOptions.FromDocumentAsync(document, globalOptions.GetFallbackSimplifierOptions(document.Project.LanguageServices), cancellationToken); + + public static SimplifierOptions? GetFallbackSimplifierOptions(this IGlobalOptionService globalOptions, HostLanguageServices languageServices) + => languageServices.GetService()?.GetOptions(globalOptions); +} diff --git a/src/Features/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs b/src/Features/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs index 7b655a7fdc579..27109a471f4a8 100644 --- a/src/Features/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs +++ b/src/Features/LanguageServer/Protocol/Handler/Definitions/AbstractGoToDefinitionHandler.cs @@ -67,7 +67,7 @@ public AbstractGoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSour { if (!typeOnly || symbol is ITypeSymbol) { - var options = _globalOptions.GetMetadataAsSourceOptions(); + var options = _globalOptions.GetMetadataAsSourceOptions(document.Project.LanguageServices); var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync(document.Project, symbol, signaturesOnly: false, options, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; diff --git a/src/Features/VisualBasic/Portable/ImplementInterface/VisualBasicImplementInterfaceCodeFixProvider.vb b/src/Features/VisualBasic/Portable/ImplementInterface/VisualBasicImplementInterfaceCodeFixProvider.vb index 41e153d3a8c24..2103001078cf6 100644 --- a/src/Features/VisualBasic/Portable/ImplementInterface/VisualBasicImplementInterfaceCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/ImplementInterface/VisualBasicImplementInterfaceCodeFixProvider.vb @@ -61,7 +61,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementInterface Dim service = document.GetLanguageService(Of IImplementInterfaceService)() Dim actions = service.GetCodeActions( document, - context.Options(document.Project.Language).ImplementTypeOptions, + context.Options(document.Project.LanguageServices).ImplementTypeOptions, Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False), typeNode, cancellationToken) diff --git a/src/Tools/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs b/src/Tools/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs index 66ecf8cdd0fcf..1fa3106504b86 100644 --- a/src/Tools/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs +++ b/src/Tools/ExternalAccess/OmniSharp.CSharp/Formatting/OmniSharpSyntaxFormattingOptionsFactory.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Formatting; +using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; @@ -76,61 +77,62 @@ public static OmniSharpSyntaxFormattingOptionsWrapper Create( bool newLineForMembersInObjectInit, bool newLineForMembersInAnonymousTypes, bool newLineForClausesInQuery) - => new(new CSharpSyntaxFormattingOptions( - new LineFormattingOptions( - UseTabs: useTabs, - TabSize: tabSize, - IndentationSize: indentationSize, - NewLine: newLine), - separateImportDirectiveGroups: separateImportDirectiveGroups, - spacing: - (spacingAfterMethodDeclarationName ? SpacePlacement.AfterMethodDeclarationName : 0) | - (spaceBetweenEmptyMethodDeclarationParentheses ? SpacePlacement.BetweenEmptyMethodDeclarationParentheses : 0) | - (spaceWithinMethodDeclarationParenthesis ? SpacePlacement.WithinMethodDeclarationParenthesis : 0) | - (spaceAfterMethodCallName ? SpacePlacement.AfterMethodCallName : 0) | - (spaceBetweenEmptyMethodCallParentheses ? SpacePlacement.BetweenEmptyMethodCallParentheses : 0) | - (spaceWithinMethodCallParentheses ? SpacePlacement.WithinMethodCallParentheses : 0) | - (spaceAfterControlFlowStatementKeyword ? SpacePlacement.AfterControlFlowStatementKeyword : 0) | - (spaceWithinExpressionParentheses ? SpacePlacement.WithinExpressionParentheses : 0) | - (spaceWithinCastParentheses ? SpacePlacement.WithinCastParentheses : 0) | - (spaceBeforeSemicolonsInForStatement ? SpacePlacement.BeforeSemicolonsInForStatement : 0) | - (spaceAfterSemicolonsInForStatement ? SpacePlacement.AfterSemicolonsInForStatement : 0) | - (spaceWithinOtherParentheses ? SpacePlacement.WithinOtherParentheses : 0) | - (spaceAfterCast ? SpacePlacement.AfterCast : 0) | - (spaceBeforeOpenSquareBracket ? SpacePlacement.BeforeOpenSquareBracket : 0) | - (spaceBetweenEmptySquareBrackets ? SpacePlacement.BetweenEmptySquareBrackets : 0) | - (spaceWithinSquareBrackets ? SpacePlacement.WithinSquareBrackets : 0) | - (spaceAfterColonInBaseTypeDeclaration ? SpacePlacement.AfterColonInBaseTypeDeclaration : 0) | - (spaceBeforeColonInBaseTypeDeclaration ? SpacePlacement.BeforeColonInBaseTypeDeclaration : 0) | - (spaceAfterComma ? SpacePlacement.AfterComma : 0) | - (spaceBeforeComma ? SpacePlacement.BeforeComma : 0) | - (spaceAfterDot ? SpacePlacement.AfterDot : 0) | - (spaceBeforeDot ? SpacePlacement.BeforeDot : 0), - spacingAroundBinaryOperator: (BinaryOperatorSpacingOptions)spacingAroundBinaryOperator, - newLines: - (newLineForMembersInObjectInit ? NewLinePlacement.BeforeMembersInObjectInitializers : 0) | - (newLineForMembersInAnonymousTypes ? NewLinePlacement.BeforeMembersInAnonymousTypes : 0) | - (newLineForElse ? NewLinePlacement.BeforeElse : 0) | - (newLineForCatch ? NewLinePlacement.BeforeCatch : 0) | - (newLineForFinally ? NewLinePlacement.BeforeFinally : 0) | - (newLinesForBracesInTypes ? NewLinePlacement.BeforeOpenBraceInTypes : 0) | - (newLinesForBracesInAnonymousTypes ? NewLinePlacement.BeforeOpenBraceInAnonymousTypes : 0) | - (newLinesForBracesInObjectCollectionArrayInitializers ? NewLinePlacement.BeforeOpenBraceInObjectCollectionArrayInitializers : 0) | - (newLinesForBracesInProperties ? NewLinePlacement.BeforeOpenBraceInProperties : 0) | - (newLinesForBracesInMethods ? NewLinePlacement.BeforeOpenBraceInMethods : 0) | - (newLinesForBracesInAccessors ? NewLinePlacement.BeforeOpenBraceInAccessors : 0) | - (newLinesForBracesInAnonymousMethods ? NewLinePlacement.BeforeOpenBraceInAnonymousMethods : 0) | - (newLinesForBracesInLambdaExpressionBody ? NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody : 0) | - (newLinesForBracesInControlBlocks ? NewLinePlacement.BeforeOpenBraceInControlBlocks : 0) | - (newLineForClausesInQuery ? NewLinePlacement.BetweenQueryExpressionClauses : 0), - labelPositioning: (LabelPositionOptions)labelPositioning, - indentation: - (indentBraces ? IndentationPlacement.Braces : 0) | - (indentBlock ? IndentationPlacement.BlockContents : 0) | - (indentSwitchCaseSection ? IndentationPlacement.SwitchCaseContents : 0) | - (indentSwitchCaseSectionWhenBlock ? IndentationPlacement.SwitchCaseContentsWhenBlock : 0) | - (indentSwitchSection ? IndentationPlacement.SwitchSection : 0), - wrappingKeepStatementsOnSingleLine: wrappingKeepStatementsOnSingleLine, - wrappingPreserveSingleLine: wrappingPreserveSingleLine)); + => new(formattingOptions: new CSharpSyntaxFormattingOptions( + new LineFormattingOptions( + UseTabs: useTabs, + TabSize: tabSize, + IndentationSize: indentationSize, + NewLine: newLine), + separateImportDirectiveGroups: separateImportDirectiveGroups, + spacing: + (spacingAfterMethodDeclarationName ? SpacePlacement.AfterMethodDeclarationName : 0) | + (spaceBetweenEmptyMethodDeclarationParentheses ? SpacePlacement.BetweenEmptyMethodDeclarationParentheses : 0) | + (spaceWithinMethodDeclarationParenthesis ? SpacePlacement.WithinMethodDeclarationParenthesis : 0) | + (spaceAfterMethodCallName ? SpacePlacement.AfterMethodCallName : 0) | + (spaceBetweenEmptyMethodCallParentheses ? SpacePlacement.BetweenEmptyMethodCallParentheses : 0) | + (spaceWithinMethodCallParentheses ? SpacePlacement.WithinMethodCallParentheses : 0) | + (spaceAfterControlFlowStatementKeyword ? SpacePlacement.AfterControlFlowStatementKeyword : 0) | + (spaceWithinExpressionParentheses ? SpacePlacement.WithinExpressionParentheses : 0) | + (spaceWithinCastParentheses ? SpacePlacement.WithinCastParentheses : 0) | + (spaceBeforeSemicolonsInForStatement ? SpacePlacement.BeforeSemicolonsInForStatement : 0) | + (spaceAfterSemicolonsInForStatement ? SpacePlacement.AfterSemicolonsInForStatement : 0) | + (spaceWithinOtherParentheses ? SpacePlacement.WithinOtherParentheses : 0) | + (spaceAfterCast ? SpacePlacement.AfterCast : 0) | + (spaceBeforeOpenSquareBracket ? SpacePlacement.BeforeOpenSquareBracket : 0) | + (spaceBetweenEmptySquareBrackets ? SpacePlacement.BetweenEmptySquareBrackets : 0) | + (spaceWithinSquareBrackets ? SpacePlacement.WithinSquareBrackets : 0) | + (spaceAfterColonInBaseTypeDeclaration ? SpacePlacement.AfterColonInBaseTypeDeclaration : 0) | + (spaceBeforeColonInBaseTypeDeclaration ? SpacePlacement.BeforeColonInBaseTypeDeclaration : 0) | + (spaceAfterComma ? SpacePlacement.AfterComma : 0) | + (spaceBeforeComma ? SpacePlacement.BeforeComma : 0) | + (spaceAfterDot ? SpacePlacement.AfterDot : 0) | + (spaceBeforeDot ? SpacePlacement.BeforeDot : 0), + spacingAroundBinaryOperator: (BinaryOperatorSpacingOptions)spacingAroundBinaryOperator, + newLines: + (newLineForMembersInObjectInit ? NewLinePlacement.BeforeMembersInObjectInitializers : 0) | + (newLineForMembersInAnonymousTypes ? NewLinePlacement.BeforeMembersInAnonymousTypes : 0) | + (newLineForElse ? NewLinePlacement.BeforeElse : 0) | + (newLineForCatch ? NewLinePlacement.BeforeCatch : 0) | + (newLineForFinally ? NewLinePlacement.BeforeFinally : 0) | + (newLinesForBracesInTypes ? NewLinePlacement.BeforeOpenBraceInTypes : 0) | + (newLinesForBracesInAnonymousTypes ? NewLinePlacement.BeforeOpenBraceInAnonymousTypes : 0) | + (newLinesForBracesInObjectCollectionArrayInitializers ? NewLinePlacement.BeforeOpenBraceInObjectCollectionArrayInitializers : 0) | + (newLinesForBracesInProperties ? NewLinePlacement.BeforeOpenBraceInProperties : 0) | + (newLinesForBracesInMethods ? NewLinePlacement.BeforeOpenBraceInMethods : 0) | + (newLinesForBracesInAccessors ? NewLinePlacement.BeforeOpenBraceInAccessors : 0) | + (newLinesForBracesInAnonymousMethods ? NewLinePlacement.BeforeOpenBraceInAnonymousMethods : 0) | + (newLinesForBracesInLambdaExpressionBody ? NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody : 0) | + (newLinesForBracesInControlBlocks ? NewLinePlacement.BeforeOpenBraceInControlBlocks : 0) | + (newLineForClausesInQuery ? NewLinePlacement.BetweenQueryExpressionClauses : 0), + labelPositioning: (LabelPositionOptions)labelPositioning, + indentation: + (indentBraces ? IndentationPlacement.Braces : 0) | + (indentBlock ? IndentationPlacement.BlockContents : 0) | + (indentSwitchCaseSection ? IndentationPlacement.SwitchCaseContents : 0) | + (indentSwitchCaseSectionWhenBlock ? IndentationPlacement.SwitchCaseContentsWhenBlock : 0) | + (indentSwitchSection ? IndentationPlacement.SwitchSection : 0), + wrappingKeepStatementsOnSingleLine: wrappingKeepStatementsOnSingleLine, + wrappingPreserveSingleLine: wrappingPreserveSingleLine), + simplifierOptions: CSharpSimplifierOptions.Default); } } diff --git a/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpFormatter.cs b/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpFormatter.cs index cadbac84be4ea..08017496c278e 100644 --- a/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpFormatter.cs +++ b/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpFormatter.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Formatting internal static class OmniSharpFormatter { public static Task FormatAsync(Document document, IEnumerable? spans, OmniSharpSyntaxFormattingOptionsWrapper options, CancellationToken cancellationToken) - => Formatter.FormatAsync(document, spans, options.UnderlyingObject, rules: null, cancellationToken); + => Formatter.FormatAsync(document, spans, options.FormattingOptions, rules: null, cancellationToken); public static async Task OrganizeImportsAsync(Document document, OmniSharpOrganizeImportsOptionsWrapper options, CancellationToken cancellationToken) { diff --git a/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpSyntaxFormattingOptionsWrapper.cs b/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpSyntaxFormattingOptionsWrapper.cs index 5ff2ccf0b9e0f..bf6039b17e0d1 100644 --- a/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpSyntaxFormattingOptionsWrapper.cs +++ b/src/Tools/ExternalAccess/OmniSharp/Formatting/OmniSharpSyntaxFormattingOptionsWrapper.cs @@ -5,20 +5,27 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Formatting { internal readonly record struct OmniSharpSyntaxFormattingOptionsWrapper { - internal readonly SyntaxFormattingOptions UnderlyingObject; + internal readonly SyntaxFormattingOptions FormattingOptions; + internal readonly SimplifierOptions SimplifierOptions; - internal OmniSharpSyntaxFormattingOptionsWrapper(SyntaxFormattingOptions underlyingObject) - => UnderlyingObject = underlyingObject; + internal OmniSharpSyntaxFormattingOptionsWrapper(SyntaxFormattingOptions formattingOptions, SimplifierOptions simplifierOptions) + { + FormattingOptions = formattingOptions; + SimplifierOptions = simplifierOptions; + } public static async ValueTask FromDocumentAsync(Document document, CancellationToken cancellationToken) { - var options = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); - return new OmniSharpSyntaxFormattingOptionsWrapper(options); + var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions: null, cancellationToken).ConfigureAwait(false); + + return new OmniSharpSyntaxFormattingOptionsWrapper(formattingOptions, simplifierOptions); } } } diff --git a/src/Tools/ExternalAccess/OmniSharp/MetadataAsSource/OmniSharpMetadataAsSourceService.cs b/src/Tools/ExternalAccess/OmniSharp/MetadataAsSource/OmniSharpMetadataAsSourceService.cs index 63c4dc0921433..ff2e30751a96d 100644 --- a/src/Tools/ExternalAccess/OmniSharp/MetadataAsSource/OmniSharpMetadataAsSourceService.cs +++ b/src/Tools/ExternalAccess/OmniSharp/MetadataAsSource/OmniSharpMetadataAsSourceService.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.MetadataAsSource { @@ -28,8 +29,11 @@ internal static class OmniSharpMetadataAsSourceService public static async Task AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService(); + var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); - return await service.AddSourceToAsync(document, symbolCompilation, symbol, formattingOptions, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions: null, cancellationToken).ConfigureAwait(false); + + return await service.AddSourceToAsync(document, symbolCompilation, symbol, formattingOptions, simplifierOptions, cancellationToken).ConfigureAwait(false); } /// @@ -46,7 +50,7 @@ public static async Task AddSourceToAsync(Document document, Compilati public static Task AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, OmniSharpSyntaxFormattingOptionsWrapper formattingOptions, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService(); - return service.AddSourceToAsync(document, symbolCompilation, symbol, formattingOptions.UnderlyingObject, cancellationToken); + return service.AddSourceToAsync(document, symbolCompilation, symbol, formattingOptions.FormattingOptions, formattingOptions.SimplifierOptions, cancellationToken); } } } diff --git a/src/VisualStudio/Core/Def/Venus/ContainedLanguageCodeSupport.cs b/src/VisualStudio/Core/Def/Venus/ContainedLanguageCodeSupport.cs index 3f1705282b801..994a49c055dcc 100644 --- a/src/VisualStudio/Core/Def/Venus/ContainedLanguageCodeSupport.cs +++ b/src/VisualStudio/Core/Def/Venus/ContainedLanguageCodeSupport.cs @@ -217,6 +217,8 @@ public static Tuple EnsureEventHandler( throw new InvalidOperationException(ServicesVSResources.Can_t_find_where_to_insert_member); } + var globalOptions = targetDocument.Project.Solution.Workspace.Services.GetRequiredService().GlobalOptions; + var options = codeGenerationService.GetOptions( targetSyntaxTree.Options, documentOptions, @@ -225,11 +227,13 @@ public static Tuple EnsureEventHandler( var newType = codeGenerationService.AddMethod(destinationType, newMethod, options, cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); + var formattingOptions = SyntaxFormattingOptions.FromDocumentAsync(targetDocument, cancellationToken).WaitAndGetResult_Venus(cancellationToken); + var simplifierOptions = globalOptions.GetSimplifierOptionsAsync(targetDocument, cancellationToken).WaitAndGetResult_Venus(cancellationToken); + newRoot = Simplifier.ReduceAsync( - targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); + targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, simplifierOptions, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); - var formattingOptions = SyntaxFormattingOptions.FromDocumentAsync(targetDocument, cancellationToken).WaitAndGetResult_Venus(cancellationToken); newRoot = Formatter.Format( newRoot, diff --git a/src/VisualStudio/Core/Def/Workspace/VisualStudioSymbolNavigationService.cs b/src/VisualStudio/Core/Def/Workspace/VisualStudioSymbolNavigationService.cs index b66f02e32a750..91e629a91de54 100644 --- a/src/VisualStudio/Core/Def/Workspace/VisualStudioSymbolNavigationService.cs +++ b/src/VisualStudio/Core/Def/Workspace/VisualStudioSymbolNavigationService.cs @@ -124,7 +124,7 @@ public VisualStudioSymbolNavigationService( private async Task GetNavigableLocationForMetadataAsync( Project project, ISymbol symbol, CancellationToken cancellationToken) { - var masOptions = _globalOptions.GetMetadataAsSourceOptions(); + var masOptions = _globalOptions.GetMetadataAsSourceOptions(project.LanguageServices); var result = await _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly: false, masOptions, cancellationToken).ConfigureAwait(false); diff --git a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs index cb2c3dc254201..adbcbe894fa56 100644 --- a/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs +++ b/src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Definitions/GoToDefinitionHandler.cs @@ -173,7 +173,7 @@ public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileSe var project = context.Document?.GetCodeProject(); if (project != null) { - var options = globalOptions.GetMetadataAsSourceOptions(); + var options = globalOptions.GetMetadataAsSourceOptions(project.LanguageServices); var declarationFile = await metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly: true, options, cancellationToken).ConfigureAwait(false); var linePosSpan = declarationFile.IdentifierLocation.GetLineSpan().Span; locations.Add(new LSP.Location diff --git a/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.cs b/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.cs index 5c6fce1e71c77..6ee54271b0f42 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.cs @@ -44,6 +44,9 @@ public CSharpSimplificationService() : base(s_reducers) { } + public override SimplifierOptions DefaultOptions + => CSharpSimplifierOptions.Default; + public override SimplifierOptions GetSimplifierOptions(AnalyzerConfigOptions options, SimplifierOptions? fallbackOptions) => CSharpSimplifierOptions.Create(options, (CSharpSimplifierOptions?)fallbackOptions); diff --git a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs index aa876c30812af..ad6f7fd99e0d4 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CSharp.Formatting; +using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; @@ -81,6 +82,8 @@ private static async Task TestAsync( var formattingOptions = CSharpSyntaxFormattingOptions.Default; + var simplifierOptions = CSharpSimplifierOptions.Default; + var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(doc, addImportOptions, CancellationToken.None) : await ImportAdder.AddImportsFromSyntaxesAsync(doc, addImportOptions, CancellationToken.None); @@ -94,7 +97,7 @@ private static async Task TestAsync( if (simplifiedText != null) { - var reduced = await Simplifier.ReduceAsync(imported); + var reduced = await Simplifier.ReduceAsync(imported, simplifierOptions, CancellationToken.None); var formatted = await Formatter.FormatAsync(reduced, SyntaxAnnotation.ElasticAnnotation, formattingOptions, CancellationToken.None); var actualText = (await formatted.GetTextAsync()).ToString(); diff --git a/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs index e9356e594fce4..4ebd4e27f1a53 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/SymbolEditorTests.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Formatting; +using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; @@ -52,7 +53,7 @@ private static async Task> GetSymbolsAsync(Solution solutio private static async Task GetActualAsync(Document document) { - document = await Simplifier.ReduceAsync(document); + document = await Simplifier.ReduceAsync(document, CSharpSimplifierOptions.Default, CancellationToken.None); document = await Formatter.FormatAsync(document, Formatter.Annotation, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); return (await document.GetSyntaxRootAsync()).ToFullString(); diff --git a/src/Workspaces/Core/Portable/ChangeNamespace/ChangeNamespaceOptions.cs b/src/Workspaces/Core/Portable/ChangeNamespace/ChangeNamespaceOptions.cs new file mode 100644 index 0000000000000..624e2dfdba43a --- /dev/null +++ b/src/Workspaces/Core/Portable/ChangeNamespace/ChangeNamespaceOptions.cs @@ -0,0 +1,47 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.AddImport; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Simplification; + +namespace Microsoft.CodeAnalysis.ChangeNamespace; + +[DataContract] +internal readonly record struct ChangeNamespaceOptions( + [property: DataMember(Order = 0)] SyntaxFormattingOptions FormattingOptions, + [property: DataMember(Order = 1)] AddImportPlacementOptions AddImportOptions, + [property: DataMember(Order = 2)] SimplifierOptions SimplifierOptions) +{ + public static async ValueTask FromDocumentAsync(Document document, ChangeNamespaceOptions? fallbackOptions, CancellationToken cancellationToken) + { + var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var addImportsOptions = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions?.SimplifierOptions, cancellationToken).ConfigureAwait(false); + + return new ChangeNamespaceOptions(formattingOptions, addImportsOptions, simplifierOptions); + } + + public static ChangeNamespaceOptions GetDefault(HostLanguageServices languageServices) + { + var formattingOptions = languageServices.GetRequiredService().DefaultOptions; + var addImportsOptions = AddImportPlacementOptions.Default; + var simplifierOptions = languageServices.GetRequiredService().DefaultOptions; + + return new ChangeNamespaceOptions(formattingOptions, addImportsOptions, simplifierOptions); + } + + public static ChangeNamespaceOptionsProvider CreateProvider(CodeActionOptionsProvider options) + => new(languageServices => new ChangeNamespaceOptions( + FormattingOptions: languageServices.GetRequiredService().DefaultOptions, + AddImportOptions: AddImportPlacementOptions.Default, + SimplifierOptions: options(languageServices).SimplifierOptions ?? languageServices.GetRequiredService().DefaultOptions)); +} + +internal delegate ChangeNamespaceOptions ChangeNamespaceOptionsProvider(HostLanguageServices languageServices); diff --git a/src/Workspaces/Core/Portable/Rename/IChangeNamespaceService.cs b/src/Workspaces/Core/Portable/ChangeNamespace/IChangeNamespaceService.cs similarity index 93% rename from src/Workspaces/Core/Portable/Rename/IChangeNamespaceService.cs rename to src/Workspaces/Core/Portable/ChangeNamespace/IChangeNamespaceService.cs index 27bb7f1d81eb4..6992bf3b149fe 100644 --- a/src/Workspaces/Core/Portable/Rename/IChangeNamespaceService.cs +++ b/src/Workspaces/Core/Portable/ChangeNamespace/IChangeNamespaceService.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.ChangeNamespace { @@ -52,12 +53,12 @@ internal interface IChangeNamespaceService : ILanguageService /// If the declared namespace for is already identical to , then it will be /// a no-op and original solution will be returned. /// - Task ChangeNamespaceAsync(Document document, SyntaxNode container, string targetNamespace, CancellationToken cancellationToken); + Task ChangeNamespaceAsync(Document document, SyntaxNode container, string targetNamespace, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); /// /// Using only the top level namespace declarations of a document, change all of them to the target namespace. Will only /// use namespace containers considered valid by /// - Task TryChangeTopLevelNamespacesAsync(Document document, string targetNamespace, CancellationToken cancellationToken); + Task TryChangeTopLevelNamespacesAsync(Document document, string targetNamespace, ChangeNamespaceOptionsProvider options, CancellationToken cancellationToken); } } diff --git a/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs b/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs index b9a3a9f39cf3c..70097a479306d 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/AbstractCodeCleanerService.cs @@ -27,7 +27,7 @@ internal abstract class AbstractCodeCleanerService : ICodeCleanerService public abstract ImmutableArray GetDefaultProviders(); protected abstract ImmutableArray GetSpansToAvoid(SyntaxNode root); - public async Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, ImmutableArray providers, CancellationToken cancellationToken) + public async Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, ImmutableArray providers, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.CodeCleanup_CleanupAsync, cancellationToken)) { @@ -455,7 +455,7 @@ private static bool CleanupWholeNode(TextSpan nodeSpan, ImmutableArray private async Task IterateAllCodeCleanupProvidersAsync( Document originalDocument, Document annotatedDocument, - SyntaxFormattingOptions options, + CodeCleanupOptions options, Func> spanGetter, ImmutableArray codeCleaners, CancellationToken cancellationToken) diff --git a/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs index aee43fe399a36..abae6e02a8bd7 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleaner.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CodeCleanup { @@ -78,7 +79,11 @@ public static Task CleanupAsync(Document document, TextSpan span, Immu public static async Task CleanupAsync(Document document, ImmutableArray spans, ImmutableArray providers = default, CancellationToken cancellationToken = default) { var cleanupService = document.GetRequiredLanguageService(); - var options = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + + var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions: null, cancellationToken).ConfigureAwait(false); + var options = new CodeCleanupOptions(formattingOptions, simplifierOptions); + return await cleanupService.CleanupAsync(document, spans, options, providers, cancellationToken).ConfigureAwait(false); } diff --git a/src/Workspaces/Core/Portable/CodeCleanup/CodeCleanupOptions.cs b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleanupOptions.cs new file mode 100644 index 0000000000000..db0f071de0198 --- /dev/null +++ b/src/Workspaces/Core/Portable/CodeCleanup/CodeCleanupOptions.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; +using System.Threading.Tasks; +using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Simplification; + +namespace Microsoft.CodeAnalysis.CodeCleanup +{ + [DataContract] + internal readonly record struct CodeCleanupOptions( + [property: DataMember(Order = 0)] SyntaxFormattingOptions FormattingOptions, + [property: DataMember(Order = 1)] SimplifierOptions SimplifierOptions) + { + public static async ValueTask FromDocumentAsync(Document document, CodeCleanupOptions? fallbackOptions, CancellationToken cancellationToken) + { + var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); + var simplifierOptions = await SimplifierOptions.FromDocumentAsync(document, fallbackOptions?.SimplifierOptions, cancellationToken).ConfigureAwait(false); + return new CodeCleanupOptions(formattingOptions, simplifierOptions); + } + } +} diff --git a/src/Workspaces/Core/Portable/CodeCleanup/ICodeCleanerService.cs b/src/Workspaces/Core/Portable/CodeCleanup/ICodeCleanerService.cs index f9f47a1551ea9..46e3eb71a1a41 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/ICodeCleanerService.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/ICodeCleanerService.cs @@ -27,7 +27,7 @@ internal interface ICodeCleanerService : ILanguageService /// /// This will run all provided code cleaners in an order that is given to the method. /// - Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, ImmutableArray providers, CancellationToken cancellationToken); + Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, ImmutableArray providers, CancellationToken cancellationToken); /// /// This will run all provided code cleaners in an order that is given to the method. diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs index 707c1d34a32fa..21831e950b539 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.cs @@ -25,11 +25,11 @@ public FormatCodeCleanupProvider(IEnumerable? rules = nu public string Name => PredefinedCodeCleanupProviderNames.Format; - public async Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, CancellationToken cancellationToken) + public async Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) { var formatter = document.GetRequiredLanguageService(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var result = formatter.GetFormattingResult(root, spans, options, _rules, cancellationToken); + var result = formatter.GetFormattingResult(root, spans, options.FormattingOptions, _rules, cancellationToken); // apply changes to an old text if it already exists return document.TryGetText(out var oldText) ? diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs index 52f2f2959a1be..04af6177ffb50 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs @@ -24,7 +24,7 @@ internal interface ICodeCleanupProvider /// /// This should apply its code clean up logic to the spans of the document. /// - Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, CancellationToken cancellationToken); + Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken); /// /// This will run all provided code cleaners in an order that is given to the method. diff --git a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs index 70ea4aefd3909..d96c3b54f8657 100644 --- a/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs +++ b/src/Workspaces/Core/Portable/CodeCleanup/Providers/SimplificationCodeCleanupProvider.cs @@ -16,8 +16,8 @@ internal class SimplificationCodeCleanupProvider : ICodeCleanupProvider { public string Name => PredefinedCodeCleanupProviderNames.Simplification; - public Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, CancellationToken cancellationToken) - => Simplifier.ReduceAsync(document, spans, null, cancellationToken); + public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) + => Simplifier.ReduceAsync(document, spans, options.SimplifierOptions, cancellationToken); public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, HostWorkspaceServices services, CancellationToken cancellationToken) { diff --git a/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs b/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs index 62ebe6c86ce69..2621ebceaf0fd 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs @@ -57,7 +57,7 @@ namespace Microsoft.CodeAnalysis.CodeFixes [Obsolete] bool ITypeScriptCodeFixContext.IsBlocking - => Options("TypeScript").IsBlocking; + => Options(Document.Project.LanguageServices).IsBlocking; /// /// Creates a code fix context to be passed into method. diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs b/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs index c2a3f38862c1d..51e14ba5b91b0 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs @@ -35,7 +35,7 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings [Obsolete] bool ITypeScriptCodeRefactoringContext.IsBlocking - => Options("TypeScript").IsBlocking; + => Options(Document.Project.LanguageServices).IsBlocking; private readonly Action _registerRefactoring; diff --git a/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs b/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs index 1928c77c44470..f72e59031232d 100644 --- a/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Options { diff --git a/src/Workspaces/Core/Portable/Rename/RenameOptions.cs b/src/Workspaces/Core/Portable/Rename/RenameOptions.cs index e7bbaf793a35c..f11865f6544ab 100644 --- a/src/Workspaces/Core/Portable/Rename/RenameOptions.cs +++ b/src/Workspaces/Core/Portable/Rename/RenameOptions.cs @@ -4,7 +4,9 @@ using System; using System.Runtime.Serialization; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.Rename { diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs b/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs index ae34cee3d372f..5d04e4187aa97 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.SyncNamespaceDocumentAction.cs @@ -29,11 +29,13 @@ public static partial class Renamer internal sealed class SyncNamespaceDocumentAction : RenameDocumentAction { private readonly AnalysisResult _analysis; + private readonly ChangeNamespaceOptionsProvider _options; - private SyncNamespaceDocumentAction(AnalysisResult analysis) + private SyncNamespaceDocumentAction(AnalysisResult analysis, ChangeNamespaceOptionsProvider options) : base(ImmutableArray.Empty) { _analysis = analysis; + _options = options; } public override string GetDescription(CultureInfo? culture) @@ -42,7 +44,7 @@ public override string GetDescription(CultureInfo? culture) internal override async Task GetModifiedSolutionAsync(Document document, DocumentRenameOptions options, CancellationToken cancellationToken) { var changeNamespaceService = document.GetRequiredLanguageService(); - var solution = await changeNamespaceService.TryChangeTopLevelNamespacesAsync(document, _analysis.TargetNamespace, cancellationToken).ConfigureAwait(false); + var solution = await changeNamespaceService.TryChangeTopLevelNamespacesAsync(document, _analysis.TargetNamespace, _options, cancellationToken).ConfigureAwait(false); // If the solution fails to update fail silently. The user will see no large // negative impact from not doing this modification, and it's possible the document @@ -50,13 +52,13 @@ internal override async Task GetModifiedSolutionAsync(Document documen return solution ?? document.Project.Solution; } - public static SyncNamespaceDocumentAction? TryCreate(Document document, IReadOnlyList newFolders, CancellationToken _) + public static SyncNamespaceDocumentAction? TryCreate(Document document, IReadOnlyList newFolders, ChangeNamespaceOptionsProvider options) { var analysisResult = Analyze(document, newFolders); if (analysisResult.HasValue) { - return new SyncNamespaceDocumentAction(analysisResult.Value); + return new SyncNamespaceDocumentAction(analysisResult.Value, options); } return null; diff --git a/src/Workspaces/Core/Portable/Rename/Renamer.cs b/src/Workspaces/Core/Portable/Rename/Renamer.cs index 163084fbccf22..7dc73d80dc5db 100644 --- a/src/Workspaces/Core/Portable/Rename/Renamer.cs +++ b/src/Workspaces/Core/Portable/Rename/Renamer.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; @@ -89,18 +90,24 @@ public static Task RenameDocumentAsync( /// The new name for the document. Pass null or the same name to keep unchanged. /// Options used to configure rename of a type contained in the document that matches the document's name. /// The new set of folders for the property - public static async Task RenameDocumentAsync( - Document document, + public static Task RenameDocumentAsync( + Document document!!, DocumentRenameOptions options, string? newDocumentName, IReadOnlyList? newDocumentFolders = null, CancellationToken cancellationToken = default) { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } + return RenameDocumentAsync(document, options, ChangeNamespaceOptions.GetDefault, newDocumentName, newDocumentFolders, cancellationToken); + } + internal static async Task RenameDocumentAsync( + Document document, + DocumentRenameOptions options, + ChangeNamespaceOptionsProvider changeNamespaceOptions, + string? newDocumentName, + IReadOnlyList? newDocumentFolders, + CancellationToken cancellationToken) + { if (document.Services.GetService() != null) { // Don't advertise that we can file rename generated documents that map to a different file. @@ -117,7 +124,7 @@ public static async Task RenameDocumentAsync( if (newDocumentFolders != null && !newDocumentFolders.SequenceEqual(document.Folders)) { - var action = SyncNamespaceDocumentAction.TryCreate(document, newDocumentFolders, cancellationToken); + var action = SyncNamespaceDocumentAction.TryCreate(document, newDocumentFolders, changeNamespaceOptions); actions.AddIfNotNull(action); } diff --git a/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs b/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs index f4b38be00b3f0..af9d5786cc8b5 100644 --- a/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs +++ b/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs @@ -39,6 +39,8 @@ protected AbstractSimplificationService(ImmutableArray reducers protected abstract ImmutableArray GetNodesAndTokensToReduce(SyntaxNode root, Func isNodeOrTokenOutsideSimplifySpans); protected abstract SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode); protected abstract bool NodeRequiresNonSpeculativeSemanticModel(SyntaxNode node); + + public abstract SimplifierOptions DefaultOptions { get; } public abstract SimplifierOptions GetSimplifierOptions(AnalyzerConfigOptions options, SimplifierOptions? fallbackOptions); protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, SyntaxNode originalNode) diff --git a/src/Workspaces/Core/Portable/Simplification/ISimplificationService.cs b/src/Workspaces/Core/Portable/Simplification/ISimplificationService.cs index bc232749545ec..aab4d215fc2c7 100644 --- a/src/Workspaces/Core/Portable/Simplification/ISimplificationService.cs +++ b/src/Workspaces/Core/Portable/Simplification/ISimplificationService.cs @@ -14,6 +14,7 @@ namespace Microsoft.CodeAnalysis.Simplification { internal interface ISimplificationService : ILanguageService { + SimplifierOptions DefaultOptions { get; } SimplifierOptions GetSimplifierOptions(AnalyzerConfigOptions options, SimplifierOptions? fallbackOptions); SyntaxNode Expand( diff --git a/src/Workspaces/Core/Portable/Simplification/Simplifier.cs b/src/Workspaces/Core/Portable/Simplification/Simplifier.cs index bb912b87993fb..74317d0b73b35 100644 --- a/src/Workspaces/Core/Portable/Simplification/Simplifier.cs +++ b/src/Workspaces/Core/Portable/Simplification/Simplifier.cs @@ -148,6 +148,12 @@ public static async Task ReduceAsync(Document document, OptionSet? opt return await ReduceAsync(document, root.FullSpan, optionSet, cancellationToken).ConfigureAwait(false); } + internal static async Task ReduceAsync(Document document, SimplifierOptions options, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + return await ReduceAsync(document, root.FullSpan, options, cancellationToken).ConfigureAwait(false); + } + /// /// Reduce the sub-trees annotated with found within the subtrees identified with the specified . /// The annotated node and all child nodes will be reduced. @@ -168,6 +174,12 @@ public static async Task ReduceAsync(Document document, SyntaxAnnotati return await ReduceAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), optionSet, cancellationToken).ConfigureAwait(false); } + internal static async Task ReduceAsync(Document document, SyntaxAnnotation annotation, SimplifierOptions options, CancellationToken cancellationToken) + { + var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + return await ReduceAsync(document, root.GetAnnotatedNodesAndTokens(annotation).Select(t => t.FullSpan), options, cancellationToken).ConfigureAwait(false); + } + /// /// Reduce the sub-trees annotated with found within the specified span. /// The annotated node and all child nodes will be reduced. @@ -182,6 +194,9 @@ public static Task ReduceAsync(Document document, TextSpan span, Optio return ReduceAsync(document, SpecializedCollections.SingletonEnumerable(span), optionSet, cancellationToken); } + internal static Task ReduceAsync(Document document, TextSpan span, SimplifierOptions options, CancellationToken cancellationToken) + => ReduceAsync(document, SpecializedCollections.SingletonEnumerable(span), options, cancellationToken); + /// /// Reduce the sub-trees annotated with found within the specified spans. /// The annotated node and all child nodes will be reduced. @@ -201,13 +216,16 @@ public static async Task ReduceAsync(Document document, IEnumerable().ReduceAsync( - document, spans.ToImmutableArrayOrEmpty(), options, cancellationToken: cancellationToken).ConfigureAwait(false); + document, spans.ToImmutableArrayOrEmpty(), options, reducers: default, cancellationToken).ConfigureAwait(false); } + internal static Task ReduceAsync(Document document, IEnumerable spans, SimplifierOptions options, CancellationToken cancellationToken) + => document.GetRequiredLanguageService().ReduceAsync( + document, spans.ToImmutableArrayOrEmpty(), options, reducers: default, cancellationToken); + internal static async Task ReduceAsync( - Document document, ImmutableArray reducers, OptionSet? optionSet = null, CancellationToken cancellationToken = default) + Document document, ImmutableArray reducers, SimplifierOptions options, CancellationToken cancellationToken) { - var options = await GetOptionsAsync(document, optionSet, cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return await document.GetRequiredLanguageService() .ReduceAsync(document, ImmutableArray.Create(root.FullSpan), options, diff --git a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs index 15195e451f58d..27bb54693dd23 100644 --- a/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs +++ b/src/Workspaces/CoreTest/CodeCleanup/MockCodeCleanupProvider.cs @@ -6,10 +6,10 @@ using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup @@ -25,8 +25,8 @@ public MockCodeCleanupProvider() public string Name => nameof(MockCodeCleanupProvider); - public Task CleanupAsync(Document document, ImmutableArray spans, SyntaxFormattingOptions options, CancellationToken cancellationToken) - => (CleanupDocumentAsyncImpl ?? throw new NotImplementedException()).Invoke(document, spans, options, cancellationToken); + public Task CleanupAsync(Document document, ImmutableArray spans, CodeCleanupOptions options, CancellationToken cancellationToken) + => (CleanupDocumentAsyncImpl ?? throw new NotImplementedException()).Invoke(document, spans, options.FormattingOptions, cancellationToken); public Task CleanupAsync(SyntaxNode root, ImmutableArray spans, SyntaxFormattingOptions options, HostWorkspaceServices services, CancellationToken cancellationToken) => Task.FromResult((CleanupNodeImpl ?? throw new NotImplementedException()).Invoke(root, spans, options, services)); diff --git a/src/Workspaces/Remote/ServiceHub/Services/EncapsulateField/RemoteEncapsulateFieldService.cs b/src/Workspaces/Remote/ServiceHub/Services/EncapsulateField/RemoteEncapsulateFieldService.cs index db5f56e87ed84..a8cae7a8cfcd7 100644 --- a/src/Workspaces/Remote/ServiceHub/Services/EncapsulateField/RemoteEncapsulateFieldService.cs +++ b/src/Workspaces/Remote/ServiceHub/Services/EncapsulateField/RemoteEncapsulateFieldService.cs @@ -53,8 +53,11 @@ public RemoteEncapsulateFieldService(in ServiceConstructionArguments arguments) var service = document.GetLanguageService(); + // TODO: + var fallbackOptions = new EncapsulateFieldOptions(); + var newSolution = await service.EncapsulateFieldsAsync( - document, fields.ToImmutable(), updateReferences, cancellationToken).ConfigureAwait(false); + document, fields.ToImmutable(), fallbackOptions, updateReferences, cancellationToken).ConfigureAwait(false); return await RemoteUtilities.GetDocumentTextChangesAsync( solution, newSolution, cancellationToken).ConfigureAwait(false); }, cancellationToken); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormatting.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormatting.cs index 974186ddbd5c5..0eebd58006a10 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormatting.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormatting.cs @@ -35,6 +35,9 @@ internal class CSharpSyntaxFormatting : AbstractSyntaxFormatting public override ImmutableArray GetDefaultFormattingRules() => _rules; + public override SyntaxFormattingOptions DefaultOptions + => CSharpSyntaxFormattingOptions.Default; + public override SyntaxFormattingOptions GetFormattingOptions(AnalyzerConfigOptions options) => CSharpSyntaxFormattingOptions.Create(options); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/AbstractSyntaxFormattingService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/AbstractSyntaxFormattingService.cs index 887b5b23f345e..caa6018f7a7c1 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/AbstractSyntaxFormattingService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/AbstractSyntaxFormattingService.cs @@ -25,6 +25,7 @@ protected AbstractSyntaxFormatting() { } + public abstract SyntaxFormattingOptions DefaultOptions { get; } public abstract SyntaxFormattingOptions GetFormattingOptions(AnalyzerConfigOptions options); public abstract ImmutableArray GetDefaultFormattingRules(); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormatting.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormatting.cs index 73af81ac1d358..79ee7fb40e671 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormatting.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormatting.cs @@ -21,7 +21,9 @@ namespace Microsoft.CodeAnalysis.Formatting { internal interface ISyntaxFormatting { + SyntaxFormattingOptions DefaultOptions { get; } SyntaxFormattingOptions GetFormattingOptions(AnalyzerConfigOptions options); + ImmutableArray GetDefaultFormattingRules(); IFormattingResult GetFormattingResult(SyntaxNode node, IEnumerable? spans, SyntaxFormattingOptions options, IEnumerable? rules, CancellationToken cancellationToken); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs index 05ca44c08662c..d4baad1761eff 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs @@ -334,7 +334,7 @@ public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) /// /// We always unilaterally add "global::" to all named types/namespaces. This /// will then be trimmed off if possible by calls to - /// + /// /// private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs index 8d93dcacb304b..bf486b845cf3a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/CodeActionOptions.cs @@ -4,6 +4,7 @@ using System.Runtime.Serialization; using Microsoft.CodeAnalysis.ExtractMethod; +using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Simplification; @@ -28,7 +29,7 @@ internal readonly record struct CodeActionOptions [DataMember(Order = 0)] public SymbolSearchOptions SearchOptions { get; init; } [DataMember(Order = 1)] public ImplementTypeOptions ImplementTypeOptions { get; init; } [DataMember(Order = 2)] public ExtractMethodOptions ExtractMethodOptions { get; init; } - [DataMember(Order = 3)] public SimplifierOptions? FallbackSimplifierOptions { get; init; } + [DataMember(Order = 3)] public SimplifierOptions? SimplifierOptions { get; init; } [DataMember(Order = 4)] public bool HideAdvancedMembers { get; init; } [DataMember(Order = 5)] public bool IsBlocking { get; init; } [DataMember(Order = 6)] public int WrappingColumn { get; init; } @@ -49,7 +50,7 @@ public CodeActionOptions( SymbolSearchOptions? SearchOptions = null, ImplementTypeOptions? ImplementTypeOptions = null, ExtractMethodOptions? ExtractMethodOptions = null, - SimplifierOptions? FallbackSimplifierOptions = null, + SimplifierOptions? SimplifierOptions = null, bool HideAdvancedMembers = false, bool IsBlocking = false, int WrappingColumn = DefaultWrappingColumn) @@ -57,7 +58,7 @@ public CodeActionOptions( this.SearchOptions = SearchOptions ?? SymbolSearchOptions.Default; this.ImplementTypeOptions = ImplementTypeOptions ?? ImplementType.ImplementTypeOptions.Default; this.ExtractMethodOptions = ExtractMethodOptions ?? ExtractMethod.ExtractMethodOptions.Default; - this.FallbackSimplifierOptions = FallbackSimplifierOptions; + this.SimplifierOptions = SimplifierOptions; this.HideAdvancedMembers = HideAdvancedMembers; this.IsBlocking = IsBlocking; this.WrappingColumn = WrappingColumn; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/IAddImportsService.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/IAddImportsService.cs index 3929b0465ec9f..faa02701a9a4f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/IAddImportsService.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/IAddImportsService.cs @@ -22,10 +22,17 @@ namespace Microsoft.CodeAnalysis.AddImport { [DataContract] internal record struct AddImportPlacementOptions( - [property: DataMember(Order = 0)] bool PlaceSystemNamespaceFirst, - [property: DataMember(Order = 1)] bool PlaceImportsInsideNamespaces, - [property: DataMember(Order = 2)] bool AllowInHiddenRegions) + [property: DataMember(Order = 0)] bool PlaceSystemNamespaceFirst = true, + [property: DataMember(Order = 1)] bool PlaceImportsInsideNamespaces = false, + [property: DataMember(Order = 2)] bool AllowInHiddenRegions = false) { + public AddImportPlacementOptions() + : this(PlaceSystemNamespaceFirst: true) + { + } + + public static readonly AddImportPlacementOptions Default = new(); + public static async Task FromDocumentAsync(Document document, CancellationToken cancellationToken) { #if CODE_STYLE diff --git a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AbstractTokensCodeCleanupProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AbstractTokensCodeCleanupProvider.vb index 9eef93cdd24c1..c7ff2a0c4b23c 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AbstractTokensCodeCleanupProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/AbstractTokensCodeCleanupProvider.vb @@ -19,7 +19,7 @@ Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers Protected MustOverride Function GetRewriterAsync( document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of Rewriter) - Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As SyntaxFormattingOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync + Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As CodeCleanupOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim rewriter As Rewriter = Await GetRewriterAsync(document, root, spans, cancellationToken).ConfigureAwait(False) Dim newRoot = rewriter.Visit(root) diff --git a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/CaseCorrectionCodeCleanupProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/CaseCorrectionCodeCleanupProvider.vb index e4cd067bbaf8f..6917e660f9053 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/CaseCorrectionCodeCleanupProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/CaseCorrectionCodeCleanupProvider.vb @@ -28,7 +28,7 @@ Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers End Get End Property - Public Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As SyntaxFormattingOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync + Public Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As CodeCleanupOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync Return CaseCorrector.CaseCorrectAsync(document, spans, cancellationToken) End Function diff --git a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb index 7ad4b805deded..f75b77fcdfc13 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/NormalizeModifiersOrOperatorsCodeCleanupProvider.vb @@ -31,9 +31,9 @@ Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers End Get End Property - Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As SyntaxFormattingOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync + Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As CodeCleanupOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) - Dim newRoot = Await CleanupAsync(root, spans, options, document.Project.Solution.Workspace.Services, cancellationToken).ConfigureAwait(False) + Dim newRoot = Await CleanupAsync(root, spans, options.FormattingOptions, document.Project.Solution.Workspace.Services, cancellationToken).ConfigureAwait(False) Return If(root Is newRoot, document, document.WithSyntaxRoot(newRoot)) End Function diff --git a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/RemoveUnnecessaryLineContinuationCodeCleanupProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/RemoveUnnecessaryLineContinuationCodeCleanupProvider.vb index 9bcd1c84bfdfc..842092f714594 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/RemoveUnnecessaryLineContinuationCodeCleanupProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/RemoveUnnecessaryLineContinuationCodeCleanupProvider.vb @@ -29,7 +29,7 @@ Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers End Get End Property - Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As SyntaxFormattingOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync + Public Async Function CleanupAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As CodeCleanupOptions, cancellationToken As CancellationToken) As Task(Of Document) Implements ICodeCleanupProvider.CleanupAsync ' Is this VB 9? If so, we shouldn't remove line continuations because implicit line continuation was introduced in VB 10. Dim parseOptions = TryCast(document.Project.ParseOptions, VisualBasicParseOptions) If parseOptions?.LanguageVersion <= LanguageVersion.VisualBasic9 Then @@ -37,7 +37,7 @@ Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers End If Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) - Dim newRoot = Await CleanupAsync(root, spans, options, document.Project.Solution.Workspace.Services, cancellationToken).ConfigureAwait(False) + Dim newRoot = Await CleanupAsync(root, spans, options.FormattingOptions, document.Project.Solution.Workspace.Services, cancellationToken).ConfigureAwait(False) Return If(newRoot Is root, document, document.WithSyntaxRoot(newRoot)) End Function diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb b/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb index 4e0a60a5a3e25..adea2938f1526 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormatting.vb @@ -28,6 +28,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Return _rules End Function + Public Overrides ReadOnly Property DefaultOptions As SyntaxFormattingOptions + Get + Return VisualBasicSyntaxFormattingOptions.Default + End Get + End Property + Public Overrides Function GetFormattingOptions(options As AnalyzerConfigOptions) As SyntaxFormattingOptions Return VisualBasicSyntaxFormattingOptions.Create(options) End Function diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb b/src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb index 68c2b415615f9..f46b72f4f0845 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.vb @@ -37,6 +37,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification MyBase.New(s_reducers) End Sub + Public Overrides ReadOnly Property DefaultOptions As SimplifierOptions + Get + Return VisualBasicSimplifierOptions.Default + End Get + End Property + Public Overrides Function GetSimplifierOptions(options As AnalyzerConfigOptions, fallbackOptions As SimplifierOptions) As SimplifierOptions Return VisualBasicSimplifierOptions.Create(options, DirectCast(fallbackOptions, VisualBasicSimplifierOptions)) End Function