diff --git a/src/EditorFeatures/CSharp/Formatting/CSharpEditorFormattingService.cs b/src/EditorFeatures/CSharp/Formatting/CSharpEditorFormattingService.cs index 6205b958b0a9e..57d6b31d58f51 100644 --- a/src/EditorFeatures/CSharp/Formatting/CSharpEditorFormattingService.cs +++ b/src/EditorFeatures/CSharp/Formatting/CSharpEditorFormattingService.cs @@ -58,11 +58,11 @@ public CSharpEditorFormattingService() public bool SupportsFormattingOnTypedCharacter(Document document, char ch) { - var options = document.Project.Solution.Workspace.Options; - var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, document.Project.Language) == FormattingOptions.IndentStyle.Smart; + var options = document.Options; + var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent) == FormattingOptions.IndentStyle.Smart; - if ((ch == '}' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, document.Project.Language) && !smartIndentOn) || - (ch == ';' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, document.Project.Language))) + if ((ch == '}' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace) && !smartIndentOn) || + (ch == ';' && !options.GetOption(FeatureOnOffOptions.AutoFormattingOnSemicolon))) { return false; } @@ -182,12 +182,10 @@ public async Task> GetFormattingChangesAsync(Document document return null; } - var options = document.Project.Solution.Workspace.Options; - // don't attempt to format on close brace if autoformat on close brace feature is off, instead just smart indent bool smartIndentOnly = token.IsKind(SyntaxKind.CloseBraceToken) && - !options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, document.Project.Language); + !document.Options.GetOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); if (!smartIndentOnly) { @@ -216,7 +214,7 @@ private static async Task GetTokenBeforeTheCaretAsync(Document docu private async Task> FormatTokenAsync(Document document, SyntaxToken token, IEnumerable formattingRules, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var formatter = CreateSmartTokenFormatter(document.Project.Solution.Workspace.Options, formattingRules, root); + var formatter = CreateSmartTokenFormatter(document.Options, formattingRules, root); var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false); return changes; } @@ -247,7 +245,7 @@ private async Task> FormatRangeAsync( } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var formatter = new SmartTokenFormatter(document.Project.Solution.Workspace.Options, formattingRules, (CompilationUnitSyntax)root); + var formatter = new SmartTokenFormatter(document.Options, formattingRules, (CompilationUnitSyntax)root); var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken); return changes; diff --git a/src/EditorFeatures/CSharp/Formatting/Indentation/SmartTokenFormatter.cs b/src/EditorFeatures/CSharp/Formatting/Indentation/SmartTokenFormatter.cs index 1233e49bf53bc..703f68bc4416e 100644 --- a/src/EditorFeatures/CSharp/Formatting/Indentation/SmartTokenFormatter.cs +++ b/src/EditorFeatures/CSharp/Formatting/Indentation/SmartTokenFormatter.cs @@ -99,7 +99,7 @@ public Task> FormatTokenAsync(Workspace workspace, SyntaxToken var smartTokenformattingRules = (new SmartTokenFormattingRule()).Concat(_formattingRules); var adjustedStartPosition = previousToken.SpanStart; - var indentStyle = workspace.Options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); + var indentStyle = _optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); if (token.IsKind(SyntaxKind.OpenBraceToken) && token.IsFirstTokenOnLine(token.SyntaxTree.GetText()) && indentStyle != FormattingOptions.IndentStyle.Smart) { adjustedStartPosition = token.SpanStart; diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs index f64bb00ec5080..ae39b3550ed02 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs @@ -141,9 +141,7 @@ protected async Task VerifySendEnterThroughToEnterAsync(string initialMarkup, st var completionList = await GetCompletionListAsync(document, position, CompletionTrigger.Default); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); - var optionService = workspace.Services.GetService(); - var options = optionService.GetOptions().WithChangedOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, sendThroughEnterEnabled); - optionService.SetOptions(options); + workspace.Options = workspace.Options.WithChangedOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, sendThroughEnterEnabled); var completionRules = CompletionHelper.GetHelper(document); Assert.Equal(expected, completionRules.SendEnterThroughToEditor(item, textTypedSoFar, workspace.Options)); diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs index 8703f54a8333e..4bdac24d06830 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs @@ -111,9 +111,8 @@ protected static async Task ExtractMethodAsync( var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); - var options = document.Project.Solution.Workspace.Options - .WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, allowMovingDeclaration) - .WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); + var options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, allowMovingDeclaration) + .WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options); @@ -145,8 +144,7 @@ protected async Task TestSelectionAsync(string codeWithMarker, bool expectedFail var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); - var options = document.Project.Solution.Workspace.Options - .WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, true); + var options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, true); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, namedSpans["b"].Single(), options); @@ -172,8 +170,7 @@ protected async Task IterateAllAsync(string code) var root = await document.GetSyntaxRootAsync(); var iterator = root.DescendantNodesAndSelf().Cast(); - var options = document.Project.Solution.Workspace.Options - .WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, true); + var options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, true); foreach (var node in iterator) { diff --git a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTestBase.cs b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTestBase.cs index c3e8e5dfaa309..7f471f8b1a1a9 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTestBase.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTestBase.cs @@ -225,10 +225,8 @@ protected static async Task AssertFormatWithPasteOrReturnAsync(string expectedWi // get original buffer var buffer = workspace.Documents.First().GetTextBuffer(); - var optionService = workspace.Services.GetService(); if (isPaste) { - optionService.SetOptions(optionService.GetOptions().WithChangedOption(FeatureOnOffOptions.FormatOnPaste, LanguageNames.CSharp, true)); var commandHandler = new FormatCommandHandler(TestWaitIndicator.Default, null, null); var commandArgs = new PasteCommandArgs(view, view.TextBuffer); commandHandler.ExecuteCommand(commandArgs, () => { }); diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/FormatterTestsBase.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/FormatterTestsBase.cs index 4328c1c4821fd..0704dbc5ebc49 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/FormatterTestsBase.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/FormatterTestsBase.cs @@ -75,7 +75,7 @@ private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextB var rules = formattingRuleProvider.CreateRule(document, position).Concat(Formatter.GetDefaultFormattingRules(document)); - var formatter = new SmartTokenFormatter(workspace.Options, rules, root); + var formatter = new SmartTokenFormatter(document.Options, rules, root); var changes = await formatter.FormatTokenAsync(workspace, token, CancellationToken.None); ApplyChanges(buffer, changes); diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs index 4bbaea4a448e9..7d667588964b3 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs @@ -1365,7 +1365,7 @@ private async Task AssertIndentUsingSmartTokenFormatterAsync( Assert.True( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), - root, line, workspace.Options, CancellationToken.None)); + root, line, document.Options, CancellationToken.None)); var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch); Assert.Equal(expectedIndentation.Value, actualIndentation); @@ -1392,7 +1392,7 @@ private async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync( Assert.False( CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter( Formatter.GetDefaultFormattingRules(workspace, root.Language), - root, line, workspace.Options, CancellationToken.None)); + root, line, document.Options, CancellationToken.None)); await TestIndentationAsync(indentationLine, expectedIndentation, workspace); } diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs index 77c596f65e492..cb8553ac626fc 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs @@ -3093,7 +3093,6 @@ internal static async Task AutoFormatTokenAsync(string markup, string expected) { var subjectDocument = workspace.Documents.Single(); - var optionService = workspace.Services.GetService(); var textUndoHistory = new Mock(); var editorOperationsFactory = new Mock(); var editorOperations = new Mock(); diff --git a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs index afa4721836e51..207e47aad38a2 100644 --- a/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/AutomaticCompletion/AbstractAutomaticLineEnderCommandHandler.cs @@ -78,7 +78,7 @@ public void ExecuteCommand(AutomaticLineEnderCommandArgs args, Action nextHandle } // feature off - if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.AutomaticLineEnder)) + if (!document.Options.GetOption(InternalFeatureOnOffOptions.AutomaticLineEnder)) { NextAction(operations, nextHandler); return; diff --git a/src/EditorFeatures/Core/Implementation/CallHierarchy/CallHierarchyDetail.cs b/src/EditorFeatures/Core/Implementation/CallHierarchy/CallHierarchyDetail.cs index 0bc5b01f70b48..e90453b41bcf5 100644 --- a/src/EditorFeatures/Core/Implementation/CallHierarchy/CallHierarchyDetail.cs +++ b/src/EditorFeatures/Core/Implementation/CallHierarchy/CallHierarchyDetail.cs @@ -102,7 +102,7 @@ public void NavigateTo() if (document != null) { var navigator = _workspace.Services.GetService(); - var options = _workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); + var options = document.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); navigator.TryNavigateToSpan(_workspace, document.Id, _span, options); } } diff --git a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs index 25ec3ab4201f0..17319ee673b26 100644 --- a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs @@ -127,15 +127,14 @@ private bool Execute( return false; } - var options = document.Project.Solution.Workspace.Options; var result = ExtractMethodService.ExtractMethodAsync( - document, spans.Single().Span.ToTextSpan(), options, cancellationToken).WaitAndGetResult(cancellationToken); + document, spans.Single().Span.ToTextSpan(), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); Contract.ThrowIfNull(result); if (!result.Succeeded && !result.SucceededWithSuggestion) { // if it failed due to out/ref parameter in async method, try it with different option - var newResult = TryWithoutMakingValueTypesRef(document, spans, options, result, cancellationToken); + var newResult = TryWithoutMakingValueTypesRef(document, spans, result, cancellationToken); if (newResult != null) { var notificationService = document.Project.Solution.Workspace.Services.GetService(); @@ -191,7 +190,7 @@ private bool TryNotifyFailureToUser(Document document, ExtractMethodResult resul var notificationService = document.Project.Solution.Workspace.Services.GetService(); // see whether we will allow best effort extraction and if it is possible. - if (!document.Project.Solution.Workspace.Options.GetOption(ExtractMethodOptions.AllowBestEffort, document.Project.Language) || + if (!document.Options.GetOption(ExtractMethodOptions.AllowBestEffort) || !result.Status.HasBestEffort() || result.Document == null) { if (notificationService != null) @@ -224,8 +223,10 @@ private bool TryNotifyFailureToUser(Document document, ExtractMethodResult resul } private static ExtractMethodResult TryWithoutMakingValueTypesRef( - Document document, NormalizedSnapshotSpanCollection spans, OptionSet options, ExtractMethodResult result, CancellationToken cancellationToken) + Document document, NormalizedSnapshotSpanCollection spans, ExtractMethodResult result, CancellationToken cancellationToken) { + OptionSet options = document.Options; + if (options.GetOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language) || !result.Reasons.IsSingle()) { return null; diff --git a/src/EditorFeatures/Core/Implementation/Formatting/Indentation/AbstractSmartTokenFormatterCommandHandler.cs b/src/EditorFeatures/Core/Implementation/Formatting/Indentation/AbstractSmartTokenFormatterCommandHandler.cs index 94976b232f3d4..02c9c03fdeaed 100644 --- a/src/EditorFeatures/Core/Implementation/Formatting/Indentation/AbstractSmartTokenFormatterCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/Formatting/Indentation/AbstractSmartTokenFormatterCommandHandler.cs @@ -45,7 +45,7 @@ public AbstractSmartTokenFormatterCommandHandler( protected bool FormatToken(ITextView view, Document document, SyntaxToken token, IEnumerable formattingRules, CancellationToken cancellationToken) { var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); - var formatter = CreateSmartTokenFormatter(document.Project.Solution.Workspace.Options, formattingRules, root); + var formatter = CreateSmartTokenFormatter(document.Options, formattingRules, root); var changes = formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).WaitAndGetResult(cancellationToken); if (changes.Count == 0) { @@ -226,14 +226,14 @@ private static void ReadjustIndentation(ITextView view, ITextBuffer subjectBuffe return; } - var options = document.Project.Solution.Workspace.Options; + var options = document.Options; // and then, insert the text document.Project.Solution.Workspace.ApplyTextChanges(document.Id, new TextChange( new TextSpan( lineInSubjectBuffer.Start.Position, firstNonWhitespaceIndex), - indentation.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs, document.Project.Language), options.GetOption(FormattingOptions.TabSize, document.Project.Language))), + indentation.CreateIndentationString(options.GetOption(FormattingOptions.UseTabs), options.GetOption(FormattingOptions.TabSize))), CancellationToken.None); } @@ -296,7 +296,7 @@ private bool TryFormatUsingTokenFormatter(ITextView view, ITextBuffer subjectBuf var position = view.GetCaretPoint(subjectBuffer).Value; var line = position.GetContainingLine(); var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); - var options = document.Project.Solution.Workspace.Options; + var options = document.Options; if (!UseSmartTokenFormatter(root, line, formattingRules, options, cancellationToken)) { return false; diff --git a/src/EditorFeatures/Core/Implementation/GoToDefinition/GoToDefinitionHelpers.cs b/src/EditorFeatures/Core/Implementation/GoToDefinition/GoToDefinitionHelpers.cs index f317f062b9193..2ab97d91347ec 100644 --- a/src/EditorFeatures/Core/Implementation/GoToDefinition/GoToDefinitionHelpers.cs +++ b/src/EditorFeatures/Core/Implementation/GoToDefinition/GoToDefinitionHelpers.cs @@ -64,7 +64,7 @@ public static bool TryGoToDefinition( symbol = ((IMethodSymbol)symbol).PartialImplementationPart ?? symbol; } - var options = project.Solution.Workspace.Options; + var options = project.Solution.Options; var preferredSourceLocations = NavigableItemFactory.GetPreferredSourceLocations(solution, symbol).ToArray(); var title = NavigableItemFactory.GetSymbolDisplayString(project, symbol); @@ -76,7 +76,7 @@ public static bool TryGoToDefinition( var externalSourceDefinitions = FindExternalDefinitionsAsync(symbol, project, externalDefinitionProviders, cancellationToken).WaitAndGetResult(cancellationToken).ToImmutableArray(); if (externalSourceDefinitions.Length > 0) { - return TryGoToDefinition(externalSourceDefinitions, title, project.Solution.Workspace.Options, presenters, throwOnHiddenDefinition); + return TryGoToDefinition(externalSourceDefinitions, title, options, presenters, throwOnHiddenDefinition); } } @@ -93,7 +93,7 @@ public static bool TryGoToDefinition( } var navigableItems = preferredSourceLocations.Select(location => NavigableItemFactory.GetItemFromSymbolLocation(solution, symbol, location)).ToImmutableArray(); - return TryGoToDefinition(navigableItems, title, project.Solution.Workspace.Options, presenters, throwOnHiddenDefinition); + return TryGoToDefinition(navigableItems, title, options, presenters, throwOnHiddenDefinition); } private static bool TryGoToDefinition( diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/Controller_ToggleCompletionMode.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/Controller_ToggleCompletionMode.cs index daaf4c1fe68cf..1ef65c010aece 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/Controller_ToggleCompletionMode.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/Controller_ToggleCompletionMode.cs @@ -25,11 +25,8 @@ void ICommandHandler.ExecuteCommand(ToggleCompl if (Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace)) { - var optionService = workspace.Services.GetService(); - var optionSet = optionService.GetOptions(); - - var wasEnabled = optionService.GetOption(EditorCompletionOptions.UseSuggestionMode); - optionService.SetOptions(optionSet.WithChangedOption(EditorCompletionOptions.UseSuggestionMode, !wasEnabled)); + var newState = !workspace.Options.GetOption(EditorCompletionOptions.UseSuggestionMode); + workspace.Options = workspace.Options.WithChangedOption(EditorCompletionOptions.UseSuggestionMode, newState); // If we don't have a computation in progress, then we don't have to do anything here. if (this.sessionOpt == null) @@ -37,7 +34,7 @@ void ICommandHandler.ExecuteCommand(ToggleCompl return; } - this.sessionOpt.SetModelBuilderState(!wasEnabled); + this.sessionOpt.SetModelBuilderState(newState); } } } diff --git a/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs index 639d03437c497..cac007a35efb8 100644 --- a/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs @@ -61,8 +61,7 @@ protected override async Task ProduceTagsAsync(TaggerContext c return; } - var options = document.Project.Solution.Workspace.Options; - if (!options.GetOption(FeatureOnOffOptions.LineSeparator, document.Project.Language)) + if (!document.Options.GetOption(FeatureOnOffOptions.LineSeparator)) { return; } diff --git a/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs b/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs index 5cfda6f227f85..b2e4a9df3956d 100644 --- a/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs +++ b/src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTaggerProvider.RenameTrackingCodeAction.cs @@ -49,7 +49,7 @@ protected override Task> ComputeOperationsAsync protected override async Task> ComputePreviewOperationsAsync(CancellationToken cancellationToken) { - if (!_document.Project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.RenameTrackingPreview, _document.Project.Language) || + if (!_document.Options.GetOption(FeatureOnOffOptions.RenameTrackingPreview) || !TryInitializeRenameTrackingCommitter(cancellationToken)) { return await SpecializedTasks.EmptyEnumerable().ConfigureAwait(false); diff --git a/src/EditorFeatures/Core/Implementation/SmartIndent/AbstractIndentationService.cs b/src/EditorFeatures/Core/Implementation/SmartIndent/AbstractIndentationService.cs index 29508744915d4..7232b8d662b99 100644 --- a/src/EditorFeatures/Core/Implementation/SmartIndent/AbstractIndentationService.cs +++ b/src/EditorFeatures/Core/Implementation/SmartIndent/AbstractIndentationService.cs @@ -42,15 +42,14 @@ private IEnumerable GetFormattingRules(Document document, int p var lineToBeIndented = textSnapshot.GetLineFromLineNumber(lineNumber); var formattingRules = GetFormattingRules(document, lineToBeIndented.Start); - var optionSet = document.Project.Solution.Workspace.Options; // enter on a token case. - if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, optionSet, cancellationToken)) + if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, document.Options, cancellationToken)) { return null; } - var indenter = await GetIndenterAsync(document, lineToBeIndented, formattingRules, optionSet, cancellationToken).ConfigureAwait(false); + var indenter = await GetIndenterAsync(document, lineToBeIndented, formattingRules, document.Options, cancellationToken).ConfigureAwait(false); return indenter.GetDesiredIndentation(); } diff --git a/src/EditorFeatures/Core/Implementation/Suggestions/SuggestedActionsSourceProvider.cs b/src/EditorFeatures/Core/Implementation/Suggestions/SuggestedActionsSourceProvider.cs index 8f99ed0207f3f..cae7b07fe579a 100644 --- a/src/EditorFeatures/Core/Implementation/Suggestions/SuggestedActionsSourceProvider.cs +++ b/src/EditorFeatures/Core/Implementation/Suggestions/SuggestedActionsSourceProvider.cs @@ -485,9 +485,8 @@ private IEnumerable GetRefactorings( { this.AssertIsForeground(); - var optionService = workspace.Services.GetService(); - if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && + if (document.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && _owner._codeRefactoringService != null && supportsFeatureService.SupportsRefactorings(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring)) @@ -623,9 +622,7 @@ private async Task HasRefactoringsAsync( SnapshotSpan range, CancellationToken cancellationToken) { - var optionService = document.Project.Solution.Workspace.Services.GetService(); - - if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && + if (document.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && provider._codeRefactoringService != null && supportsFeatureService.SupportsRefactorings(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring)) diff --git a/src/EditorFeatures/Core/Implementation/TodoComment/AbstractTodoCommentIncrementalAnalyzer.cs b/src/EditorFeatures/Core/Implementation/TodoComment/AbstractTodoCommentIncrementalAnalyzer.cs index b27c8ef654f80..78b39c27e671a 100644 --- a/src/EditorFeatures/Core/Implementation/TodoComment/AbstractTodoCommentIncrementalAnalyzer.cs +++ b/src/EditorFeatures/Core/Implementation/TodoComment/AbstractTodoCommentIncrementalAnalyzer.cs @@ -22,14 +22,12 @@ internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer private readonly TodoCommentIncrementalAnalyzerProvider _owner; private readonly Workspace _workspace; - private readonly IOptionService _optionService; private readonly TodoCommentTokens _todoCommentTokens; private readonly TodoCommentState _state; - public TodoCommentIncrementalAnalyzer(Workspace workspace, IOptionService optionService, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens) + public TodoCommentIncrementalAnalyzer(Workspace workspace, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens) { _workspace = workspace; - _optionService = optionService; _owner = owner; _todoCommentTokens = todoCommentTokens; @@ -46,12 +44,12 @@ public Task DocumentResetAsync(Document document, CancellationToken cancellation public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { - Contract.ThrowIfFalse(document.IsFromPrimaryBranch()); - // it has an assumption that this will not be called concurrently for same document. // in fact, in current design, it won't be even called concurrently for different documents. // but, can be called concurrently for different documents in future if we choose to. - if (!_optionService.GetOption(InternalFeatureOnOffOptions.TodoComments)) + Contract.ThrowIfFalse(document.IsFromPrimaryBranch()); + + if (!document.Options.GetOption(InternalFeatureOnOffOptions.TodoComments)) { return; } @@ -78,7 +76,7 @@ public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancel return; } - var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(_workspace), cancellationToken).ConfigureAwait(false); + var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(document), cancellationToken).ConfigureAwait(false); var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false); var data = new Data(textVersion, syntaxVersion, items); diff --git a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentIncrementalAnalyzerProvider.cs b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentIncrementalAnalyzerProvider.cs index c0699f5ec0d6a..b726d90800b4e 100644 --- a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentIncrementalAnalyzerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentIncrementalAnalyzerProvider.cs @@ -29,7 +29,7 @@ public TodoCommentIncrementalAnalyzerProvider(TodoCommentTokens todoCommentToken public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return s_analyzers.GetValue(workspace, w => - new TodoCommentIncrementalAnalyzer(w, w.Services.GetService(), this, _todoCommentTokens)); + new TodoCommentIncrementalAnalyzer(w, this, _todoCommentTokens)); } internal void RaiseTaskListUpdated(object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray items) diff --git a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentTokens.cs b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentTokens.cs index ee54e612ca62d..e146f768bc99d 100644 --- a/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentTokens.cs +++ b/src/EditorFeatures/Core/Implementation/TodoComment/TodoCommentTokens.cs @@ -71,10 +71,9 @@ public TokenInfo(string optionText, ImmutableArray tokens private TokenInfo _lastTokenInfo; - public ImmutableArray GetTokens(Workspace workspace) + public ImmutableArray GetTokens(Document document) { - var optionService = workspace.Services.GetService(); - var optionText = optionService.GetOption(TodoCommentOptions.TokenList); + var optionText = document.Options.GetOption(TodoCommentOptions.TokenList); var lastInfo = _lastTokenInfo; if (lastInfo != null && lastInfo.OptionText == optionText) diff --git a/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs b/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs index 5c166ec457cdb..508c820b0bd5d 100644 --- a/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs +++ b/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs @@ -12,43 +12,13 @@ namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextBufferExtensions { - public static IEnumerable GetOpenDocumentIds(this ITextBuffer buffer) - { - var container = buffer.AsTextContainer(); - - Workspace workspace; - if (Workspace.TryGetWorkspace(container, out workspace)) - { - return workspace.GetRelatedDocumentIds(container); - } - - return SpecializedCollections.EmptyEnumerable(); - } - - internal static OptionSet TryGetOptions(this ITextBuffer textBuffer) - { - Workspace workspace; - - if (Workspace.TryGetWorkspace(textBuffer.AsTextContainer(), out workspace)) - { - var service = workspace.Services.GetService(); - - if (service != null) - { - return service.GetOptions(); - } - } - - return null; - } - internal static T GetOption(this ITextBuffer buffer, Option option) { - var options = TryGetOptions(buffer); + var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - if (options != null) + if (document != null) { - return options.GetOption(option); + return document.Options.GetOption(option); } return option.DefaultValue; @@ -59,20 +29,14 @@ internal static T GetOption(this ITextBuffer buffer, PerLanguageOption opt // Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is. try { - Workspace workspace; - if (!Workspace.TryGetWorkspace(buffer.AsTextContainer(), out workspace)) - { - return option.DefaultValue; - } + var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); - var service = workspace.Services.GetService(); - if (service == null) + if (document != null) { - return option.DefaultValue; + return document.Options.GetOption(option); } - var language = workspace.Services.GetLanguageServices(buffer).Language; - return service.GetOption(option, language); + return option.DefaultValue; } catch (Exception e) when (FatalError.Report(e)) { diff --git a/src/EditorFeatures/Test/Completion/AbstractCompletionProviderTests.cs b/src/EditorFeatures/Test/Completion/AbstractCompletionProviderTests.cs index 381c10db4dd9f..bdfeee9b8ba39 100644 --- a/src/EditorFeatures/Test/Completion/AbstractCompletionProviderTests.cs +++ b/src/EditorFeatures/Test/Completion/AbstractCompletionProviderTests.cs @@ -65,7 +65,7 @@ internal static CompletionHelper GetCompletionHelper(Document document) internal static async Task GetCompletionListContextAsync(CompletionProvider provider, Document document, int position, CompletionTrigger triggerInfo, OptionSet options = null) { - options = options ?? document.Project.Solution.Workspace.Options; + options = options ?? document.Options; var service = document.Project.LanguageServices.GetService(); var text = await document.GetTextAsync(); var span = service.GetDefaultItemSpan(text, position); @@ -542,13 +542,12 @@ private async Task VerifyItemWithReferenceWorkerAsync(string xmlString, string e { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { - var optionsService = testWorkspace.Services.GetService(); var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); - optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)); + testWorkspace.Options = testWorkspace.Options.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers); var triggerInfo = CompletionTrigger.Default; @@ -630,7 +629,6 @@ protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expec { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { - var optionsService = testWorkspace.Services.GetService(); var position = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer(); diff --git a/src/EditorFeatures/Test/Extensions/WorkspaceExtensions.cs b/src/EditorFeatures/Test/Extensions/WorkspaceExtensions.cs index 44bfd45040d48..8b796dfe73cbe 100644 --- a/src/EditorFeatures/Test/Extensions/WorkspaceExtensions.cs +++ b/src/EditorFeatures/Test/Extensions/WorkspaceExtensions.cs @@ -11,14 +11,13 @@ public static void ApplyOptions(this Workspace workspace, IDictionary(); - var optionSet = optionService.GetOptions(); + var optionSet = workspace.Options; foreach (var option in options) { optionSet = optionSet.WithChangedOption(option.Key, option.Value); } - optionService.SetOptions(optionSet); + workspace.Options = optionSet; } } } diff --git a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs index a2c5b3137c2f2..5b60edc6aec72 100644 --- a/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs +++ b/src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs @@ -79,8 +79,6 @@ public RenameTrackingTestState( OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue }; - var optionService = this.Workspace.Services.GetService(); - // Mock the action taken by the workspace INotificationService var notificationService = Workspace.Services.GetService() as INotificationServiceCallback; var callback = new Action((message, title, severity) => _notificationMessage = message); diff --git a/src/EditorFeatures/Test/SignatureHelp/AbstractSignatureHelpProviderTests.cs b/src/EditorFeatures/Test/SignatureHelp/AbstractSignatureHelpProviderTests.cs index 71c6b5861b4e7..263f1eea44358 100644 --- a/src/EditorFeatures/Test/SignatureHelp/AbstractSignatureHelpProviderTests.cs +++ b/src/EditorFeatures/Test/SignatureHelp/AbstractSignatureHelpProviderTests.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; @@ -351,13 +352,12 @@ protected async Task VerifyItemWithReferenceWorkerAsync(string xmlString, IEnume { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { - var optionsService = testWorkspace.Services.GetService(); var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = testWorkspace.CurrentSolution.GetDocument(documentId); var code = (await document.GetTextAsync()).ToString(); - optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(Microsoft.CodeAnalysis.Completion.CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)); + testWorkspace.Options = testWorkspace.Options.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers); IList textSpans = null; diff --git a/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs b/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs index 16f9becd17fda..d0c18e8c72c4c 100644 --- a/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs +++ b/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs @@ -955,15 +955,13 @@ internal WorkspaceWaiter() private static void SetOptions(Workspace workspace) { - var optionService = workspace.Services.GetService(); - // override default timespan to make test run faster - optionService.SetOptions(optionService.GetOptions().WithChangedOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS, 0) - .WithChangedOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS, 0) - .WithChangedOption(InternalSolutionCrawlerOptions.PreviewBackOffTimeSpanInMS, 0) - .WithChangedOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS, 0) - .WithChangedOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS, 0) - .WithChangedOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS, 100)); + workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS, 0) + .WithChangedOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS, 0) + .WithChangedOption(InternalSolutionCrawlerOptions.PreviewBackOffTimeSpanInMS, 0) + .WithChangedOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS, 0) + .WithChangedOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS, 0) + .WithChangedOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS, 100); } private class WorkCoordinatorWorkspace : TestWorkspace diff --git a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs index c9621f90ae4e7..8a275a97c8b15 100644 --- a/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs +++ b/src/EditorFeatures/Test/Tagging/AsynchronousTaggerTests.cs @@ -123,13 +123,6 @@ private static TestTaggerEventSource CreateEventSource() return new TestTaggerEventSource(); } - private static Mock CreateFeatureOptionsMock() - { - var featureOptions = new Mock(MockBehavior.Strict); - featureOptions.Setup(s => s.GetOption(EditorComponentOnOffOptions.Tagger)).Returns(true); - return featureOptions; - } - private sealed class TaggerOperationListener : AsynchronousOperationListener { } diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb index 74421f475ad80..9ef7ee7c29364 100644 --- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticProviderTests.vb @@ -277,11 +277,10 @@ Namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics.UnitTests ' turn off diagnostic If Not enabled Then - Dim optionService = workspace.Services.GetService(Of IOptionService)() - optionService.SetOptions( - optionService.GetOptions().WithChangedOption(ServiceComponentOnOffOptions.DiagnosticProvider, False) _ + workspace.Options = workspace.Options _ + .WithChangedOption(ServiceComponentOnOffOptions.DiagnosticProvider, False) _ .WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.CSharp, False) _ - .WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.VisualBasic, False)) + .WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.VisualBasic, False) End If Dim registrationService = workspace.Services.GetService(Of ISolutionCrawlerRegistrationService)() diff --git a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb index 406c141b38209..33dd1b2451e3f 100644 --- a/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb +++ b/src/EditorFeatures/Test2/Diagnostics/DiagnosticServiceTests.vb @@ -702,8 +702,7 @@ class AnonymousFunctions Dim project = workspace.CurrentSolution.Projects.Single() ' turn off heuristic - Dim options = workspace.Services.GetService(Of IOptionService)() - options.SetOptions(options.GetOptions.WithChangedOption(InternalDiagnosticsOptions.UseCompilationEndCodeFixHeuristic, False)) + workspace.Options = workspace.Options.WithChangedOption(InternalDiagnosticsOptions.UseCompilationEndCodeFixHeuristic, False) Dim analyzer = New CompilationEndedAnalyzer Dim analyzerReference = New AnalyzerImageReference(ImmutableArray.Create(Of DiagnosticAnalyzer)(analyzer)) diff --git a/src/EditorFeatures/Test2/IntelliSense/VisualBasicSignatureHelpCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/VisualBasicSignatureHelpCommandHandlerTests.vb index d336f3db787b3..b8c49d8d8a1b9 100644 --- a/src/EditorFeatures/Test2/IntelliSense/VisualBasicSignatureHelpCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/VisualBasicSignatureHelpCommandHandlerTests.vb @@ -281,7 +281,7 @@ End Class ) ' disable implicit sig help then type a trigger character -> no session should be available - state.Workspace.Options = state.Workspace.Options.WithChangedOption(SignatureHelpOptions.ShowSignatureHelp, "Visual Basic", False) + state.Workspace.Options = state.Workspace.Options.WithChangedOption(SignatureHelpOptions.ShowSignatureHelp, LanguageNames.VisualBasic, False) state.SendTypeChars("(") Await state.AssertNoSignatureHelpSession() diff --git a/src/EditorFeatures/Test2/Rename/DashboardTests.vb b/src/EditorFeatures/Test2/Rename/DashboardTests.vb index 745f27be680fd..4988fefce0dea 100644 --- a/src/EditorFeatures/Test2/Rename/DashboardTests.vb +++ b/src/EditorFeatures/Test2/Rename/DashboardTests.vb @@ -579,7 +579,7 @@ class D : B Next End If - workspace.Services.GetService(Of IOptionService)().SetOptions(optionSet) + workspace.Options = optionSet Dim sessionInfo = renameService.StartInlineSession( document, document.GetSyntaxTreeAsync().Result.GetRoot().FindToken(cursorPosition).Span, CancellationToken.None) diff --git a/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb b/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb index cbdfeb834a415..c83efc120b0be 100644 --- a/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb +++ b/src/EditorFeatures/Test2/Rename/InlineRenameTests.vb @@ -102,9 +102,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) - - Dim optionService = workspace.Services.GetService(Of IOptionService)() - optionService.SetOptions(optionSet) + workspace.Options = optionSet Dim session = StartSession(workspace) diff --git a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb index 4e1899d97aafe..87dbf3eb7d582 100644 --- a/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb +++ b/src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb @@ -45,8 +45,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Return End If - Dim optionService = document.Project.Solution.Workspace.Services.GetService(Of IOptionService)() - If Not (isExplicitFormat OrElse optionService.GetOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic)) Then + If Not (isExplicitFormat OrElse document.Options.GetOption(FeatureOnOffOptions.PrettyListing)) Then Return End If @@ -229,13 +228,12 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Dim token = vbTree.GetRoot(cancellationToken).FindToken(Math.Min(endPosition, syntaxTree.GetRoot(cancellationToken).FullSpan.End)) Dim node = token.Parent - Dim optionSet = document.Project.Solution.Workspace.Options ' collect all indent operation Dim operations = New List(Of IndentBlockOperation)() While node IsNot Nothing operations.AddRange(FormattingOperations.GetIndentBlockOperations( - Formatter.GetDefaultFormattingRules(document), node, lastToken:=Nothing, optionSet:=optionSet)) + Formatter.GetDefaultFormattingRules(document), node, lastToken:=Nothing, optionSet:=document.Options)) node = node.Parent End While diff --git a/src/EditorFeatures/VisualBasic/NavigationBar/AbstractGenerateCodeItem.vb b/src/EditorFeatures/VisualBasic/NavigationBar/AbstractGenerateCodeItem.vb index 5325afbee06aa..a8a0a732c8f5f 100644 --- a/src/EditorFeatures/VisualBasic/NavigationBar/AbstractGenerateCodeItem.vb +++ b/src/EditorFeatures/VisualBasic/NavigationBar/AbstractGenerateCodeItem.vb @@ -43,7 +43,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar Return Formatter.FormatAsync(newDocument, Formatter.Annotation, - options:=newDocument.Project.Solution.Workspace.Options, + options:=newDocument.Options, cancellationToken:=cancellationToken, rules:=formatterRules).WaitAndGetResult(cancellationToken) End Function diff --git a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicNavigationBarItemService.vb b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicNavigationBarItemService.vb index 52a9a52d7ef31..099f49ead0959 100644 --- a/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicNavigationBarItemService.vb +++ b/src/EditorFeatures/VisualBasic/NavigationBar/VisualBasicNavigationBarItemService.vb @@ -511,7 +511,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar Dim newDocument = generateCodeItem.GetGeneratedDocumentAsync(document, cancellationToken).WaitAndGetResult(cancellationToken) Dim generatedTree = newDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken) Dim generatedNode = generatedTree.GetAnnotatedNodes(AbstractGenerateCodeItem.GeneratedSymbolAnnotation).Single().FirstAncestorOrSelf(Of MethodBlockBaseSyntax) - Dim indentSize = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.IndentationSize, LanguageNames.VisualBasic) + Dim indentSize = newDocument.Options.GetOption(FormattingOptions.IndentationSize) Dim navigationPoint = NavigationPointHelpers.GetNavigationPoint(generatedTree.GetText(text.Encoding), indentSize, generatedNode) Using transaction = New CaretPreservingEditTransaction(VBEditorResources.GenerateMember, textView, _textUndoHistoryRegistry, _editorOperationsFactoryService) diff --git a/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb b/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb index 3c1f37fa810d1..f31ee5ffb3d8d 100644 --- a/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/Utilities/CommandHandlers/AbstractImplementAbstractClassOrInterfaceCommandHandler.vb @@ -101,7 +101,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers Return False End If - If Not document.Project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) Then + If Not document.Options.GetOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers) Then Return False End If diff --git a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.vb index e2a8e1c2a0ae0..c128c6ce1ad73 100644 --- a/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.vb @@ -115,7 +115,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.Complet Dim item = completionList.Items.First(Function(i) i.DisplayText.StartsWith(textTypedSoFar)) Dim helper = CompletionHelper.GetHelper(document) - Assert.Equal(expected, helper.SendEnterThroughToEditor(item, textTypedSoFar, workspace.Options)) + Assert.Equal(expected, helper.SendEnterThroughToEditor(item, textTypedSoFar, document.Options)) End Using End Function diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb index e775d7993473d..c77fd2642e952 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/ImplementInterface/ImplementInterfaceCommandHandlerTests.vb @@ -66,9 +66,7 @@ Interface IFoo End Interface") Dim commandHandler = MoveCaretAndCreateCommandHandler(workspace) - - Dim optionServices = workspace.Services.GetService(Of IOptionService)() - optionServices.SetOptions(optionServices.GetOptions().WithChangedOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic, False)) + workspace.Options = workspace.Options.WithChangedOption(FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic, False) Dim nextHandlerCalled = False Dim view = workspace.Documents.Single().GetTextView() diff --git a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb index 07b1a5ef7c06a..bcd97528ac8e6 100644 --- a/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb +++ b/src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb @@ -38,9 +38,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGenera End Property Private Sub DisableLineCommit(workspace As Workspace) - ' Disable line commit - Dim optionsService = workspace.Services.GetService(Of IOptionService)() - optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False)) + workspace.Options = workspace.Options.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False) End Sub Private Async Function VerifyTypedCharAppliedAsync(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), diff --git a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.vb b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.vb index 1ab69d967cab3..af17f73ae38e0 100644 --- a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.vb @@ -97,9 +97,8 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Assert.NotNull(document) - Dim options = document.Project.Solution.Workspace.Options. - WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, allowMovingDeclaration). - WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct) + Dim options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, allowMovingDeclaration) _ + .WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, snapshotSpan.Span.ToTextSpan(), options) @@ -130,7 +129,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod Dim document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id) Assert.NotNull(document) - Dim options = document.Project.Solution.Workspace.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, True) + Dim options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, True) Dim sdocument = Await SemanticDocument.CreateAsync(document, CancellationToken.None) Dim validator = New VisualBasicSelectionValidator(sdocument, namedSpans("b").Single(), options) Dim result = Await validator.GetValidSelectionAsync(CancellationToken.None) @@ -164,8 +163,7 @@ End Class Dim root = Await document.GetSyntaxRootAsync() Dim iterator = root.DescendantNodesAndSelf() - Dim options = document.Project.Solution.Workspace.Options _ - .WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, True) + Dim options = document.Options.WithChangedOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language, True) For Each node In iterator Try diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/FormattingTestBase.vb b/src/EditorFeatures/VisualBasicTest/Formatting/FormattingTestBase.vb index 1a4f15c0799db..1b5b16be42733 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/FormattingTestBase.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/FormattingTestBase.vb @@ -38,7 +38,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting Dim changes = Formatter.GetFormattedTextChanges( Await syntaxTree.GetRootAsync(), workspace.Documents.First(Function(d) d.SelectedSpans.Any()).SelectedSpans, - workspace, workspace.Options, rules, CancellationToken.None) + workspace, document.Options, rules, CancellationToken.None) AssertResult(expected, clonedBuffer, changes) End Using End Function diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb index 27f5633b23715..5e2578250aeec 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndentProviderTests.vb @@ -15,76 +15,41 @@ Imports Moq Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Formatting.Indentation Public Class SmartIndentProviderTests - Private Class MockWaitIndicator - Implements IWaitIndicator - Public Function StartWait(title As String, message As String, allowCancel As Boolean, showProgress As Boolean) As IWaitContext Implements IWaitIndicator.StartWait - Throw New NotImplementedException() - End Function - - Public Function Wait(title As String, message As String, allowCancel As Boolean, showProgress As Boolean, action As Action(Of IWaitContext)) As WaitIndicatorResult Implements IWaitIndicator.Wait - Throw New NotImplementedException() - End Function - End Class - Public Sub GetSmartIndent1() - Dim workspace = New TestWorkspace() - Dim provider = New SmartIndentProvider() Assert.ThrowsAny(Of ArgumentException)( Function() provider.CreateSmartIndent(Nothing)) End Sub - + - Public Sub GetSmartIndent2() - Dim workspace = New TestWorkspace() - Dim optionsService = workspace.Services.GetService(Of IOptionService)() - Dim initialState = optionsService.GetOption(InternalFeatureOnOffOptions.SmartIndenter) - Assert.Equal(True, initialState) - - Dim provider = New SmartIndentProvider() - - ' connect things together - Dim textView = New Mock(Of ITextView)(MockBehavior.Strict) - Dim subjectBuffer = workspace.ExportProvider.GetExportedValue(Of ITextBufferFactoryService)().CreateTextBuffer() - workspace.RegisterText(subjectBuffer.AsTextContainer()) + Public Async Sub GetSmartIndent2() + Using workspace = Await TestWorkspace.CreateCSharpAsync("") + Assert.Equal(True, workspace.Options.GetOption(InternalFeatureOnOffOptions.SmartIndenter)) - textView.SetupGet(Function(x) x.Options).Returns(TestEditorOptions.Instance) - textView.SetupGet(Function(x) x.TextBuffer).Returns(subjectBuffer) - textView.SetupGet(Function(x) x.Caret).Returns(New Mock(Of ITextCaret)(MockBehavior.Strict).Object) + Dim document = workspace.Projects.Single().Documents.Single() + Dim provider = New SmartIndentProvider() + Dim smartIndenter = provider.CreateSmartIndent(document.GetTextView()) - Dim smartIndenter = provider.CreateSmartIndent(textView.Object) - Assert.NotNull(smartIndenter) + Assert.NotNull(smartIndenter) + End Using End Sub - + - Public Sub GetSmartIndent3() - Dim workspace = New TestWorkspace() - Dim optionsService = workspace.Services.GetService(Of IOptionService)() - Dim initialState = optionsService.GetOption(InternalFeatureOnOffOptions.SmartIndenter) - Assert.Equal(True, initialState) - - optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(InternalFeatureOnOffOptions.SmartIndenter, False)) - - Dim provider = New SmartIndentProvider() - - ' connect things together - Dim textView = New Mock(Of ITextView)(MockBehavior.Strict) - Dim subjectBuffer = workspace.ExportProvider.GetExportedValue(Of ITextBufferFactoryService)().CreateTextBuffer() - workspace.RegisterText(subjectBuffer.AsTextContainer()) - - textView.SetupGet(Function(x) x.Options).Returns(TestEditorOptions.Instance) - textView.SetupGet(Function(x) x.TextBuffer).Returns(subjectBuffer) - - Dim smartIndenter = provider.CreateSmartIndent(textView.Object) + Public Async Sub GetSmartIndent3() + Using workspace = Await TestWorkspace.CreateCSharpAsync("") + workspace.Options = workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.SmartIndenter, False) - optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(InternalFeatureOnOffOptions.SmartIndenter, True)) + Dim document = workspace.Projects.Single().Documents.Single() + Dim provider = New SmartIndentProvider() + Dim smartIndenter = provider.CreateSmartIndent(document.GetTextView()) - Assert.Null(smartIndenter) + Assert.Null(smartIndenter) + End Using End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndenterTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndenterTests.vb index 1f7a3cf2ecef4..ad184f56a15cb 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndenterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartIndenterTests.vb @@ -2924,9 +2924,8 @@ End Class End Function Friend Shared Sub SetIndentStyle(buffer As ITextBuffer, indentStyle As FormattingOptions.IndentStyle) - Dim optionService = buffer.GetWorkspace().Services.GetService(Of IOptionService)() - Dim optionSet = optionService.GetOptions() - optionService.SetOptions(optionSet.WithChangedOption(FormattingOptions.SmartIndent, LanguageNames.VisualBasic, indentStyle)) + Dim workspace = buffer.GetWorkspace() + workspace.Options = workspace.Options.WithChangedOption(FormattingOptions.SmartIndent, LanguageNames.VisualBasic, indentStyle) End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb index b170c5923e932..7faad13851d10 100644 --- a/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Formatting/Indentation/SmartTokenFormatter_FormatTokenTests.vb @@ -195,7 +195,7 @@ End Class Assert.True(VisualBasicIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, line, workspace.Options, Nothing, ignoreMissingToken)) - Dim smartFormatter = New SmartTokenFormatter(workspace.Options, formattingRules, root) + Dim smartFormatter = New SmartTokenFormatter(document.Options, formattingRules, root) Dim changes = Await smartFormatter.FormatTokenAsync(workspace, token, Nothing) Using edit = buffer.CreateEdit() diff --git a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnMiscellaneousCommandsTests.vb b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnMiscellaneousCommandsTests.vb index 14c6cde82d622..9f68c2cad509c 100644 --- a/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnMiscellaneousCommandsTests.vb +++ b/src/EditorFeatures/VisualBasicTest/LineCommit/CommitOnMiscellaneousCommandsTests.vb @@ -132,11 +132,7 @@ End Module ) ' Turn off pretty listing - Dim optionService = testData.Workspace.GetService(Of IOptionService)() - Dim optionSet = optionService.GetOptions() - Dim prettyListing = optionSet.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False) - optionService.SetOptions(prettyListing) - + testData.Workspace.Options = testData.Workspace.Options.WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False) testData.CommandHandler.ExecuteCommand(New FormatDocumentCommandArgs(testData.View, testData.Buffer), Sub() Exit Sub) Assert.Equal(" Sub Main()", testData.Buffer.CurrentSnapshot.GetLineFromLineNumber(1).GetText()) End Using diff --git a/src/Features/CSharp/Portable/CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs b/src/Features/CSharp/Portable/CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs index 67799d084a315..0d99bcface093 100644 --- a/src/Features/CSharp/Portable/CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/AddImport/CSharpAddImportCodeFixProvider.cs @@ -481,8 +481,7 @@ private async Task AddImportWorkerAsync( .Single(); newRoot = newRoot.TrackNodes(newUsing); var documentWithSyntaxRoot = document.WithSyntaxRoot(newRoot); - var options = document.Project.Solution.Workspace.Options; - var simplifiedDocument = await Simplifier.ReduceAsync(documentWithSyntaxRoot, newUsing.Span, options, cancellationToken).ConfigureAwait(false); + var simplifiedDocument = await Simplifier.ReduceAsync(documentWithSyntaxRoot, newUsing.Span, cancellationToken: cancellationToken).ConfigureAwait(false); newRoot = (CompilationUnitSyntax)await simplifiedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var simplifiedUsing = newRoot.GetCurrentNode(newUsing); diff --git a/src/Features/CSharp/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs b/src/Features/CSharp/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs index 35ac8f0e7818c..c8db9697a8aba 100644 --- a/src/Features/CSharp/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.cs @@ -13,7 +13,7 @@ private class RemoveUnnecessaryCastFixAllProvider : BatchSimplificationFixAllPro { internal static new readonly RemoveUnnecessaryCastFixAllProvider Instance = new RemoveUnnecessaryCastFixAllProvider(); - protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Workspace workspace, out string codeActionId, CancellationToken cancellationToken) + protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Document document, out string codeActionId, CancellationToken cancellationToken) { codeActionId = null; return GetCastNode(root, model, diagnostic.Location.SourceSpan, cancellationToken); diff --git a/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs b/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs index cb9c742ac68be..158c260422b8e 100644 --- a/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.cs @@ -11,11 +11,11 @@ private class SimplifyTypeNamesFixAllProvider : BatchSimplificationFixAllProvide { internal static new readonly SimplifyTypeNamesFixAllProvider Instance = new SimplifyTypeNamesFixAllProvider(); - protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Workspace workspace, out string codeActionId, CancellationToken cancellationToken) + protected override SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Document document, out string codeActionId, CancellationToken cancellationToken) { codeActionId = null; string diagnosticId; - var node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, workspace.Options, out diagnosticId, cancellationToken); + var node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, document.Options, out diagnosticId, cancellationToken); if (node != null) { codeActionId = GetCodeActionId(diagnosticId, node.ToString()); diff --git a/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs b/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs index 981b1610eb52f..3440dee13232d 100644 --- a/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs @@ -65,9 +65,8 @@ 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 optionSet = document.Project.Solution.Workspace.Options; string diagnosticId; - var node = GetNodeToSimplify(root, model, span, optionSet, out diagnosticId, cancellationToken); + var node = GetNodeToSimplify(root, model, span, document.Options, out diagnosticId, cancellationToken); if (node == null) { return; diff --git a/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs b/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs index f48a97744e379..7eb1b9d1fa8fc 100644 --- a/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs +++ b/src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs @@ -820,8 +820,6 @@ internal override async Task TryAddUsingsOrImportToDocumentAsync(Solut return updatedSolution; } - var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language); - SyntaxNode root = null; if (modifiedRoot == null) { @@ -851,6 +849,7 @@ internal override async Task TryAddUsingsOrImportToDocumentAsync(Solut return updatedSolution; } + var placeSystemNamespaceFirst = document.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } diff --git a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs index 9e2b15ac1dbd9..a5bd15b82ffbd 100644 --- a/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs +++ b/src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs @@ -30,8 +30,6 @@ protected override Task IntroduceLocalAsync( bool isConstant, CancellationToken cancellationToken) { - var options = document.Project.Solution.Workspace.Options; - var newLocalNameToken = GenerateUniqueLocalName(document, expression, isConstant, cancellationToken); var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); @@ -42,7 +40,7 @@ protected override Task IntroduceLocalAsync( var declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers, SyntaxFactory.VariableDeclaration( - this.GetTypeSyntax(document, expression, isConstant, options, cancellationToken), + this.GetTypeSyntax(document, expression, isConstant, cancellationToken), SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, @@ -120,7 +118,7 @@ private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet return null; } - private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, bool isConstant, OptionSet options, CancellationToken cancellationToken) + private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, bool isConstant, CancellationToken cancellationToken) { var typeSymbol = GetTypeSymbol(document, expression, cancellationToken); if (typeSymbol.ContainsAnonymousType()) @@ -130,7 +128,7 @@ private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax exp if (!isConstant && CanUseVar(typeSymbol) && - TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, options, cancellationToken)) + TypeStyleHelper.IsImplicitTypePreferred(expression, document.SemanticModel, document.Document.Options, cancellationToken)) { return SyntaxFactory.IdentifierName("var"); } diff --git a/src/Features/CSharp/Portable/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.cs b/src/Features/CSharp/Portable/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.cs index 2fded1485a34f..495489ae94b64 100644 --- a/src/Features/CSharp/Portable/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.cs +++ b/src/Features/CSharp/Portable/RemoveUnnecessaryImports/CSharpRemoveUnnecessaryImportsService.cs @@ -84,7 +84,7 @@ private Task FormatResultAsync(Document document, CompilationUnitSyn { var spans = new List(); AddFormattingSpans(newRoot, spans, cancellationToken); - return Formatter.FormatAsync(newRoot, spans, document.Project.Solution.Workspace, document.Project.Solution.Workspace.Options, cancellationToken: cancellationToken); + return Formatter.FormatAsync(newRoot, spans, document.Project.Solution.Workspace, document.Options, cancellationToken: cancellationToken); } private void AddFormattingSpans( diff --git a/src/Features/Core/Portable/CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs index fb6a31b088a72..92a2901598e39 100644 --- a/src/Features/Core/Portable/CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/AddImport/AbstractAddImportCodeFixProvider.cs @@ -79,9 +79,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) return; } - var options = document.Project.Solution.Workspace.Options; - var placeSystemNamespaceFirst = options.GetOption( - OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language); + var placeSystemNamespaceFirst = document.Options.GetOption( + OrganizerOptions.PlaceSystemNamespaceFirst); using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken)) { @@ -502,4 +501,4 @@ internal override bool IsApplicable(Workspace workspace) } } } -} \ No newline at end of file +} diff --git a/src/Features/Core/Portable/CodeFixes/NamingStyle/AbstractNamingStyleCodeFixProvider.cs b/src/Features/Core/Portable/CodeFixes/NamingStyle/AbstractNamingStyleCodeFixProvider.cs index a0a4f5a2c4cd4..41f345efcd4cd 100644 --- a/src/Features/Core/Portable/CodeFixes/NamingStyle/AbstractNamingStyleCodeFixProvider.cs +++ b/src/Features/Core/Portable/CodeFixes/NamingStyle/AbstractNamingStyleCodeFixProvider.cs @@ -49,7 +49,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) solution, symbol, fixedName, - solution.Workspace.Options, + document.Options, c).ConfigureAwait(false), nameof(AbstractNamingStyleCodeFixProvider)), diagnostic); diff --git a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs index 7ae55192884a2..c9fc7c8a79c54 100644 --- a/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/CodeRefactorings/ExtractMethod/AbstractExtractMethodCodeRefactoringProvider.cs @@ -59,17 +59,15 @@ private async Task> GetCodeActionAsync( TextSpan textSpan, CancellationToken cancellationToken) { - var options = document.Project.Solution.Workspace.Options; var result = await ExtractMethodService.ExtractMethodAsync( document, textSpan, - options, - cancellationToken).ConfigureAwait(false); + cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(result); if (result.Succeeded || result.SucceededWithSuggestion) { - var description = options.GetOption(ExtractMethodOptions.AllowMovingDeclaration, document.Project.Language) ? + var description = document.Options.GetOption(ExtractMethodOptions.AllowMovingDeclaration) ? FeaturesResources.ExtractMethodLocal : FeaturesResources.ExtractMethod; var codeAction = new MyCodeAction(description, (c) => AddRenameAnnotationAsync(result.Document, result.InvocationNameToken, c)); diff --git a/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs b/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs index 457c8b69490dd..5a405ffe98cc2 100644 --- a/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs +++ b/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs @@ -172,7 +172,7 @@ public override async Task GetCompletionsAsync( var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var defaultItemSpan = this.GetDefaultItemSpan(text, caretPosition); - options = options ?? document.Project.Solution.Workspace.Options; + options = options ?? document.Options; var providers = GetProviders(roles, trigger); var completionProviderToIndex = GetCompletionProviderToIndex(providers); diff --git a/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_IncrementalAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_IncrementalAnalyzer.cs index 54b225f61cd3b..c5c965476e201 100644 --- a/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_IncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_IncrementalAnalyzer.cs @@ -29,9 +29,7 @@ private DiagnosticAnalyzerService() public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { - var optionService = workspace.Services.GetService(); - - if (!optionService.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) + if (!workspace.Options.GetOption(ServiceComponentOnOffOptions.DiagnosticProvider)) { return null; } diff --git a/src/Features/Core/Portable/Diagnostics/EngineV1/DiagnosticIncrementalAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/EngineV1/DiagnosticIncrementalAnalyzer.cs index cf87ee75ee2cd..7ce5ee89d5090 100644 --- a/src/Features/Core/Portable/Diagnostics/EngineV1/DiagnosticIncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/Diagnostics/EngineV1/DiagnosticIncrementalAnalyzer.cs @@ -143,7 +143,7 @@ private Task ClearOnlyDocumentStates(Document document) private bool CheckOptions(Project project, bool forceAnalysis) { var workspace = project.Solution.Workspace; - if (ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, project.Language) && + if (ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(project) && workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) { return true; @@ -169,7 +169,7 @@ internal CompilationWithAnalyzers GetCompilationWithAnalyzers( Func analyzerExceptionFilter = ex => { - if (project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException)) + if (project.Solution.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException)) { // if option is on, crash the host to get crash dump. FatalError.ReportUnlessCanceled(ex); diff --git a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs index d97a6125b81cb..b1f694f1fd97f 100644 --- a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs +++ b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs @@ -404,16 +404,13 @@ private async Task UpdateAnalyzerTelemetryDataAsync(CompilationWithAnalyzers ana private static async Task FullAnalysisEnabledAsync(Project project, bool ignoreFullAnalysisOptions, CancellationToken cancellationToken) { - var workspace = project.Solution.Workspace; - var language = project.Language; - if (ignoreFullAnalysisOptions) { return await project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false); } - if (!ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, language) || - !workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) + if (!ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(project) || + !project.Solution.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) { return false; } diff --git a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ProjectState.cs b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ProjectState.cs index 9c8cab70b691a..d16165ff6ec01 100644 --- a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ProjectState.cs +++ b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ProjectState.cs @@ -225,7 +225,7 @@ public async Task MergeAsync(ActiveFileState state, Document document) var semantic = state.GetAnalysisData(AnalysisKind.Semantic); var project = document.Project; - var fullAnalysis = ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(project.Solution.Workspace, project.Language); + var fullAnalysis = ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(project); // keep from build flag if full analysis is off var fromBuild = fullAnalysis ? false : lastResult.FromBuild; diff --git a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs index 83ed92840c7e8..41da910cc78c6 100644 --- a/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs +++ b/src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_IncrementalAnalyzer.cs @@ -228,7 +228,7 @@ private IEnumerable GetStateSetsForFullSolutionAnalysis(IEnumerable !s.FromBuild(project.Id)); } diff --git a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs index 9872fbfee0860..e9d51f637bec7 100644 --- a/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs +++ b/src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs @@ -239,7 +239,7 @@ private async Task UpdateReferencesAsync( var constructorSyntaxes = GetConstructorNodes(field.ContainingType).ToSet(); if (finalFieldName != field.Name && constructorSyntaxes.Count > 0) { - solution = await Renamer.RenameSymbolAsync(solution, field, finalFieldName, solution.Workspace.Options, + solution = await Renamer.RenameSymbolAsync(solution, field, finalFieldName, solution.Options, location => constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false); document = solution.GetDocument(document.Id); @@ -249,13 +249,13 @@ private async Task UpdateReferencesAsync( } // Outside the constructor we want to rename references to the field to final property name. - return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options, + return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Options, location => !constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false); } else { // Just rename everything. - return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false); + return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Options, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Features/Core/Portable/ExtractMethod/AbstractExtractMethodService.cs b/src/Features/Core/Portable/ExtractMethod/AbstractExtractMethodService.cs index 4bfd5bdf96bc6..e1e5ec34e4e69 100644 --- a/src/Features/Core/Portable/ExtractMethod/AbstractExtractMethodService.cs +++ b/src/Features/Core/Portable/ExtractMethod/AbstractExtractMethodService.cs @@ -21,7 +21,7 @@ public async Task ExtractMethodAsync( OptionSet options, CancellationToken cancellationToken) { - options = options ?? document.Project.Solution.Workspace.Options; + options = options ?? document.Options; var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); diff --git a/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs b/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs index cd996c98c12d8..f60406e410ac2 100644 --- a/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs +++ b/src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.GenerateLocalCodeAction.cs @@ -53,7 +53,7 @@ private async Task GetNewRoot(CancellationToken cancellationToken) var semanticModel = await _document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - if (_service.TryConvertToLocalDeclaration(_state.LocalType, _state.IdentifierToken, _document.Project.Solution.Workspace.Options, semanticModel, cancellationToken, out newRoot)) + if (_service.TryConvertToLocalDeclaration(_state.LocalType, _state.IdentifierToken, _document.Options, semanticModel, cancellationToken, out newRoot)) { return newRoot; } diff --git a/src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs b/src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs index 82a423e6c34b4..7f91b16bbb445 100644 --- a/src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs +++ b/src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.IntroduceVariableAllOccurrenceCodeAction.cs @@ -26,7 +26,6 @@ internal IntroduceVariableAllOccurrenceCodeAction( protected override async Task PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { - var optionSet = document.Project.Solution.Workspace.Options.WithChangedOption(FormattingOptions.AllowDisjointSpanMerging, true); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); diff --git a/src/Features/Core/Portable/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs b/src/Features/Core/Portable/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs index fee718dc672ec..fe0e6b39664ba 100644 --- a/src/Features/Core/Portable/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs +++ b/src/Features/Core/Portable/MakeMethodSynchronous/AbstractMakeMethodSynchronousCodeFixProvider.cs @@ -65,13 +65,12 @@ private async Task RenameThenRemoveAsyncTokenAsync(Document document, var name = methodSymbol.Name; var newName = name.Substring(0, name.Length - AsyncSuffix.Length); var solution = document.Project.Solution; - var options = solution.Workspace.Options; // Store the path to this node. That way we can find it post rename. var syntaxPath = new SyntaxPath(node); // Rename the method to remove the 'Async' suffix, then remove the 'async' keyword. - var newSolution = await Renamer.RenameSymbolAsync(solution, methodSymbol, newName, options, cancellationToken).ConfigureAwait(false); + var newSolution = await Renamer.RenameSymbolAsync(solution, methodSymbol, newName, solution.Options, cancellationToken).ConfigureAwait(false); var newDocument = newSolution.GetDocument(document.Id); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs b/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs index cfe9f0894de6a..91f279363ee02 100644 --- a/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs +++ b/src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs @@ -14,8 +14,7 @@ internal static class DocumentExtensions { public static bool ShouldHideAdvancedMembers(this Document document) { - return document.Project.Solution.Workspace.Options - .GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language); + return document.Options.GetOption(CompletionOptions.HideAdvancedMembers); } public static async Task ReplaceNodeAsync(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken) where TNode : SyntaxNode diff --git a/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs b/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs index 6898a9c22edb4..c62b2b0dd551b 100644 --- a/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs +++ b/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs @@ -18,15 +18,14 @@ internal static class ServiceFeatureOnOffOptions /// public static readonly PerLanguageOption ClosedFileDiagnostic = new PerLanguageOption(OptionName, "Closed File Diagnostic", defaultValue: null); - public static bool IsClosedFileDiagnosticsEnabled(Workspace workspace, string language) + public static bool IsClosedFileDiagnosticsEnabled(Project project) { - var optionsService = workspace.Services.GetService(); - return optionsService != null && IsClosedFileDiagnosticsEnabled(optionsService, language); + return IsClosedFileDiagnosticsEnabled(project.Solution.Options, project.Language); } - public static bool IsClosedFileDiagnosticsEnabled(IOptionService optionService, string language) + public static bool IsClosedFileDiagnosticsEnabled(OptionSet options, string language) { - var option = optionService.GetOption(ClosedFileDiagnostic, language); + var option = options.GetOption(ClosedFileDiagnostic, language); if (!option.HasValue) { return language == LanguageNames.CSharp ? diff --git a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs index c83ff95205411..88146c63ca8cf 100644 --- a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs +++ b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs @@ -78,7 +78,7 @@ private async Task ProcessResult(CodeFixContext context, Diagnostic di var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var solution = context.Document.Project.Solution; - var fieldLocations = await Renamer.GetRenameLocationsAsync(solution, fieldSymbol, solution.Workspace.Options, cancellationToken).ConfigureAwait(false); + var fieldLocations = await Renamer.GetRenameLocationsAsync(solution, fieldSymbol, solution.Options, cancellationToken).ConfigureAwait(false); // First, create the updated property we want to replace the old property with var isWrittenToOutsideOfConstructor = IsWrittenToOutsideOfConstructorOrProperty(fieldSymbol, fieldLocations, property, cancellationToken); diff --git a/src/Features/VisualBasic/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.vb index 27efefba9412e..82453b4941b24 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/RemoveUnnecessaryCast/RemoveUnnecessaryCastCodeFixProvider.RemoveUnnecessaryCastFixAllProvider.vb @@ -15,7 +15,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.RemoveUnnecessaryCast Friend Shared Shadows ReadOnly Instance As RemoveUnnecessaryCastFixAllProvider = New RemoveUnnecessaryCastFixAllProvider() - Protected Overrides Function GetNodeToSimplify(root As SyntaxNode, model As SemanticModel, diagnostic As Diagnostic, workspace As Workspace, ByRef codeActionId As String, cancellationToken As CancellationToken) As SyntaxNode + Protected Overrides Function GetNodeToSimplify(root As SyntaxNode, model As SemanticModel, diagnostic As Diagnostic, document As Document, ByRef codeActionId As String, cancellationToken As CancellationToken) As SyntaxNode codeActionId = Nothing Return GetCastNode(root, model, diagnostic.Location.SourceSpan, cancellationToken) End Function diff --git a/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.vb index 9fc4d82650299..54545cc668bbf 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.SimplifyTypeNamesFixAllProvider.vb @@ -13,10 +13,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Friend Shared Shadows ReadOnly Instance As SimplifyTypeNamesFixAllProvider = New SimplifyTypeNamesFixAllProvider - Protected Overrides Function GetNodeToSimplify(root As SyntaxNode, model As SemanticModel, diagnostic As Diagnostic, workspace As Workspace, ByRef codeActionId As String, cancellationToken As CancellationToken) As SyntaxNode + Protected Overrides Function GetNodeToSimplify(root As SyntaxNode, model As SemanticModel, diagnostic As Diagnostic, document As Document, ByRef codeActionId As String, cancellationToken As CancellationToken) As SyntaxNode codeActionId = Nothing Dim diagnosticId As String = Nothing - Dim node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, workspace.Options, diagnosticId, cancellationToken) + Dim node = SimplifyTypeNamesCodeFixProvider.GetNodeToSimplify(root, model, diagnostic.Location.SourceSpan, document.Options, diagnosticId, cancellationToken) If node IsNot Nothing Then codeActionId = GetCodeActionId(diagnosticId, node.ToString) End If diff --git a/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.vb index 74a05cb8f513b..a9bebfa7f6e5c 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.vb @@ -50,10 +50,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) - Dim optionSet = document.Project.Solution.Workspace.Options Dim model = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim diagnosticId As String = Nothing - Dim node = GetNodeToSimplify(root, model, span, optionSet, diagnosticId, cancellationToken) + Dim node = GetNodeToSimplify(root, model, span, document.Options, diagnosticId, cancellationToken) If node Is Nothing Then Return End If diff --git a/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb b/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb index 836f751daf682..f3a3fcab1a626 100644 --- a/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb +++ b/src/Features/VisualBasic/Portable/GenerateType/VisualBasicGenerateTypeService.vb @@ -628,7 +628,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateType Return updatedSolution End If - Dim placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language) + Dim placeSystemNamespaceFirst = document.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst) Dim root As SyntaxNode = Nothing If (modifiedRoot Is Nothing) Then root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) diff --git a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs index 2deaa328b3d07..753733611d765 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpPackage.cs +++ b/src/VisualStudio/CSharp/Impl/CSharpPackage.cs @@ -139,8 +139,7 @@ protected override object GetAutomationObject(string name) if (name == "CSharp-Specific") { var workspace = this.ComponentModel.GetService(); - var optionService = workspace.Services.GetService(); - return new Options.AutomationObject(optionService); + return new Options.AutomationObject(workspace); } return base.GetAutomationObject(name); diff --git a/src/VisualStudio/CSharp/Impl/DesignerAttribute/CSharpDesignerAttributeIncrementalAnalyzerProvider.cs b/src/VisualStudio/CSharp/Impl/DesignerAttribute/CSharpDesignerAttributeIncrementalAnalyzerProvider.cs index c6346da2a69fd..efab969c629bc 100644 --- a/src/VisualStudio/CSharp/Impl/DesignerAttribute/CSharpDesignerAttributeIncrementalAnalyzerProvider.cs +++ b/src/VisualStudio/CSharp/Impl/DesignerAttribute/CSharpDesignerAttributeIncrementalAnalyzerProvider.cs @@ -37,18 +37,16 @@ public CSharpDesignerAttributeIncrementalAnalyzerProvider( public IIncrementalAnalyzer CreatePerLanguageIncrementalAnalyzer(Workspace workspace, IIncrementalAnalyzerProvider provider) { - var optionService = workspace.Services.GetService(); - return new DesignerAttributeIncrementalAnalyzer(_serviceProvider, optionService, _notificationService, _asyncListeners); + return new DesignerAttributeIncrementalAnalyzer(_serviceProvider, _notificationService, _asyncListeners); } private class DesignerAttributeIncrementalAnalyzer : AbstractDesignerAttributeIncrementalAnalyzer { public DesignerAttributeIncrementalAnalyzer( IServiceProvider serviceProvider, - IOptionService optionService, IForegroundNotificationService notificationService, IEnumerable> asyncListeners) : - base(serviceProvider, optionService, notificationService, asyncListeners) + base(serviceProvider, notificationService, asyncListeners) { } diff --git a/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs b/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs index b5d60632c58c9..d55e278dcdf14 100644 --- a/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs +++ b/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs @@ -20,11 +20,11 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options [ComVisible(true)] public class AutomationObject { - private readonly IOptionService _optionService; + private readonly Workspace _workspace; - internal AutomationObject(IOptionService optionService) + internal AutomationObject(Workspace workspace) { - _optionService = optionService; + _workspace = workspace; } public int AutoComment @@ -142,15 +142,13 @@ public int Indent_FlushLabelsLeft { get { - var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); + var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); } } @@ -158,15 +156,12 @@ public int Indent_UnindentLabels { get { - var option = _optionService.GetOption(CSharpFormattingOptions.LabelPositioning); - return (int)option; + return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); } set { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); } } @@ -360,16 +355,14 @@ public int Space_AroundBinaryOperator { get { - var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); + var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); } } @@ -479,14 +472,12 @@ public string Style_NamingPreferences { get { - return _optionService.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp); + return _workspace.Options.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp); } set { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, value); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, value); } } @@ -524,8 +515,7 @@ public string Style_UseImplicitTypeWherePossible { get { - var option = _optionService.GetOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); - return GetUseVarOption(option); + return GetUseVarOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); } set { @@ -537,8 +527,7 @@ public string Style_UseImplicitTypeWhereApparent { get { - var option = _optionService.GetOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); - return GetUseVarOption(option); + return GetUseVarOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); } set { @@ -550,8 +539,7 @@ public string Style_UseImplicitTypeForIntrinsicTypes { get { - var option = _optionService.GetOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); - return GetUseVarOption(option); + return GetUseVarOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); } set { @@ -563,15 +551,12 @@ public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { - var option = _optionService.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); - return (int)option; + return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); } set { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); } } @@ -595,31 +580,27 @@ public int Wrapping_PreserveSingleLine private int GetBooleanOption(Option key) { - return _optionService.GetOption(key) ? 1 : 0; + return _workspace.Options.GetOption(key) ? 1 : 0; } private int GetBooleanOption(PerLanguageOption key) { - return _optionService.GetOption(key, LanguageNames.CSharp) ? 1 : 0; + return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } private void SetBooleanOption(Option key, int value) { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(key, value != 0); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(key, value != 0); } private void SetBooleanOption(PerLanguageOption key, int value) { - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, value != 0); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value != 0); } private int GetBooleanOption(PerLanguageOption key) { - var option = _optionService.GetOption(key, LanguageNames.CSharp); + var option = _workspace.Options.GetOption(key, LanguageNames.CSharp); if (!option.HasValue) { return -1; @@ -631,24 +612,18 @@ private int GetBooleanOption(PerLanguageOption key) private void SetBooleanOption(PerLanguageOption key, int value) { bool? boolValue = (value < 0) ? (bool?)null : (value > 0); - var optionSet = _optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(key, LanguageNames.CSharp, boolValue); - _optionService.SetOptions(optionSet); + _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, boolValue); } - private static string GetUseVarOption(SimpleCodeStyleOption option) + private string GetUseVarOption(Option option) { - return option.ToXElement().ToString(); + return _workspace.Options.GetOption(option).ToXElement().ToString(); } private void SetUseVarOption(Option option, string value) { - SimpleCodeStyleOption convertedValue = SimpleCodeStyleOption.Default; - var optionSet = _optionService.GetOptions(); - - convertedValue = SimpleCodeStyleOption.FromXElement(XElement.Parse(value)); - optionSet = optionSet.WithChangedOption(option, convertedValue); - _optionService.SetOptions(optionSet); + var convertedValue = SimpleCodeStyleOption.FromXElement(XElement.Parse(value)); + _workspace.Options = _workspace.Options.WithChangedOption(option, convertedValue); } } } diff --git a/src/VisualStudio/CSharp/Test/Options/OptionViewModelTests.cs b/src/VisualStudio/CSharp/Test/Options/OptionViewModelTests.cs index 869c8fcceb586..f4c5e62ecea32 100644 --- a/src/VisualStudio/CSharp/Test/Options/OptionViewModelTests.cs +++ b/src/VisualStudio/CSharp/Test/Options/OptionViewModelTests.cs @@ -73,9 +73,7 @@ public async Task TestOptionLoading() { using (var workspace = await TestWorkspace.CreateCSharpAsync("")) { - var optionService = workspace.GetService(); - var optionSet = optionService.GetOptions(); - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, true); + var optionSet = workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, true); var serviceProvider = new MockServiceProvider(workspace.ExportProvider); using (var viewModel = new SpacingViewModel(optionSet, serviceProvider)) @@ -100,35 +98,10 @@ public async Task TestOptionSaving() var initial = checkbox.IsChecked; checkbox.IsChecked = !checkbox.IsChecked; - var optionService = workspace.GetService(); - var optionSet = optionService.GetOptions(); - - var changedOptions = viewModel.ApplyChangedOptions(optionSet); + var changedOptions = viewModel.ApplyChangedOptions(workspace.Options); Assert.NotEqual(changedOptions.GetOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName), initial); } } } - - [WpfFact, Trait(Traits.Feature, Traits.Features.Options)] - public async Task TestFeatureBasedSaving() - { - using (var workspace = await TestWorkspace.CreateCSharpAsync("")) - { - // Set an option for an unrelated feature - var optionService = workspace.GetService(); - var optionSet = optionService.GetOptions(); - var expectedValue = !CSharpFormattingOptions.NewLineForCatch.DefaultValue; - optionSet = optionSet.WithChangedOption(CSharpFormattingOptions.NewLineForCatch, expectedValue); - optionService.SetOptions(optionSet); - - // Save the options - var serviceProvider = new MockServiceProvider(workspace.ExportProvider); - using (var viewModel = new SpacingViewModel(workspace.Options, serviceProvider)) - { - var changedOptions = optionService.GetOptions(); - Assert.Equal(changedOptions.GetOption(CSharpFormattingOptions.NewLineForCatch), expectedValue); - } - } - } } } diff --git a/src/VisualStudio/Core/Def/Implementation/DesignerAttribute/AbstractDesignerAttributeIncrementalAnalyzer.cs b/src/VisualStudio/Core/Def/Implementation/DesignerAttribute/AbstractDesignerAttributeIncrementalAnalyzer.cs index 50875ce84b468..f55dc6965bf58 100644 --- a/src/VisualStudio/Core/Def/Implementation/DesignerAttribute/AbstractDesignerAttributeIncrementalAnalyzer.cs +++ b/src/VisualStudio/Core/Def/Implementation/DesignerAttribute/AbstractDesignerAttributeIncrementalAnalyzer.cs @@ -21,7 +21,6 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.DesignerAttribu { internal abstract partial class AbstractDesignerAttributeIncrementalAnalyzer : ForegroundThreadAffinitizedObject { - private readonly IOptionService _optionService; private readonly IForegroundNotificationService _notificationService; private readonly IServiceProvider _serviceProvider; @@ -37,14 +36,12 @@ internal abstract partial class AbstractDesignerAttributeIncrementalAnalyzer : F public AbstractDesignerAttributeIncrementalAnalyzer( IServiceProvider serviceProvider, - IOptionService optionService, IForegroundNotificationService notificationService, IEnumerable> asyncListeners) { _serviceProvider = serviceProvider; Contract.ThrowIfNull(_serviceProvider); - _optionService = optionService; _notificationService = notificationService; _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.DesignerAttribute); @@ -72,7 +69,7 @@ public async System.Threading.Tasks.Task AnalyzeDocumentAsync(Document document, cancellationToken.ThrowIfCancellationRequested(); - if (!_optionService.GetOption(InternalFeatureOnOffOptions.DesignerAttributes)) + if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.DesignerAttributes)) { return; } diff --git a/src/VisualStudio/Core/Def/Implementation/Diagnostics/MiscellaneousDiagnosticAnalyzerService.cs b/src/VisualStudio/Core/Def/Implementation/Diagnostics/MiscellaneousDiagnosticAnalyzerService.cs index b8811b5938ff9..356ea2c568b9a 100644 --- a/src/VisualStudio/Core/Def/Implementation/Diagnostics/MiscellaneousDiagnosticAnalyzerService.cs +++ b/src/VisualStudio/Core/Def/Implementation/Diagnostics/MiscellaneousDiagnosticAnalyzerService.cs @@ -152,8 +152,8 @@ public void RemoveProject(ProjectId projectId) private bool CheckOptions(Document document) { - if (ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_workspace, document.Project.Language) && - _workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) + if (ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(document.Project) && + document.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) { return true; } diff --git a/src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`3.cs b/src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`3.cs index 02ba74b45382c..6646f3b15bcac 100644 --- a/src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`3.cs +++ b/src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`3.cs @@ -115,17 +115,16 @@ protected override void SetupNewTextView(IVsTextView textView) var commandHandlerFactory = Package.ComponentModel.GetService(); var workspace = Package.ComponentModel.GetService(); - var optionsService = workspace.Services.GetService(); // The lifetime of CommandFilter is married to the view wpfTextView.GetOrCreateAutoClosingProperty(v => new StandaloneCommandFilter( - (TLanguageService)this, v, commandHandlerFactory, optionsService, EditorAdaptersFactoryService).AttachToVsTextView()); + (TLanguageService)this, v, commandHandlerFactory, EditorAdaptersFactoryService).AttachToVsTextView()); var openDocument = wpfTextView.TextBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault(); var isOpenMetadataAsSource = openDocument != null && openDocument.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource; - ConditionallyCollapseOutliningRegions(textView, wpfTextView, optionsService, isOpenMetadataAsSource); + ConditionallyCollapseOutliningRegions(textView, wpfTextView, workspace, isOpenMetadataAsSource); // If this is a metadata-to-source view, we want to consider the file read-only IVsTextLines vsTextLines; @@ -144,7 +143,7 @@ protected override void SetupNewTextView(IVsTextView textView) } } - private void ConditionallyCollapseOutliningRegions(IVsTextView textView, IWpfTextView wpfTextView, IOptionService optionsService, bool isOpenMetadataAsSource) + private void ConditionallyCollapseOutliningRegions(IVsTextView textView, IWpfTextView wpfTextView, Workspace workspace, bool isOpenMetadataAsSource) { var outliningManagerService = this.Package.ComponentModel.GetService(); var outliningManager = outliningManagerService.GetOutliningManager(wpfTextView); @@ -153,7 +152,7 @@ private void ConditionallyCollapseOutliningRegions(IVsTextView textView, IWpfTex return; } - if (!optionsService.GetOption(FeatureOnOffOptions.Outlining, this.RoslynLanguageName)) + if (!workspace.Options.GetOption(FeatureOnOffOptions.Outlining, this.RoslynLanguageName)) { outliningManager.Enabled = false; } diff --git a/src/VisualStudio/Core/Def/Implementation/Options/AbstractLanguageSettingsSerializer.cs b/src/VisualStudio/Core/Def/Implementation/Options/AbstractLanguageSettingsSerializer.cs index fac7372bb4d43..0eb086366c5d0 100644 --- a/src/VisualStudio/Core/Def/Implementation/Options/AbstractLanguageSettingsSerializer.cs +++ b/src/VisualStudio/Core/Def/Implementation/Options/AbstractLanguageSettingsSerializer.cs @@ -231,8 +231,7 @@ private void RefreshOption(PerLanguageOption option) var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var visualStudioWorkspace = componentModel.GetService(); - var optionService = visualStudioWorkspace.Services.GetService(); - optionService.SetOptions(optionService.GetOptions().WithChangedOption(optionKey, value)); + visualStudioWorkspace.Options = visualStudioWorkspace.Options.WithChangedOption(optionKey, value); } } } diff --git a/src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.cs b/src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.cs index ad870487ad5ad..0f73f55d58933 100644 --- a/src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.cs +++ b/src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.cs @@ -174,8 +174,7 @@ private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { - var optionService = document.Project.Solution.Workspace.Services.GetService(); - var tabSize = optionService.GetOption(FormattingOptions.TabSize, document.Project.Language); + var tabSize = document.Options.GetOption(FormattingOptions.TabSize); indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize); } else @@ -525,8 +524,7 @@ private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationT return; } - var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService(); - var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language); + var placeSystemNamespaceFirst = documentWithImports.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } diff --git a/src/VisualStudio/Core/Def/Implementation/StandaloneCommandFilter.cs b/src/VisualStudio/Core/Def/Implementation/StandaloneCommandFilter.cs index 98043d002e98e..17e26463d1c7c 100644 --- a/src/VisualStudio/Core/Def/Implementation/StandaloneCommandFilter.cs +++ b/src/VisualStudio/Core/Def/Implementation/StandaloneCommandFilter.cs @@ -23,14 +23,12 @@ internal sealed class StandaloneCommandFilter /// The IWpfTextView of the view. /// The MEF imported ICommandHandlerServiceFactory. - /// The feature options service. /// The editor adapter /// The language service internal StandaloneCommandFilter( TLanguageService languageService, IWpfTextView wpfTextView, ICommandHandlerServiceFactory commandHandlerServiceFactory, - IOptionService featureOptionsService, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(languageService, wpfTextView, editorAdaptersFactoryService, commandHandlerServiceFactory) { diff --git a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs index 81d36699f4108..0813a8cd36042 100644 --- a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs +++ b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedDocument.cs @@ -66,7 +66,6 @@ internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVi private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; - private readonly IOptionService _optionService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; @@ -95,7 +94,6 @@ public ContainedDocument( _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; - _optionService = _workspace.Services.GetService(); _hostType = GetHostType(); string filePath; @@ -1008,7 +1006,7 @@ private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan { if (_hostType == HostType.HTML) { - return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); + return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) @@ -1066,7 +1064,7 @@ private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan } } - return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); + return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } diff --git a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguageCodeSupport.cs b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguageCodeSupport.cs index ab0123462a47c..92dc356b37f21 100644 --- a/src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguageCodeSupport.cs +++ b/src/VisualStudio/Core/Def/Implementation/Venus/ContainedLanguageCodeSupport.cs @@ -217,8 +217,13 @@ public static Tuple EnsureEventHandler( var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); - var workspace = targetDocument.Project.Solution.Workspace; - newRoot = Formatter.FormatAsync(newRoot, Formatter.Annotation, workspace, workspace.Options, formattingRules, cancellationToken).WaitAndGetResult_Venus(cancellationToken); + newRoot = Formatter.FormatAsync( + newRoot, + Formatter.Annotation, + targetDocument.Project.Solution.Workspace, + targetDocument.Options, + formattingRules, + cancellationToken).WaitAndGetResult_Venus(cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); diff --git a/src/VisualStudio/Core/Def/Implementation/VirtualMemoryNotificationListener.cs b/src/VisualStudio/Core/Def/Implementation/VirtualMemoryNotificationListener.cs index c130cb1434ff1..6cdada80298ef 100644 --- a/src/VisualStudio/Core/Def/Implementation/VirtualMemoryNotificationListener.cs +++ b/src/VisualStudio/Core/Def/Implementation/VirtualMemoryNotificationListener.cs @@ -85,7 +85,7 @@ public int OnBroadcastMessage(uint msg, IntPtr wParam, IntPtr lParam) _workspace.Options.GetOption(InternalFeatureOnOffOptions.FullSolutionAnalysisMemoryMonitor) && _workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis)) { - _workspace.Services.GetService().SetOptions(_workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, false)); + _workspace.Options = _workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, false); // let user know full analysis is turned off due to memory concern // no close info bar action diff --git a/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs b/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs index b3f9132ce091a..73290b22384b2 100644 --- a/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs +++ b/src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs @@ -547,10 +547,8 @@ public void Rename(ISymbol symbol, string newName, Solution solution) nodeKeyValidation.AddProject(project); } - var optionSet = workspace.Services.GetService().GetOptions(); - // Rename symbol. - var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, optionSet).WaitAndGetResult_CodeModel(CancellationToken.None); + var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Options).WaitAndGetResult_CodeModel(CancellationToken.None); var changedDocuments = newSolution.GetChangedDocuments(solution); // Notify third parties of the coming rename operation and let exceptions propagate out diff --git a/src/VisualStudio/Core/Impl/Options/AbstractCheckBoxViewModel.cs b/src/VisualStudio/Core/Impl/Options/AbstractCheckBoxViewModel.cs index f6ae57adb2403..a45d38e7ae185 100644 --- a/src/VisualStudio/Core/Impl/Options/AbstractCheckBoxViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/AbstractCheckBoxViewModel.cs @@ -17,12 +17,12 @@ internal abstract class AbstractCheckBoxViewModel : AbstractNotifyPropertyChange internal virtual string GetPreview() => _isChecked ? _truePreview : _falsePreview; - public AbstractCheckBoxViewModel(IOption option, string description, string preview, AbstractOptionPreviewViewModel info, OptionSet options) - : this(option, description, preview, preview, info, options) + public AbstractCheckBoxViewModel(IOption option, string description, string preview, AbstractOptionPreviewViewModel info) + : this(option, description, preview, preview, info) { } - public AbstractCheckBoxViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionSet options) + public AbstractCheckBoxViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info) { _truePreview = truePreview; _falsePreview = falsePreview; diff --git a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs index 82c779cb03ffc..3e088d889897d 100644 --- a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs @@ -43,10 +43,12 @@ internal abstract class AbstractOptionPreviewViewModel : AbstractNotifyPropertyC public ObservableCollection CodeStyleItems { get; set; } public OptionSet Options { get; set; } + private readonly OptionSet _originalOptions; protected AbstractOptionPreviewViewModel(OptionSet options, IServiceProvider serviceProvider, string language) { this.Options = options; + _originalOptions = options; this.Items = new List(); this.CodeStyleItems = new ObservableCollection(); @@ -64,7 +66,7 @@ protected AbstractOptionPreviewViewModel(OptionSet options, IServiceProvider ser internal OptionSet ApplyChangedOptions(OptionSet optionSet) { - foreach (var optionKey in this.Options.GetAccessedOptions()) + foreach (var optionKey in this.Options.GetChangedOptions(_originalOptions)) { if (ShouldPersistOption(optionKey)) { diff --git a/src/VisualStudio/Core/Impl/Options/CheckBoxViewModel.cs b/src/VisualStudio/Core/Impl/Options/CheckBoxViewModel.cs index c58cdd665fe4a..8764e1da25f99 100644 --- a/src/VisualStudio/Core/Impl/Options/CheckBoxViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/CheckBoxViewModel.cs @@ -12,7 +12,7 @@ public CheckBoxOptionViewModel(IOption option, string description, string previe } public CheckBoxOptionViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionSet options) - : base(option, description, truePreview, falsePreview, info, options) + : base(option, description, truePreview, falsePreview, info) { SetProperty(ref _isChecked, (bool)options.GetOption(new OptionKey(option, option.IsPerLanguage ? info.Language : null))); } diff --git a/src/VisualStudio/Core/Impl/Options/CheckBoxWithComboViewModel.cs b/src/VisualStudio/Core/Impl/Options/CheckBoxWithComboViewModel.cs index 7aede44c09615..8d388bfec0456 100644 --- a/src/VisualStudio/Core/Impl/Options/CheckBoxWithComboViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/CheckBoxWithComboViewModel.cs @@ -26,7 +26,7 @@ public CheckBoxWithComboOptionViewModel(IOption option, string description, stri } public CheckBoxWithComboOptionViewModel(IOption option, string description, string truePreview, string falsePreview, AbstractOptionPreviewViewModel info, OptionSet options, IList items) - : base(option, description, truePreview, falsePreview, info, options) + : base(option, description, truePreview, falsePreview, info) { NotificationOptions = items; diff --git a/src/VisualStudio/Core/Impl/Options/FullSolutionAnalysisOptionBinding.cs b/src/VisualStudio/Core/Impl/Options/FullSolutionAnalysisOptionBinding.cs index cfb8b32a6ddc3..49c032df059b9 100644 --- a/src/VisualStudio/Core/Impl/Options/FullSolutionAnalysisOptionBinding.cs +++ b/src/VisualStudio/Core/Impl/Options/FullSolutionAnalysisOptionBinding.cs @@ -26,7 +26,7 @@ public bool Value { get { - return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_optionService, _languageName) && + return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_optionService.GetOptions(), _languageName) && _optionService.GetOption(_fullSolutionAnalysis); } diff --git a/src/VisualStudio/Core/Test/Snippets/CSharpSnippetExpansionClientTests.vb b/src/VisualStudio/Core/Test/Snippets/CSharpSnippetExpansionClientTests.vb index dd776dab1a614..5c9c0794a2baa 100644 --- a/src/VisualStudio/Core/Test/Snippets/CSharpSnippetExpansionClientTests.vb +++ b/src/VisualStudio/Core/Test/Snippets/CSharpSnippetExpansionClientTests.vb @@ -276,12 +276,10 @@ using G= H.I; Using workspace = Await TestWorkspace.CreateAsync(workspaceXml) Dim document = workspace.Documents.Single() - Dim optionService = workspace.Services.GetService(Of IOptionService)() - Dim optionSet = optionService.GetOptions() - optionSet = optionSet.WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) - optionSet = optionSet.WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) - optionSet = optionSet.WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize) - optionService.SetOptions(optionSet) + workspace.Options = workspace.Options _ + .WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) _ + .WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) _ + .WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize) Dim snippetExpansionClient = New SnippetExpansionClient( Guids.CSharpLanguageServiceId, diff --git a/src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb b/src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb index b84cf6597f650..e9a9181e163f8 100644 --- a/src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb +++ b/src/VisualStudio/Core/Test/Snippets/SnippetTestState.vb @@ -33,8 +33,8 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets Public Sub New(workspaceElement As XElement, languageName As String, startActiveSession As Boolean, extraParts As IEnumerable(Of Type), Optional workspaceKind As String = Nothing) MyBase.New(workspaceElement, extraParts:=CreatePartCatalog(extraParts), workspaceKind:=workspaceKind) - Dim optionService = Workspace.Services.GetService(Of IOptionService)() - optionService.SetOptions(optionService.GetOptions().WithChangedOption(InternalFeatureOnOffOptions.Snippets, True)) + Workspace.Options = Workspace.Options.WithChangedOption(InternalFeatureOnOffOptions.Snippets, True) + Dim mockEditorAdaptersFactoryService = New Mock(Of IVsEditorAdaptersFactoryService) Dim mockSVsServiceProvider = New Mock(Of SVsServiceProvider) SnippetCommandHandler = If(languageName = LanguageNames.CSharp, diff --git a/src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetExpansionClientTests.vb b/src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetExpansionClientTests.vb index e326bf197e81c..832398b28a45d 100644 --- a/src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetExpansionClientTests.vb +++ b/src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetExpansionClientTests.vb @@ -355,12 +355,10 @@ End Class Using workspace = Await TestWorkspace.CreateAsync(workspaceXml) Dim document = workspace.Documents.Single() - Dim optionService = workspace.Services.GetService(Of IOptionService)() - Dim optionSet = optionService.GetOptions() - optionSet = optionSet.WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) - optionSet = optionSet.WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) - optionSet = optionSet.WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize) - optionService.SetOptions(optionSet) + workspace.Options = workspace.Options _ + .WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) _ + .WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) _ + .WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize) Dim snippetExpansionClient = New SnippetExpansionClient( Guids.CSharpLanguageServiceId, diff --git a/src/VisualStudio/VisualBasic/Impl/DesignerAttribute/BasicDesignerAttributeIncrementalAnalyzerProvider.vb b/src/VisualStudio/VisualBasic/Impl/DesignerAttribute/BasicDesignerAttributeIncrementalAnalyzerProvider.vb index b47a21782412d..3a86d537693e7 100644 --- a/src/VisualStudio/VisualBasic/Impl/DesignerAttribute/BasicDesignerAttributeIncrementalAnalyzerProvider.vb +++ b/src/VisualStudio/VisualBasic/Impl/DesignerAttribute/BasicDesignerAttributeIncrementalAnalyzerProvider.vb @@ -30,8 +30,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.DesignerAttribute End Sub Public Function CreatePerLanguageIncrementalAnalyzer(workspace As Workspace, provider As IIncrementalAnalyzerProvider) As IIncrementalAnalyzer Implements IPerLanguageIncrementalAnalyzerProvider.CreatePerLanguageIncrementalAnalyzer - Dim optionService = workspace.Services.GetService(Of IOptionService)() - Return New DesignerAttributeIncrementalAnalyzer(Me._serviceProvider, optionService, Me._notificationService, Me._asyncListeners) + Return New DesignerAttributeIncrementalAnalyzer(Me._serviceProvider, Me._notificationService, Me._asyncListeners) End Function Private Class DesignerAttributeIncrementalAnalyzer @@ -39,10 +38,9 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.DesignerAttribute Public Sub New( serviceProvider As IServiceProvider, - optionService As IOptionService, notificationService As IForegroundNotificationService, asyncListeners As IEnumerable(Of Lazy(Of IAsynchronousOperationListener, FeatureMetadata))) - MyBase.New(serviceProvider, optionService, notificationService, asyncListeners) + MyBase.New(serviceProvider, notificationService, asyncListeners) End Sub Protected Overrides Function GetAllTopLevelTypeDefined(node As SyntaxNode) As IEnumerable(Of SyntaxNode) diff --git a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb index fac01bda7264c..c2a83060bdd3b 100644 --- a/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb +++ b/src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb @@ -133,8 +133,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() - Dim optionService = workspace.Services.GetService(Of IOptionService)() - Return New AutomationObject(optionService) + Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) diff --git a/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb b/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb index d9a3ef277be52..fcc6394896b0c 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb @@ -11,10 +11,10 @@ Imports Microsoft.CodeAnalysis.Simplification Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Public Class AutomationObject - Private ReadOnly _optionService As IOptionService + Private ReadOnly _workspace As Workspace - Friend Sub New(optionService As IOptionService) - _optionService = optionService + Friend Sub New(workspace As Workspace) + _workspace = workspace End Sub Public Property AutoComment As Boolean @@ -47,7 +47,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Public Property ClosedFileDiagnostics As Boolean Get - Return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_optionService, LanguageNames.VisualBasic) + Return ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(_workspace.Options, LanguageNames.VisualBasic) End Get Set(value As Boolean) ' Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics'). @@ -221,27 +221,23 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options End Property Private Function GetBooleanOption(key As [Option](Of Boolean)) As Boolean - Return _optionService.GetOption(key) + Return _workspace.Options.GetOption(key) End Function Private Sub SetBooleanOption(key As [Option](Of Boolean), value As Boolean) - Dim optionSet = _optionService.GetOptions() - optionSet = optionSet.WithChangedOption(key, value) - _optionService.SetOptions(optionSet) + _workspace.Options = _workspace.Options.WithChangedOption(key, value) End Sub Private Function GetBooleanOption(key As [PerLanguageOption](Of Boolean)) As Boolean - Return _optionService.GetOption(key, LanguageNames.VisualBasic) + Return _workspace.Options.GetOption(key, LanguageNames.VisualBasic) End Function Private Sub SetBooleanOption(key As [PerLanguageOption](Of Boolean), value As Boolean) - Dim optionSet = _optionService.GetOptions() - optionSet = optionSet.WithChangedOption(key, LanguageNames.VisualBasic, value) - _optionService.SetOptions(optionSet) + _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.VisualBasic, value) End Sub Private Function GetBooleanOption(key As PerLanguageOption(Of Boolean?)) As Integer - Dim [option] = _optionService.GetOption(key, LanguageNames.VisualBasic) + Dim [option] = _workspace.Options.GetOption(key, LanguageNames.VisualBasic) If Not [option].HasValue Then Return -1 End If @@ -251,9 +247,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Private Sub SetBooleanOption(key As PerLanguageOption(Of Boolean?), value As Integer) Dim boolValue As Boolean? = If(value < 0, Nothing, value > 0) - Dim optionSet = _optionService.GetOptions() - optionSet = optionSet.WithChangedOption(key, LanguageNames.VisualBasic, boolValue) - _optionService.SetOptions(optionSet) + _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.VisualBasic, boolValue) End Sub End Class End Namespace diff --git a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs index 3e619f2ebc4cc..bfc8429e085d0 100644 --- a/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs +++ b/src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs @@ -34,7 +34,7 @@ private Document GetDocument(string code) private async Task TestAsync(string initialText, string importsAddedText, string simplifiedText, OptionSet options = null) { var doc = GetDocument(initialText); - options = options ?? doc.Project.Solution.Workspace.Options; + options = options ?? doc.Options; var imported = await ImportAdder.AddImportsAsync(doc, options); diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchSimplificationFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchSimplificationFixAllProvider.cs index 119f226dee7e1..0b5db276a02b8 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchSimplificationFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchSimplificationFixAllProvider.cs @@ -37,7 +37,7 @@ public override async Task AddDocumentFixesAsync( /// /// Get node on which to add simplifier and formatter annotation for fixing the given diagnostic. /// - protected virtual SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Workspace workspace, out string codeActionEquivalenceKey, CancellationToken cancellationToken) + protected virtual SyntaxNode GetNodeToSimplify(SyntaxNode root, SemanticModel model, Diagnostic diagnostic, Document document, out string codeActionEquivalenceKey, CancellationToken cancellationToken) { codeActionEquivalenceKey = null; var span = diagnostic.Location.SourceSpan; @@ -56,7 +56,7 @@ protected virtual Task AddSimplifyAnnotationsAsync(Document document, /// /// By default, this property returns false and will just add to each node to simplify - /// returned by . + /// returned by . /// /// Override this property to return true if the fix all provider needs to add simplify annotations/fixup any of the parent nodes of the nodes to simplify. /// This could be the case if simplifying certain nodes can enable cascaded simplifications, such as parentheses removal on parenting node. @@ -77,7 +77,7 @@ private async Task AddSimplifierAnnotationsAsync( foreach (var diagnostic in diagnostics) { string codeActionEquivalenceKey; - var node = GetNodeToSimplify(root, model, diagnostic, fixAllState.Solution.Workspace, out codeActionEquivalenceKey, cancellationToken); + var node = GetNodeToSimplify(root, model, diagnostic, document, out codeActionEquivalenceKey, cancellationToken); if (node != null && fixAllState.CodeActionEquivalenceKey == codeActionEquivalenceKey) { nodesToSimplify.Add(node); diff --git a/src/Workspaces/Core/Portable/Editing/ImportAdderService.cs b/src/Workspaces/Core/Portable/Editing/ImportAdderService.cs index bfa44fbab06be..4fd62d0201b03 100644 --- a/src/Workspaces/Core/Portable/Editing/ImportAdderService.cs +++ b/src/Workspaces/Core/Portable/Editing/ImportAdderService.cs @@ -18,7 +18,7 @@ internal abstract class ImportAdderService : ILanguageService { public async Task AddImportsAsync(Document document, IEnumerable spans, OptionSet options, CancellationToken cancellationToken) { - options = options ?? document.Project.Solution.Workspace.Options; + options = options ?? document.Options; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/Core/Portable/Formatting/Formatter.cs b/src/Workspaces/Core/Portable/Formatting/Formatter.cs index ac0a575deafee..a1f8d9105a803 100644 --- a/src/Workspaces/Core/Portable/Formatting/Formatter.cs +++ b/src/Workspaces/Core/Portable/Formatting/Formatter.cs @@ -133,7 +133,7 @@ internal static async Task FormatAsync(Document document, IEnumerable< } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(await FormatAsync(root, spans, document.Project.Solution.Workspace, options, rules, cancellationToken).ConfigureAwait(false)); + return document.WithSyntaxRoot(await FormatAsync(root, spans, document.Project.Solution.Workspace, options ?? document.Options, rules, cancellationToken).ConfigureAwait(false)); } /// @@ -162,7 +162,7 @@ internal static async Task FormatAsync(Document document, SyntaxAnnota } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return document.WithSyntaxRoot(await FormatAsync(root, annotation, document.Project.Solution.Workspace, options, rules, cancellationToken).ConfigureAwait(false)); + return document.WithSyntaxRoot(await FormatAsync(root, annotation, document.Project.Solution.Workspace, options ?? document.Options, rules, cancellationToken).ConfigureAwait(false)); } /// diff --git a/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs b/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs new file mode 100644 index 0000000000000..6f1e19823b8b5 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.CodeAnalysis.Options +{ + /// + /// An that comes from . It behaves just like a normal + /// but remembers which language the is, so you don't have to + /// pass that information redundantly when calling . + /// + public sealed class DocumentOptionSet : OptionSet + { + private readonly OptionSet _backingOptionSet; + private readonly string _language; + + internal DocumentOptionSet(OptionSet backingOptionSet, string language) + { + _backingOptionSet = backingOptionSet; + _language = language; + } + + public override object GetOption(OptionKey optionKey) + { + return _backingOptionSet.GetOption(optionKey); + } + + public override T GetOption(Option option) + { + return _backingOptionSet.GetOption(option); + } + + public T GetOption(PerLanguageOption option) + { + return _backingOptionSet.GetOption(option, _language); + } + + public override T GetOption(PerLanguageOption option, string language) + { + return _backingOptionSet.GetOption(option, language); + } + + public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object value) + { + return new DocumentOptionSet(_backingOptionSet.WithChangedOption(optionAndLanguage, value), _language); + } + + public override OptionSet WithChangedOption(Option option, T value) + { + return new DocumentOptionSet(_backingOptionSet.WithChangedOption(option, value), _language); + } + + public override OptionSet WithChangedOption(PerLanguageOption option, string language, T value) + { + return new DocumentOptionSet(_backingOptionSet.WithChangedOption(option, language, value), _language); + } + + internal override IEnumerable GetChangedOptions(OptionSet optionSet) + { + return _backingOptionSet.GetChangedOptions(optionSet); + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/OptionService.cs b/src/Workspaces/Core/Portable/Options/OptionService.cs index de73f3c956e4e..a066982b0ac1e 100644 --- a/src/Workspaces/Core/Portable/Options/OptionService.cs +++ b/src/Workspaces/Core/Portable/Options/OptionService.cs @@ -92,7 +92,7 @@ public IEnumerable GetRegisteredOptions() public OptionSet GetOptions() { - return new OptionSet(this); + return new WorkspaceOptionSet(this); } public T GetOption(Option option) @@ -131,11 +131,18 @@ public void SetOptions(OptionSet optionSet) throw new ArgumentNullException(nameof(optionSet)); } + var workspaceOptionSet = optionSet as WorkspaceOptionSet; + + if (workspaceOptionSet == null) + { + throw new ArgumentException(WorkspacesResources.OptionsDidNotComeFromWorkspace, paramName: nameof(optionSet)); + } + var changedOptions = new List(); lock (_gate) { - foreach (var optionKey in optionSet.GetAccessedOptions()) + foreach (var optionKey in workspaceOptionSet.GetAccessedOptions()) { var setValue = optionSet.GetOption(optionKey); object currentValue = this.GetOption(optionKey); diff --git a/src/Workspaces/Core/Portable/Options/OptionSet.cs b/src/Workspaces/Core/Portable/Options/OptionSet.cs index eac193bb2ec29..9f068894789f2 100644 --- a/src/Workspaces/Core/Portable/Options/OptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/OptionSet.cs @@ -1,110 +1,41 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; -using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Options { - public sealed class OptionSet + public abstract class OptionSet { - private readonly IOptionService _service; - - private readonly object _gate = new object(); - private ImmutableDictionary _values; - - internal OptionSet(IOptionService service) - { - _service = service; - _values = ImmutableDictionary.Create(); - } - - private OptionSet(IOptionService service, ImmutableDictionary values) - { - _service = service; - _values = values; - } - /// /// Gets the value of the option. /// - public T GetOption(Option option) - { - return (T)GetOption(new OptionKey(option, language: null)); - } + public abstract object GetOption(OptionKey optionKey); /// /// Gets the value of the option. /// - public T GetOption(PerLanguageOption option, string language) - { - return (T)GetOption(new OptionKey(option, language)); - } + public abstract T GetOption(Option option); /// /// Gets the value of the option. /// - public object GetOption(OptionKey optionKey) - { - lock (_gate) - { - object value; - - if (!_values.TryGetValue(optionKey, out value)) - { - value = _service != null ? _service.GetOption(optionKey) : optionKey.Option.DefaultValue; - _values = _values.Add(optionKey, value); - } - - return value; - } - } + public abstract T GetOption(PerLanguageOption option, string language); /// /// Creates a new that contains the changed value. /// - public OptionSet WithChangedOption(Option option, T value) - { - return WithChangedOption(new OptionKey(option, language: null), value); - } + public abstract OptionSet WithChangedOption(OptionKey optionAndLanguage, object value); /// /// Creates a new that contains the changed value. /// - public OptionSet WithChangedOption(PerLanguageOption option, string language, T value) - { - return WithChangedOption(new OptionKey(option, language), value); - } + public abstract OptionSet WithChangedOption(Option option, T value); /// /// Creates a new that contains the changed value. /// - public OptionSet WithChangedOption(OptionKey optionAndLanguage, object value) - { - // make sure we first load this in current optionset - this.GetOption(optionAndLanguage); - - return new OptionSet(_service, _values.SetItem(optionAndLanguage, value)); - } - - /// - /// Gets a list of all the options that were accessed. - /// - internal IEnumerable GetAccessedOptions() - { - var optionSet = _service.GetOptions(); - return GetChangedOptions(optionSet); - } + public abstract OptionSet WithChangedOption(PerLanguageOption option, string language, T value); - internal IEnumerable GetChangedOptions(OptionSet optionSet) - { - foreach (var kvp in _values) - { - var currentValue = optionSet.GetOption(kvp.Key); - if (!object.Equals(currentValue, kvp.Value)) - { - yield return kvp.Key; - } - } - } + internal abstract IEnumerable GetChangedOptions(OptionSet optionSet); } -} +} \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs b/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs new file mode 100644 index 0000000000000..177929230871d --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Options +{ + /// + /// An implementation of that fetches values it doesn't know about to the workspace's option service. It ensures a contract + /// that values are immutable from this instance once observed. + /// + internal sealed class WorkspaceOptionSet : OptionSet + { + private readonly IOptionService _service; + + private readonly object _gate = new object(); + private ImmutableDictionary _values; + + internal WorkspaceOptionSet(IOptionService service) + { + _service = service; + _values = ImmutableDictionary.Create(); + } + + private WorkspaceOptionSet(IOptionService service, ImmutableDictionary values) + { + _service = service; + _values = values; + } + + public override T GetOption(Option option) + { + return (T)GetOption(new OptionKey(option, language: null)); + } + + public override T GetOption(PerLanguageOption option, string language) + { + return (T)GetOption(new OptionKey(option, language)); + } + + public override object GetOption(OptionKey optionKey) + { + lock (_gate) + { + object value; + + if (!_values.TryGetValue(optionKey, out value)) + { + value = _service != null ? _service.GetOption(optionKey) : optionKey.Option.DefaultValue; + _values = _values.Add(optionKey, value); + } + + return value; + } + } + + public override OptionSet WithChangedOption(Option option, T value) + { + return WithChangedOption(new OptionKey(option, language: null), value); + } + + public override OptionSet WithChangedOption(PerLanguageOption option, string language, T value) + { + return WithChangedOption(new OptionKey(option, language), value); + } + + public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object value) + { + // make sure we first load this in current optionset + this.GetOption(optionAndLanguage); + + return new WorkspaceOptionSet(_service, _values.SetItem(optionAndLanguage, value)); + } + + /// + /// Gets a list of all the options that were accessed. + /// + internal IEnumerable GetAccessedOptions() + { + var optionSet = _service.GetOptions(); + return GetChangedOptions(optionSet); + } + + internal override IEnumerable GetChangedOptions(OptionSet optionSet) + { + foreach (var kvp in _values) + { + var currentValue = optionSet.GetOption(kvp.Key); + if (!object.Equals(currentValue, kvp.Value)) + { + yield return kvp.Key; + } + } + } + } +} diff --git a/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt b/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt index b7592bfbd1d33..b62335ab13523 100644 --- a/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt +++ b/src/Workspaces/Core/Portable/PublicAPI.Shipped.txt @@ -502,12 +502,12 @@ Microsoft.CodeAnalysis.Options.OptionKey.Language.get -> string Microsoft.CodeAnalysis.Options.OptionKey.Option.get -> Microsoft.CodeAnalysis.Options.IOption Microsoft.CodeAnalysis.Options.OptionKey.OptionKey(Microsoft.CodeAnalysis.Options.IOption option, string language = null) -> void Microsoft.CodeAnalysis.Options.OptionSet -Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> object -Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.Option option) -> T -Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language) -> T -Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet -Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.Option option, T value) -> Microsoft.CodeAnalysis.Options.OptionSet -Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language, T value) -> Microsoft.CodeAnalysis.Options.OptionSet +abstract Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> object +abstract Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.Option option) -> T +abstract Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language) -> T +abstract Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet +abstract Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.Option option, T value) -> Microsoft.CodeAnalysis.Options.OptionSet +abstract Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language, T value) -> Microsoft.CodeAnalysis.Options.OptionSet Microsoft.CodeAnalysis.Options.PerLanguageOption Microsoft.CodeAnalysis.Options.PerLanguageOption.DefaultValue.get -> T Microsoft.CodeAnalysis.Options.PerLanguageOption.Feature.get -> string diff --git a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt index fd36c025d7a12..f534f361a9833 100644 --- a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt @@ -2,9 +2,19 @@ Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddSwitchSections(Microsoft.CodeA abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement) -> System.Collections.Generic.IReadOnlyList abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement, int index, System.Collections.Generic.IEnumerable switchSections) -> Microsoft.CodeAnalysis.SyntaxNode static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> bool +Microsoft.CodeAnalysis.Document.Options.get -> Microsoft.CodeAnalysis.Options.DocumentOptionSet +Microsoft.CodeAnalysis.Options.DocumentOptionSet +Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option) -> T +Microsoft.CodeAnalysis.Solution.Options.get -> Microsoft.CodeAnalysis.Options.OptionSet abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NameOfExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> object +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption(Microsoft.CodeAnalysis.Options.Option option) -> T +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language) -> T +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.Option option, T value) -> Microsoft.CodeAnalysis.Options.OptionSet +override Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.PerLanguageOption option, string language, T value) -> Microsoft.CodeAnalysis.Options.OptionSet static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.NamingPreferences.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyEventAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyFieldAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyMethodAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyPropertyAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption +static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyPropertyAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs index 3b084701e5cd0..29a94826bcb9f 100644 --- a/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs +++ b/src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs @@ -203,8 +203,7 @@ internal async Task SimplifyAsync(Solution solution, IEnumerable GetRenameLocationsAsync(Solution solution, cancellationToken.ThrowIfCancellationRequested(); - options = options ?? solution.Workspace.Options; + options = options ?? solution.Options; return RenameLocations.FindAsync(symbol, solution, options, cancellationToken); } diff --git a/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs b/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs index 97cafc3146f13..858414ae3ec38 100644 --- a/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs +++ b/src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs @@ -48,7 +48,7 @@ protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, Syntax return document; } - optionSet = optionSet ?? document.Project.Solution.Workspace.Options; + optionSet = optionSet ?? document.Options; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs index 718ae78ff58d9..8db76cad9d7e5 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Document.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -425,5 +426,18 @@ private string GetDebuggerDisplay() { return this.Name; } + + /// + /// Returns the options that should be applied to this document. This consists of global options from , + /// merged with any settings the user has specified at the solution, project, and document levels. + /// + public DocumentOptionSet Options + { + get + { + // TODO: merge with document-specific options + return new DocumentOptionSet(Project.Solution.Options, Project.Language); + } + } } } diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs index 9750d0064ff3a..0a7662f0a4a12 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index ea1674ffcc718..e122e0533d200 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; @@ -2283,5 +2284,18 @@ private void CheckContainsAdditionalDocument(DocumentId documentId) throw new InvalidOperationException(WorkspacesResources.DocumentNotInSolution); } } + + /// + /// Returns the options that should be applied to this solution. This consists of global options from , + /// merged with any settings the user has specified at the solution level. + /// + public OptionSet Options + { + get + { + // TODO: merge with solution-specific options + return this.Workspace.Options; + } + } } } diff --git a/src/Workspaces/Core/Portable/Workspaces.csproj b/src/Workspaces/Core/Portable/Workspaces.csproj index afcf65e9995ef..b936c7f4fbf43 100644 --- a/src/Workspaces/Core/Portable/Workspaces.csproj +++ b/src/Workspaces/Core/Portable/Workspaces.csproj @@ -395,6 +395,8 @@ + + @@ -653,7 +655,7 @@ - + diff --git a/src/Workspaces/Core/Portable/WorkspacesResources.Designer.cs b/src/Workspaces/Core/Portable/WorkspacesResources.Designer.cs index 1d2ff6061562e..fc44ee628f48f 100644 --- a/src/Workspaces/Core/Portable/WorkspacesResources.Designer.cs +++ b/src/Workspaces/Core/Portable/WorkspacesResources.Designer.cs @@ -799,6 +799,15 @@ internal static string OpenDocumentNotSupported { } } + /// + /// Looks up a localized string similar to The options being set didn't originate from a workspace.. + /// + internal static string OptionsDidNotComeFromWorkspace { + get { + return ResourceManager.GetString("OptionsDidNotComeFromWorkspace", resourceCulture); + } + } + /// /// Looks up a localized string similar to Specified path must be absolute.. /// diff --git a/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs b/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs index 6e96384c44cc8..3eb23cb8a25c7 100644 --- a/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs @@ -156,7 +156,6 @@ public void OptionSetIsImmutable() var newOptionSet = optionSet.WithChangedOption(optionKey, false); Assert.NotSame(optionSet, newOptionSet); Assert.NotEqual(optionSet, newOptionSet); - Assert.NotEqual(optionSet.GetAccessedOptions().Count(), newOptionSet.GetAccessedOptions().Count()); } } }