diff --git a/eng/config/BannedSymbols.txt b/eng/config/BannedSymbols.txt
index 8a51cac5d9646..31de0c338aeba 100644
--- a/eng/config/BannedSymbols.txt
+++ b/eng/config/BannedSymbols.txt
@@ -9,6 +9,8 @@ M:Microsoft.CodeAnalysis.QuickInfo.QuickInfoService.GetQuickInfoAsync(Microsoft.
M:Microsoft.CodeAnalysis.CodeFixes.FixAllContext.#ctor(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider,Microsoft.CodeAnalysis.CodeFixes.FixAllScope,System.String,System.Collections.Generic.IEnumerable{System.String},Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider,System.Threading.CancellationToken); Use internal overload instead
M:Microsoft.CodeAnalysis.CodeFixes.FixAllContext.#ctor(Microsoft.CodeAnalysis.Document,System.Nullable{Microsoft.CodeAnalysis.Text.TextSpan},Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider,Microsoft.CodeAnalysis.CodeFixes.FixAllScope,System.String,System.Collections.Generic.IEnumerable{System.String},Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider,System.Threading.CancellationToken); Use internal overload instead
M:Microsoft.CodeAnalysis.CodeFixes.FixAllContext.#ctor(Microsoft.CodeAnalysis.Project,Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider,Microsoft.CodeAnalysis.CodeFixes.FixAllScope,System.String,System.Collections.Generic.IEnumerable{System.String},Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider,System.Threading.CancellationToken); Use internal overload instead
+M:Microsoft.CodeAnalysis.Document.GetOptionsAsync(System.Threading.CancellationToken); Use Document.GetAnalyzerConfigOptionsAsync instead
+T:Microsoft.CodeAnalysis.Options.DocumentOptionSet; Use AnalyzerConfigOptions instead
M:Microsoft.VisualStudio.Shell.ServiceExtensions.GetService``2(System.IServiceProvider); Use RoslynServiceExtensions instead. This extension internally relies on ThreadHelper, which is incompatible with testing.
M:Microsoft.VisualStudio.Shell.ServiceExtensions.GetService``2(System.IServiceProvider,System.Boolean); Use RoslynServiceExtensions instead. This extension internally relies on ThreadHelper, which is incompatible with testing
M:Microsoft.VisualStudio.Shell.ServiceExtensions.GetServiceAsync``2(Microsoft.VisualStudio.Shell.IAsyncServiceProvider); Use RoslynServiceExtensions instead. This extension internally relies on ThreadHelper, which is incompatible with testing
@@ -25,6 +27,7 @@ M:Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.Synt
M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead
M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,Microsoft.CodeAnalysis.Text.TextSpan,Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead
M:Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode,System.Collections.Generic.IEnumerable{Microsoft.CodeAnalysis.Text.TextSpan},Microsoft.CodeAnalysis.Workspace,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload with SyntaxFormattingOptions instead
+M:Microsoft.CodeAnalysis.Formatting.Formatter.OrganizeImportsAsync(Microsoft.CodeAnalysis.Document,System.Threading.CancellationToken); Call IOrganizeImportsService.OrganizeImportsAsync directly
M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions
M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.SyntaxAnnotation,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions
M:Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document,Microsoft.CodeAnalysis.Text.TextSpan,Microsoft.CodeAnalysis.Options.OptionSet,System.Threading.CancellationToken); Use overload that takes SimplifierOptions
diff --git a/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs
index e98030f3b1242..9294203fccde4 100644
--- a/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs
@@ -48,9 +48,8 @@ protected override void InitializeWorker(AnalysisContext context)
public void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var statement = context.Node;
- var cancellationToken = context.CancellationToken;
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferBraces, statement.SyntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferBraces;
if (option.Value == PreferBracesPreference.None)
{
return;
@@ -102,7 +101,7 @@ public void AnalyzeNode(SyntaxNodeAnalysisContext context)
return;
}
- if (ContainsInterleavedDirective(statement, embeddedStatement, cancellationToken))
+ if (ContainsInterleavedDirective(statement, embeddedStatement, context.CancellationToken))
{
return;
}
diff --git a/src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems b/src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems
index ae97995d350bd..e0ea0cd616b51 100644
--- a/src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems
+++ b/src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems
@@ -19,6 +19,7 @@
+
@@ -60,7 +61,6 @@
-
diff --git a/src/Analyzers/CSharp/Analyzers/CodeStyle/CSharpAnalyzerOptionsProvider.cs b/src/Analyzers/CSharp/Analyzers/CodeStyle/CSharpAnalyzerOptionsProvider.cs
new file mode 100644
index 0000000000000..49b8beb1542a7
--- /dev/null
+++ b/src/Analyzers/CSharp/Analyzers/CodeStyle/CSharpAnalyzerOptionsProvider.cs
@@ -0,0 +1,142 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using Microsoft.CodeAnalysis.AddImport;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Formatting;
+using Microsoft.CodeAnalysis.CSharp.Simplification;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Options;
+
+namespace Microsoft.CodeAnalysis.Diagnostics;
+
+///
+/// Provides C# analyzers a convenient access to editorconfig options with fallback to IDE default values.
+///
+internal readonly struct CSharpAnalyzerOptionsProvider
+{
+ ///
+ /// Document editorconfig options.
+ ///
+ private readonly AnalyzerConfigOptions _options;
+
+ ///
+ /// Fallback options - the default options in Code Style layer.
+ ///
+ private readonly IdeAnalyzerOptions _fallbackOptions;
+
+ public CSharpAnalyzerOptionsProvider(AnalyzerConfigOptions options, IdeAnalyzerOptions fallbackOptions)
+ {
+ _options = options;
+ _fallbackOptions = fallbackOptions;
+ }
+
+ public CSharpAnalyzerOptionsProvider(AnalyzerConfigOptions options, AnalyzerOptions fallbackOptions)
+ : this(options, fallbackOptions.GetIdeOptions())
+ {
+ }
+
+ // SimplifierOptions
+
+ public CodeStyleOption2 VarForBuiltInTypes => GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes, FallbackSimplifierOptions.VarForBuiltInTypes);
+ public CodeStyleOption2 VarWhenTypeIsApparent => GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, FallbackSimplifierOptions.VarWhenTypeIsApparent);
+ public CodeStyleOption2 VarElsewhere => GetOption(CSharpCodeStyleOptions.VarElsewhere, FallbackSimplifierOptions.VarElsewhere);
+ public CodeStyleOption2 PreferSimpleDefaultExpression => GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, FallbackSimplifierOptions.PreferSimpleDefaultExpression);
+ public CodeStyleOption2 PreferParameterNullChecking => GetOption(CSharpCodeStyleOptions.PreferParameterNullChecking, FallbackSimplifierOptions.PreferParameterNullChecking);
+ public CodeStyleOption2 AllowEmbeddedStatementsOnSameLine => GetOption(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, FallbackSimplifierOptions.AllowEmbeddedStatementsOnSameLine);
+ public CodeStyleOption2 PreferThrowExpression => GetOption(CSharpCodeStyleOptions.PreferThrowExpression, FallbackSimplifierOptions.PreferThrowExpression);
+ public CodeStyleOption2 PreferBraces => GetOption(CSharpCodeStyleOptions.PreferBraces, FallbackSimplifierOptions.PreferBraces);
+
+ internal CSharpSimplifierOptions GetSimplifierOptions()
+ => _options.GetCSharpSimplifierOptions(FallbackSimplifierOptions);
+
+ // SyntaxFormattingOptions
+
+ public CodeStyleOption2 NamespaceDeclarations => GetOption(CSharpCodeStyleOptions.NamespaceDeclarations, FallbackSyntaxFormattingOptions.NamespaceDeclarations);
+ public CodeStyleOption2 PreferTopLevelStatements => GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements, FallbackSyntaxFormattingOptions.PreferTopLevelStatements);
+
+ // AddImportPlacementOptions
+
+ public CodeStyleOption2 UsingDirectivePlacement => GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, FallbackAddImportPlacementOptions.UsingDirectivePlacement);
+
+ // CodeStyleOptions
+
+ public CodeStyleOption2 ImplicitObjectCreationWhenTypeIsApparent => GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, FallbackCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent);
+ public CodeStyleOption2 PreferNullCheckOverTypeCheck => GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, FallbackCodeStyleOptions.PreferNullCheckOverTypeCheck);
+ public CodeStyleOption2 AllowBlankLinesBetweenConsecutiveBraces => GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, FallbackCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces);
+ public CodeStyleOption2 AllowBlankLineAfterColonInConstructorInitializer => GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, FallbackCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer);
+ public CodeStyleOption2 PreferConditionalDelegateCall => GetOption(CSharpCodeStyleOptions.PreferConditionalDelegateCall, FallbackCodeStyleOptions.PreferConditionalDelegateCall);
+ public CodeStyleOption2 PreferSwitchExpression => GetOption(CSharpCodeStyleOptions.PreferSwitchExpression, FallbackCodeStyleOptions.PreferSwitchExpression);
+ public CodeStyleOption2 PreferPatternMatching => GetOption(CSharpCodeStyleOptions.PreferPatternMatching, FallbackCodeStyleOptions.PreferPatternMatching);
+ public CodeStyleOption2 PreferPatternMatchingOverAsWithNullCheck => GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, FallbackCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck);
+ public CodeStyleOption2 PreferPatternMatchingOverIsWithCastCheck => GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, FallbackCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck);
+ public CodeStyleOption2 PreferNotPattern => GetOption(CSharpCodeStyleOptions.PreferNotPattern, FallbackCodeStyleOptions.PreferNotPattern);
+ public CodeStyleOption2 PreferExtendedPropertyPattern => GetOption(CSharpCodeStyleOptions.PreferExtendedPropertyPattern, FallbackCodeStyleOptions.PreferExtendedPropertyPattern);
+ public CodeStyleOption2 PreferInlinedVariableDeclaration => GetOption(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, FallbackCodeStyleOptions.PreferInlinedVariableDeclaration);
+ public CodeStyleOption2 PreferDeconstructedVariableDeclaration => GetOption(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, FallbackCodeStyleOptions.PreferDeconstructedVariableDeclaration);
+ public CodeStyleOption2 PreferIndexOperator => GetOption(CSharpCodeStyleOptions.PreferIndexOperator, FallbackCodeStyleOptions.PreferIndexOperator);
+ public CodeStyleOption2 PreferRangeOperator => GetOption(CSharpCodeStyleOptions.PreferRangeOperator, FallbackCodeStyleOptions.PreferRangeOperator);
+ public CodeStyleOption2 PreferUtf8StringLiterals => GetOption(CSharpCodeStyleOptions.PreferUtf8StringLiterals, FallbackCodeStyleOptions.PreferUtf8StringLiterals);
+ public CodeStyleOption2 PreferredModifierOrder => GetOption(CSharpCodeStyleOptions.PreferredModifierOrder, FallbackCodeStyleOptions.PreferredModifierOrder);
+ public CodeStyleOption2 PreferSimpleUsingStatement => GetOption(CSharpCodeStyleOptions.PreferSimpleUsingStatement, FallbackCodeStyleOptions.PreferSimpleUsingStatement);
+ public CodeStyleOption2 PreferLocalOverAnonymousFunction => GetOption(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, FallbackCodeStyleOptions.PreferLocalOverAnonymousFunction);
+ public CodeStyleOption2 PreferTupleSwap => GetOption(CSharpCodeStyleOptions.PreferTupleSwap, FallbackCodeStyleOptions.PreferTupleSwap);
+ public CodeStyleOption2 UnusedValueExpressionStatement => GetOption(CSharpCodeStyleOptions.UnusedValueExpressionStatement, FallbackCodeStyleOptions.UnusedValueExpressionStatement);
+ public CodeStyleOption2 UnusedValueAssignment => GetOption(CSharpCodeStyleOptions.UnusedValueAssignment, FallbackCodeStyleOptions.UnusedValueAssignment);
+ public CodeStyleOption2 PreferMethodGroupConversion => GetOption(CSharpCodeStyleOptions.PreferMethodGroupConversion, FallbackCodeStyleOptions.PreferMethodGroupConversion);
+
+ // CodeGenerationOptions
+
+ internal CSharpCodeGenerationOptions GetCodeGenerationOptions()
+ => _options.GetCSharpCodeGenerationOptions(FallbackCodeGenerationOptions);
+
+ public CodeStyleOption2 PreferExpressionBodiedLambdas => GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, FallbackCodeStyleOptions.PreferExpressionBodiedLambdas);
+ public CodeStyleOption2 PreferStaticLocalFunction => GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction, FallbackCodeStyleOptions.PreferStaticLocalFunction);
+
+ private TValue GetOption(Option2 option, TValue defaultValue)
+ => _options.GetEditorConfigOption(option, defaultValue);
+
+ private CSharpIdeCodeStyleOptions FallbackCodeStyleOptions
+ => (CSharpIdeCodeStyleOptions?)_fallbackOptions.CodeStyleOptions ?? CSharpIdeCodeStyleOptions.Default;
+
+ private CSharpSimplifierOptions FallbackSimplifierOptions
+ => (CSharpSimplifierOptions?)_fallbackOptions.CleanupOptions?.SimplifierOptions ?? CSharpSimplifierOptions.Default;
+
+ private CSharpSyntaxFormattingOptions FallbackSyntaxFormattingOptions
+ => (CSharpSyntaxFormattingOptions?)_fallbackOptions.CleanupOptions?.FormattingOptions ?? CSharpSyntaxFormattingOptions.Default;
+
+ private AddImportPlacementOptions FallbackAddImportPlacementOptions
+ => _fallbackOptions.CleanupOptions?.AddImportOptions ?? AddImportPlacementOptions.Default;
+
+ private CSharpCodeGenerationOptions FallbackCodeGenerationOptions
+ => (CSharpCodeGenerationOptions?)_fallbackOptions.GenerationOptions ?? CSharpCodeGenerationOptions.Default;
+
+ public static explicit operator CSharpAnalyzerOptionsProvider(AnalyzerOptionsProvider provider)
+ => new(provider.GetAnalyzerConfigOptions(), provider.GetFallbackOptions());
+
+ public static implicit operator AnalyzerOptionsProvider(CSharpAnalyzerOptionsProvider provider)
+ => new(provider._options, provider._fallbackOptions);
+}
+
+internal static class CSharpAnalyzerOptionsProviders
+{
+ public static CSharpAnalyzerOptionsProvider GetCSharpAnalyzerOptions(this SemanticModelAnalysisContext context)
+ => new(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.SemanticModel.SyntaxTree), context.Options);
+
+ public static CSharpAnalyzerOptionsProvider GetCSharpAnalyzerOptions(this SyntaxNodeAnalysisContext context)
+ => new(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree), context.Options);
+
+ public static CSharpAnalyzerOptionsProvider GetCSharpAnalyzerOptions(this SyntaxTreeAnalysisContext context)
+ => new(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree), context.Options);
+
+ public static CSharpAnalyzerOptionsProvider GetCSharpAnalyzerOptions(this CodeBlockAnalysisContext context)
+ => new(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.SemanticModel.SyntaxTree), context.Options);
+
+ public static CSharpAnalyzerOptionsProvider GetCSharpAnalyzerOptions(this OperationAnalysisContext context)
+ => new(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Operation.Syntax.SyntaxTree), context.Options);
+}
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertNamespaceAnalysis.cs b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertNamespaceAnalysis.cs
index 7aa7dbbead3cd..05b9c965a7d68 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertNamespaceAnalysis.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertNamespaceAnalysis.cs
@@ -4,6 +4,7 @@
using System.Collections.Immutable;
using System.Linq;
+using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
@@ -27,12 +28,11 @@ public static (string title, string equivalenceKey) GetInfo(NamespaceDeclaration
_ => throw ExceptionUtilities.UnexpectedValue(preference),
};
- public static bool CanOfferUseBlockScoped(OptionSet optionSet, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer)
+ public static bool CanOfferUseBlockScoped(CodeStyleOption2 option, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer)
{
if (declaration is not FileScopedNamespaceDeclarationSyntax)
return false;
- var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations);
var userPrefersRegularNamespaces = option.Value == NamespaceDeclarationPreference.BlockScoped;
var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress;
var forRefactoring = !forAnalyzer;
@@ -44,11 +44,11 @@ public static bool CanOfferUseBlockScoped(OptionSet optionSet, BaseNamespaceDecl
return canOffer;
}
- internal static bool CanOfferUseFileScoped(OptionSet optionSet, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer)
- => CanOfferUseFileScoped(optionSet, root, declaration, forAnalyzer, root.SyntaxTree.Options.LanguageVersion());
+ internal static bool CanOfferUseFileScoped(CodeStyleOption2 option, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration, bool forAnalyzer)
+ => CanOfferUseFileScoped(option, root, declaration, forAnalyzer, root.SyntaxTree.Options.LanguageVersion());
internal static bool CanOfferUseFileScoped(
- OptionSet optionSet,
+ CodeStyleOption2 option,
CompilationUnitSyntax root,
BaseNamespaceDeclarationSyntax declaration,
bool forAnalyzer,
@@ -63,7 +63,6 @@ internal static bool CanOfferUseFileScoped(
if (version < LanguageVersion.CSharp10)
return false;
- var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations);
var userPrefersFileScopedNamespaces = option.Value == NamespaceDeclarationPreference.FileScoped;
var analyzerDisabled = option.Notification.Severity == ReportDiagnostic.Suppress;
var forRefactoring = !forAnalyzer;
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs
index 4b6d0dfef636e..b8288c97c4d5f 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToBlockScopedNamespaceDiagnosticAnalyzer.cs
@@ -36,24 +36,16 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeNamespace(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)context.Node;
- var syntaxTree = namespaceDeclaration.SyntaxTree;
- var cancellationToken = context.CancellationToken;
- var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
-
- var diagnostic = AnalyzeNamespace(optionSet, namespaceDeclaration);
+ var diagnostic = AnalyzeNamespace(context.GetCSharpAnalyzerOptions().NamespaceDeclarations, namespaceDeclaration);
if (diagnostic != null)
context.ReportDiagnostic(diagnostic);
}
- private Diagnostic? AnalyzeNamespace(OptionSet optionSet, FileScopedNamespaceDeclarationSyntax declaration)
+ private Diagnostic? AnalyzeNamespace(CodeStyleOption2 option, FileScopedNamespaceDeclarationSyntax declaration)
{
- var tree = declaration.SyntaxTree;
- var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations);
-
- if (!ConvertNamespaceAnalysis.CanOfferUseBlockScoped(optionSet, declaration, forAnalyzer: true))
+ if (!ConvertNamespaceAnalysis.CanOfferUseBlockScoped(option, declaration, forAnalyzer: true))
return null;
// if the diagnostic is hidden, show it anywhere from the `namespace` keyword through the name.
@@ -61,7 +53,7 @@ private void AnalyzeNamespace(SyntaxNodeAnalysisContext context)
var severity = option.Notification.Severity;
var diagnosticLocation = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) != ReportDiagnostic.Hidden
? declaration.Name.GetLocation()
- : tree.GetLocation(TextSpan.FromBounds(declaration.SpanStart, declaration.SemicolonToken.Span.End));
+ : declaration.SyntaxTree.GetLocation(TextSpan.FromBounds(declaration.SpanStart, declaration.SemicolonToken.Span.End));
return DiagnosticHelper.Create(
this.Descriptor,
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs
index 2f8ed54e81d6f..a1b53d61f3b65 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertNamespace/ConvertToFileScopedNamespaceDiagnosticAnalyzer.cs
@@ -36,26 +36,20 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeNamespace(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
var namespaceDeclaration = (NamespaceDeclarationSyntax)context.Node;
var syntaxTree = namespaceDeclaration.SyntaxTree;
var cancellationToken = context.CancellationToken;
var root = (CompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken);
- var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
-
- var diagnostic = AnalyzeNamespace(optionSet, root, namespaceDeclaration);
+ var diagnostic = AnalyzeNamespace(context.GetCSharpAnalyzerOptions().NamespaceDeclarations, root, namespaceDeclaration);
if (diagnostic != null)
context.ReportDiagnostic(diagnostic);
}
- private Diagnostic? AnalyzeNamespace(OptionSet optionSet, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration)
+ private Diagnostic? AnalyzeNamespace(CodeStyleOption2 option, CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax declaration)
{
- var tree = declaration.SyntaxTree;
- var option = optionSet.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations);
-
- if (!ConvertNamespaceAnalysis.CanOfferUseFileScoped(optionSet, root, declaration, forAnalyzer: true))
+ if (!ConvertNamespaceAnalysis.CanOfferUseFileScoped(option, root, declaration, forAnalyzer: true))
return null;
// if the diagnostic is hidden, show it anywhere from the `namespace` keyword through the name.
@@ -63,7 +57,7 @@ private void AnalyzeNamespace(SyntaxNodeAnalysisContext context)
var severity = option.Notification.Severity;
var diagnosticLocation = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) != ReportDiagnostic.Hidden
? declaration.Name.GetLocation()
- : tree.GetLocation(TextSpan.FromBounds(declaration.SpanStart, declaration.Name.Span.End));
+ : declaration.SyntaxTree.GetLocation(TextSpan.FromBounds(declaration.SpanStart, declaration.Name.Span.End));
return DiagnosticHelper.Create(
this.Descriptor,
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToProgramMainDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToProgramMainDiagnosticAnalyzer.cs
index 8822bc3889bc4..65a76845f21e6 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToProgramMainDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToProgramMainDiagnosticAnalyzer.cs
@@ -42,11 +42,8 @@ protected override void InitializeWorker(AnalysisContext context)
private void ProcessCompilationUnit(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
var root = (CompilationUnitSyntax)context.Node;
-
- var optionSet = options.GetAnalyzerOptionSet(root.SyntaxTree, context.CancellationToken);
- var option = optionSet.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements);
+ var option = context.GetCSharpAnalyzerOptions().PreferTopLevelStatements;
if (!CanOfferUseProgramMain(option, root, context.Compilation, forAnalyzer: true))
return;
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToTopLevelStatementsDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToTopLevelStatementsDiagnosticAnalyzer.cs
index 7a668226ddbbb..a432c494c0491 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToTopLevelStatementsDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertProgram/ConvertToTopLevelStatementsDiagnosticAnalyzer.cs
@@ -48,12 +48,8 @@ protected override void InitializeWorker(AnalysisContext context)
private void ProcessCompilationUnit(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
- var root = (CompilationUnitSyntax)context.Node;
-
// Don't want to suggest moving if the user doesn't have a preference for top-level-statements.
- var optionSet = options.GetAnalyzerOptionSet(root.SyntaxTree, context.CancellationToken);
- var option = optionSet.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements);
+ var option = context.GetCSharpAnalyzerOptions().PreferTopLevelStatements;
if (!CanOfferUseTopLevelStatements(option, forAnalyzer: true))
return;
@@ -64,6 +60,7 @@ private void ProcessCompilationUnit(SyntaxNodeAnalysisContext context)
// Ok, the user does like top level statements. Check if we can find a suitable hit in this type that
// indicates we're on the entrypoint of the program.
+ var root = (CompilationUnitSyntax)context.Node;
var methodDeclarations = root.DescendantNodes(n => n is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax or ClassDeclarationSyntax).OfType();
foreach (var methodDeclaration in methodDeclarations)
{
diff --git a/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs
index c564bd3b73b80..7907456bd8568 100644
--- a/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs
@@ -7,6 +7,7 @@
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -40,19 +41,14 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
- var switchStatement = context.Node;
- var syntaxTree = switchStatement.SyntaxTree;
-
- var options = context.Options;
- var cancellationToken = context.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferSwitchExpression, syntaxTree, cancellationToken);
+ var styleOption = context.GetCSharpAnalyzerOptions().PreferSwitchExpression;
if (!styleOption.Value)
{
// User has disabled this feature.
return;
}
+ var switchStatement = context.Node;
if (switchStatement.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
{
return;
diff --git a/src/Analyzers/CSharp/Analyzers/InlineDeclaration/CSharpInlineDeclarationDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/InlineDeclaration/CSharpInlineDeclarationDiagnosticAnalyzer.cs
index 958e0a7e64a85..7f1cc89fb341b 100644
--- a/src/Analyzers/CSharp/Analyzers/InlineDeclaration/CSharpInlineDeclarationDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/InlineDeclaration/CSharpInlineDeclarationDiagnosticAnalyzer.cs
@@ -8,6 +8,7 @@
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -59,25 +60,22 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol? expressionType)
{
- var argumentNode = (ArgumentSyntax)context.Node;
- var csOptions = (CSharpParseOptions)context.Node.SyntaxTree.Options;
+ var syntaxTree = context.Node.SyntaxTree;
+ var csOptions = (CSharpParseOptions)syntaxTree.Options;
if (csOptions.LanguageVersion < LanguageVersion.CSharp7)
{
// out-vars are not supported prior to C# 7.0.
return;
}
- var options = context.Options;
- var syntaxTree = context.Node.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- var option = options.GetOption(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, syntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferInlinedVariableDeclaration;
if (!option.Value)
{
// Don't bother doing any work if the user doesn't even have this preference set.
return;
}
+ var argumentNode = (ArgumentSyntax)context.Node;
if (argumentNode.RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
// Immediately bail if this is not an out-argument. If it's not an out-argument
@@ -122,6 +120,8 @@ private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context, INamedTypeSymb
return;
}
+ var cancellationToken = context.CancellationToken;
+
var semanticModel = context.SemanticModel;
if (semanticModel.GetSymbolInfo(argumentExpression, cancellationToken).Symbol is not ILocalSymbol outLocalSymbol)
{
diff --git a/src/Analyzers/CSharp/Analyzers/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessAnalyzer.cs
index 6a4ef5206002c..ba4751097221a 100644
--- a/src/Analyzers/CSharp/Analyzers/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessAnalyzer.cs
@@ -5,6 +5,7 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -37,19 +38,13 @@ protected override void InitializeWorker(AnalysisContext context)
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
- var options = syntaxContext.Options;
- var syntaxTree = syntaxContext.Node.SyntaxTree;
- var cancellationToken = syntaxContext.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferConditionalDelegateCall, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferConditionalDelegateCall;
if (!styleOption.Value)
{
- // Bail immediately if the user has disabled this feature.
+ // Bail if the user has disabled this feature.
return;
}
- var severity = styleOption.Notification.Severity;
-
// look for the form "if (a != null)" or "if (null != a)"
var ifStatement = (IfStatementSyntax)syntaxContext.Node;
@@ -93,6 +88,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
return;
}
+ var severity = styleOption.Notification.Severity;
var condition = (BinaryExpressionSyntax)ifStatement.Condition;
if (TryCheckVariableAndIfStatementForm(
syntaxContext, ifStatement, condition,
diff --git a/src/Analyzers/CSharp/Analyzers/MakeLocalFunctionStatic/MakeLocalFunctionStaticDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/MakeLocalFunctionStatic/MakeLocalFunctionStaticDiagnosticAnalyzer.cs
index 045a203d9e77e..47bb26366544d 100644
--- a/src/Analyzers/CSharp/Analyzers/MakeLocalFunctionStatic/MakeLocalFunctionStaticDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/MakeLocalFunctionStatic/MakeLocalFunctionStaticDiagnosticAnalyzer.cs
@@ -42,9 +42,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
return;
}
- var syntaxTree = context.Node.SyntaxTree;
- var cancellationToken = context.CancellationToken;
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction, syntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferStaticLocalFunction;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/CSharp/Analyzers/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs
index 6c3993d33454c..3ad7b5d86f483 100644
--- a/src/Analyzers/CSharp/Analyzers/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs
@@ -56,7 +56,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context)
{
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, context.Node.SyntaxTree, context.CancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().UsingDirectivePlacement;
if (option.Value != AddImportPlacement.OutsideNamespace)
return;
@@ -66,7 +66,7 @@ private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context)
private static void AnalyzeCompilationUnitNode(SyntaxNodeAnalysisContext context)
{
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, context.Node.SyntaxTree, context.CancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().UsingDirectivePlacement;
var compilationUnit = (CompilationUnitSyntax)context.Node;
if (option.Value != AddImportPlacement.InsideNamespace
diff --git a/src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.cs
index dcd1369de5365..156d3ff51486c 100644
--- a/src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/NewLines/ConsecutiveBracePlacement/ConsecutiveBracePlacementDiagnosticAnalyzer.cs
@@ -6,6 +6,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
@@ -33,7 +34,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
- var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces);
+ var option = context.GetCSharpAnalyzerOptions().AllowBlankLinesBetweenConsecutiveBraces;
if (option.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.cs
index c43f692c79b48..2eb320a8024ad 100644
--- a/src/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementDiagnosticAnalyzer.cs
@@ -7,6 +7,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -34,7 +35,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
- var option = context.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer);
+ var option = context.GetCSharpAnalyzerOptions().AllowBlankLineAfterColonInConstructorInitializer;
if (option.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementDiagnosticAnalyzer.cs
index e39cde3804d3e..830a990ece23d 100644
--- a/src/Analyzers/CSharp/Analyzers/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementDiagnosticAnalyzer.cs
@@ -7,6 +7,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -33,7 +34,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
- var option = context.GetOption(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine);
+ var option = context.GetCSharpAnalyzerOptions().AllowEmbeddedStatementsOnSameLine;
if (option.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
index 2f5a2f6cebd85..84d285e5bdda7 100644
--- a/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
@@ -3,7 +3,9 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -22,6 +24,9 @@ public CSharpOrderModifiersDiagnosticAnalyzer()
{
}
+ protected override CodeStyleOption2 GetPreferredOrderStyle(SyntaxTreeAnalysisContext context)
+ => context.GetCSharpAnalyzerOptions().PreferredModifierOrder;
+
protected override void Recurse(
SyntaxTreeAnalysisContext context,
Dictionary preferredOrder,
diff --git a/src/Analyzers/CSharp/Analyzers/QualifyMemberAccess/CSharpQualifyMemberAccessDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/QualifyMemberAccess/CSharpQualifyMemberAccessDiagnosticAnalyzer.cs
index e180a2c800faa..6417e85a8a9ef 100644
--- a/src/Analyzers/CSharp/Analyzers/QualifyMemberAccess/CSharpQualifyMemberAccessDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/QualifyMemberAccess/CSharpQualifyMemberAccessDiagnosticAnalyzer.cs
@@ -9,18 +9,19 @@
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.QualifyMemberAccess;
using Microsoft.CodeAnalysis.Shared.Extensions;
+using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpQualifyMemberAccessDiagnosticAnalyzer
- : AbstractQualifyMemberAccessDiagnosticAnalyzer
+ : AbstractQualifyMemberAccessDiagnosticAnalyzer
{
protected override string GetLanguageName()
=> LanguageNames.CSharp;
- protected override CSharpSimplifierOptions GetSimplifierOptions(AnalyzerOptions options, SyntaxTree syntaxTree)
- => options.GetCSharpSimplifierOptions(syntaxTree);
+ protected override ISimplification Simplification
+ => CSharpSimplification.Instance;
protected override bool IsAlreadyQualifiedMemberAccess(ExpressionSyntax node)
=> node.IsKind(SyntaxKind.ThisExpression);
diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
index 25cf721c05f31..b814e0258ae14 100644
--- a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryLambdaExpression/CSharpRemoveUnnecessaryLambdaExpressionDiagnosticAnalyzer.cs
@@ -9,6 +9,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -62,7 +63,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol?
var semanticModel = context.SemanticModel;
var syntaxTree = semanticModel.SyntaxTree;
- var preference = context.GetOption(CSharpCodeStyleOptions.PreferMethodGroupConversion);
+ var preference = context.GetCSharpAnalyzerOptions().PreferMethodGroupConversion;
if (preference.Notification.Severity == ReportDiagnostic.Suppress)
{
// User doesn't care about this rule.
diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
index 27d4df2cb6859..ba8cd581eaa65 100644
--- a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
@@ -40,7 +40,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
- var fadeCode = context.Options.GetIdeOptions().FadeOutUnreachableCode;
+ var fadeCode = context.GetIdeAnalyzerOptions().FadeOutUnreachableCode;
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
index acca9e9d33600..49aa7b1def4c5 100644
--- a/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -12,7 +13,7 @@
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- internal class CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer : AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer
+ internal sealed class CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer : AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer
{
public CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer()
: base(unusedValueExpressionStatementOption: CSharpCodeStyleOptions.UnusedValueExpressionStatement,
@@ -33,6 +34,12 @@ protected override bool MethodHasHandlesClause(IMethodSymbol method)
protected override bool IsIfConditionalDirective(SyntaxNode node)
=> node is IfDirectiveTriviaSyntax;
+ protected override CodeStyleOption2 GetUnusedValueExpressionStatementOption(AnalyzerOptionsProvider provider)
+ => ((CSharpAnalyzerOptionsProvider)provider).UnusedValueExpressionStatement;
+
+ protected override CodeStyleOption2 GetUnusedValueAssignmentOption(AnalyzerOptionsProvider provider)
+ => ((CSharpAnalyzerOptionsProvider)provider).UnusedValueAssignment;
+
protected override bool ShouldBailOutFromRemovableAssignmentAnalysis(IOperation unusedSymbolWriteOperation)
{
// We don't want to recommend removing the write operation if it is within a statement
diff --git a/src/Analyzers/CSharp/Analyzers/Simplification/CSharpSimplifierOptionsFactory.cs b/src/Analyzers/CSharp/Analyzers/Simplification/CSharpSimplifierOptionsFactory.cs
deleted file mode 100644
index b931a6d3236c4..0000000000000
--- a/src/Analyzers/CSharp/Analyzers/Simplification/CSharpSimplifierOptionsFactory.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.CodeAnalysis.Diagnostics;
-using Roslyn.Utilities;
-
-namespace Microsoft.CodeAnalysis.CSharp.Simplification;
-
-internal static class CSharpSimplifierOptionsFactory
-{
- internal static CSharpSimplifierOptions GetCSharpSimplifierOptions(this AnalyzerOptions options, SyntaxTree syntaxTree)
- {
- var configOptions = options.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree);
- var ideOptions = options.GetIdeOptions();
-
-#if CODE_STYLE
- var fallbackOptions = (CSharpSimplifierOptions?)null;
-#else
- var fallbackOptions = (CSharpSimplifierOptions?)ideOptions.CleanupOptions?.SimplifierOptions;
-#endif
- return CSharpSimplifierOptions.Create(configOptions, fallbackOptions);
- }
-}
diff --git a/src/Analyzers/CSharp/Analyzers/SimplifyPropertyPattern/CSharpSimplifyPropertyPatternDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/SimplifyPropertyPattern/CSharpSimplifyPropertyPatternDiagnosticAnalyzer.cs
index b8c23b4bae93e..7259fff8ccd45 100644
--- a/src/Analyzers/CSharp/Analyzers/SimplifyPropertyPattern/CSharpSimplifyPropertyPatternDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/SimplifyPropertyPattern/CSharpSimplifyPropertyPatternDiagnosticAnalyzer.cs
@@ -52,12 +52,8 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSubpattern(SyntaxNodeAnalysisContext syntaxContext)
{
- var options = syntaxContext.Options;
- var syntaxTree = syntaxContext.Node.SyntaxTree;
- var cancellationToken = syntaxContext.CancellationToken;
-
// Bail immediately if the user has disabled this feature.
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferExtendedPropertyPattern, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferExtendedPropertyPattern;
if (!styleOption.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
index 2d69dba72b897..141ecd5ab5388 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs
@@ -43,7 +43,7 @@ private void AnalyzeCoalesceExpression(SyntaxNodeAnalysisContext context)
var coalesceExpression = (BinaryExpressionSyntax)context.Node;
- var option = context.GetOption(CodeStyleOptions2.PreferCompoundAssignment, coalesceExpression.Language);
+ var option = context.GetAnalyzerOptions().PreferCompoundAssignment;
// Bail immediately if the user has disabled this feature.
if (!option.Value)
diff --git a/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
index f307fd5d2ca39..d91b1fa484072 100644
--- a/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseDeconstruction/CSharpUseDeconstructionDiagnosticAnalyzer.cs
@@ -42,8 +42,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
- var cancellationToken = context.CancellationToken;
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, context.Node.SyntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferDeconstructedVariableDeclaration;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs
index ba272b9522e9a..45e9ec0c6c5c9 100644
--- a/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs
@@ -35,7 +35,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var cancellationToken = context.CancellationToken;
var syntaxTree = context.Node.SyntaxTree;
- var preference = context.Options.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, syntaxTree, cancellationToken);
+ var preference = context.GetCSharpAnalyzerOptions().PreferSimpleDefaultExpression;
var parseOptions = (CSharpParseOptions)syntaxTree.Options;
var defaultExpression = (DefaultExpressionSyntax)context.Node;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs
index a059441051ba5..9873326d450e2 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs
@@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -24,6 +26,9 @@ private UseExpressionBodyForAccessorsHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedAccessors;
+
protected override BlockSyntax? GetBody(AccessorDeclarationSyntax declaration)
=> declaration.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs
index 1cc4dc3bb8219..f4594ebec841f 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs
@@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -24,6 +26,9 @@ private UseExpressionBodyForConstructorsHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedConstructors;
+
protected override BlockSyntax? GetBody(ConstructorDeclarationSyntax declaration)
=> declaration.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs
index fc12ad3102e70..cbeeaa26d4e8f 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs
@@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -24,6 +26,9 @@ private UseExpressionBodyForConversionOperatorsHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedOperators;
+
protected override BlockSyntax? GetBody(ConversionOperatorDeclarationSyntax declaration)
=> declaration.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs
index b5327f6e4bf1a..172a3494e6165 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs
@@ -7,6 +7,7 @@
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -28,6 +29,9 @@ private UseExpressionBodyForIndexersHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedIndexers;
+
protected override BlockSyntax GetBody(IndexerDeclarationSyntax declaration)
=> GetBodyFromSingleGetAccessor(declaration.AccessorList);
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
index 5dd65fd98daaf..f5db5c1bf4288 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs
@@ -5,6 +5,8 @@
#nullable disable
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -27,6 +29,9 @@ private UseExpressionBodyForLocalFunctionHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedLocalFunctions;
+
protected override BlockSyntax GetBody(LocalFunctionStatementSyntax statement)
=> statement.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
index 6484dc079e4ac..3cfd363852a1d 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs
@@ -5,6 +5,8 @@
#nullable disable
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -27,6 +29,9 @@ private UseExpressionBodyForMethodsHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedMethods;
+
protected override BlockSyntax GetBody(MethodDeclarationSyntax declaration)
=> declaration.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs
index e5c33d59906c5..644c5f0ac6a54 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs
@@ -5,6 +5,8 @@
#nullable disable
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -26,6 +28,9 @@ private UseExpressionBodyForOperatorsHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedOperators;
+
protected override BlockSyntax GetBody(OperatorDeclarationSyntax declaration)
=> declaration.Body;
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs
index 53066d7605658..8e7730e35ca1b 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs
@@ -7,6 +7,7 @@
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -28,6 +29,9 @@ private UseExpressionBodyForPropertiesHelper()
{
}
+ public override CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options)
+ => options.PreferExpressionBodiedProperties;
+
protected override BlockSyntax GetBody(PropertyDeclarationSyntax declaration)
=> GetBodyFromSingleGetAccessor(declaration.AccessorList);
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs
index cb2b176770a5f..20feb442061c1 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs
@@ -7,10 +7,7 @@
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Diagnostics.CodeAnalysis;
-
-#if CODE_STYLE
-using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
-#endif
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
@@ -23,11 +20,12 @@ internal abstract class UseExpressionBodyHelper
public abstract EnforceOnBuild EnforceOnBuild { get; }
public abstract ImmutableArray SyntaxKinds { get; }
+ public abstract CodeStyleOption2 GetExpressionBodyPreference(CSharpCodeGenerationOptions options);
public abstract BlockSyntax? GetBody(SyntaxNode declaration);
public abstract ArrowExpressionClauseSyntax? GetExpressionBody(SyntaxNode declaration);
- public abstract bool CanOfferUseExpressionBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer);
- public abstract bool CanOfferUseBlockBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer, out bool fixesError, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? expressionBody);
+ public abstract bool CanOfferUseExpressionBody(CodeStyleOption2 preference, SyntaxNode declaration, bool forAnalyzer);
+ public abstract bool CanOfferUseBlockBody(CodeStyleOption2 preference, SyntaxNode declaration, bool forAnalyzer, out bool fixesError, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? expressionBody);
public abstract SyntaxNode Update(SemanticModel semanticModel, SyntaxNode declaration, bool useExpressionBody);
public abstract Location GetDiagnosticLocation(SyntaxNode declaration);
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs
index b8f2049c95638..3db4ec9edf106 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs
@@ -7,6 +7,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -72,11 +73,11 @@ protected UseExpressionBodyHelper(
public override ArrowExpressionClauseSyntax? GetExpressionBody(SyntaxNode declaration)
=> GetExpressionBody((TDeclaration)declaration);
- public override bool CanOfferUseExpressionBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer)
- => CanOfferUseExpressionBody(optionSet, (TDeclaration)declaration, forAnalyzer);
+ public override bool CanOfferUseExpressionBody(CodeStyleOption2 preference, SyntaxNode declaration, bool forAnalyzer)
+ => CanOfferUseExpressionBody(preference, (TDeclaration)declaration, forAnalyzer);
- public override bool CanOfferUseBlockBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer, out bool fixesError, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? expressionBody)
- => CanOfferUseBlockBody(optionSet, (TDeclaration)declaration, forAnalyzer, out fixesError, out expressionBody);
+ public override bool CanOfferUseBlockBody(CodeStyleOption2 preference, SyntaxNode declaration, bool forAnalyzer, out bool fixesError, [NotNullWhen(true)] out ArrowExpressionClauseSyntax? expressionBody)
+ => CanOfferUseBlockBody(preference, (TDeclaration)declaration, forAnalyzer, out fixesError, out expressionBody);
public sealed override SyntaxNode Update(SemanticModel semanticModel, SyntaxNode declaration, bool useExpressionBody)
=> Update(semanticModel, (TDeclaration)declaration, useExpressionBody);
@@ -92,12 +93,10 @@ protected virtual Location GetDiagnosticLocation(TDeclaration declaration)
}
public bool CanOfferUseExpressionBody(
- OptionSet optionSet, TDeclaration declaration, bool forAnalyzer)
+ CodeStyleOption2 preference, TDeclaration declaration, bool forAnalyzer)
{
- var currentOptionValue = optionSet.GetOption(Option);
- var preference = currentOptionValue.Value;
- var userPrefersExpressionBodies = preference != ExpressionBodyPreference.Never;
- var analyzerDisabled = currentOptionValue.Notification.Severity == ReportDiagnostic.Suppress;
+ var userPrefersExpressionBodies = preference.Value != ExpressionBodyPreference.Never;
+ var analyzerDisabled = preference.Notification.Severity == ReportDiagnostic.Suppress;
// If the user likes expression bodies, then we offer expression bodies from the diagnostic analyzer.
// If the user does not like expression bodies then we offer expression bodies from the refactoring provider.
@@ -110,7 +109,7 @@ public bool CanOfferUseExpressionBody(
// They don't have an expression body. See if we could convert the block they
// have into one.
- var conversionPreference = forAnalyzer ? preference : ExpressionBodyPreference.WhenPossible;
+ var conversionPreference = forAnalyzer ? preference.Value : ExpressionBodyPreference.WhenPossible;
return TryConvertToExpressionBody(declaration, conversionPreference,
expressionWhenOnSingleLine: out _, semicolonWhenOnSingleLine: out _);
@@ -174,16 +173,14 @@ protected bool TryConvertToExpressionBodyForBaseProperty(
}
public bool CanOfferUseBlockBody(
- OptionSet optionSet,
+ CodeStyleOption2 preference,
TDeclaration declaration,
bool forAnalyzer,
out bool fixesError,
[NotNullWhen(true)] out ArrowExpressionClauseSyntax? expressionBody)
{
- var currentOptionValue = optionSet.GetOption(Option);
- var preference = currentOptionValue.Value;
- var userPrefersBlockBodies = preference == ExpressionBodyPreference.Never;
- var analyzerDisabled = currentOptionValue.Notification.Severity == ReportDiagnostic.Suppress;
+ var userPrefersBlockBodies = preference.Value == ExpressionBodyPreference.Never;
+ var analyzerDisabled = preference.Notification.Severity == ReportDiagnostic.Suppress;
expressionBody = GetExpressionBody(declaration);
if (expressionBody?.TryConvertToBlock(
diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
index f3de1871fe248..8d3703f1e526e 100644
--- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs
@@ -4,7 +4,9 @@
using System.Collections.Immutable;
using System.Linq;
+using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
@@ -50,10 +52,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
- var syntaxTree = context.Node.SyntaxTree;
- var cancellationToken = context.CancellationToken;
- var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
+ var options = context.GetCSharpAnalyzerOptions().GetCodeGenerationOptions();
var nodeKind = context.Node.Kind();
@@ -63,13 +62,13 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var grandparent = context.Node.GetRequiredParent().GetRequiredParent();
if (grandparent.Kind() == SyntaxKind.PropertyDeclaration &&
- AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForPropertiesHelper.Instance) != null)
+ AnalyzeSyntax(options, grandparent, UseExpressionBodyForPropertiesHelper.Instance) != null)
{
return;
}
if (grandparent.Kind() == SyntaxKind.IndexerDeclaration &&
- AnalyzeSyntax(optionSet, grandparent, UseExpressionBodyForIndexersHelper.Instance) != null)
+ AnalyzeSyntax(options, grandparent, UseExpressionBodyForIndexersHelper.Instance) != null)
{
return;
}
@@ -79,7 +78,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
if (helper.SyntaxKinds.Contains(nodeKind))
{
- var diagnostic = AnalyzeSyntax(optionSet, context.Node, helper);
+ var diagnostic = AnalyzeSyntax(options, context.Node, helper);
if (diagnostic != null)
{
context.ReportDiagnostic(diagnostic);
@@ -90,12 +89,12 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
}
private static Diagnostic? AnalyzeSyntax(
- OptionSet optionSet, SyntaxNode declaration, UseExpressionBodyHelper helper)
+ CSharpCodeGenerationOptions options, SyntaxNode declaration, UseExpressionBodyHelper helper)
{
- var preferExpressionBodiedOption = optionSet.GetOption(helper.Option);
- var severity = preferExpressionBodiedOption.Notification.Severity;
+ var preference = helper.GetExpressionBodyPreference(options);
+ var severity = preference.Notification.Severity;
- if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: true))
+ if (helper.CanOfferUseExpressionBody(preference, declaration, forAnalyzer: true))
{
var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden
? declaration.GetLocation()
@@ -108,7 +107,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
location, severity, additionalLocations: additionalLocations, properties: properties);
}
- if (helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: true, out var fixesError, out var expressionBody))
+ if (helper.CanOfferUseBlockBody(preference, declaration, forAnalyzer: true, out var fixesError, out var expressionBody))
{
// They have an expression body. Create a diagnostic to convert it to a block
// if they don't want expression bodies for this member.
diff --git a/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs
index 71af8d9bad828..a7562d39f6354 100644
--- a/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs
@@ -37,16 +37,13 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
- var options = context.Options;
var syntaxTree = context.Node.SyntaxTree;
- var semanticModel = context.SemanticModel;
- var cancellationToken = context.CancellationToken;
// Not available prior to C# 9.
if (syntaxTree.Options.LanguageVersion() < LanguageVersion.CSharp9)
return;
- var styleOption = options.GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, syntaxTree, cancellationToken);
+ var styleOption = context.GetCSharpAnalyzerOptions().ImplicitObjectCreationWhenTypeIsApparent;
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
@@ -65,6 +62,8 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var objectCreation = (ObjectCreationExpressionSyntax)context.Node;
TypeSyntax? typeNode;
+ var semanticModel = context.SemanticModel;
+ var cancellationToken = context.CancellationToken;
if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
@@ -76,7 +75,7 @@ objectCreation.Parent.Parent.Parent is VariableDeclarationSyntax variableDeclara
var helper = CSharpUseImplicitTypeHelper.Instance;
if (helper.ShouldAnalyzeVariableDeclaration(variableDeclaration, cancellationToken))
{
- var simplifierOptions = context.Options.GetCSharpSimplifierOptions(syntaxTree);
+ var simplifierOptions = context.GetCSharpAnalyzerOptions().GetSimplifierOptions();
if (helper.AnalyzeTypeName(typeNode, semanticModel, simplifierOptions, cancellationToken).IsStylePreferred)
{
diff --git a/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs b/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
index 61b66eb9d4c92..6f976b6947d45 100644
--- a/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs
@@ -55,7 +55,6 @@ protected override void InitializeWorker(AnalysisContext context)
private void HandleVariableDeclaration(SyntaxNodeAnalysisContext context)
{
var declarationStatement = context.Node;
- var syntaxTree = context.Node.SyntaxTree;
var cancellationToken = context.CancellationToken;
var semanticModel = context.SemanticModel;
@@ -65,7 +64,7 @@ private void HandleVariableDeclaration(SyntaxNodeAnalysisContext context)
return;
}
- var simplifierOptions = context.Options.GetCSharpSimplifierOptions(syntaxTree);
+ var simplifierOptions = context.GetCSharpAnalyzerOptions().GetSimplifierOptions();
var typeStyle = Helper.AnalyzeTypeName(
declaredType, semanticModel, simplifierOptions, cancellationToken);
diff --git a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.cs
index a5cca6b434aaa..370ab9d158fd8 100644
--- a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.cs
@@ -177,7 +177,7 @@ private void AnalyzeInvokedMember(
return;
// Don't bother analyzing if the user doesn't like using Index/Range operators.
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferIndexOperator, binaryExpression.SyntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferIndexOperator;
if (!option.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
index c446d62bb52ae..99d59c8b0719f 100644
--- a/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
@@ -74,23 +74,19 @@ protected override void InitializeWorker(AnalysisContext context)
});
}
- private void AnalyzeInvocation(
- OperationAnalysisContext context, InfoCache infoCache)
+ private void AnalyzeInvocation(OperationAnalysisContext context, InfoCache infoCache)
{
- var operation = context.Operation;
- var syntaxTree = operation.SemanticModel!.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
// Check if the user wants these operators.
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferRangeOperator, syntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferRangeOperator;
if (!option.Value)
return;
+ var operation = context.Operation;
var result = AnalyzeInvocation((IInvocationOperation)operation, infoCache);
if (result == null)
return;
- if (CSharpSemanticFacts.Instance.IsInExpressionTree(operation.SemanticModel, operation.Syntax, infoCache.ExpressionOfTType, cancellationToken))
+ if (CSharpSemanticFacts.Instance.IsInExpressionTree(operation.SemanticModel, operation.Syntax, infoCache.ExpressionOfTType, context.CancellationToken))
return;
context.ReportDiagnostic(CreateDiagnostic(result.Value, option.Notification.Severity));
diff --git a/src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
index 8eddca62e9f03..694fa3e91ee03 100644
--- a/src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
@@ -21,29 +21,29 @@ internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUs
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals);
- protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken)
+ protected override void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
switch (context.Node.Kind())
{
case SyntaxKind.NameColon:
- ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken);
+ ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context);
break;
case SyntaxKind.NameEquals:
- ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken);
+ ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context);
break;
}
}
- private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken)
+ private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context)
{
if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument))
{
return;
}
+ var syntaxTree = context.Node.SyntaxTree;
var parseOptions = (CSharpParseOptions)syntaxTree.Options;
- var preference = options.GetOption(
- CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken);
+ var preference = context.GetAnalyzerOptions().PreferInferredTupleNames;
if (!preference.Value ||
!CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions))
{
@@ -61,15 +61,14 @@ private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnal
additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan))));
}
- private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken)
+ private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context)
{
if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor))
{
return;
}
- var preference = options.GetOption(
- CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken);
+ var preference = context.GetAnalyzerOptions().PreferInferredAnonymousTypeMemberNames;
if (!preference.Value ||
!CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor))
{
@@ -84,7 +83,7 @@ private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAn
nameEquals.GetLocation(),
preference.Notification.Severity,
additionalLocations: ImmutableArray.Empty,
- additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan))));
+ additionalUnnecessaryLocations: ImmutableArray.Create(context.Node.SyntaxTree.GetLocation(fadeSpan))));
}
}
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
index 65fa7ec208d27..97d8fb93e8a37 100644
--- a/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs
@@ -43,18 +43,14 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
- var cancellationToken = context.CancellationToken;
-
- var semanticModel = context.SemanticModel;
- var syntaxTree = semanticModel.SyntaxTree;
-
- var option = context.Options.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language, syntaxTree, cancellationToken);
+ var option = context.GetAnalyzerOptions().PreferIsNullCheckOverReferenceEqualityMethod;
if (!option.Value)
{
return;
}
var binaryExpression = (BinaryExpressionSyntax)context.Node;
+ var semanticModel = context.SemanticModel;
if (!IsObjectCastAndNullCheck(semanticModel, binaryExpression.Left, binaryExpression.Right) &&
!IsObjectCastAndNullCheck(semanticModel, binaryExpression.Right, binaryExpression.Left))
diff --git a/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs
index 5ebc11a04aa7d..5ef4c84b979a2 100644
--- a/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs
@@ -44,7 +44,7 @@ protected override void InitializeWorker(AnalysisContext context)
private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity)
{
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferNullCheckOverTypeCheck;
if (!option.Value)
{
severity = ReportDiagnostic.Default;
diff --git a/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
index 0a744ffc75192..870167cfb603f 100644
--- a/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseLocalFunction/CSharpUseLocalFunctionDiagnosticAnalyzer.cs
@@ -70,11 +70,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext, INamedTypeSymbol? expressionType)
{
- var options = syntaxContext.Options;
- var syntaxTree = syntaxContext.Node.SyntaxTree;
- var cancellationToken = syntaxContext.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferLocalOverAnonymousFunction;
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
@@ -108,6 +104,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext, INamedTyp
return;
}
+ var cancellationToken = syntaxContext.CancellationToken;
var local = semanticModel.GetDeclaredSymbol(localDeclaration.Declaration.Variables[0], cancellationToken);
if (local == null)
{
diff --git a/src/Analyzers/CSharp/Analyzers/UseParameterNullChecking/CSharpUseParameterNullCheckingDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseParameterNullChecking/CSharpUseParameterNullCheckingDiagnosticAnalyzer.cs
index e6402204cebb3..b3725c399473d 100644
--- a/src/Analyzers/CSharp/Analyzers/UseParameterNullChecking/CSharpUseParameterNullCheckingDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseParameterNullChecking/CSharpUseParameterNullCheckingDiagnosticAnalyzer.cs
@@ -102,12 +102,7 @@ private void AnalyzeSyntax(
IMethodSymbol argumentNullExceptionStringConstructor,
IMethodSymbol? referenceEqualsMethod)
{
- var cancellationToken = context.CancellationToken;
-
- var semanticModel = context.SemanticModel;
- var syntaxTree = semanticModel.SyntaxTree;
-
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferParameterNullChecking, syntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferParameterNullChecking;
if (!option.Value)
{
return;
@@ -131,6 +126,9 @@ private void AnalyzeSyntax(
return;
}
+ var cancellationToken = context.CancellationToken;
+ var semanticModel = context.SemanticModel;
+
var methodSymbol = node is AnonymousFunctionExpressionSyntax
? (IMethodSymbol?)semanticModel.GetSymbolInfo(node, cancellationToken).Symbol
: (IMethodSymbol?)semanticModel.GetDeclaredSymbol(node, cancellationToken);
diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs
index ab35e699fba96..da07ded9d37f1 100644
--- a/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs
@@ -66,7 +66,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
return;
var cancellationToken = context.CancellationToken;
- var styleOption = context.Options.GetOption(CSharpCodeStyleOptions.PreferPatternMatching, syntaxTree, cancellationToken);
+ var styleOption = context.GetCSharpAnalyzerOptions().PreferPatternMatching;
if (!styleOption.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs
index 882fabea89b1e..2e7279c53a56e 100644
--- a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs
@@ -58,10 +58,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
return;
}
- var options = syntaxContext.Options;
- var cancellationToken = syntaxContext.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferPatternMatchingOverAsWithNullCheck;
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
@@ -92,6 +89,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
}
}
+ var cancellationToken = syntaxContext.CancellationToken;
if (semanticModel.GetSymbolInfo(comparison, cancellationToken).GetAnySymbol().IsUserDefinedOperator())
{
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs
index 1cd16f268b061..58aee7d8e1841 100644
--- a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs
@@ -48,11 +48,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
- var options = syntaxContext.Options;
- var syntaxTree = syntaxContext.Node.SyntaxTree;
- var cancellationToken = syntaxContext.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferPatternMatchingOverIsWithCastCheck;
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
@@ -63,6 +59,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
// "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring
// in projects targeting a lesser version.
+ var syntaxTree = syntaxContext.Node.SyntaxTree;
if (syntaxTree.Options.LanguageVersion() < LanguageVersion.CSharp7)
{
return;
@@ -100,6 +97,7 @@ private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
return;
}
+ var cancellationToken = syntaxContext.CancellationToken;
var semanticModel = syntaxContext.SemanticModel;
var localSymbol = (ILocalSymbol)semanticModel.GetRequiredDeclaredSymbol(declarator, cancellationToken);
var isType = semanticModel.GetTypeInfo(castExpression.Type).Type;
diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpUseNotPatternDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpUseNotPatternDiagnosticAnalyzer.cs
index 8573a3cc7dcf9..22eb9b3e6e3f0 100644
--- a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpUseNotPatternDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpUseNotPatternDiagnosticAnalyzer.cs
@@ -54,18 +54,13 @@ protected override void InitializeWorker(AnalysisContext context)
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
- var node = syntaxContext.Node;
- var syntaxTree = node.SyntaxTree;
-
- var options = syntaxContext.Options;
- var cancellationToken = syntaxContext.CancellationToken;
-
// Bail immediately if the user has disabled this feature.
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferNotPattern, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferNotPattern;
if (!styleOption.Value)
return;
// Look for the form: !(...)
+ var node = syntaxContext.Node;
if (node is not PrefixUnaryExpressionSyntax(SyntaxKind.LogicalNotExpression)
{
Operand: ParenthesizedExpressionSyntax parenthesizedExpression
diff --git a/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs
index afdcf914b0e02..a6ed7194931ce 100644
--- a/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs
@@ -116,7 +116,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
return;
}
- var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferSimpleUsingStatement, syntaxTree, cancellationToken);
+ var option = context.GetCSharpAnalyzerOptions().PreferSimpleUsingStatement;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs
index 83bf4a2a32768..eaa426af470dd 100644
--- a/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs
@@ -3,7 +3,9 @@
// See the LICENSE file in the project root for more information.
using System.Threading;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Diagnostics;
@@ -19,6 +21,9 @@ public CSharpUseThrowExpressionDiagnosticAnalyzer()
{
}
+ protected override CodeStyleOption2 PreferThrowExpressionStyle(OperationAnalysisContext context)
+ => context.GetCSharpAnalyzerOptions().PreferThrowExpression;
+
protected override bool IsSupported(Compilation compilation)
=> compilation.LanguageVersion() >= LanguageVersion.CSharp7;
diff --git a/src/Analyzers/CSharp/Analyzers/UseTupleSwap/CSharpUseTupleSwapDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseTupleSwap/CSharpUseTupleSwapDiagnosticAnalyzer.cs
index ab56c84b265c3..cc27ffb5ac1dc 100644
--- a/src/Analyzers/CSharp/Analyzers/UseTupleSwap/CSharpUseTupleSwapDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseTupleSwap/CSharpUseTupleSwapDiagnosticAnalyzer.cs
@@ -61,11 +61,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext syntaxContext)
{
- var options = syntaxContext.Options;
- var syntaxTree = syntaxContext.Node.SyntaxTree;
- var cancellationToken = syntaxContext.CancellationToken;
-
- var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferTupleSwap, syntaxTree, cancellationToken);
+ var styleOption = syntaxContext.GetCSharpAnalyzerOptions().PreferTupleSwap;
if (!styleOption.Value)
return;
diff --git a/src/Analyzers/CSharp/Analyzers/UseUTF8StringLiteral/UseUTF8StringLiteralDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseUTF8StringLiteral/UseUTF8StringLiteralDiagnosticAnalyzer.cs
index 392cb91c74b0a..af6d671787255 100644
--- a/src/Analyzers/CSharp/Analyzers/UseUTF8StringLiteral/UseUTF8StringLiteralDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseUTF8StringLiteral/UseUTF8StringLiteralDiagnosticAnalyzer.cs
@@ -33,7 +33,7 @@ public enum ArrayCreationOperationLocation
public UseUTF8StringLiteralDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseUTF8StringLiteralDiagnosticId,
EnforceOnBuildValues.UseUTF8StringLiteral,
- CSharpCodeStyleOptions.PreferUTF8StringLiterals,
+ CSharpCodeStyleOptions.PreferUtf8StringLiterals,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Convert_to_UTF8_string_literal), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_UTF8_string_literal), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
@@ -59,7 +59,7 @@ private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol
var arrayCreationOperation = (IArrayCreationOperation)context.Operation;
// Don't offer if the user doesn't want it
- var option = context.GetOption(CSharpCodeStyleOptions.PreferUTF8StringLiterals);
+ var option = context.GetCSharpAnalyzerOptions().PreferUtf8StringLiterals;
if (!option.Value)
return;
diff --git a/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs
index 44ea9b207bf3f..f5a87f37db9ce 100644
--- a/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/AddInheritdoc/AddInheritdocCodeFixProvider.cs
@@ -13,6 +13,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
@@ -97,12 +98,12 @@ protected override async Task FixAllAsync(Document document, ImmutableArray comment.
var xmlSpaceAfterTripleSlash = Token(leading: TriviaList(DocumentationCommentExterior("///")), SyntaxKind.XmlTextLiteralToken, text: " ", valueText: " ", trailing: default);
diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs
index e1911e95d818b..969bae5494f04 100644
--- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceCodeFixProvider.cs
@@ -70,8 +70,8 @@ protected override async Task FixAllAsync(
var namespaceDecl = (BaseNamespaceDeclarationSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
- var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(CSharpSyntaxFormatting.Instance, fallbackOptions, cancellationToken).ConfigureAwait(false);
- var converted = await ConvertAsync(document, namespaceDecl, formattingOptions, cancellationToken).ConfigureAwait(false);
+ var options = await document.GetCSharpCodeFixOptionsProviderAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var converted = await ConvertAsync(document, namespaceDecl, options.GetFormattingOptions(), cancellationToken).ConfigureAwait(false);
editor.ReplaceNode(
editor.OriginalRoot,
diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs
index b32372fde10d8..779bc531903e5 100644
--- a/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs
+++ b/src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs
@@ -89,7 +89,7 @@ public static async Task ConvertAsync(Document document, BaseNamespace
return null;
// Auto-formatting options are not relevant since they only control behavior on typing.
- var indentationOptions = new IndentationOptions(options, AutoFormattingOptions.Default);
+ var indentationOptions = new IndentationOptions(options);
var indentation = indentationService.GetIndentation(document, openBraceLine + 1, indentationOptions, cancellationToken);
diff --git a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs
index 8c2e1915c9af0..51e0bc614a527 100644
--- a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs
+++ b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.AddNewKeywordAction.cs
@@ -12,54 +12,45 @@
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
-
-#if CODE_STYLE
-using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
-#else
-using Microsoft.CodeAnalysis.Options;
-#endif
+using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.HideBase
{
internal partial class HideBaseCodeFixProvider
{
- private class AddNewKeywordAction : CodeActions.CodeAction
+ private class AddNewKeywordAction : CodeAction
{
private readonly Document _document;
private readonly SyntaxNode _node;
+ private readonly CodeActionOptionsProvider _fallbackOptions;
public override string Title => CSharpCodeFixesResources.Hide_base_member;
- public AddNewKeywordAction(Document document, SyntaxNode node)
+ public AddNewKeywordAction(Document document, SyntaxNode node, CodeActionOptionsProvider fallbackOptions)
{
_document = document;
_node = node;
+ _fallbackOptions = fallbackOptions;
}
protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken)
{
var root = await _document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
+ var options = await _document.GetCSharpCodeFixOptionsProviderAsync(_fallbackOptions, cancellationToken).ConfigureAwait(false);
-#if CODE_STYLE
- var options = _document.Project.AnalyzerOptions.GetAnalyzerOptionSet(_node.SyntaxTree, cancellationToken);
-#else
- var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
-
- var newNode = GetNewNode(_node, options);
+ var newNode = GetNewNode(_node, options.PreferredModifierOrder.Value);
var newRoot = root.ReplaceNode(_node, newNode);
return _document.WithSyntaxRoot(newRoot);
}
- private static SyntaxNode GetNewNode(SyntaxNode node, OptionSet options)
+ private static SyntaxNode GetNewNode(SyntaxNode node, string preferredModifierOrder)
{
var syntaxFacts = CSharpSyntaxFacts.Instance;
var modifiers = syntaxFacts.GetModifiers(node);
var newModifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword));
- var option = options.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder);
- if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder) ||
+ if (!CSharpOrderModifiersHelper.Instance.TryGetOrComputePreferredOrder(preferredModifierOrder, out var preferredOrder) ||
!AbstractOrderModifiersHelpers.IsOrdered(preferredOrder, modifiers))
{
return syntaxFacts.WithModifiers(node, newModifiers);
diff --git a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs
index 91f4ad6c7aee0..221d08dc6c512 100644
--- a/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/HideBase/HideBaseCodeFixProvider.cs
@@ -7,6 +7,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
@@ -45,7 +46,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
if (originalNode == null)
return;
- context.RegisterCodeFix(new AddNewKeywordAction(context.Document, originalNode), context.Diagnostics);
+ context.RegisterCodeFix(new AddNewKeywordAction(context.Document, originalNode, context.GetOptionsProvider()), context.Diagnostics);
}
}
}
diff --git a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs
index ba3ba696829af..4a0b969452f36 100644
--- a/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/InlineDeclaration/CSharpInlineDeclarationCodeFixProvider.cs
@@ -57,11 +57,7 @@ protected override async Task FixAllAsync(
Document document, ImmutableArray diagnostics,
SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
-#if CODE_STYLE
- var optionSet = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken);
-#else
- var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
+ var options = await document.GetCSharpCodeFixOptionsProviderAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
// Gather all statements to be removed
// We need this to find the statements we can safely attach trivia to
@@ -93,7 +89,7 @@ await editor.ApplyExpressionLevelSemanticEditsAsync(
(_1, _2, _3) => true,
(semanticModel, currentRoot, t, currentNode)
=> ReplaceIdentifierWithInlineDeclaration(
- optionSet, semanticModel, currentRoot, t.declarator,
+ options, semanticModel, currentRoot, t.declarator,
t.identifier, currentNode, declarationsToRemove, document.Project.Solution.Workspace.Services,
cancellationToken),
cancellationToken).ConfigureAwait(false);
@@ -116,7 +112,7 @@ private static (VariableDeclaratorSyntax declarator, IdentifierNameSyntax identi
}
private static SyntaxNode ReplaceIdentifierWithInlineDeclaration(
- OptionSet options, SemanticModel semanticModel,
+ CSharpCodeFixOptionsProvider options, SemanticModel semanticModel,
SyntaxNode currentRoot, VariableDeclaratorSyntax declarator,
IdentifierNameSyntax identifier, SyntaxNode currentNode,
HashSet declarationsToRemove,
@@ -261,7 +257,7 @@ private static SyntaxNode ReplaceIdentifierWithInlineDeclaration(
}
public static TypeSyntax GenerateTypeSyntaxOrVar(
- ITypeSymbol symbol, OptionSet options)
+ ITypeSymbol symbol, CSharpCodeFixOptionsProvider options)
{
var useVar = IsVarDesired(symbol, options);
@@ -274,16 +270,16 @@ public static TypeSyntax GenerateTypeSyntaxOrVar(
: symbol.GenerateTypeSyntax();
}
- private static bool IsVarDesired(ITypeSymbol type, OptionSet options)
+ private static bool IsVarDesired(ITypeSymbol type, CSharpCodeFixOptionsProvider options)
{
// If they want it for intrinsics, and this is an intrinsic, then use var.
if (type.IsSpecialType() == true)
{
- return options.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes).Value;
+ return options.VarForBuiltInTypes.Value;
}
// If they want "var" whenever possible, then use "var".
- return options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Value;
+ return options.VarElsewhere.Value;
}
private static DeclarationExpressionSyntax GetDeclarationExpression(
diff --git a/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs
index 8fd0aa048df7e..00e7438ad6932 100644
--- a/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs
@@ -25,12 +25,6 @@
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
-#if CODE_STYLE
-using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
-#else
-using Microsoft.CodeAnalysis.Options;
-#endif
-
namespace Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives
{
///
@@ -64,19 +58,13 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
-#if CODE_STYLE
- var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
-#else
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
- var simplifierOptions = await document.GetSimplifierOptionsAsync(CSharpSimplification.Instance, context.GetOptionsProvider(), cancellationToken).ConfigureAwait(false);
-
- var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement);
+ var options = await document.GetCSharpCodeFixOptionsProviderAsync(context.GetOptionsProvider(), cancellationToken).ConfigureAwait(false);
+ var simplifierOptions = options.GetSimplifierOptions();
// Read the preferred placement option and verify if it can be applied to this code file.
// There are cases where we will not be able to fix the diagnostic and the user will need to resolve
// it manually.
- var (placement, preferPreservation) = DeterminePlacement(compilationUnit, codeStyleOption);
+ var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options.UsingDirectivePlacement);
if (preferPreservation)
return;
@@ -153,7 +141,7 @@ private static async Task GetTransformedDocumentAsync(
// Simplify usings now that they have been moved and are in the proper context.
#if CODE_STYLE
-#pragma warning disable RS0030 // Do not used banned APIs
+#pragma warning disable RS0030 // Do not used banned APIs (ReduceAsync with SimplifierOptions isn't public)
return await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, optionSet: null, cancellationToken).ConfigureAwait(false);
#pragma warning restore
#else
diff --git a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs
index dd41a9e4dc596..263043f4849c0 100644
--- a/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs
@@ -39,27 +39,20 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
CSharpCodeFixesResources.Place_statement_on_following_line,
- c => UpdateDocumentAsync(document, diagnostic, c),
+ c => FixAllAsync(document, ImmutableArray.Create(diagnostic), context.GetOptionsProvider(), c),
nameof(CSharpCodeFixesResources.Place_statement_on_following_line)),
context.Diagnostics);
return Task.CompletedTask;
}
- private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
- => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken);
-
- public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken)
+ public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CodeActionOptionsProvider codeActionOptionsProvider, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace.Services);
-#if CODE_STYLE
- var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken);
-#else
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
+ var options = await document.GetCSharpCodeFixOptionsProviderAsync(codeActionOptionsProvider, cancellationToken).ConfigureAwait(false);
- var endOfLineTrivia = SyntaxFactory.ElasticEndOfLine(options.GetOption(FormattingOptions2.NewLine, LanguageNames.CSharp));
+ var endOfLineTrivia = SyntaxFactory.ElasticEndOfLine(options.NewLine);
foreach (var diagnostic in diagnostics)
FixOne(editor, diagnostic, endOfLineTrivia, cancellationToken);
@@ -142,6 +135,6 @@ private static SyntaxToken AddLeadingTrivia(SyntaxToken token, SyntaxTrivia triv
public override FixAllProvider GetFixAllProvider()
=> FixAllProvider.Create(
- async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false));
+ async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.GetOptionsProvider(), context.CancellationToken).ConfigureAwait(false));
}
}
diff --git a/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs
index 61753e17ce410..00e6c8a620590 100644
--- a/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs
@@ -5,25 +5,32 @@
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
+using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.OrderModifiers;
namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared]
- internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider
+ internal sealed class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider
{
private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpOrderModifiersCodeFixProvider()
- : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance)
+ : base(CSharpSyntaxFacts.Instance, CSharpOrderModifiersHelper.Instance)
{
}
+ protected override CodeStyleOption2 GetCodeStyleOption(AnalyzerOptionsProvider options)
+ => ((CSharpAnalyzerOptionsProvider)options).PreferredModifierOrder;
+
protected override ImmutableArray FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267);
}
}
diff --git a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs
index 8f751d5842722..55fad8454a415 100644
--- a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs
@@ -54,10 +54,10 @@ protected override async Task FixAllAsync(
// to replace one at a time, and only actually replace if it's still safe to do so.
var parseOptions = (CSharpParseOptions)document.Project.ParseOptions;
- var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var preferSimpleDefaultExpression = document.Project.AnalyzerOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, tree, cancellationToken).Value;
- var workspace = document.Project.Solution.Workspace;
+ var options = (CSharpAnalyzerOptionsProvider)await document.GetAnalyzerOptionsProviderAsync(cancellationToken).ConfigureAwait(false);
+ var preferSimpleDefaultExpression = options.PreferSimpleDefaultExpression.Value;
+
var originalRoot = editor.OriginalRoot;
var originalNodes = diagnostics.SelectAsArray(
diff --git a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs
index 29134c5de0c6b..143b42bf932bb 100644
--- a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs
+++ b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs
@@ -377,7 +377,7 @@ enum E
},
Options =
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault },
},
}.RunAsync();
}
@@ -399,7 +399,7 @@ ref struct S1 { }
}",
Options =
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault },
},
}.RunAsync();
}
@@ -421,7 +421,7 @@ readonly struct S1 { }
}",
Options =
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault },
},
}.RunAsync();
}
@@ -437,7 +437,7 @@ internal class [|C1|] { }",
class C1 { }",
Options =
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault },
},
}.RunAsync();
}
diff --git a/src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.cs
index 006957cb9a605..5526c4045304a 100644
--- a/src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.cs
@@ -4,6 +4,7 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Precedence;
using Roslyn.Utilities;
@@ -23,25 +24,27 @@ protected AbstractParenthesesDiagnosticAnalyzer(
{
}
- protected static PerLanguageOption2> GetLanguageOption(PrecedenceKind precedenceKind)
- {
- switch (precedenceKind)
+ protected static CodeStyleOption2 GetLanguageOption(AnalyzerOptionsProvider options, PrecedenceKind precedenceKind)
+ => precedenceKind switch
{
- case PrecedenceKind.Arithmetic:
- case PrecedenceKind.Shift:
- case PrecedenceKind.Bitwise:
- return CodeStyleOptions2.ArithmeticBinaryParentheses;
- case PrecedenceKind.Relational:
- case PrecedenceKind.Equality:
- return CodeStyleOptions2.RelationalBinaryParentheses;
- case PrecedenceKind.Logical:
- case PrecedenceKind.Coalesce:
- return CodeStyleOptions2.OtherBinaryParentheses;
- case PrecedenceKind.Other:
- return CodeStyleOptions2.OtherParentheses;
- }
+ PrecedenceKind.Arithmetic or PrecedenceKind.Shift or PrecedenceKind.Bitwise => options.ArithmeticBinaryParentheses,
+ PrecedenceKind.Relational or PrecedenceKind.Equality => options.RelationalBinaryParentheses,
+ PrecedenceKind.Logical or PrecedenceKind.Coalesce => options.OtherBinaryParentheses,
+ PrecedenceKind.Other => options.OtherParentheses,
+ _ => throw ExceptionUtilities.UnexpectedValue(precedenceKind),
+ };
- throw ExceptionUtilities.UnexpectedValue(precedenceKind);
- }
+ protected static string GetEquivalenceKey(PrecedenceKind precedenceKind)
+ => precedenceKind switch
+ {
+ PrecedenceKind.Arithmetic or PrecedenceKind.Shift or PrecedenceKind.Bitwise => "ArithmeticBinary",
+ PrecedenceKind.Relational or PrecedenceKind.Equality => "RelationalBinary",
+ PrecedenceKind.Logical or PrecedenceKind.Coalesce => "OtherBinary",
+ PrecedenceKind.Other => "Other",
+ _ => throw ExceptionUtilities.UnexpectedValue(precedenceKind),
+ };
+
+ protected static ImmutableArray GetAllEquivalenceKeys()
+ => ImmutableArray.Create("ArithmeticBinary", "RelationalBinary", "OtherBinary", "Other");
}
}
diff --git a/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs
index 462188d6dcd5e..860d166bda010 100644
--- a/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs
@@ -14,7 +14,7 @@ internal abstract class AbstractAddAccessibilityModifiersDiagnosticAnalyzer option, TCompilationUnitSyntax compilationUnitSyntax);
diff --git a/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs
index 93d00393d172d..910a78bb03352 100644
--- a/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs
@@ -4,11 +4,13 @@
using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Precedence;
using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses;
+using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddRequiredParentheses
{
@@ -26,15 +28,9 @@ internal abstract class AbstractAddRequiredParenthesesDiagnosticAnalyzer<
static AbstractAddRequiredParenthesesDiagnosticAnalyzer()
{
- var options = new[]
- {
- CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses,
- CodeStyleOptions2.OtherParentheses, CodeStyleOptions2.RelationalBinaryParentheses
- };
-
var includeArray = new[] { false, true };
- foreach (var option in options)
+ foreach (var equivalenceKey in GetAllEquivalenceKeys())
{
foreach (var includeInFixAll in includeArray)
{
@@ -44,16 +40,12 @@ static AbstractAddRequiredParenthesesDiagnosticAnalyzer()
properties = properties.Add(AddRequiredParenthesesConstants.IncludeInFixAll, "");
}
- var equivalenceKey = GetEquivalenceKey(option);
properties = properties.Add(AddRequiredParenthesesConstants.EquivalenceKey, equivalenceKey);
s_cachedProperties.Add((includeInFixAll, equivalenceKey), properties);
}
}
}
- private static string GetEquivalenceKey(PerLanguageOption2> parentPrecedence)
- => parentPrecedence.Name;
-
private static ImmutableDictionary GetProperties(bool includeInFixAll, string equivalenceKey)
=> s_cachedProperties[(includeInFixAll, equivalenceKey)];
@@ -94,16 +86,20 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
return;
}
- var childPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(binaryLike));
- var parentPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(parentBinaryLike));
+ var options = context.GetAnalyzerOptions();
+ var childPrecedenceKind = _precedenceService.GetPrecedenceKind(binaryLike);
+ var parentPrecedenceKind = _precedenceService.GetPrecedenceKind(parentBinaryLike);
+
+ var childEquivalenceKey = GetEquivalenceKey(childPrecedenceKind);
+ var parentEquivalenceKey = GetEquivalenceKey(parentPrecedenceKind);
// only add parentheses within the same precedence band.
- if (parentPrecedence != childPrecedence)
+ if (childEquivalenceKey != parentEquivalenceKey)
{
return;
}
- var preference = context.GetOption(parentPrecedence, binaryLike.Language);
+ var preference = GetLanguageOption(options, childPrecedenceKind);
if (preference.Value != ParenthesesPreference.AlwaysForClarity)
{
return;
@@ -111,14 +107,13 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var additionalLocations = ImmutableArray.Create(binaryLike.GetLocation());
var precedence = GetPrecedence(binaryLike);
- var equivalenceKey = GetEquivalenceKey(parentPrecedence);
// In a case like "a + b * c * d", we'll add parens to make "a + (b * c * d)".
// To make this user experience more pleasant, we will place the diagnostic on
// both *'s.
AddDiagnostics(
context, binaryLike, precedence, preference.Notification.Severity,
- additionalLocations, equivalenceKey, includeInFixAll: true);
+ additionalLocations, childEquivalenceKey, includeInFixAll: true);
}
private void AddDiagnostics(
diff --git a/src/Analyzers/Core/Analyzers/Analyzers.projitems b/src/Analyzers/Core/Analyzers/Analyzers.projitems
index 0429c552528a5..02e058b758a0e 100644
--- a/src/Analyzers/Core/Analyzers/Analyzers.projitems
+++ b/src/Analyzers/Core/Analyzers/Analyzers.projitems
@@ -31,7 +31,6 @@
-
@@ -85,7 +84,6 @@
-
diff --git a/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs
index 4d9824659ce63..ed5c19ef9d007 100644
--- a/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs
@@ -50,8 +50,8 @@ private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
return;
}
- if (!context.Options.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
- || string.IsNullOrEmpty(fileHeaderTemplate))
+ var fileHeaderTemplate = context.GetAnalyzerOptions().FileHeaderTemplate;
+ if (string.IsNullOrEmpty(fileHeaderTemplate))
{
return;
}
diff --git a/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs
index b65af4b04aa1e..ef0817a7c738c 100644
--- a/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/ForEachCast/AbstractForEachCastDiagnosticAnalyzer.cs
@@ -63,7 +63,7 @@ protected void AnalyzeSyntax(
if (context.Node is not TForEachStatementSyntax node)
return;
- var option = context.GetOption(CodeStyleOptions2.ForEachExplicitCastInSource, semanticModel.Language);
+ var option = context.GetAnalyzerOptions().ForEachExplicitCastInSource;
Contract.ThrowIfFalse(option.Value is ForEachExplicitCastInSourcePreference.Always or ForEachExplicitCastInSourcePreference.WhenStronglyTyped);
if (semanticModel.GetOperation(node, cancellationToken) is not IForEachLoopOperation loopOperation)
diff --git a/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs b/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs
index 5b7888a4a96b5..39823b1f37fe5 100644
--- a/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/Formatting/AbstractFormattingAnalyzer.cs
@@ -34,7 +34,7 @@ protected sealed override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
- var options = context.Options.GetSyntaxFormattingOptions(context.Tree, SyntaxFormatting);
+ var options = context.GetAnalyzerOptions().GetSyntaxFormattingOptions(SyntaxFormatting);
FormattingAnalyzerHelper.AnalyzeSyntaxTree(context, SyntaxFormatting, Descriptor, options);
}
}
diff --git a/src/Analyzers/Core/Analyzers/Helpers/AnalyzerOptionsExtensions.cs b/src/Analyzers/Core/Analyzers/Helpers/AnalyzerOptionsExtensions.cs
deleted file mode 100644
index 307510969c339..0000000000000
--- a/src/Analyzers/Core/Analyzers/Helpers/AnalyzerOptionsExtensions.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.Serialization;
-using System.Diagnostics.CodeAnalysis;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.CodeCleanup;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Host;
-using Roslyn.Utilities;
-
-#if CODE_STYLE
-using TOption = Microsoft.CodeAnalysis.Options.IOption2;
-#else
-using TOption = Microsoft.CodeAnalysis.Options.IOption;
-#endif
-
-#if CODE_STYLE
-namespace Microsoft.CodeAnalysis.CodeCleanup
-{
- internal readonly struct CodeCleanupOptions
- {
- }
-}
-#endif
-
-namespace Microsoft.CodeAnalysis.Diagnostics
-{
- ///
- /// IDE specific options available to analyzers in a specific project (language).
- ///
- /// Default values for , or null if not available (the project language does not support these options).
- [DataContract]
- internal sealed record class IdeAnalyzerOptions(
- [property: DataMember(Order = 0)] bool CrashOnAnalyzerException = IdeAnalyzerOptions.DefaultCrashOnAnalyzerException,
- [property: DataMember(Order = 1)] bool FadeOutUnusedImports = IdeAnalyzerOptions.DefaultFadeOutUnusedImports,
- [property: DataMember(Order = 2)] bool FadeOutUnreachableCode = IdeAnalyzerOptions.DefaultFadeOutUnreachableCode,
- [property: DataMember(Order = 3)] bool ReportInvalidPlaceholdersInStringDotFormatCalls = IdeAnalyzerOptions.DefaultReportInvalidPlaceholdersInStringDotFormatCalls,
- [property: DataMember(Order = 4)] bool ReportInvalidRegexPatterns = IdeAnalyzerOptions.DefaultReportInvalidRegexPatterns,
- [property: DataMember(Order = 5)] bool ReportInvalidJsonPatterns = IdeAnalyzerOptions.DefaultReportInvalidJsonPatterns,
- [property: DataMember(Order = 6)] bool DetectAndOfferEditorFeaturesForProbableJsonStrings = IdeAnalyzerOptions.DefaultDetectAndOfferEditorFeaturesForProbableJsonStrings,
- [property: DataMember(Order = 7)] CodeCleanupOptions? CleanupOptions = null)
- {
- public const bool DefaultCrashOnAnalyzerException = false;
- public const bool DefaultFadeOutUnusedImports = true;
- public const bool DefaultFadeOutUnreachableCode = true;
- public const bool DefaultReportInvalidPlaceholdersInStringDotFormatCalls = true;
- public const bool DefaultReportInvalidRegexPatterns = true;
- public const bool DefaultReportInvalidJsonPatterns = true;
- public const bool DefaultDetectAndOfferEditorFeaturesForProbableJsonStrings = true;
-
- public static readonly IdeAnalyzerOptions CodeStyleDefault = new(
- CrashOnAnalyzerException: false,
- FadeOutUnusedImports: false,
- FadeOutUnreachableCode: false);
-
-#if !CODE_STYLE
- public static IdeAnalyzerOptions GetDefault(HostLanguageServices languageServices)
- => new(CleanupOptions: CodeCleanupOptions.GetDefault(languageServices));
-#endif
- }
-
- internal static partial class AnalyzerOptionsExtensions
- {
- public static IdeAnalyzerOptions GetIdeOptions(this AnalyzerOptions options)
-#if CODE_STYLE
- => IdeAnalyzerOptions.CodeStyleDefault;
-#else
- => (options is WorkspaceAnalyzerOptions workspaceOptions) ? workspaceOptions.IdeOptions : IdeAnalyzerOptions.CodeStyleDefault;
-#endif
-
- public static SyntaxFormattingOptions GetSyntaxFormattingOptions(this AnalyzerOptions options, SyntaxTree tree, ISyntaxFormatting formatting)
- {
-#if CODE_STYLE
- var fallbackOptions = (SyntaxFormattingOptions?)null;
-#else
- var fallbackOptions = options.GetIdeOptions().CleanupOptions?.FormattingOptions;
-#endif
- return formatting.GetFormattingOptions(options.AnalyzerConfigOptionsProvider.GetOptions(tree), fallbackOptions);
- }
-
- public static T GetOption(this SemanticModelAnalysisContext context, Option2 option)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.SemanticModel.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this SyntaxNodeAnalysisContext context, Option2 option)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Node.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this SyntaxTreeAnalysisContext context, Option2 option)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Tree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this OperationAnalysisContext context, Option2 option)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Operation.Syntax.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this SemanticModelAnalysisContext context, PerLanguageOption2 option, string? language)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.SemanticModel.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, language, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this SyntaxNodeAnalysisContext context, PerLanguageOption2 option, string? language)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Node.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, language, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this SyntaxTreeAnalysisContext context, PerLanguageOption2 option, string? language)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Tree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, language, syntaxTree, cancellationToken);
- }
-
- public static T GetOption(this OperationAnalysisContext context, PerLanguageOption2 option, string? language)
- {
- var analyzerOptions = context.Options;
- var syntaxTree = context.Operation.Syntax.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- return analyzerOptions.GetOption(option, language, syntaxTree, cancellationToken);
- }
-
- public static bool TryGetEditorConfigOption(this AnalyzerOptions analyzerOptions, TOption option, SyntaxTree syntaxTree, [MaybeNullWhen(false)] out T value)
- {
- var configOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree);
- return configOptions.TryGetEditorConfigOption(option, out value);
- }
- }
-}
diff --git a/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs
index e43a3d0071f43..59059cfe0fede 100644
--- a/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs
@@ -100,7 +100,7 @@ void OnSymbolEnd(SymbolAnalysisContext symbolEndContext)
var (isCandidate, written) = value;
if (isCandidate && !written)
{
- var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken);
+ var option = GetCodeStyleOption(field, symbolEndContext.Options);
var diagnostic = DiagnosticHelper.Create(
Descriptor,
field.Locations[0],
@@ -166,7 +166,7 @@ void UpdateFieldStateOnWrite(IFieldSymbol field)
{
Debug.Assert(IsCandidateField(field, threadStaticAttribute, dataContractAttribute, dataMemberAttribute));
- var option = GetCodeStyleOption(field, options, cancellationToken);
+ var option = GetCodeStyleOption(field, options);
if (option == null || !option.Value)
{
return default;
@@ -219,7 +219,7 @@ private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbo
return true;
}
- private static CodeStyleOption2 GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken)
- => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken);
+ private static CodeStyleOption2 GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options)
+ => options.GetAnalyzerOptions(field.Locations[0].SourceTree).PreferReadonly;
}
}
diff --git a/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs b/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs
index f0884382b3d8e..d0654f0214c51 100644
--- a/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs
+++ b/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs
@@ -128,12 +128,13 @@ void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
return null;
}
- var namingPreferences = GetNamingStylePreferences(compilation, symbol, options, cancellationToken);
- if (namingPreferences == null)
+ var sourceTree = symbol.Locations.FirstOrDefault()?.SourceTree;
+ if (sourceTree == null)
{
return null;
}
+ var namingPreferences = options.GetAnalyzerOptions(sourceTree).NamingPreferences;
var namingStyleRules = namingPreferences.Rules;
if (!namingStyleRules.TryGetApplicableRule(symbol, out var applicableRule) ||
@@ -167,21 +168,6 @@ void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
return DiagnosticHelper.Create(Descriptor, symbol.Locations.First(), applicableRule.EnforcementLevel, additionalLocations: null, builder.ToImmutable(), failureReason);
}
- private static NamingStylePreferences? GetNamingStylePreferences(
- Compilation compilation,
- ISymbol symbol,
- AnalyzerOptions options,
- CancellationToken cancellationToken)
- {
- var sourceTree = symbol.Locations.FirstOrDefault()?.SourceTree;
- if (sourceTree == null)
- {
- return null;
- }
-
- return options.GetOption(NamingStyleOptions.NamingPreferences, compilation.Language, sourceTree, cancellationToken);
- }
-
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
}
diff --git a/src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs
index 23953de87f2b0..b1495b0f7d8bd 100644
--- a/src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs
@@ -39,13 +39,14 @@ protected sealed override void InitializeWorker(AnalysisContext context)
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
- var cancellationToken = context.CancellationToken;
- var tree = context.Tree;
- var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language);
+ var option = context.GetAnalyzerOptions().AllowStatementImmediatelyAfterBlock;
if (option.Value)
return;
- Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken);
+ var cancellationToken = context.CancellationToken;
+ var root = context.Tree.GetRoot(cancellationToken);
+
+ Recurse(context, option.Notification.Severity, root, cancellationToken);
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken)
diff --git a/src/Analyzers/Core/Analyzers/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesDiagnosticAnalyzer.cs
index 68fe7dd278f87..aa547ccba89ad 100644
--- a/src/Analyzers/Core/Analyzers/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesDiagnosticAnalyzer.cs
@@ -35,13 +35,12 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeTree(SyntaxTreeAnalysisContext context)
{
- var option = context.GetOption(CodeStyleOptions2.AllowMultipleBlankLines, context.Tree.Options.Language);
+ var option = context.GetAnalyzerOptions().AllowMultipleBlankLines;
if (option.Value)
return;
- var tree = context.Tree;
var cancellationToken = context.CancellationToken;
- var root = tree.GetRoot(cancellationToken);
+ var root = context.Tree.GetRoot(cancellationToken);
Recurse(context, option.Notification.Severity, root, cancellationToken);
}
diff --git a/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs
index 4663d2ff4c60b..5dcbe9d0a1746 100644
--- a/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs
@@ -14,7 +14,6 @@ namespace Microsoft.CodeAnalysis.OrderModifiers
internal abstract class AbstractOrderModifiersDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private readonly ISyntaxFacts _syntaxFacts;
- private readonly Option2> _option;
private readonly AbstractOrderModifiersHelpers _helpers;
protected AbstractOrderModifiersDiagnosticAnalyzer(
@@ -30,7 +29,6 @@ protected AbstractOrderModifiersDiagnosticAnalyzer(
new LocalizableResourceString(nameof(AnalyzersResources.Modifiers_are_not_ordered), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
- _option = option;
_helpers = helpers;
}
@@ -40,9 +38,11 @@ public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
+ protected abstract CodeStyleOption2 GetPreferredOrderStyle(SyntaxTreeAnalysisContext context);
+
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
- var option = context.GetOption(_option);
+ var option = GetPreferredOrderStyle(context);
if (!_helpers.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder))
{
return;
diff --git a/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs
index a5e4bbd501530..8a4167e5ebce1 100644
--- a/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs
@@ -10,22 +10,16 @@
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
-#if CODE_STYLE
-using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
-#endif
-
namespace Microsoft.CodeAnalysis.QualifyMemberAccess
{
internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer<
TLanguageKindEnum,
TExpressionSyntax,
- TSimpleNameSyntax,
- TSimplifierOptions>
+ TSimpleNameSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TLanguageKindEnum : struct
where TExpressionSyntax : SyntaxNode
where TSimpleNameSyntax : TExpressionSyntax
- where TSimplifierOptions : SimplifierOptions
{
protected AbstractQualifyMemberAccessDiagnosticAnalyzer()
: base(IDEDiagnosticIds.AddThisOrMeQualificationDiagnosticId,
@@ -64,7 +58,7 @@ protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.MethodReference, OperationKind.Invocation);
protected abstract Location GetLocation(IOperation operation);
- protected abstract TSimplifierOptions GetSimplifierOptions(AnalyzerOptions options, SyntaxTree syntaxTree);
+ protected abstract ISimplification Simplification { get; }
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
@@ -127,7 +121,7 @@ private void AnalyzeOperation(OperationAnalysisContext context, IOperation opera
_ => throw ExceptionUtilities.UnexpectedValue(operation),
};
- var simplifierOptions = GetSimplifierOptions(context.Options, context.Operation.Syntax.SyntaxTree);
+ var simplifierOptions = context.GetAnalyzerOptions().GetSimplifierOptions(Simplification);
if (!simplifierOptions.TryGetQualifyMemberAccessOption(symbolKind, out var optionValue))
return;
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs
index 9b032c8a380d4..e5b9ea063f46d 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs
@@ -137,7 +137,7 @@ private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
// for us appropriately.
unnecessaryImports = MergeImports(unnecessaryImports);
- var fadeOut = context.Options.GetIdeOptions().FadeOutUnusedImports;
+ var fadeOut = context.GetIdeAnalyzerOptions().FadeOutUnusedImports;
DiagnosticDescriptor descriptor;
if (GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocComment, cancellationToken))
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer.cs
index 9179b2d43cc7b..8f96217e96f7a 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer.cs
@@ -81,8 +81,8 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
break;
}
- var option = GetLanguageOption(precedence);
- var preference = context.GetOption(option, parenthesizedExpression.Language);
+ var options = context.GetAnalyzerOptions();
+ var preference = GetLanguageOption(options, precedence);
if (preference.Notification.Severity == ReportDiagnostic.Suppress)
{
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs
index 95220efc83ae5..a487a3d60afc0 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs
@@ -109,8 +109,7 @@ public async Task AnalyzeAsync(
}
// Bail out if analyzer has been turned off through options.
- var option = compilationWithAnalyzers.AnalysisOptions.Options?.GetOption(
- CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, tree, cancellationToken).Trim();
+ var option = compilationWithAnalyzers.AnalysisOptions.Options?.GetAnalyzerOptions(tree).RemoveUnnecessarySuppressionExclusions.Trim();
var (userIdExclusions, userCategoryExclusions, analyzerDisabled) = ParseUserExclusions(option);
if (analyzerDisabled)
{
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs
index 54e1f0deb591e..7ed12dc30871c 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs
@@ -82,9 +82,7 @@ public static void Analyze(OperationBlockStartAnalysisContext context, SymbolSta
// All operation blocks for a symbol belong to the same tree.
var firstBlock = context.OperationBlocks[0];
if (!symbolStartAnalyzer._compilationAnalyzer.TryGetOptions(firstBlock.Syntax.SyntaxTree,
- firstBlock.Language,
context.Options,
- context.CancellationToken,
out var options))
{
return;
@@ -595,7 +593,7 @@ private void AnalyzeUnusedValueAssignments(
if (shouldReport)
{
- _symbolStartAnalyzer.ReportUnusedParameterDiagnostic(unusedParameter, hasReference, context.ReportDiagnostic, context.Options, context.CancellationToken);
+ _symbolStartAnalyzer.ReportUnusedParameterDiagnostic(unusedParameter, hasReference, context.ReportDiagnostic, context.Options);
}
}
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs
index fcb6875d21240..4c76ad200e6a1 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs
@@ -121,7 +121,7 @@ private void OnSymbolEnd(SymbolAnalysisContext context)
{
foreach (var (parameter, hasReference) in _unusedParameters)
{
- ReportUnusedParameterDiagnostic(parameter, hasReference, context.ReportDiagnostic, context.Options, context.CancellationToken);
+ ReportUnusedParameterDiagnostic(parameter, hasReference, context.ReportDiagnostic, context.Options);
}
}
@@ -129,8 +129,7 @@ private void ReportUnusedParameterDiagnostic(
IParameterSymbol parameter,
bool hasReference,
Action reportDiagnostic,
- AnalyzerOptions analyzerOptions,
- CancellationToken cancellationToken)
+ AnalyzerOptions analyzerOptions)
{
if (!IsUnusedParameterCandidate(parameter))
{
@@ -138,7 +137,7 @@ private void ReportUnusedParameterDiagnostic(
}
var location = parameter.Locations[0];
- var option = analyzerOptions.GetOption(CodeStyleOptions2.UnusedParameters, parameter.Language, location.SourceTree, cancellationToken);
+ var option = analyzerOptions.GetAnalyzerOptions(location.SourceTree).UnusedParameters;
if (option.Notification.Severity == ReportDiagnostic.Suppress ||
!ShouldReportUnusedParameters(parameter.ContainingSymbol, option.Value, option.Notification.Severity))
{
diff --git a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
index 58684220ca925..9e11f83d22ebc 100644
--- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
@@ -100,8 +100,6 @@ protected AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer(
.Add(s_unusedParameterRule, CodeStyleOptions2.UnusedParameters),
language)
{
- UnusedValueExpressionStatementOption = unusedValueExpressionStatementOption;
- UnusedValueAssignmentOption = unusedValueAssignmentOption;
}
protected abstract bool IsRecordDeclaration(SyntaxNode node);
@@ -109,8 +107,8 @@ protected AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer(
protected abstract bool SupportsDiscard(SyntaxTree tree);
protected abstract bool MethodHasHandlesClause(IMethodSymbol method);
protected abstract bool IsIfConditionalDirective(SyntaxNode node);
- private Option2> UnusedValueExpressionStatementOption { get; }
- private Option2> UnusedValueAssignmentOption { get; }
+ protected abstract CodeStyleOption2 GetUnusedValueExpressionStatementOption(AnalyzerOptionsProvider provider);
+ protected abstract CodeStyleOption2 GetUnusedValueAssignmentOption(AnalyzerOptionsProvider provider);
///
/// Indicates if we should bail from removable assignment analysis for the given
@@ -196,18 +194,16 @@ protected sealed override void InitializeWorker(AnalysisContext context)
compilationContext => SymbolStartAnalyzer.CreateAndRegisterActions(compilationContext, this));
}
- private bool TryGetOptions(
- SyntaxTree syntaxTree,
- string language,
- AnalyzerOptions analyzerOptions,
- CancellationToken cancellationToken,
- out Options options)
+ private bool TryGetOptions(SyntaxTree syntaxTree, AnalyzerOptions analyzerOptions, out Options options)
{
options = null;
- var unusedParametersOption = analyzerOptions.GetOption(CodeStyleOptions2.UnusedParameters, language, syntaxTree, cancellationToken);
- var (unusedValueExpressionStatementPreference, unusedValueExpressionStatementSeverity) = GetPreferenceAndSeverity(UnusedValueExpressionStatementOption);
- var (unusedValueAssignmentPreference, unusedValueAssignmentSeverity) = GetPreferenceAndSeverity(UnusedValueAssignmentOption);
+ var optionsProvider = analyzerOptions.GetAnalyzerOptions(syntaxTree);
+
+ var unusedParametersOption = optionsProvider.UnusedParameters;
+ var (unusedValueExpressionStatementPreference, unusedValueExpressionStatementSeverity) = GetPreferenceAndSeverity(GetUnusedValueExpressionStatementOption(optionsProvider));
+ var (unusedValueAssignmentPreference, unusedValueAssignmentSeverity) = GetPreferenceAndSeverity(GetUnusedValueAssignmentOption(optionsProvider));
+
if (unusedParametersOption.Notification.Severity == ReportDiagnostic.Suppress &&
unusedValueExpressionStatementSeverity == ReportDiagnostic.Suppress &&
unusedValueAssignmentSeverity == ReportDiagnostic.Suppress)
@@ -221,10 +217,8 @@ private bool TryGetOptions(
return true;
// Local functions.
- (UnusedValuePreference preference, ReportDiagnostic severity) GetPreferenceAndSeverity(
- Option2> codeStyleOption)
+ (UnusedValuePreference preference, ReportDiagnostic severity) GetPreferenceAndSeverity(CodeStyleOption2 option)
{
- var option = analyzerOptions.GetOption(codeStyleOption, syntaxTree, cancellationToken);
var preferenceOpt = option?.Value;
if (preferenceOpt == null ||
option.Notification.Severity == ReportDiagnostic.Suppress)
diff --git a/src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs
index 400f515c55b20..59d2a0312030e 100644
--- a/src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs
@@ -63,20 +63,15 @@ protected sealed override void InitializeWorker(AnalysisContext context)
private void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext context)
{
- var semanticModel = context.SemanticModel;
- var syntaxTree = semanticModel.SyntaxTree;
- var options = context.Options;
- var cancellationToken = context.CancellationToken;
-
- var styleOption = options.GetOption(
- CodeStyleOptions2.PreferSimplifiedBooleanExpressions,
- semanticModel.Language, syntaxTree, cancellationToken);
+ var styleOption = context.GetAnalyzerOptions().PreferSimplifiedBooleanExpressions;
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
+ var semanticModel = context.SemanticModel;
+ var cancellationToken = context.CancellationToken;
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
SyntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var conditionNode, out var whenTrueNode, out var whenFalseNode);
diff --git a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
index 34cbe384700fd..dad44fac24a4f 100644
--- a/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs
@@ -41,24 +41,14 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeInterpolation(OperationAnalysisContext context)
{
- var interpolation = (IInterpolationOperation)context.Operation;
-
- var syntaxTree = interpolation.Syntax.SyntaxTree;
- var cancellationToken = context.CancellationToken;
- var optionSet = context.Options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
- if (optionSet == null)
- {
- return;
- }
-
- var language = interpolation.Language;
- var option = optionSet.GetOption(CodeStyleOptions2.PreferSimplifiedInterpolation, language);
+ var option = context.GetAnalyzerOptions().PreferSimplifiedInterpolation;
if (!option.Value)
{
// No point in analyzing if the option is off.
return;
}
+ var interpolation = (IInterpolationOperation)context.Operation;
GetHelpers().UnwrapInterpolation(
GetVirtualCharService(), GetSyntaxFacts(), interpolation, out _, out var alignment, out _,
out var formatString, out var unnecessaryLocations);
diff --git a/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
index d3b18fe7b3f34..1f998e87d2fa1 100644
--- a/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs
@@ -55,7 +55,7 @@ private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
var semanticModel = context.SemanticModel;
// Don't even bother doing the analysis if the user doesn't even want auto-props.
- var option = context.GetOption(CodeStyleOptions2.PreferAutoProperties, semanticModel.Language);
+ var option = context.GetAnalyzerOptions().PreferAutoProperties;
if (!option.Value)
{
return;
@@ -322,7 +322,7 @@ private void Process(AnalysisResult result, SemanticModelAnalysisContext context
propertyDeclaration.GetLocation(),
variableDeclarator.GetLocation());
- var option = context.GetOption(CodeStyleOptions2.PreferAutoProperties, propertyDeclaration.Language);
+ var option = context.GetAnalyzerOptions().PreferAutoProperties;
if (option.Notification.Severity == ReportDiagnostic.Suppress)
{
// Avoid reporting diagnostics when the feature is disabled. This primarily avoids reporting the hidden
diff --git a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs
index aa1738669697e..f7436057827f1 100644
--- a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs
@@ -49,7 +49,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var cancellationToken = context.CancellationToken;
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
- var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language);
+ var option = context.GetAnalyzerOptions().PreferCoalesceExpression;
if (!option.Value)
return;
diff --git a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs
index e6b08a4307230..b77d667770cf5 100644
--- a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs
@@ -50,7 +50,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
var cancellationToken = context.CancellationToken;
- var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language);
+ var option = context.GetAnalyzerOptions().PreferCoalesceExpression;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs
index af5705125fef7..db0614f7ebe0f 100644
--- a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs
@@ -77,7 +77,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ien
var language = objectCreationExpression.Language;
var cancellationToken = context.CancellationToken;
- var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language);
+ var option = context.GetAnalyzerOptions().PreferCollectionInitializer;
if (!option.Value)
{
// not point in analyzing if the option is off.
@@ -124,8 +124,7 @@ private void FadeOutCode(
{
var syntaxTree = context.Node.SyntaxTree;
- var fadeOutCode = context.GetOption(
- CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language);
+ var fadeOutCode = context.GetIdeAnalyzerOptions().FadeOutComplexObjectInitialization;
if (!fadeOutCode)
return;
diff --git a/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs
index af90b5a3c4339..4b5759f979934 100644
--- a/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs
@@ -73,7 +73,7 @@ private void AnalyzeAssignment(SyntaxNodeAnalysisContext context)
var cancellationToken = context.CancellationToken;
var syntaxTree = assignment.SyntaxTree;
- var option = context.GetOption(CodeStyleOptions2.PreferCompoundAssignment, assignment.Language);
+ var option = context.GetAnalyzerOptions().PreferCompoundAssignment;
if (!option.Value)
{
// Bail immediately if the user has disabled this feature.
diff --git a/src/Analyzers/Core/Analyzers/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs
index 8f9f90435ae0d..521e324487d55 100644
--- a/src/Analyzers/Core/Analyzers/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs
@@ -16,8 +16,6 @@ internal abstract class AbstractUseConditionalExpressionDiagnosticAnalyzer<
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TIfStatementSyntax : SyntaxNode
{
- private readonly PerLanguageOption2> _option;
-
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
@@ -32,11 +30,11 @@ protected AbstractUseConditionalExpressionDiagnosticAnalyzer(
new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
message)
{
- _option = option;
}
protected abstract ISyntaxFacts GetSyntaxFacts();
protected abstract bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol);
+ protected abstract CodeStyleOption2 GetStylePreference(OperationAnalysisContext context);
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.Conditional);
@@ -49,9 +47,7 @@ private void AnalyzeOperation(OperationAnalysisContext context)
return;
}
- var language = ifStatement.Language;
-
- var option = context.GetOption(_option, language);
+ var option = GetStylePreference(context);
if (!option.Value)
{
return;
diff --git a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs
index 95dc54f63bef9..28cadc2c712a2 100644
--- a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs
@@ -22,6 +22,9 @@ protected AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer(
{
}
+ protected sealed override CodeStyleOption2 GetStylePreference(OperationAnalysisContext context)
+ => context.GetAnalyzerOptions().PreferConditionalExpressionOverAssignment;
+
protected override bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol)
=> UseConditionalExpressionForAssignmentHelpers.TryMatchPattern(
GetSyntaxFacts(), ifOperation, out _, out _, out _, out _);
diff --git a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
index 316b82c63e712..b291e7981cccd 100644
--- a/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
@@ -22,6 +22,9 @@ protected AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer(
{
}
+ protected sealed override CodeStyleOption2 GetStylePreference(OperationAnalysisContext context)
+ => context.GetAnalyzerOptions().PreferConditionalExpressionOverReturn;
+
protected override bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol)
=> UseConditionalExpressionForReturnHelpers.TryMatchPattern(
GetSyntaxFacts(), ifOperation, containingSymbol, out _, out _, out _, out _);
diff --git a/src/Analyzers/Core/Analyzers/UseConditionalExpression/UseConditionalExpressionOptions.cs b/src/Analyzers/Core/Analyzers/UseConditionalExpression/UseConditionalExpressionOptions.cs
deleted file mode 100644
index f2ff3f2e8d263..0000000000000
--- a/src/Analyzers/Core/Analyzers/UseConditionalExpression/UseConditionalExpressionOptions.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.CodeAnalysis.Options;
-
-namespace Microsoft.CodeAnalysis.UseConditionalExpression
-{
- internal static class UseConditionalExpressionOptions
- {
- public static readonly PerLanguageOption2 ConditionalExpressionWrappingLength = new(
- nameof(UseConditionalExpressionOptions),
- nameof(ConditionalExpressionWrappingLength), defaultValue: 120,
- storageLocation: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ConditionalExpressionWrappingLength)}"));
- }
-}
diff --git a/src/Analyzers/Core/Analyzers/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs
index 2c9f69c11ce95..ca2efb155e6e8 100644
--- a/src/Analyzers/Core/Analyzers/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs
@@ -33,7 +33,7 @@ protected override void InitializeWorker(AnalysisContext context)
private void AnalyzeOperation(OperationAnalysisContext context)
{
// We only create a diagnostic if the option's value is set to true.
- var option = context.GetOption(CodeStyleOptions2.PreferExplicitTupleNames, context.Compilation.Language);
+ var option = context.GetAnalyzerOptions().PreferExplicitTupleNames;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/Core/Analyzers/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs
index f657ef7d025f3..ab45495bbf6df 100644
--- a/src/Analyzers/Core/Analyzers/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs
@@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.UseInferredMemberName
{
internal abstract class AbstractUseInferredMemberNameDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
- protected abstract void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken);
+ protected abstract void AnalyzeSyntax(SyntaxNodeAnalysisContext context);
public AbstractUseInferredMemberNameDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId,
@@ -25,15 +25,5 @@ public AbstractUseInferredMemberNameDiagnosticAnalyzer()
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
-
- protected void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
- {
- var cancellationToken = context.CancellationToken;
-
- var syntaxTree = context.Node.SyntaxTree;
- var options = context.Options;
-
- LanguageSpecificAnalyzeSyntax(context, syntaxTree, options, cancellationToken);
- }
}
}
diff --git a/src/Analyzers/Core/Analyzers/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs
index b842fa5fc362d..a666c4596ea1b 100644
--- a/src/Analyzers/Core/Analyzers/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs
@@ -59,7 +59,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, IMethodSymbol refe
var semanticModel = context.SemanticModel;
- var option = context.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language);
+ var option = context.GetAnalyzerOptions().PreferIsNullCheckOverReferenceEqualityMethod;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
index 6b1c9183d870d..611fb8b279530 100644
--- a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs
@@ -89,7 +89,7 @@ private void AnalyzeSyntax(
{
var conditionalExpression = (TConditionalExpressionSyntax)context.Node;
- var option = context.GetOption(CodeStyleOptions2.PreferNullPropagation, conditionalExpression.Language);
+ var option = context.GetAnalyzerOptions().PreferNullPropagation;
if (!option.Value)
{
return;
diff --git a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
index 1f6a416f68469..d7a659e87616c 100644
--- a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs
@@ -67,7 +67,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node;
var language = objectCreationExpression.Language;
- var option = context.GetOption(CodeStyleOptions2.PreferObjectInitializer, language);
+ var option = context.GetAnalyzerOptions().PreferObjectInitializer;
if (!option.Value)
{
// not point in analyzing if the option is off.
@@ -111,8 +111,7 @@ private void FadeOutCode(
{
var syntaxTree = context.Node.SyntaxTree;
- var fadeOutCode = context.GetOption(
- CodeStyleOptions2.PreferObjectInitializer_FadeOutCode, context.Node.Language);
+ var fadeOutCode = context.GetIdeAnalyzerOptions().FadeOutComplexObjectInitialization;
if (!fadeOutCode)
return;
diff --git a/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs
index 20ea5247730cd..906f807ee1c2a 100644
--- a/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs
@@ -64,13 +64,11 @@ private void AnalyzeOperationBlock(Analyzer analyzer, OperationBlockAnalysisCont
// We've got multiple members to hash, or multiple statements that can be reduced at this point.
Debug.Assert(elementCount >= 2 || statements.Length >= 2);
- var syntaxTree = operation.Syntax.SyntaxTree;
- var cancellationToken = context.CancellationToken;
-
- var option = context.Options.GetOption(CodeStyleOptions2.PreferSystemHashCode, operation.Language, syntaxTree, cancellationToken);
+ var option = context.Options.GetIdeOptions().PreferSystemHashCode;
if (option?.Value != true)
return;
+ var cancellationToken = context.CancellationToken;
var operationLocation = operation.Syntax.GetLocation();
var declarationLocation = context.OwningSymbol.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken).GetLocation();
context.ReportDiagnostic(DiagnosticHelper.Create(
diff --git a/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs
index 22cd0fa3dffea..ac248ab899c67 100644
--- a/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs
@@ -36,8 +36,6 @@ namespace Microsoft.CodeAnalysis.UseThrowExpression
internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer :
AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
- private readonly Option2> _preferThrowExpressionOption;
-
protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2> preferThrowExpressionOption, string language)
: base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId,
EnforceOnBuildValues.UseThrowExpression,
@@ -46,9 +44,10 @@ protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2 PreferThrowExpressionStyle(OperationAnalysisContext context);
+
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
@@ -95,7 +94,7 @@ private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol
return;
}
- var option = context.GetOption(_preferThrowExpressionOption);
+ var option = PreferThrowExpressionStyle(context);
if (!option.Value)
return;
diff --git a/src/Analyzers/Core/Analyzers/ValidateFormatString/AbstractValidateFormatStringDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/ValidateFormatString/AbstractValidateFormatStringDiagnosticAnalyzer.cs
index 1557eb566c449..72951a6fc3a12 100644
--- a/src/Analyzers/Core/Analyzers/ValidateFormatString/AbstractValidateFormatStringDiagnosticAnalyzer.cs
+++ b/src/Analyzers/Core/Analyzers/ValidateFormatString/AbstractValidateFormatStringDiagnosticAnalyzer.cs
@@ -85,7 +85,7 @@ public override void Initialize(AnalysisContext context)
[PerformanceSensitive(
"https://github.com/dotnet/roslyn/issues/23583",
- Constraint = nameof(AnalyzerOptionsExtensions.GetOption) + " is expensive and should be avoided if a syntax-based fast path exists.")]
+ Constraint = "Reading editorconfig options is expensive and should be avoided if a syntax-based fast path exists.")]
private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol formatProviderType)
{
var syntaxFacts = GetSyntaxFacts();
@@ -96,7 +96,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol for
return;
}
- if (!context.Options.GetIdeOptions().ReportInvalidPlaceholdersInStringDotFormatCalls)
+ if (!context.GetIdeAnalyzerOptions().ReportInvalidPlaceholdersInStringDotFormatCalls)
{
return;
}
diff --git a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs
index 46e253db0c7c7..14d5fad49b431 100644
--- a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs
@@ -17,6 +17,7 @@
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
+using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FileHeaders
{
@@ -34,7 +35,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
CodeFixesResources.Add_file_header,
- cancellationToken => GetTransformedDocumentAsync(context.Document, cancellationToken),
+ cancellationToken => GetTransformedDocumentAsync(context.Document, context.GetOptionsProvider(), cancellationToken),
nameof(AbstractFileHeaderCodeFixProvider)),
diagnostic);
}
@@ -42,21 +43,14 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
return Task.CompletedTask;
}
- private async Task GetTransformedDocumentAsync(Document document, CancellationToken cancellationToken)
- => document.WithSyntaxRoot(await GetTransformedSyntaxRootAsync(document, cancellationToken).ConfigureAwait(false));
+ private async Task GetTransformedDocumentAsync(Document document, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
+ => document.WithSyntaxRoot(await GetTransformedSyntaxRootAsync(document, fallbackOptions, cancellationToken).ConfigureAwait(false));
- private async Task GetTransformedSyntaxRootAsync(Document document, CancellationToken cancellationToken)
+ private async Task GetTransformedSyntaxRootAsync(Document document, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
-#if CODE_STYLE
- var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);
-#else
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
-
- var newLine = options.GetOption(FormattingOptions2.NewLine, document.Project.Language);
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
var generator = document.GetRequiredLanguageService();
- var newLineTrivia = generator.EndOfLine(newLine);
+ var newLineTrivia = generator.EndOfLine(options.NewLine);
return await GetTransformedSyntaxRootAsync(generator.SyntaxFacts, FileHeaderHelper, newLineTrivia, document, fileHeaderTemplate: null, cancellationToken).ConfigureAwait(false);
}
@@ -68,13 +62,13 @@ internal static async Task GetTransformedSyntaxRootAsync(ISyntaxFact
// If we weren't given a header lets get the one from editorconfig
if (fileHeaderTemplate is null &&
- !document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out fileHeaderTemplate))
+ !document.Project.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree).TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, out fileHeaderTemplate))
{
// No header supplied, no editorconfig setting, nothing to do
return root;
}
- if (string.IsNullOrEmpty(fileHeaderTemplate))
+ if (RoslynString.IsNullOrEmpty(fileHeaderTemplate))
{
// Header template is empty, nothing to do. This shouldn't be possible if this method is called in
// reaction to a diagnostic, but this method is also used when creating new documents so lets be defensive.
@@ -238,7 +232,7 @@ public override FixAllProvider GetFixAllProvider()
if (diagnostics.IsEmpty)
return null;
- return await this.GetTransformedDocumentAsync(document, context.CancellationToken).ConfigureAwait(false);
+ return await this.GetTransformedDocumentAsync(document, context.GetOptionsProvider(), context.CancellationToken).ConfigureAwait(false);
});
}
}
diff --git a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs
index f88d08e1c244f..9739bc7cda65d 100644
--- a/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/Formatting/FormattingCodeFixProvider.cs
@@ -40,7 +40,8 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
private async Task FixOneAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
{
- var formattingOptions = await context.Document.GetSyntaxFormattingOptionsAsync(SyntaxFormatting, context.GetOptionsProvider(), cancellationToken).ConfigureAwait(false);
+ var options = await context.Document.GetCodeFixOptionsAsync(context.GetOptionsProvider(), cancellationToken).ConfigureAwait(false);
+ var formattingOptions = options.GetFormattingOptions(SyntaxFormatting);
var tree = await context.Document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var updatedTree = await FormattingCodeFixHelper.FixOneAsync(tree, SyntaxFormatting, formattingOptions, diagnostic, cancellationToken).ConfigureAwait(false);
return context.Document.WithText(await updatedTree.GetTextAsync(cancellationToken).ConfigureAwait(false));
@@ -48,7 +49,8 @@ private async Task FixOneAsync(CodeFixContext context, Diagnostic diag
protected override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
- var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(SyntaxFormatting, fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var formattingOptions = options.GetFormattingOptions(SyntaxFormatting);
var updatedRoot = Formatter.Format(editor.OriginalRoot, SyntaxFormatting, formattingOptions, cancellationToken);
editor.ReplaceNode(editor.OriginalRoot, updatedRoot);
}
diff --git a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs
index cdb10c3daf4ca..321d61a6991d8 100644
--- a/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/NewLines/ConsecutiveStatementPlacement/ConsecutiveStatementPlacementCodeFixProvider.cs
@@ -36,28 +36,22 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
var diagnostic = context.Diagnostics.First();
context.RegisterCodeFix(CodeAction.Create(
CodeFixesResources.Add_blank_line_after_block,
- c => UpdateDocumentAsync(document, diagnostic, c),
+ c => UpdateDocumentAsync(document, diagnostic, context.GetOptionsProvider(), c),
nameof(CodeFixesResources.Add_blank_line_after_block)),
context.Diagnostics);
return Task.CompletedTask;
}
- private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
- => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken);
+ private static Task UpdateDocumentAsync(Document document, Diagnostic diagnostic, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
+ => FixAllAsync(document, ImmutableArray.Create(diagnostic), fallbackOptions, cancellationToken);
- public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CancellationToken cancellationToken)
+ public static async Task FixAllAsync(Document document, ImmutableArray diagnostics, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
-#if CODE_STYLE
- var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken);
-#else
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
-#endif
-
- var newLine = options.GetOption(FormattingOptions2.NewLine, document.Project.Language);
var generator = document.GetRequiredLanguageService();
- var endOfLineTrivia = generator.EndOfLine(newLine);
+ var endOfLineTrivia = generator.EndOfLine(options.NewLine);
var nextTokens = diagnostics.Select(d => d.AdditionalLocations[0].FindToken(cancellationToken));
var newRoot = root.ReplaceTokens(
@@ -68,6 +62,6 @@ public static async Task FixAllAsync(Document document, ImmutableArray
}
public override FixAllProvider GetFixAllProvider()
- => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false));
+ => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.GetOptionsProvider(), context.CancellationToken).ConfigureAwait(false));
}
}
diff --git a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs
index b93529bbf9e35..f437f7d3d67ac 100644
--- a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs
@@ -22,20 +22,18 @@ namespace Microsoft.CodeAnalysis.OrderModifiers
internal abstract class AbstractOrderModifiersCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
private readonly ISyntaxFacts _syntaxFacts;
- private readonly Option2> _option;
private readonly AbstractOrderModifiersHelpers _helpers;
protected AbstractOrderModifiersCodeFixProvider(
ISyntaxFacts syntaxFacts,
- Option2> option,
AbstractOrderModifiersHelpers helpers)
{
_syntaxFacts = syntaxFacts;
- _option = option;
_helpers = helpers;
}
protected abstract ImmutableArray FixableCompilerErrorIds { get; }
+ protected abstract CodeStyleOption2 GetCodeStyleOption(AnalyzerOptionsProvider options);
public sealed override ImmutableArray FixableDiagnosticIds
=> FixableCompilerErrorIds.Add(IDEDiagnosticIds.OrderModifiersDiagnosticId);
@@ -54,8 +52,8 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
protected override async Task FixAllAsync(
Document document, ImmutableArray diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
- var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var option = document.Project.AnalyzerOptions.GetOption(_option, tree, cancellationToken);
+ var options = await document.GetAnalyzerOptionsProviderAsync(cancellationToken).ConfigureAwait(false);
+ var option = GetCodeStyleOption(options);
if (!_helpers.TryGetOrComputePreferredOrder(option.Value, out var preferredOrder))
{
return;
diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs
index 1a70925b76634..ac0509bc82fb4 100644
--- a/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsCodeFixProvider.cs
@@ -40,11 +40,13 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
private async Task RemoveUnnecessaryImportsAsync(
Document document,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService();
- var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(GetSyntaxFormatting(), options, cancellationToken).ConfigureAwait(false);
+
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var formattingOptions = options.GetFormattingOptions(GetSyntaxFormatting());
return await service.RemoveUnnecessaryImportsAsync(document, formattingOptions, cancellationToken).ConfigureAwait(false);
}
}
diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs
index dda8bfc7b1903..e27df4315b41c 100644
--- a/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs
@@ -264,7 +264,8 @@ private static async Task PreprocessDocumentAsync(Document document, I
protected sealed override async Task FixAllAsync(Document document, ImmutableArray diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
- var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(GetSyntaxFormatting(), fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var formattingOptions = options.GetFormattingOptions(GetSyntaxFormatting());
var preprocessedDocument = await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false);
var newRoot = await GetNewRootAsync(preprocessedDocument, formattingOptions, diagnostics, cancellationToken).ConfigureAwait(false);
editor.ReplaceNode(editor.OriginalRoot, newRoot);
diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs
index 60faa3c5db1fc..c92bb05cc1177 100644
--- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs
@@ -46,7 +46,7 @@ internal abstract class AbstractUseConditionalExpressionCodeFixProvider<
protected abstract Task FixOneAsync(
Document document, Diagnostic diagnostic,
- SyntaxEditor editor, CancellationToken cancellationToken);
+ SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken);
protected override async Task FixAllAsync(
Document document, ImmutableArray diagnostics, SyntaxEditor editor,
@@ -62,7 +62,7 @@ protected override async Task FixAllAsync(
foreach (var diagnostic in diagnostics)
{
await FixOneAsync(
- document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false);
+ document, diagnostic, nestedEditor, fallbackOptions, cancellationToken).ConfigureAwait(false);
}
var changedRoot = nestedEditor.GetChangedRoot();
@@ -78,7 +78,8 @@ await FixOneAsync(
#else
var provider = document.Project.Solution.Workspace.Services;
#endif
- var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(GetSyntaxFormatting(), fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var options = await document.GetCodeFixOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false);
+ var formattingOptions = options.GetFormattingOptions(GetSyntaxFormatting());
var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, provider, formattingOptions, rules, cancellationToken);
changedRoot = formattedRoot;
@@ -96,7 +97,7 @@ protected async Task CreateConditionalExpressionAsync(
Document document, IConditionalOperation ifOperation,
IOperation trueStatement, IOperation falseStatement,
IOperation trueValue, IOperation falseValue,
- bool isRef, CancellationToken cancellationToken)
+ bool isRef, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService();
@@ -129,7 +130,7 @@ protected async Task CreateConditionalExpressionAsync(
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation);
var makeMultiLine = await MakeMultiLineAsync(
document, condition,
- trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false);
+ trueValue.Syntax, falseValue.Syntax, fallbackOptions, cancellationToken).ConfigureAwait(false);
if (makeMultiLine)
{
conditionalExpression = conditionalExpression.WithAdditionalAnnotations(
@@ -157,7 +158,7 @@ private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool
/// Checks if we should wrap the conditional expression over multiple lines.
///
private static async Task MakeMultiLineAsync(
- Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax,
+ Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax, CodeActionOptionsProvider fallbackOptions,
CancellationToken cancellationToken)
{
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
@@ -168,13 +169,12 @@ private static async Task MakeMultiLineAsync(
return true;
}
-#if CODE_STYLE
- var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
- var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken);
-#else
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
- var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength);
+ // the option is currently not an editorconfig option, so not available in code style layer
+ var wrappingLength =
+#if !CODE_STYLE
+ fallbackOptions.GetOptions(document.Project.LanguageServices)?.ConditionalExpressionWrappingLength ??
#endif
+ CodeActionOptions.DefaultConditionalExpressionWrappingLength;
if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength)
{
diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs
index b6384b2fb5506..22f9c9adc622d 100644
--- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentCodeFixProvider.cs
@@ -55,7 +55,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
///
protected override async Task FixOneAsync(
Document document, Diagnostic diagnostic,
- SyntaxEditor editor, CancellationToken cancellationToken)
+ SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService();
var ifStatement = diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
@@ -76,7 +76,9 @@ protected override async Task FixOneAsync(
trueStatement, falseStatement,
trueAssignment?.Value ?? trueStatement,
falseAssignment?.Value ?? falseStatement,
- trueAssignment?.IsRef == true, cancellationToken).ConfigureAwait(false);
+ trueAssignment?.IsRef == true,
+ fallbackOptions,
+ cancellationToken).ConfigureAwait(false);
// See if we're assigning to a variable declared directly above the if statement. If so,
// try to inline the conditional directly into the initializer for that variable.
diff --git a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs
index 8996271183b81..888716d33eccc 100644
--- a/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs
+++ b/src/Analyzers/Core/CodeFixes/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnCodeFixProvider.cs
@@ -41,7 +41,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
protected override async Task FixOneAsync(
Document document, Diagnostic diagnostic,
- SyntaxEditor editor, CancellationToken cancellationToken)
+ SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService();
var ifStatement = (TIfStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
@@ -64,7 +64,9 @@ protected override async Task FixOneAsync(
trueStatement, falseStatement,
trueReturn?.ReturnedValue ?? trueStatement,
falseReturn?.ReturnedValue ?? falseStatement,
- anyReturn.GetRefKind(containingSymbol) != RefKind.None, cancellationToken).ConfigureAwait(false);
+ anyReturn.GetRefKind(containingSymbol) != RefKind.None,
+ fallbackOptions,
+ cancellationToken).ConfigureAwait(false);
var generatorInternal = document.GetRequiredLanguageService();
var returnStatement = anyReturn.Kind == OperationKind.YieldReturn
diff --git a/src/Analyzers/VisualBasic/Analyzers/CodeStyle/VisualBasicAnalyzerOptionsProvider.vb b/src/Analyzers/VisualBasic/Analyzers/CodeStyle/VisualBasicAnalyzerOptionsProvider.vb
new file mode 100644
index 0000000000000..f65569559fddf
--- /dev/null
+++ b/src/Analyzers/VisualBasic/Analyzers/CodeStyle/VisualBasicAnalyzerOptionsProvider.vb
@@ -0,0 +1,120 @@
+' Licensed to the .NET Foundation under one or more agreements.
+' The .NET Foundation licenses this file to you under the MIT license.
+' See the LICENSE file in the project root for more information.
+
+Imports System.Runtime.CompilerServices
+Imports Microsoft.CodeAnalysis.CodeStyle
+Imports Microsoft.CodeAnalysis.Options
+Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle
+Imports Microsoft.CodeAnalysis.VisualBasic.Simplification
+
+Namespace Microsoft.CodeAnalysis.Diagnostics
+ '''
+ ''' Provides Visual Basic analyzers a convenient access to editorconfig options with fallback to IDE default values.
+ '''
+ Friend Structure VisualBasicAnalyzerOptionsProvider
+ '''
+ ''' Document editorconfig options.
+ '''
+ Private ReadOnly _options As AnalyzerConfigOptions
+
+ '''
+ ''' Fallback options - the default options in Code Style layer.
+ '''
+ Private ReadOnly _fallbackOptions As IdeAnalyzerOptions
+
+ Public Sub New(options As AnalyzerConfigOptions, fallbackOptions As IdeAnalyzerOptions)
+ _options = options
+ _fallbackOptions = fallbackOptions
+ End Sub
+
+ Public Sub New(options As AnalyzerConfigOptions, fallbackOptions As AnalyzerOptions)
+ MyClass.New(options, fallbackOptions.GetIdeOptions())
+ End Sub
+
+ Public Function GetSimplifierOptions() As VisualBasicSimplifierOptions
+ Return _options.GetVisualBasicSimplifierOptions(FallbackSimplifierOptions)
+ End Function
+
+ Public ReadOnly Property PreferredModifierOrder As CodeStyleOption2(Of String)
+ Get
+ Return GetOption(VisualBasicCodeStyleOptions.PreferredModifierOrder, FallbackCodeStyleOptions.PreferredModifierOrder)
+ End Get
+ End Property
+
+ Public ReadOnly Property PreferIsNotExpression As CodeStyleOption2(Of Boolean)
+ Get
+ Return GetOption(VisualBasicCodeStyleOptions.PreferIsNotExpression, FallbackCodeStyleOptions.PreferIsNotExpression)
+ End Get
+ End Property
+
+ Public ReadOnly Property PreferSimplifiedObjectCreation As CodeStyleOption2(Of Boolean)
+ Get
+ Return GetOption(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, FallbackCodeStyleOptions.PreferSimplifiedObjectCreation)
+ End Get
+ End Property
+
+ Public ReadOnly Property UnusedValueExpressionStatement As CodeStyleOption2(Of UnusedValuePreference)
+ Get
+ Return GetOption(VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, FallbackCodeStyleOptions.UnusedValueExpressionStatement)
+ End Get
+ End Property
+
+ Public ReadOnly Property UnusedValueAssignment As CodeStyleOption2(Of UnusedValuePreference)
+ Get
+ Return GetOption(VisualBasicCodeStyleOptions.UnusedValueAssignment, FallbackCodeStyleOptions.UnusedValueAssignment)
+ End Get
+ End Property
+
+ Private Function GetOption(Of TValue)([option] As Option2(Of CodeStyleOption2(Of TValue)), defaultValue As CodeStyleOption2(Of TValue)) As CodeStyleOption2(Of TValue)
+ Return _options.GetEditorConfigOption([option], defaultValue)
+ End Function
+
+ Private ReadOnly Property FallbackSimplifierOptions As VisualBasicSimplifierOptions
+ Get
+ Return If(DirectCast(_fallbackOptions.CleanupOptions?.SimplifierOptions, VisualBasicSimplifierOptions), VisualBasicSimplifierOptions.Default)
+ End Get
+ End Property
+
+ Private ReadOnly Property FallbackCodeStyleOptions As VisualBasicIdeCodeStyleOptions
+ Get
+ Return If(DirectCast(_fallbackOptions.CodeStyleOptions, VisualBasicIdeCodeStyleOptions), VisualBasicIdeCodeStyleOptions.Default)
+ End Get
+ End Property
+
+ Public Shared Narrowing Operator CType(provider As AnalyzerOptionsProvider) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(provider.GetAnalyzerConfigOptions(), provider.GetFallbackOptions())
+ End Operator
+
+ Public Shared Widening Operator CType(provider As VisualBasicAnalyzerOptionsProvider) As AnalyzerOptionsProvider
+ Return New AnalyzerOptionsProvider(provider._options, provider._fallbackOptions)
+ End Operator
+ End Structure
+
+ Friend Module VisualBasicAnalyzerOptionsProviders
+
+ Public Function GetVisualBasicAnalyzerOptions(context As SemanticModelAnalysisContext) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.SemanticModel.SyntaxTree), context.Options)
+ End Function
+
+
+ Public Function GetVisualBasicAnalyzerOptions(context As SyntaxNodeAnalysisContext) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Node.SyntaxTree), context.Options)
+ End Function
+
+
+ Public Function GetVisualBasicAnalyzerOptions(context As SyntaxTreeAnalysisContext) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Tree), context.Options)
+ End Function
+
+
+ Public Function GetVisualBasicAnalyzerOptions(context As OperationAnalysisContext) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.Operation.Syntax.SyntaxTree), context.Options)
+ End Function
+
+
+ Public Function GetVisualBasicAnalyzerOptions(context As CodeBlockAnalysisContext) As VisualBasicAnalyzerOptionsProvider
+ Return New VisualBasicAnalyzerOptionsProvider(context.Options.AnalyzerConfigOptionsProvider.GetOptions(context.SemanticModel.SyntaxTree), context.Options)
+ End Function
+ End Module
+End Namespace
diff --git a/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb
index 2fcc707c4c1f8..1b4c58c2d5a4c 100644
--- a/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb
@@ -2,6 +2,7 @@
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
+Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.OrderModifiers
Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle
@@ -20,6 +21,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers
LanguageNames.VisualBasic)
End Sub
+ Protected Overrides Function GetPreferredOrderStyle(context As SyntaxTreeAnalysisContext) As CodeStyleOption2(Of String)
+ Return context.GetVisualBasicAnalyzerOptions().PreferredModifierOrder
+ End Function
+
Protected Overrides Sub Recurse(
context As SyntaxTreeAnalysisContext,
preferredOrder As Dictionary(Of Integer, Integer),
diff --git a/src/Analyzers/VisualBasic/Analyzers/QualifyMemberAccess/VisualBasicQualifyMemberAccessDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/QualifyMemberAccess/VisualBasicQualifyMemberAccessDiagnosticAnalyzer.vb
index 46aaf5e54f4c9..17140ff3275a1 100644
--- a/src/Analyzers/VisualBasic/Analyzers/QualifyMemberAccess/VisualBasicQualifyMemberAccessDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/QualifyMemberAccess/VisualBasicQualifyMemberAccessDiagnosticAnalyzer.vb
@@ -6,19 +6,22 @@ Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.QualifyMemberAccess
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Simplification
+Imports Microsoft.CodeAnalysis.Simplification
Namespace Microsoft.CodeAnalysis.VisualBasic.QualifyMemberAccess
Friend NotInheritable Class VisualBasicQualifyMemberAccessDiagnosticAnalyzer
- Inherits AbstractQualifyMemberAccessDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, SimpleNameSyntax, VisualBasicSimplifierOptions)
+ Inherits AbstractQualifyMemberAccessDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, SimpleNameSyntax)
Protected Overrides Function GetLanguageName() As String
Return LanguageNames.VisualBasic
End Function
- Protected Overrides Function GetSimplifierOptions(options As AnalyzerOptions, syntaxTree As SyntaxTree) As VisualBasicSimplifierOptions
- Return options.GetVisualBasicSimplifierOptions(syntaxTree)
- End Function
+ Protected Overrides ReadOnly Property Simplification As ISimplification
+ Get
+ Return VisualBasicSimplification.Instance
+ End Get
+ End Property
Protected Overrides Function IsAlreadyQualifiedMemberAccess(node As ExpressionSyntax) As Boolean
Return node.IsKind(SyntaxKind.MeExpression)
diff --git a/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb
index 0793ef3ebc050..e39bf4080a7bb 100644
--- a/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb
@@ -2,6 +2,7 @@
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
+Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues
@@ -20,6 +21,14 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues
LanguageNames.VisualBasic)
End Sub
+ Protected Overrides Function GetUnusedValueExpressionStatementOption(provider As AnalyzerOptionsProvider) As CodeStyleOption2(Of UnusedValuePreference)
+ Return CType(provider, VisualBasicAnalyzerOptionsProvider).UnusedValueExpressionStatement
+ End Function
+
+ Protected Overrides Function GetUnusedValueAssignmentOption(provider As AnalyzerOptionsProvider) As CodeStyleOption2(Of UnusedValuePreference)
+ Return CType(provider, VisualBasicAnalyzerOptionsProvider).UnusedValueAssignment
+ End Function
+
Protected Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean
Return False
End Function
diff --git a/src/Analyzers/VisualBasic/Analyzers/Simplification/VisualBasicSimplifierOptionsFactory.vb b/src/Analyzers/VisualBasic/Analyzers/Simplification/VisualBasicSimplifierOptionsFactory.vb
deleted file mode 100644
index 34c589d637c12..0000000000000
--- a/src/Analyzers/VisualBasic/Analyzers/Simplification/VisualBasicSimplifierOptionsFactory.vb
+++ /dev/null
@@ -1,24 +0,0 @@
-' Licensed to the .NET Foundation under one or more agreements.
-' The .NET Foundation licenses this file to you under the MIT license.
-' See the LICENSE file in the project root for more information.
-
-Imports System.Runtime.CompilerServices
-Imports Microsoft.CodeAnalysis.Diagnostics
-
-Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
- Friend Module VisualBasicSimplifierOptionsFactory
-
- Public Function GetVisualBasicSimplifierOptions(options As AnalyzerOptions, syntaxTree As SyntaxTree) As VisualBasicSimplifierOptions
- Dim configOptions = options.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree)
- Dim ideOptions = options.GetIdeOptions()
-
-#If CODE_STYLE Then
- Dim fallbackOptions As VisualBasicSimplifierOptions = Nothing
-#Else
- Dim fallbackOptions = DirectCast(ideOptions.CleanupOptions?.SimplifierOptions, VisualBasicSimplifierOptions)
-#End If
- Return VisualBasicSimplifierOptions.Create(configOptions, fallbackOptions)
- End Function
- End Module
-End Namespace
-
diff --git a/src/Analyzers/VisualBasic/Analyzers/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationDiagnosticAnalyzer.vb
index 047c0a2b797cf..1d3c7dab45686 100644
--- a/src/Analyzers/VisualBasic/Analyzers/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationDiagnosticAnalyzer.vb
@@ -35,15 +35,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation
' which can be simplified to
' Dim x As New SomeType()
- Dim node = context.Node
- Dim tree = node.SyntaxTree
- Dim cancellationToken = context.CancellationToken
-
- Dim styleOption = context.Options.GetOption(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, tree, cancellationToken)
+ Dim styleOption = context.GetVisualBasicAnalyzerOptions().PreferSimplifiedObjectCreation
If Not styleOption.Value Then
Return
End If
+ Dim node = context.Node
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
Dim asClauseType = variableDeclarator.AsClause?.Type()
If asClauseType Is Nothing Then
@@ -55,6 +52,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation
Return
End If
+ Dim cancellationToken = context.CancellationToken
Dim symbolInfo = context.SemanticModel.GetTypeInfo(objectCreation, cancellationToken)
If symbolInfo.Type IsNot Nothing AndAlso symbolInfo.Type.Equals(symbolInfo.ConvertedType, SymbolEqualityComparer.Default) Then
context.ReportDiagnostic(DiagnosticHelper.Create(Descriptor, variableDeclarator.GetLocation(), styleOption.Notification.Severity,
diff --git a/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb
index 18efec569d8d0..40bb8d0c8b8e5 100644
--- a/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb
@@ -24,37 +24,27 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName
SyntaxKind.NameColonEquals, SyntaxKind.NamedFieldInitializer)
End Sub
- Protected Overrides Sub LanguageSpecificAnalyzeSyntax(context As SyntaxNodeAnalysisContext,
- syntaxTree As SyntaxTree,
- options As AnalyzerOptions,
- cancellationToken As CancellationToken)
- Dim parseOptions = DirectCast(syntaxTree.Options, VisualBasicParseOptions)
+ Protected Overrides Sub AnalyzeSyntax(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.NameColonEquals
- ReportDiagnosticsIfNeeded(DirectCast(context.Node, NameColonEqualsSyntax), context, options, syntaxTree, parseOptions, cancellationToken)
+ ReportDiagnosticsIfNeeded(DirectCast(context.Node, NameColonEqualsSyntax), context)
Exit Select
Case SyntaxKind.NamedFieldInitializer
- ReportDiagnosticsIfNeeded(DirectCast(context.Node, NamedFieldInitializerSyntax), context, options, syntaxTree, cancellationToken)
+ ReportDiagnosticsIfNeeded(DirectCast(context.Node, NamedFieldInitializerSyntax), context)
Exit Select
End Select
End Sub
- Private Sub ReportDiagnosticsIfNeeded(nameColonEquals As NameColonEqualsSyntax,
- context As SyntaxNodeAnalysisContext,
- options As AnalyzerOptions,
- syntaxTree As SyntaxTree,
- parseOptions As VisualBasicParseOptions,
- cancellationToken As CancellationToken)
+ Private Sub ReportDiagnosticsIfNeeded(nameColonEquals As NameColonEqualsSyntax, context As SyntaxNodeAnalysisContext)
If Not nameColonEquals.IsParentKind(SyntaxKind.SimpleArgument) Then
Return
End If
+ Dim syntaxTree = context.Node.SyntaxTree
Dim argument = DirectCast(nameColonEquals.Parent, SimpleArgumentSyntax)
- Dim preference = options.GetOption(
- CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken)
- If Not preference.Value OrElse
- Not CanSimplifyTupleName(argument, parseOptions) Then
+ Dim preference = context.GetAnalyzerOptions().PreferInferredTupleNames
+ If Not preference.Value OrElse Not CanSimplifyTupleName(argument, DirectCast(syntaxTree.Options, VisualBasicParseOptions)) Then
Return
End If
@@ -69,27 +59,20 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName
additionalUnnecessaryLocations:=ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan))))
End Sub
- Private Sub ReportDiagnosticsIfNeeded(
- fieldInitializer As NamedFieldInitializerSyntax,
- context As SyntaxNodeAnalysisContext,
- options As AnalyzerOptions,
- syntaxTree As SyntaxTree,
- cancellationToken As CancellationToken)
+ Private Sub ReportDiagnosticsIfNeeded(fieldInitializer As NamedFieldInitializerSyntax, context As SyntaxNodeAnalysisContext)
If Not fieldInitializer.Parent.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression) Then
Return
End If
- Dim preference = options.GetOption(
- CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken)
- If Not preference.Value OrElse
- Not CanSimplifyNamedFieldInitializer(fieldInitializer) Then
-
+ Dim preference = context.GetAnalyzerOptions().PreferInferredAnonymousTypeMemberNames
+ If Not preference.Value OrElse Not CanSimplifyNamedFieldInitializer(fieldInitializer) Then
Return
End If
Dim fadeSpan = TextSpan.FromBounds(fieldInitializer.Name.SpanStart, fieldInitializer.EqualsToken.Span.End)
' Create a normal diagnostic
+ Dim syntaxTree = context.Node.SyntaxTree
context.ReportDiagnostic(
DiagnosticHelper.CreateWithLocationTags(
Descriptor,
diff --git a/src/Analyzers/VisualBasic/Analyzers/UseIsNotExpression/VisualBasicUseIsNotDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/UseIsNotExpression/VisualBasicUseIsNotDiagnosticAnalyzer.vb
index 719a784d27b81..1d45d92b2af15 100644
--- a/src/Analyzers/VisualBasic/Analyzers/UseIsNotExpression/VisualBasicUseIsNotDiagnosticAnalyzer.vb
+++ b/src/Analyzers/VisualBasic/Analyzers/UseIsNotExpression/VisualBasicUseIsNotDiagnosticAnalyzer.vb
@@ -50,11 +50,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseIsNotExpression
Return
End If
- Dim options = syntaxContext.Options
- Dim cancellationToken = syntaxContext.CancellationToken
-
' Bail immediately if the user has disabled this feature.
- Dim styleOption = options.GetOption(VisualBasicCodeStyleOptions.PreferIsNotExpression, syntaxTree, cancellationToken)
+ Dim styleOption = syntaxContext.GetVisualBasicAnalyzerOptions().PreferIsNotExpression
If Not styleOption.Value Then
Return
End If
diff --git a/src/Analyzers/VisualBasic/Analyzers/VisualBasicAnalyzers.projitems b/src/Analyzers/VisualBasic/Analyzers/VisualBasicAnalyzers.projitems
index 72e888f4bef43..070ab2de95fab 100644
--- a/src/Analyzers/VisualBasic/Analyzers/VisualBasicAnalyzers.projitems
+++ b/src/Analyzers/VisualBasic/Analyzers/VisualBasicAnalyzers.projitems
@@ -16,6 +16,7 @@
+
@@ -36,7 +37,6 @@
-
diff --git a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb
index 56538b61ca959..30e17a46e3b1b 100644
--- a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb
+++ b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb
@@ -6,23 +6,28 @@ Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
+Imports Microsoft.CodeAnalysis.CodeStyle
+Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.OrderModifiers
Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers
- Friend Class VisualBasicOrderModifiersCodeFixProvider
+ Friend NotInheritable Class VisualBasicOrderModifiersCodeFixProvider
Inherits AbstractOrderModifiersCodeFixProvider
Public Sub New()
MyBase.New(VisualBasicSyntaxFacts.Instance,
- VisualBasicCodeStyleOptions.PreferredModifierOrder,
VisualBasicOrderModifiersHelper.Instance)
End Sub
+ Protected Overrides Function GetCodeStyleOption(options As AnalyzerOptionsProvider) As CodeStyleOption2(Of String)
+ Return CType(options, VisualBasicAnalyzerOptionsProvider).PreferredModifierOrder
+ End Function
+
Protected Overrides ReadOnly Property FixableCompilerErrorIds As ImmutableArray(Of String) =
ImmutableArray(Of String).Empty
End Class
diff --git a/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb b/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb
index f8296812fa0ae..a1121699eefb0 100644
--- a/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb
+++ b/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb
@@ -419,7 +419,7 @@ end namespace"
Dim test As New VerifyVB.Test()
test.TestCode = source
test.FixedCode = fixedSource
- test.Options.Add(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault)
+ test.Options.Add(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault)
Await test.RunAsync()
End Function
diff --git a/src/CodeStyle/Core/Analyzers/Options/AnalyzerOptionsExtensions.cs b/src/CodeStyle/Core/Analyzers/Options/AnalyzerOptionsExtensions.cs
deleted file mode 100644
index c3a38a3e69e64..0000000000000
--- a/src/CodeStyle/Core/Analyzers/Options/AnalyzerOptionsExtensions.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading;
-using Microsoft.CodeAnalysis.Options;
-
-namespace Microsoft.CodeAnalysis.Diagnostics
-{
- internal static partial class AnalyzerOptionsExtensions
- {
-#pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer.
- public static T GetOption(this AnalyzerOptions analyzerOptions, IOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken)
-#pragma warning restore IDE0060 // Remove unused parameter
- {
- if (analyzerOptions.TryGetEditorConfigOption(option, syntaxTree, out var value))
- {
- return value;
- }
-
- return (T)option.DefaultValue!;
- }
-
- public static T GetOption(this AnalyzerOptions analyzerOptions, Option2 option, SyntaxTree syntaxTree, CancellationToken cancellationToken)
- => GetOption(analyzerOptions, option, language: null, syntaxTree, cancellationToken);
-
- public static T GetOption(this AnalyzerOptions analyzerOptions, PerLanguageOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken)
- => GetOption(analyzerOptions, (IOption2)option, language, syntaxTree, cancellationToken);
-
-#pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer.
- public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken)
-#pragma warning restore IDE0060 // Remove unused parameter
- => analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree);
- }
-}
diff --git a/src/EditorFeatures/CSharp/AddImports/CSharpAddImportPlacementOptionsStorage.cs b/src/EditorFeatures/CSharp/AddImports/CSharpAddImportPlacementOptionsStorage.cs
index ad0d107bfa788..dc0dd06280961 100644
--- a/src/EditorFeatures/CSharp/AddImports/CSharpAddImportPlacementOptionsStorage.cs
+++ b/src/EditorFeatures/CSharp/AddImports/CSharpAddImportPlacementOptionsStorage.cs
@@ -29,8 +29,10 @@ public AddImportPlacementOptions GetOptions(IGlobalOptionService globalOptions)
}
internal static AddImportPlacementOptions GetCSharpAddImportPlacementOptions(IGlobalOptionService globalOptions)
- => new(
- PlaceSystemNamespaceFirst: globalOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp),
- PlaceImportsInsideNamespaces: globalOptions.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement).Value == AddImportPlacement.InsideNamespace,
- AllowInHiddenRegions: false); // no global option available);
+ => new()
+ {
+ PlaceSystemNamespaceFirst = globalOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp),
+ UsingDirectivePlacement = globalOptions.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement),
+ AllowInHiddenRegions = AddImportPlacementOptions.Default.AllowInHiddenRegions // no global option available);
+ };
}
diff --git a/src/EditorFeatures/CSharp/CodeGeneration/CSharpCodeGenerationOptionsStorage.cs b/src/EditorFeatures/CSharp/CodeGeneration/CSharpCodeGenerationOptionsStorage.cs
index bcc22b55fd833..6066335b7f7c0 100644
--- a/src/EditorFeatures/CSharp/CodeGeneration/CSharpCodeGenerationOptionsStorage.cs
+++ b/src/EditorFeatures/CSharp/CodeGeneration/CSharpCodeGenerationOptionsStorage.cs
@@ -27,15 +27,18 @@ public CodeGenerationOptions GetOptions(IGlobalOptionService globalOptions)
}
public static CSharpCodeGenerationOptions GetCSharpCodeGenerationOptions(this IGlobalOptionService globalOptions)
- => new(
- preferExpressionBodiedMethods: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods),
- preferExpressionBodiedAccessors: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors),
- preferExpressionBodiedProperties: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties),
- preferExpressionBodiedIndexers: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers),
- preferExpressionBodiedConstructors: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors),
- preferExpressionBodiedOperators: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators),
- preferExpressionBodiedLocalFunctions: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions),
- preferExpressionBodiedLambdas: globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas),
- preferStaticLocalFunction: globalOptions.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction),
- namespaceDeclarations: globalOptions.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations));
+ => new()
+ {
+ Common = globalOptions.GetCommonCodeGenerationOptions(LanguageNames.CSharp),
+ PreferExpressionBodiedMethods = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods),
+ PreferExpressionBodiedAccessors = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors),
+ PreferExpressionBodiedProperties = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties),
+ PreferExpressionBodiedIndexers = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers),
+ PreferExpressionBodiedConstructors = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors),
+ PreferExpressionBodiedOperators = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators),
+ PreferExpressionBodiedLocalFunctions = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions),
+ PreferExpressionBodiedLambdas = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas),
+ PreferStaticLocalFunction = globalOptions.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction),
+ NamespaceDeclarations = globalOptions.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations)
+ };
}
diff --git a/src/EditorFeatures/CSharp/CodeStyle/CSharpCodeStyleOptionsStorage.cs b/src/EditorFeatures/CSharp/CodeStyle/CSharpCodeStyleOptionsStorage.cs
new file mode 100644
index 0000000000000..310a71de65532
--- /dev/null
+++ b/src/EditorFeatures/CSharp/CodeStyle/CSharpCodeStyleOptionsStorage.cs
@@ -0,0 +1,59 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Composition;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.Host.Mef;
+using Microsoft.CodeAnalysis.Options;
+
+namespace Microsoft.CodeAnalysis.CSharp.CodeStyle;
+
+internal static class CSharpCodeStyleOptionsStorage
+{
+ [ExportLanguageService(typeof(ICodeStyleOptionsStorage), LanguageNames.CSharp), Shared]
+ private sealed class Service : ICodeStyleOptionsStorage
+ {
+ [ImportingConstructor]
+ [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
+ public Service()
+ {
+ }
+
+ public IdeCodeStyleOptions GetOptions(IGlobalOptionService globalOptions)
+ => GetCSharpCodeStyleOptions(globalOptions);
+ }
+
+ public static CSharpIdeCodeStyleOptions GetCSharpCodeStyleOptions(this IGlobalOptionService globalOptions)
+ => new()
+ {
+ Common = globalOptions.GetCommonCodeStyleOptions(LanguageNames.CSharp),
+ ImplicitObjectCreationWhenTypeIsApparent = globalOptions.GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent),
+ PreferNullCheckOverTypeCheck = globalOptions.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck),
+ AllowBlankLinesBetweenConsecutiveBraces = globalOptions.GetOption(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces),
+ AllowBlankLineAfterColonInConstructorInitializer = globalOptions.GetOption(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer),
+ PreferConditionalDelegateCall = globalOptions.GetOption(CSharpCodeStyleOptions.PreferConditionalDelegateCall),
+ PreferSwitchExpression = globalOptions.GetOption(CSharpCodeStyleOptions.PreferSwitchExpression),
+ PreferPatternMatching = globalOptions.GetOption(CSharpCodeStyleOptions.PreferPatternMatching),
+ PreferPatternMatchingOverAsWithNullCheck = globalOptions.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck),
+ PreferPatternMatchingOverIsWithCastCheck = globalOptions.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck),
+ PreferNotPattern = globalOptions.GetOption(CSharpCodeStyleOptions.PreferNotPattern),
+ PreferExtendedPropertyPattern = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExtendedPropertyPattern),
+ PreferInlinedVariableDeclaration = globalOptions.GetOption(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration),
+ PreferDeconstructedVariableDeclaration = globalOptions.GetOption(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration),
+ PreferIndexOperator = globalOptions.GetOption(CSharpCodeStyleOptions.PreferIndexOperator),
+ PreferRangeOperator = globalOptions.GetOption(CSharpCodeStyleOptions.PreferRangeOperator),
+ PreferUtf8StringLiterals = globalOptions.GetOption(CSharpCodeStyleOptions.PreferUtf8StringLiterals),
+ PreferredModifierOrder = globalOptions.GetOption(CSharpCodeStyleOptions.PreferredModifierOrder),
+ PreferSimpleUsingStatement = globalOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleUsingStatement),
+ PreferLocalOverAnonymousFunction = globalOptions.GetOption(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction),
+ PreferTupleSwap = globalOptions.GetOption(CSharpCodeStyleOptions.PreferTupleSwap),
+ UnusedValueExpressionStatement = globalOptions.GetOption(CSharpCodeStyleOptions.UnusedValueExpressionStatement),
+ UnusedValueAssignment = globalOptions.GetOption(CSharpCodeStyleOptions.UnusedValueAssignment),
+ PreferMethodGroupConversion = globalOptions.GetOption(CSharpCodeStyleOptions.PreferMethodGroupConversion),
+ PreferExpressionBodiedLambdas = globalOptions.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas),
+ PreferStaticLocalFunction = globalOptions.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction)
+ };
+}
diff --git a/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs b/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs
index c69e5095e5583..2dc085774397a 100644
--- a/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs
+++ b/src/EditorFeatures/CSharp/ConvertNamespace/ConvertNamespaceCommandHandler.cs
@@ -41,16 +41,12 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.CompleteStatement
internal sealed class ConvertNamespaceCommandHandler : IChainedCommandHandler
{
///
- /// A fake option set where the 'use file scoped' namespace option is on. That way we can call into the helpers
+ /// Option setting 'use file scoped'. That way we can call into the helpers
/// and have the results come back positive for converting to file-scoped regardless of the current option
/// value.
///
- private static readonly OptionSet s_optionSet = new OptionValueSet(
- ImmutableDictionary.Empty.Add(
- new OptionKey(CSharpCodeStyleOptions.NamespaceDeclarations.ToPublicOption()),
- new CodeStyleOption2(
- NamespaceDeclarationPreference.FileScoped,
- NotificationOption2.Suggestion)));
+ private static readonly CodeStyleOption2 s_fileScopedNamespacePreferenceOption =
+ new(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Suggestion);
private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
@@ -148,7 +144,7 @@ public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler,
return default;
// Pass in our special options, and C#10 so that if we can convert this to file-scoped, we will.
- if (!ConvertNamespaceAnalysis.CanOfferUseFileScoped(s_optionSet, root, namespaceDecl, forAnalyzer: true, LanguageVersion.CSharp10))
+ if (!ConvertNamespaceAnalysis.CanOfferUseFileScoped(s_fileScopedNamespacePreferenceOption, root, namespaceDecl, forAnalyzer: true, LanguageVersion.CSharp10))
return default;
var formattingOptions = document.GetSyntaxFormattingOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
diff --git a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs
index 5606d85163c18..c4ced23d2c59a 100644
--- a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs
+++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager.cs
@@ -12,6 +12,7 @@
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
@@ -24,8 +25,9 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup
internal sealed partial class EventHookupSessionManager
{
public readonly IThreadingContext ThreadingContext;
-
private readonly IToolTipService _toolTipService;
+ private readonly IGlobalOptionService _globalOptions;
+
private IToolTipPresenter _toolTipPresenter;
internal EventHookupSession CurrentSession { get; set; }
@@ -35,10 +37,14 @@ internal sealed partial class EventHookupSessionManager
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public EventHookupSessionManager(IThreadingContext threadingContext, IToolTipService toolTipService)
+ public EventHookupSessionManager(
+ IThreadingContext threadingContext,
+ IToolTipService toolTipService,
+ IGlobalOptionService globalOptions)
{
ThreadingContext = threadingContext;
_toolTipService = toolTipService;
+ _globalOptions = globalOptions;
}
internal void EventHookupFoundInSession(EventHookupSession analyzedSession)
@@ -112,7 +118,7 @@ internal void BeginSession(
IAsynchronousOperationListener asyncListener,
Mutex testSessionHookupMutex)
{
- CurrentSession = new EventHookupSession(this, eventHookupCommandHandler, textView, subjectBuffer, asyncListener, testSessionHookupMutex);
+ CurrentSession = new EventHookupSession(this, eventHookupCommandHandler, textView, subjectBuffer, asyncListener, _globalOptions, testSessionHookupMutex);
}
internal void CancelAndDismissExistingSessions()
diff --git a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs
index 023e5695f872d..0b15a219962aa 100644
--- a/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs
+++ b/src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs
@@ -19,6 +19,7 @@
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
@@ -46,6 +47,7 @@ internal class EventHookupSession
private readonly ITrackingSpan _trackingSpan;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
+ private readonly IGlobalOptionService _globalOptions;
public event Action Dismissed = () => { };
@@ -100,12 +102,14 @@ public EventHookupSession(
ITextView textView,
ITextBuffer subjectBuffer,
IAsynchronousOperationListener asyncListener,
+ IGlobalOptionService globalOptions,
Mutex testSessionHookupMutex)
{
_threadingContext = eventHookupSessionManager.ThreadingContext;
var cancellationToken = _cancellationTokenSource.Token;
_textView = textView;
_subjectBuffer = subjectBuffer;
+ _globalOptions = globalOptions;
this.TESTSessionHookupMutex = testSessionHookupMutex;
var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
@@ -180,7 +184,9 @@ private async Task DetermineIfEventHookupAndGetHandlerNameAsync(Document
var namingRule = await document.GetApplicableNamingRuleAsync(
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new DeclarationModifiers(isStatic: plusEqualsToken.Value.Parent.IsInStaticContext()),
- Accessibility.Private, cancellationToken).ConfigureAwait(false);
+ Accessibility.Private,
+ _globalOptions.CreateProvider(),
+ cancellationToken).ConfigureAwait(false);
return GetEventHandlerName(
eventSymbol, plusEqualsToken.Value, semanticModel,
diff --git a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs
index 23f62b98e5281..71afe5236003f 100644
--- a/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs
+++ b/src/EditorFeatures/CSharp/Formatting/CSharpFormattingInteractionService.cs
@@ -121,10 +121,13 @@ public async Task> GetFormattingChangesAsync(Document
if (await service.ShouldFormatOnTypedCharacterAsync(document, typedChar, position, cancellationToken).ConfigureAwait(false))
{
var fallbackOptions = _globalOptions.GetCSharpSyntaxFormattingOptions();
- var autoFormattingOptions = _globalOptions.GetAutoFormattingOptions(LanguageNames.CSharp);
- var indentStyle = _globalOptions.GetOption(IndentationOptionsStorage.SmartIndent, LanguageNames.CSharp);
var formattingOptions = await _indentationManager.GetInferredFormattingOptionsAsync(document, fallbackOptions, explicitFormat: false, cancellationToken).ConfigureAwait(false);
- var indentationOptions = new IndentationOptions(formattingOptions, autoFormattingOptions, indentStyle);
+
+ var indentationOptions = new IndentationOptions(formattingOptions)
+ {
+ AutoFormattingOptions = _globalOptions.GetAutoFormattingOptions(LanguageNames.CSharp),
+ IndentStyle = _globalOptions.GetOption(IndentationOptionsStorage.SmartIndent, LanguageNames.CSharp)
+ };
return await service.GetFormattingChangesOnTypedCharacterAsync(document, position, indentationOptions, cancellationToken).ConfigureAwait(false);
}
diff --git a/src/EditorFeatures/CSharp/Formatting/CSharpSyntaxFormattingOptionsStorage.cs b/src/EditorFeatures/CSharp/Formatting/CSharpSyntaxFormattingOptionsStorage.cs
index 46fbaea7a03eb..1fb25372b00e6 100644
--- a/src/EditorFeatures/CSharp/Formatting/CSharpSyntaxFormattingOptionsStorage.cs
+++ b/src/EditorFeatures/CSharp/Formatting/CSharpSyntaxFormattingOptionsStorage.cs
@@ -30,10 +30,10 @@ public SyntaxFormattingOptions GetOptions(IGlobalOptionService globalOptions)
}
public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(this IGlobalOptionService globalOptions)
- => new(
- lineFormatting: globalOptions.GetLineFormattingOptions(LanguageNames.CSharp),
- separateImportDirectiveGroups: globalOptions.GetOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp),
- spacing:
+ => new()
+ {
+ Common = globalOptions.GetCommonSyntaxFormattingOptions(LanguageNames.CSharp),
+ Spacing =
(globalOptions.GetOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration) ? SpacePlacement.IgnoreAroundVariableDeclaration : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName) ? SpacePlacement.AfterMethodDeclarationName : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses) ? SpacePlacement.BetweenEmptyMethodDeclarationParentheses : 0) |
@@ -57,8 +57,8 @@ public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(thi
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceBeforeComma) ? SpacePlacement.BeforeComma : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceAfterDot) ? SpacePlacement.AfterDot : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.SpaceBeforeDot) ? SpacePlacement.BeforeDot : 0),
- spacingAroundBinaryOperator: globalOptions.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator),
- newLines:
+ SpacingAroundBinaryOperator = globalOptions.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator),
+ NewLines =
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit) ? NewLinePlacement.BeforeMembersInObjectInitializers : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes) ? NewLinePlacement.BeforeMembersInAnonymousTypes : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForElse) ? NewLinePlacement.BeforeElse : 0) |
@@ -74,13 +74,16 @@ public static CSharpSyntaxFormattingOptions GetCSharpSyntaxFormattingOptions(thi
(globalOptions.GetOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody) ? NewLinePlacement.BeforeOpenBraceInLambdaExpressionBody : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks) ? NewLinePlacement.BeforeOpenBraceInControlBlocks : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.NewLineForClausesInQuery) ? NewLinePlacement.BetweenQueryExpressionClauses : 0),
- labelPositioning: globalOptions.GetOption(CSharpFormattingOptions2.LabelPositioning),
- indentation:
+ LabelPositioning = globalOptions.GetOption(CSharpFormattingOptions2.LabelPositioning),
+ Indentation =
(globalOptions.GetOption(CSharpFormattingOptions2.IndentBraces) ? IndentationPlacement.Braces : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentBlock) ? IndentationPlacement.BlockContents : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSection) ? IndentationPlacement.SwitchCaseContents : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock) ? IndentationPlacement.SwitchCaseContentsWhenBlock : 0) |
(globalOptions.GetOption(CSharpFormattingOptions2.IndentSwitchSection) ? IndentationPlacement.SwitchSection : 0),
- wrappingKeepStatementsOnSingleLine: globalOptions.GetOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine),
- wrappingPreserveSingleLine: globalOptions.GetOption(CSharpFormattingOptions2.WrappingPreserveSingleLine));
+ WrappingKeepStatementsOnSingleLine = globalOptions.GetOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine),
+ WrappingPreserveSingleLine = globalOptions.GetOption(CSharpFormattingOptions2.WrappingPreserveSingleLine),
+ NamespaceDeclarations = globalOptions.GetOption(CSharpCodeStyleOptions.NamespaceDeclarations),
+ PreferTopLevelStatements = globalOptions.GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements)
+ };
}
diff --git a/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs b/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs
index 003bb8a6aa192..b182d031c8e5f 100644
--- a/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs
+++ b/src/EditorFeatures/CSharp/Simplification/CSharpSimplifierOptionsStorage.cs
@@ -28,16 +28,16 @@ public SimplifierOptions GetOptions(IGlobalOptionService globalOptions)
}
public static CSharpSimplifierOptions GetCSharpSimplifierOptions(this IGlobalOptionService globalOptions)
- => new(
- qualifyFieldAccess: globalOptions.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp),
- qualifyPropertyAccess: globalOptions.GetOption(CodeStyleOptions2.QualifyPropertyAccess, LanguageNames.CSharp),
- qualifyMethodAccess: globalOptions.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.CSharp),
- qualifyEventAccess: globalOptions.GetOption(CodeStyleOptions2.QualifyEventAccess, LanguageNames.CSharp),
- preferPredefinedTypeKeywordInMemberAccess: globalOptions.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.CSharp),
- preferPredefinedTypeKeywordInDeclaration: globalOptions.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.CSharp),
- varForBuiltInTypes: globalOptions.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes),
- varWhenTypeIsApparent: globalOptions.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent),
- varElsewhere: globalOptions.GetOption(CSharpCodeStyleOptions.VarElsewhere),
- preferSimpleDefaultExpression: globalOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression),
- preferBraces: globalOptions.GetOption(CSharpCodeStyleOptions.PreferBraces));
+ => new()
+ {
+ Common = globalOptions.GetCommonSimplifierOptions(LanguageNames.CSharp),
+ VarForBuiltInTypes = globalOptions.GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes),
+ VarWhenTypeIsApparent = globalOptions.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent),
+ VarElsewhere = globalOptions.GetOption(CSharpCodeStyleOptions.VarElsewhere),
+ PreferSimpleDefaultExpression = globalOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression),
+ PreferParameterNullChecking = globalOptions.GetOption(CSharpCodeStyleOptions.PreferParameterNullChecking),
+ AllowEmbeddedStatementsOnSameLine = globalOptions.GetOption(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine),
+ PreferBraces = globalOptions.GetOption(CSharpCodeStyleOptions.PreferBraces),
+ PreferThrowExpression = globalOptions.GetOption(CSharpCodeStyleOptions.PreferThrowExpression),
+ };
}
diff --git a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs
index f7e7b9268100b..cb4a12bf858bb 100644
--- a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs
+++ b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral
{
- [ExportGlobalOptionProvider(LanguageNames.CSharp), Shared]
- internal sealed class SplitStringLiteralOptions : IOptionProvider
+ internal sealed class SplitStringLiteralOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public SplitStringLiteralOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- Enabled);
-
public static PerLanguageOption2 Enabled =
new(nameof(SplitStringLiteralOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitStringLiterals"));
diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs
index 3016951f6643a..3061500938ecb 100644
--- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs
+++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs
@@ -908,10 +908,7 @@ class Inner2
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
- onAfterWorkspaceCreated: w =>
- {
- w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true)));
- });
+ options: Option(FormattingOptions2.InsertFinalNewLine, true));
}
[WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")]
@@ -949,10 +946,7 @@ class Inner2
await TestMoveTypeToNewFileAsync(
code, codeAfterMove, expectedDocumentName, destinationDocumentText,
- onAfterWorkspaceCreated: w =>
- {
- w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false)));
- });
+ options: Option(FormattingOptions2.InsertFinalNewLine, false));
}
[WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")]
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs
index b678981c1a3cd..dc5cb8036fe9d 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.cs
@@ -51,13 +51,14 @@ private protected override Task BaseVerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null, bool skipSpeculation = false)
{
return base.VerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, skipSpeculation: skipSpeculation);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation);
}
private protected override async Task VerifyWorkerAsync(
@@ -66,19 +67,20 @@ private protected override async Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger,
bool checkForAbsence, int? glyph, int? matchPriority,
bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null,
- bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null, bool skipSpeculation = false)
{
- await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
- await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
- await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters);
+ await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options, skipSpeculation: skipSpeculation);
+ await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation);
+ await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options);
// Items cannot be partially written if we're checking for their absence,
// or if we're verifying that the list will show up (without specifying an actual item)
if (!checkForAbsence && expectedItemOrNull != null)
{
- await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
- await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
- await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters);
+ await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options, skipSpeculation: skipSpeculation);
+ await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation);
+ await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options);
}
}
@@ -90,7 +92,8 @@ private async Task VerifyInFrontOfCommentAsync(
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
- string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List matchingFilters, bool skipSpeculation = false)
+ string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List matchingFilters,
+ CompletionOptions options, bool skipSpeculation = false)
{
code = code.Substring(0, position) + insertText + "/**/" + code.Substring(position);
position += insertText.Length;
@@ -99,7 +102,8 @@ await base.VerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph,
matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix,
- inlineDescription, isComplexTextEdit, matchingFilters, flags: null, skipSpeculation: skipSpeculation);
+ inlineDescription, isComplexTextEdit, matchingFilters, flags: null,
+ options, skipSpeculation: skipSpeculation);
}
private async Task VerifyInFrontOfCommentAsync(
@@ -108,13 +112,13 @@ private async Task VerifyInFrontOfCommentAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit,
- List matchingFilters, bool skipSpeculation = false)
+ List matchingFilters, CompletionOptions options, bool skipSpeculation = false)
{
await VerifyInFrontOfCommentAsync(
code, position, string.Empty, usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation);
}
private protected async Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync(
@@ -123,13 +127,13 @@ private protected async Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit,
- List matchingFilters, bool skipSpeculation = false)
+ List matchingFilters, CompletionOptions options, bool skipSpeculation = false)
{
await VerifyInFrontOfCommentAsync(
code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, skipSpeculation: skipSpeculation);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, options, skipSpeculation: skipSpeculation);
}
protected static string AddInsideMethod(string text)
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs
index f528845711a88..1a4450dbb2d62 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/CrefCompletionProviderTests.cs
@@ -34,17 +34,17 @@ private protected override async Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
await VerifyAtPositionAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
- isComplexTextEdit, matchingFilters, flags);
+ isComplexTextEdit, matchingFilters, flags, options);
await VerifyAtEndOfFileAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
- isComplexTextEdit, matchingFilters, flags);
+ isComplexTextEdit, matchingFilters, flags, options);
// Items cannot be partially written if we're checking for their absence,
// or if we're verifying that the list will show up (without specifying an actual item)
@@ -53,12 +53,12 @@ await VerifyAtEndOfFileAsync(
await VerifyAtPosition_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options);
await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null, options);
}
}
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs
index 72bf2ff1a344c..ba2b9fe1ddaae 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs
@@ -8,6 +8,8 @@
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
@@ -697,9 +699,11 @@ public async Task Parameter13()
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption(
- new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp),
- ParameterCamelCaseWithPascalCaseFallback())));
+
+ var options = new CompletionOptions()
+ {
+ NamingStyleFallbackOptions = ParameterCamelCaseWithPascalCaseFallback()
+ };
var markup = @"
using System.Threading;
@@ -708,8 +712,8 @@ public class C
void Goo(CancellationToken $$
}
";
- await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter);
- await VerifyItemIsAbsentAsync(markup, "CancellationToken");
+ await VerifyItemExistsAsync(markup, "cancellationToken", glyph: (int)Glyph.Parameter, options: options);
+ await VerifyItemIsAbsentAsync(markup, "CancellationToken", options: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
@@ -2415,9 +2419,11 @@ public async Task CustomNamingStyleInsideClass()
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption(
- new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp),
- NamesEndWithSuffixPreferences())));
+
+ var options = new CompletionOptions()
+ {
+ NamingStyleFallbackOptions = NamesEndWithSuffixPreferences()
+ };
var markup = @"
class Configuration
@@ -2426,13 +2432,13 @@ class Configuration
}
";
await VerifyItemExistsAsync(markup, "ConfigurationField", glyph: (int)Glyph.FieldPublic,
- expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name);
+ expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name, options: options);
await VerifyItemExistsAsync(markup, "ConfigurationProperty", glyph: (int)Glyph.PropertyPublic,
- expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name);
+ expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name, options: options);
await VerifyItemExistsAsync(markup, "ConfigurationMethod", glyph: (int)Glyph.MethodPublic,
- expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name);
- await VerifyItemIsAbsentAsync(markup, "ConfigurationLocal");
- await VerifyItemIsAbsentAsync(markup, "ConfigurationLocalFunction");
+ expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name, options: options);
+ await VerifyItemIsAbsentAsync(markup, "ConfigurationLocal", options: options);
+ await VerifyItemIsAbsentAsync(markup, "ConfigurationLocalFunction", options: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
@@ -2441,9 +2447,11 @@ public async Task CustomNamingStyleInsideMethod()
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption(
- new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp),
- NamesEndWithSuffixPreferences())));
+
+ var options = new CompletionOptions()
+ {
+ NamingStyleFallbackOptions = NamesEndWithSuffixPreferences()
+ };
var markup = @"
class Configuration
@@ -2455,12 +2463,12 @@ void M()
}
";
await VerifyItemExistsAsync(markup, "ConfigurationLocal", glyph: (int)Glyph.Local,
- expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name);
+ expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name, options: options);
await VerifyItemExistsAsync(markup, "ConfigurationLocalFunction", glyph: (int)Glyph.MethodPublic,
- expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name);
- await VerifyItemIsAbsentAsync(markup, "ConfigurationField");
- await VerifyItemIsAbsentAsync(markup, "ConfigurationMethod");
- await VerifyItemIsAbsentAsync(markup, "ConfigurationProperty");
+ expectedDescriptionOrNull: CSharpFeaturesResources.Suggested_name, options: options);
+ await VerifyItemIsAbsentAsync(markup, "ConfigurationField", options: options);
+ await VerifyItemIsAbsentAsync(markup, "ConfigurationMethod", options: options);
+ await VerifyItemIsAbsentAsync(markup, "ConfigurationProperty", options: options);
}
[WorkItem(31304, "https://github.com/dotnet/roslyn/issues/31304")]
@@ -2873,9 +2881,11 @@ public async Task ConflictingLocalVariable()
using var workspaceFixture = GetOrCreateWorkspaceFixture();
var workspace = workspaceFixture.Target.GetWorkspace(ExportProvider);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption(
- new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp),
- MultipleCamelCaseLocalRules())));
+
+ var options = new CompletionOptions()
+ {
+ NamingStyleFallbackOptions = MultipleCamelCaseLocalRules()
+ };
var markup = @"
public class MyClass
@@ -2887,7 +2897,7 @@ void M()
}
}
";
- await VerifyItemExistsAsync(markup, "myClass1", glyph: (int)Glyph.Local);
+ await VerifyItemExistsAsync(markup, "myClass1", glyph: (int)Glyph.Local, options: options);
}
private static NamingStylePreferences MultipleCamelCaseLocalRules()
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs
index 64b49d5e68b12..cfde13317732a 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs
@@ -35,13 +35,13 @@ private protected override Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
return BaseVerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
[Fact]
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
index 01eeb2900f505..c6de0cddb6809 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
@@ -38,7 +38,7 @@ private protected override Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
return BaseVerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs
index 96782593c5ee6..5e50a3369668d 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests_NoInteractive.cs
@@ -32,13 +32,13 @@ private protected override Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit,
- List matchingFilters, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
return base.VerifyWorkerAsync(code, position,
expectedItemOrNull, expectedDescriptionOrNull,
SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs
index 3968c9abbeb8b..a39114becbcd7 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs
@@ -43,18 +43,18 @@ private protected override async Task VerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
// We don't need to try writing comments in from of items in doc comments.
await VerifyAtPositionAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
- isComplexTextEdit, matchingFilters, flags);
+ isComplexTextEdit, matchingFilters, flags, options);
await VerifyAtEndOfFileAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
- isComplexTextEdit, matchingFilters, flags);
+ isComplexTextEdit, matchingFilters, flags, options);
// Items cannot be partially written if we're checking for their absence,
// or if we're verifying that the list will show up (without specifying an actual item)
@@ -63,12 +63,12 @@ await VerifyAtEndOfFileAsync(
await VerifyAtPosition_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
}
diff --git a/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs b/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs
index 6ab74c89276ad..a508282d1fc08 100644
--- a/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs
+++ b/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs
@@ -6,6 +6,7 @@
using System;
using System.Collections.Immutable;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
diff --git a/src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs
index 838fc48d9e4f5..93a7bcb562ded 100644
--- a/src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs
+++ b/src/EditorFeatures/CSharpTest/ConvertProgram/ConvertToProgramMainAnalyzerTests.cs
@@ -205,7 +205,7 @@ static void Main(string[] args)
TestState = { OutputKind = OutputKind.ConsoleApplication },
Options =
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Never },
{ CSharpCodeStyleOptions.PreferTopLevelStatements, false, NotificationOption2.Suggestion },
},
}.RunAsync();
diff --git a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs
index 7948d86cd5920..11a9f08e8fa74 100644
--- a/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs
+++ b/src/EditorFeatures/CSharpTest/ExtractInterface/ExtractInterfaceTests.cs
@@ -954,7 +954,7 @@ public void Goo() { }
markup, LanguageNames.CSharp,
options: new OptionsCollection(LanguageNames.CSharp)
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Silent }
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Always, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs
index 19610dfd66bab..80e8731319772 100644
--- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs
+++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs
@@ -17,6 +17,7 @@
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractMethod;
+using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
@@ -130,11 +131,10 @@ protected static async Task ExtractMethodAsync(
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
Assert.NotNull(document);
- var options = new ExtractMethodGenerationOptions(
- ExtractOptions: new ExtractMethodOptions(dontPutOutOrRefOnStruct),
- CodeGenerationOptions: CodeGenerationOptions.GetDefault(document.Project.LanguageServices),
- AddImportOptions: AddImportPlacementOptions.Default,
- NamingPreferences: _ => NamingStylePreferences.Default);
+ var options = new ExtractMethodGenerationOptions(CodeGenerationOptions.GetDefault(document.Project.LanguageServices))
+ {
+ ExtractOptions = new() { DontPutOutOrRefOnStruct = dontPutOutOrRefOnStruct }
+ };
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options.ExtractOptions, localFunction: false);
diff --git a/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs b/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs
index c0659745a7f1d..7ec2af1028a7f 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs
@@ -7,6 +7,7 @@
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities.Formatting;
@@ -37,9 +38,9 @@ namespace Goo;
internal class C
{
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) }
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
@@ -59,9 +60,9 @@ namespace Bar
await TestAsync(
testCode: testCode,
expected: testCode,
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) }
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10));
}
@@ -80,9 +81,9 @@ internal class C
await TestAsync(
testCode: testCode,
expected: testCode,
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) }
},
parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
@@ -104,9 +105,9 @@ internal class C
{
}
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error) }
});
}
@@ -119,9 +120,9 @@ public async Task TestOrganizeUsingsWithNoUsings()
await TestAsync(
testCode: testCode,
expected: testCode,
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2(AddImportPlacement.OutsideNamespace, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2(AddImportPlacement.OutsideNamespace, NotificationOption2.Error) }
});
}
@@ -140,9 +141,9 @@ namespace Goo
namespace Goo
{
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CodeStyleOptions2.FileHeaderTemplate, "This is a banner.")
+ { CodeStyleOptions2.FileHeaderTemplate, "This is a banner." }
});
}
@@ -165,9 +166,9 @@ internal class C
{
}
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
+ { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) }
});
}
@@ -188,10 +189,10 @@ namespace Goo;
internal class C
{
}",
- options: new (OptionKey, object)[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (new OptionKey(CSharpCodeStyleOptions.NamespaceDeclarations), new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)),
- (new OptionKey(CodeStyleOptions2.RequireAccessibilityModifiers, Language), new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error) },
+ { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) }
});
}
@@ -232,9 +233,9 @@ internal class D
{
}
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error))
+ { CodeStyleOptions2.AccessibilityModifiersRequired, new CodeStyleOption2(AccessibilityModifiersRequired.Always, NotificationOption2.Error) }
});
}
@@ -250,9 +251,9 @@ namespace Goo
{
using System;
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2(AddImportPlacement.InsideNamespace, NotificationOption2.Error))
+ { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2(AddImportPlacement.InsideNamespace, NotificationOption2.Error) }
});
}
@@ -267,9 +268,9 @@ public async Task TestPreferTopLevelStatements()
// See https://aka.ms/new-console-template for more information
Console.WriteLine(""Hello, World!"");",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: true, notification: NotificationOption2.Suggestion))
+ { CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: true, notification: NotificationOption2.Suggestion) }
});
}
@@ -289,9 +290,9 @@ private static void Main(string[] args)
Console.WriteLine(""Hello, World!"");
}
}",
- options: new[]
+ options: new OptionsCollection(LanguageNames.CSharp)
{
- (CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: false, notification: NotificationOption2.Suggestion))
+ { CSharpCodeStyleOptions.PreferTopLevelStatements, new CodeStyleOption2(value: false, notification: NotificationOption2.Suggestion) }
});
}
}
diff --git a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs
index 3dd3a6319fc83..1f80efedcdc8d 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/CodeCleanupTests.cs
@@ -21,6 +21,7 @@
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
@@ -608,7 +609,7 @@ TestWorkspace GetTestWorkspaceForLanguage(string language)
/// Indicates whether 'using' directives should be organized into separated groups. Default is true.
/// The to test code cleanup.
private protected static Task AssertCodeCleanupResult(string expected, string code, bool systemUsingsFirst = true, bool separateUsingGroups = false)
- => AssertCodeCleanupResult(expected, code, CSharpCodeStyleOptions.PreferOutsidePlacementWithSilentEnforcement, systemUsingsFirst, separateUsingGroups);
+ => AssertCodeCleanupResult(expected, code, new(AddImportPlacement.OutsideNamespace, NotificationOption2.Silent), systemUsingsFirst, separateUsingGroups);
///
/// Assert the expected code value equals the actual processed input .
@@ -623,16 +624,17 @@ private protected static async Task AssertCodeCleanupResult(string expected, str
{
using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf);
- var solution = workspace.CurrentSolution
- .WithOptions(workspace.Options
- .WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, systemUsingsFirst)
- .WithChangedOption(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp, separateUsingGroups)
- .WithChangedOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredImportPlacement))
- .WithAnalyzerReferences(new[]
- {
- new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile),
- new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile)
- });
+ // must set global options since incremental analyzer infra reads from global options
+ var globalOptions = workspace.GlobalOptions;
+ globalOptions.SetGlobalOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp), separateUsingGroups);
+ globalOptions.SetGlobalOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), systemUsingsFirst);
+ globalOptions.SetGlobalOption(new OptionKey(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement), preferredImportPlacement);
+
+ var solution = workspace.CurrentSolution.WithAnalyzerReferences(new[]
+ {
+ new AnalyzerFileReference(typeof(CSharpCompilerDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile),
+ new AnalyzerFileReference(typeof(UseExpressionBodyDiagnosticAnalyzer).Assembly.Location, TestAnalyzerAssemblyLoader.LoadFromFile)
+ });
workspace.TryApplyChanges(solution);
@@ -647,14 +649,8 @@ private protected static async Task AssertCodeCleanupResult(string expected, str
var enabledDiagnostics = codeCleanupService.GetAllDiagnostics();
- var fallbackOptions = new CodeActionOptions(
- CleanupOptions: CodeCleanupOptions.GetDefault(document.Project.LanguageServices) with
- {
- FormattingOptions = new CSharpSyntaxFormattingOptions(separateImportDirectiveGroups: separateUsingGroups)
- });
-
var newDoc = await codeCleanupService.CleanupAsync(
- document, enabledDiagnostics, new ProgressTracker(), fallbackOptions.CreateProvider(), CancellationToken.None);
+ document, enabledDiagnostics, new ProgressTracker(), globalOptions.CreateProvider(), CancellationToken.None);
var actual = await newDoc.GetTextAsync();
diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs
index b60f6cc7f0286..50ce8977d91ae 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs
@@ -10,6 +10,8 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests;
@@ -47,9 +49,10 @@ protected static async Task GetSmartTokenFormatterIndentationWorkerAsync(
TestWorkspace workspace,
ITextBuffer buffer,
int indentationLine,
- char ch)
+ char ch,
+ bool useTabs)
{
- await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch);
+ await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch, useTabs);
return buffer.CurrentSnapshot.GetLineFromLineNumber(indentationLine).GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(TestEditorOptions.Instance);
}
@@ -58,14 +61,15 @@ protected static async Task TokenFormatAsync(
TestWorkspace workspace,
ITextBuffer buffer,
int indentationLine,
- char ch)
+ char ch,
+ bool useTabs)
{
- await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch);
+ await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch, useTabs);
return buffer.CurrentSnapshot.GetText();
}
- private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch)
+ private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch, bool useTabs)
{
var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().First();
var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync();
@@ -84,8 +88,13 @@ private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextB
var rules = ImmutableArray.Create(formattingRuleProvider.CreateRule(document, position)).AddRange(Formatter.GetDefaultFormattingRules(document));
var options = new IndentationOptions(
- await document.GetSyntaxFormattingOptionsAsync(fallbackOptions: null, CancellationToken.None).ConfigureAwait(false),
- AutoFormattingOptions.Default);
+ new CSharpSyntaxFormattingOptions
+ {
+ Common = new SyntaxFormattingOptions.CommonOptions()
+ {
+ LineFormatting = new LineFormattingOptions { UseTabs = useTabs }
+ }
+ });
var formatter = new CSharpSmartTokenFormatter(options, rules, root);
var changes = await formatter.FormatTokenAsync(token, CancellationToken.None);
@@ -114,8 +123,6 @@ protected static async Task GetSmartTokenFormatterIndentationAsync(
{
// create tree service
using var workspace = TestWorkspace.CreateCSharp(code, composition: s_composition);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
- .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
if (baseIndentation.HasValue)
{
@@ -125,7 +132,7 @@ protected static async Task GetSmartTokenFormatterIndentationAsync(
}
var buffer = workspace.Documents.First().GetTextBuffer();
- return await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch);
+ return await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch, useTabs);
}
}
}
diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs
index 1c6364e60f59c..09d4e858cae60 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs
@@ -1511,15 +1511,14 @@ private static async Task AssertIndentUsingSmartTokenFormatterAsync(
var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax;
var options = new IndentationOptions(
- CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions(UseTabs: useTabs)),
- AutoFormattingOptions.Default);
+ CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions { UseTabs = useTabs }));
Assert.True(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(document),
root, line.AsTextLine(), options, out _));
- var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch);
+ var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch, useTabs);
Assert.Equal(expectedIndentation.Value, actualIndentation);
}
@@ -1552,10 +1551,10 @@ private async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax;
- var options = new IndentationOptions(
- CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions(UseTabs: useTabs)),
- AutoFormattingOptions.Default,
- IndentStyle: indentStyle);
+ var options = new IndentationOptions(CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions { UseTabs = useTabs }))
+ {
+ IndentStyle = indentStyle
+ };
Assert.False(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs
index ce659cca8ffc7..f00b8dab34c87 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs
@@ -3588,8 +3588,7 @@ private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string e
Assert.Equal(tokenKind, endToken.Kind());
var options = new IndentationOptions(
- CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions(UseTabs: useTabs)),
- AutoFormattingOptions.Default);
+ CSharpSyntaxFormattingOptions.Default.With(new LineFormattingOptions { UseTabs = useTabs }));
var formatter = new CSharpSmartTokenFormatter(options, rules, root);
diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs
index 41b2146c86421..089c2de24cac8 100644
--- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs
+++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs
@@ -645,12 +645,9 @@ private static async Task AssertSmartTokenFormatterOpenBraceAsync(
// create tree service
using var workspace = TestWorkspace.CreateCSharp(code);
- workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
- .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs)));
-
var buffer = workspace.Documents.First().GetTextBuffer();
- var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{');
+ var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{', useTabs);
Assert.Equal(expected, actual);
}
diff --git a/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs b/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs
index 5c48b85324502..407f7edc844f3 100644
--- a/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs
+++ b/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersTests.cs
@@ -11,6 +11,7 @@
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
using Microsoft.CodeAnalysis.PickMembers;
@@ -30,7 +31,7 @@ public class GenerateEqualsAndGetHashCodeFromMembersTests
private class TestWithDialog : VerifyCS.Test
{
private static readonly TestComposition s_composition =
- FeaturesTestCompositions.Features.AddParts(typeof(TestPickMembersService));
+ EditorTestCompositions.EditorFeatures.AddParts(typeof(TestPickMembersService));
public ImmutableArray MemberNames;
public Action> OptionsCallback;
diff --git a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
index 6f16ab5c1d2a3..23029296cb17d 100644
--- a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
+++ b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
@@ -7287,10 +7287,10 @@ void M() { }
public int Prop => throw new System.NotImplementedException();
}",
- CodeActionOptions = CodeActionOptions.Default with
+ CodeActionOptions = (CSharpCodeActionOptions.Default with
{
- ImplementTypeOptions = new ImplementTypeOptions(InsertionBehavior: ImplementTypeInsertionBehavior.AtTheEnd)
- }
+ ImplementTypeOptions = new() { InsertionBehavior = ImplementTypeInsertionBehavior.AtTheEnd }
+ }).CreateProvider()
}.RunAsync();
}
@@ -7462,10 +7462,10 @@ class Class : IInterface
public int ReadWriteProp { get; set; }
public int WriteOnlyProp { set => throw new System.NotImplementedException(); }
}",
- CodeActionOptions = CodeActionOptions.Default with
+ CodeActionOptions = (CSharpCodeActionOptions.Default with
{
- ImplementTypeOptions = new ImplementTypeOptions(PropertyGenerationBehavior: ImplementTypePropertyGenerationBehavior.PreferAutoProperties)
- }
+ ImplementTypeOptions = new() { PropertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferAutoProperties }
+ }).CreateProvider()
}.RunAsync();
}
diff --git a/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs b/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs
index 6f3f3177adf98..893f42386627d 100644
--- a/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs
+++ b/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs
@@ -1466,9 +1466,9 @@ public C([|string p__End, string p_test_t|])
}", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix)));
}
- private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning));
- private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Warning));
- private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Warning));
+ private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning));
+ private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Never, NotificationOption2.Warning));
+ private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Always, NotificationOption2.Warning));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)]
public async Task TestCreateFieldWithTopLevelNullability()
diff --git a/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs b/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs
index f30ccc97d11e1..49b11b7cca634 100644
--- a/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs
+++ b/src/EditorFeatures/Core.Cocoa/Snippets/AbstractSnippetExpansionClient.cs
@@ -147,8 +147,8 @@ private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
- var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
- _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize));
+ var lineFormattingOptions = document.GetLineFormattingOptionsAsync(GlobalOptions, CancellationToken.None).AsTask().WaitAndGetResult(CancellationToken.None);
+ _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, lineFormattingOptions.TabSize);
}
else
{
diff --git a/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsViewOptions.cs b/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsViewOptions.cs
index 5b5bc6ae4b7f6..6f2f8ac0dae9d 100644
--- a/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsViewOptions.cs
+++ b/src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsViewOptions.cs
@@ -11,19 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.InlineHints
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class InlineHintsViewOptions : IOptionProvider
+ internal sealed class InlineHintsViewOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public InlineHintsViewOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- DisplayAllHintsWhilePressingAltF1,
- ColorHints);
-
private const string FeatureName = "InlineHintsOptions";
public static readonly Option2 DisplayAllHintsWhilePressingAltF1 = new(
diff --git a/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs b/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs
index facd6b6bfe102..bea932d165ace 100644
--- a/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs
+++ b/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs
@@ -270,7 +270,7 @@ protected static Task> GetCodeFixesAsy
SnapshotSpan range,
Func addOperationScope,
CodeActionRequestPriority priority,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
bool isBlocking,
CancellationToken cancellationToken)
{
@@ -283,7 +283,7 @@ protected static Task> GetCodeFixesAsy
return UnifiedSuggestedActionsSource.GetFilterAndOrderCodeFixesAsync(
workspace, state.Target.Owner._codeFixService, document, range.Span.ToTextSpan(),
- priority, options, isBlocking, addOperationScope, cancellationToken).AsTask();
+ priority, fallbackOptions, isBlocking, addOperationScope, cancellationToken).AsTask();
}
private static string GetFixCategory(DiagnosticSeverity severity)
@@ -311,7 +311,7 @@ protected static Task> GetRefactorings
TextSpan? selection,
Func addOperationScope,
CodeActionRequestPriority priority,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
bool isBlocking,
CancellationToken cancellationToken)
{
@@ -341,7 +341,7 @@ protected static Task> GetRefactorings
var filterOutsideSelection = !requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring);
return UnifiedSuggestedActionsSource.GetFilterAndOrderCodeRefactoringsAsync(
- workspace, state.Target.Owner._codeRefactoringService, document, selection.Value, priority, options, isBlocking,
+ workspace, state.Target.Owner._codeRefactoringService, document, selection.Value, priority, fallbackOptions, isBlocking,
addOperationScope, filterOutsideSelection, cancellationToken);
}
@@ -420,7 +420,7 @@ await InvokeBelowInputPriorityAsync(() =>
ReferenceCountedDisposable state,
Document document,
SnapshotSpan range,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
CancellationToken cancellationToken)
{
foreach (var order in Orderings)
@@ -441,7 +441,7 @@ await InvokeBelowInputPriorityAsync(() =>
state.Target.SubjectBuffer.SupportsCodeFixes())
{
var result = await state.Target.Owner._codeFixService.GetMostSevereFixAsync(
- document, range.Span.ToTextSpan(), priority, options, isBlocking: false, cancellationToken).ConfigureAwait(false);
+ document, range.Span.ToTextSpan(), priority, fallbackOptions, isBlocking: false, cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
@@ -464,7 +464,7 @@ await InvokeBelowInputPriorityAsync(() =>
private async Task TryGetRefactoringSuggestedActionCategoryAsync(
Document document,
TextSpan? selection,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
CancellationToken cancellationToken)
{
using var state = _state.TryAddReference();
@@ -483,7 +483,7 @@ await InvokeBelowInputPriorityAsync(() =>
state.Target.SubjectBuffer.SupportsRefactorings())
{
if (await state.Target.Owner._codeRefactoringService.HasRefactoringsAsync(
- document, selection.Value, options, cancellationToken).ConfigureAwait(false))
+ document, selection.Value, fallbackOptions, cancellationToken).ConfigureAwait(false))
{
return PredefinedSuggestedActionCategoryNames.Refactoring;
}
@@ -636,12 +636,12 @@ private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId? c
if (document == null)
return null;
- var options = GlobalOptions.GetCodeActionOptionsProvider();
+ var fallbackOptions = GlobalOptions.GetCodeActionOptionsProvider();
using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var linkedToken = linkedTokenSource.Token;
- var errorTask = Task.Run(() => GetFixLevelAsync(state, document, range, options, linkedToken), linkedToken);
+ var errorTask = Task.Run(() => GetFixLevelAsync(state, document, range, fallbackOptions, linkedToken), linkedToken);
var selection = await GetSpanAsync(state, range, linkedToken).ConfigureAwait(false);
@@ -649,7 +649,7 @@ private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId? c
if (selection != null)
{
refactoringTask = Task.Run(
- () => TryGetRefactoringSuggestedActionCategoryAsync(document, selection, options, linkedToken), linkedToken);
+ () => TryGetRefactoringSuggestedActionCategoryAsync(document, selection, fallbackOptions, linkedToken), linkedToken);
}
// If we happen to get the result of the error task before the refactoring task,
diff --git a/src/EditorFeatures/Core/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs b/src/EditorFeatures/Core/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs
index 968f3e3a85fd2..1f4e7eb6da94d 100644
--- a/src/EditorFeatures/Core/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs
+++ b/src/EditorFeatures/Core/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs
@@ -94,8 +94,7 @@ private bool CompleteComment(
var service = document.GetRequiredLanguageService();
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var text = syntaxTree.GetText(cancellationToken);
- var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
- var options = _globalOptions.GetDocumentationCommentOptions(documentOptions);
+ var options = document.GetDocumentationCommentOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
// Apply snippet in reverse order so that the first applied snippet doesn't affect span of next snippets.
var snapshots = textView.Selection.GetSnapshotSpansOnBuffer(subjectBuffer).OrderByDescending(s => s.Span.Start);
@@ -337,8 +336,7 @@ private void InsertExteriorTriviaIfNeeded(IDocumentationCommentSnippetService se
return;
}
- var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
- var options = _globalOptions.GetDocumentationCommentOptions(documentOptions);
+ var options = document.GetDocumentationCommentOptionsAsync(_globalOptions, CancellationToken.None).AsTask().WaitAndGetResult(CancellationToken.None);
var snippet = service.GetDocumentationCommentSnippetFromPreviousLine(options, currentLine, previousLine);
if (snippet != null)
diff --git a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs
index 1974ed22ab9aa..a25b8e6233a30 100644
--- a/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs
+++ b/src/EditorFeatures/Core/EditorConfigSettings/DataProvider/NamingStyles/NamingStyleSettingsProvider.cs
@@ -6,6 +6,7 @@
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
@@ -35,15 +36,16 @@ protected override void UpdateOptions(AnalyzerConfigOptions _, OptionSet optionS
return;
}
- var options = project.State.AnalyzerOptions;
var document = project.Documents.FirstOrDefault();
if (document is null)
{
return;
}
- var sourceTree = document.GetRequiredSyntaxTreeSynchronously(default(CancellationToken));
- if (options.TryGetEditorConfigOption(NamingStyleOptions.NamingPreferences, sourceTree, out NamingStylePreferences? namingPreferences) &&
+ var sourceTree = document.GetRequiredSyntaxTreeSynchronously(CancellationToken.None);
+ var configOptions = project.State.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(sourceTree);
+
+ if (configOptions.TryGetEditorConfigOption(NamingStyleOptions.NamingPreferences, out NamingStylePreferences? namingPreferences) &&
namingPreferences is not null)
{
AddNamingStylePreferences(namingPreferences, isInEditorConfig: true);
diff --git a/src/EditorFeatures/Core/EditorConfigSettings/Updater/NamingStyles/SourceTextExtensions.cs b/src/EditorFeatures/Core/EditorConfigSettings/Updater/NamingStyles/SourceTextExtensions.cs
index 3cb5f64e19ff0..f259cfd32e0b7 100644
--- a/src/EditorFeatures/Core/EditorConfigSettings/Updater/NamingStyles/SourceTextExtensions.cs
+++ b/src/EditorFeatures/Core/EditorConfigSettings/Updater/NamingStyles/SourceTextExtensions.cs
@@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.EditorConfig;
using Microsoft.CodeAnalysis.EditorConfig.Parsing;
diff --git a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptFormattingInteractionService.cs b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptFormattingInteractionService.cs
index 8b6f154e38c29..ed037254993fa 100644
--- a/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptFormattingInteractionService.cs
+++ b/src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptFormattingInteractionService.cs
@@ -25,6 +25,7 @@ internal interface IVSTypeScriptFormattingInteractionService
///
bool SupportsFormattingOnTypedCharacter(Document document, char ch);
+#pragma warning disable RS0030 // Do not used banned APIs (backwards compat)
///
/// Returns the text changes necessary to format the document. If "textSpan" is provided,
/// only the text changes necessary to format that span are needed.
@@ -47,5 +48,6 @@ internal interface IVSTypeScriptFormattingInteractionService
/// Returns the text changes necessary to format the document after the user enters a Return
/// The position provided is the position of the caret in the document after Return.
Task> GetFormattingChangesOnReturnAsync(Document document, int position, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
+#pragma warning restore
}
}
diff --git a/src/EditorFeatures/Core/Formatting/IndentationManagerExtensions.cs b/src/EditorFeatures/Core/Formatting/IndentationManagerExtensions.cs
index a7904a0edcaaf..da7fc9ca259ff 100644
--- a/src/EditorFeatures/Core/Formatting/IndentationManagerExtensions.cs
+++ b/src/EditorFeatures/Core/Formatting/IndentationManagerExtensions.cs
@@ -26,11 +26,13 @@ public static async Task GetInferredFormattingOptionsAs
indentationManager.GetIndentation(snapshot.TextBuffer, explicitFormat, out var convertTabsToSpaces, out var tabSize, out var indentSize);
- return options.With(new LineFormattingOptions(
- UseTabs: !convertTabsToSpaces,
- IndentationSize: indentSize,
- TabSize: tabSize,
- NewLine: options.NewLine));
+ return options.With(new LineFormattingOptions()
+ {
+ UseTabs = !convertTabsToSpaces,
+ IndentationSize = indentSize,
+ TabSize = tabSize,
+ NewLine = options.NewLine
+ });
}
}
}
diff --git a/src/EditorFeatures/Core/InlineDiagnostics/InlineDiagnosticsOptions.cs b/src/EditorFeatures/Core/InlineDiagnostics/InlineDiagnosticsOptions.cs
index 7fdd27c56f116..6d490bb641834 100644
--- a/src/EditorFeatures/Core/InlineDiagnostics/InlineDiagnosticsOptions.cs
+++ b/src/EditorFeatures/Core/InlineDiagnostics/InlineDiagnosticsOptions.cs
@@ -11,19 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.InlineDiagnostics
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class InlineDiagnosticsOptions : IOptionProvider
+ internal sealed class InlineDiagnosticsOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public InlineDiagnosticsOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- EnableInlineDiagnostics,
- Location);
-
public static readonly PerLanguageOption2 EnableInlineDiagnostics =
new("InlineDiagnosticsOptions",
"EnableInlineDiagnostics",
diff --git a/src/Features/Core/Portable/InlineHints/InlineHintsGlobalStateOption.cs b/src/EditorFeatures/Core/InlineHints/InlineHintsGlobalStateOption.cs
similarity index 100%
rename from src/Features/Core/Portable/InlineHints/InlineHintsGlobalStateOption.cs
rename to src/EditorFeatures/Core/InlineHints/InlineHintsGlobalStateOption.cs
diff --git a/src/EditorFeatures/Core/LanguageServer/Handlers/CodeActions/CodeActionHelpers.cs b/src/EditorFeatures/Core/LanguageServer/Handlers/CodeActions/CodeActionHelpers.cs
index 5c23208f8d35f..571cdda77f6b0 100644
--- a/src/EditorFeatures/Core/LanguageServer/Handlers/CodeActions/CodeActionHelpers.cs
+++ b/src/EditorFeatures/Core/LanguageServer/Handlers/CodeActions/CodeActionHelpers.cs
@@ -35,13 +35,13 @@ public static async Task GetVSCodeActionsAsync(
CodeActionParams request,
CodeActionsCache codeActionsCache,
Document document,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
ICodeFixService codeFixService,
ICodeRefactoringService codeRefactoringService,
CancellationToken cancellationToken)
{
var actionSets = await GetActionSetsAsync(
- document, options, codeFixService, codeRefactoringService, request.Range, cancellationToken).ConfigureAwait(false);
+ document, fallbackOptions, codeFixService, codeRefactoringService, request.Range, cancellationToken).ConfigureAwait(false);
if (actionSets.IsDefaultOrEmpty)
return Array.Empty();
@@ -186,13 +186,13 @@ public static async Task> GetCodeActionsAsync(
CodeActionsCache codeActionsCache,
Document document,
LSP.Range selection,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
ICodeFixService codeFixService,
ICodeRefactoringService codeRefactoringService,
CancellationToken cancellationToken)
{
var actionSets = await GetActionSetsAsync(
- document, options, codeFixService, codeRefactoringService, selection, cancellationToken).ConfigureAwait(false);
+ document, fallbackOptions, codeFixService, codeRefactoringService, selection, cancellationToken).ConfigureAwait(false);
if (actionSets.IsDefaultOrEmpty)
return ImmutableArray.Empty;
@@ -242,7 +242,7 @@ private static CodeAction GetNestedActionsFromActionSet(IUnifiedSuggestedAction
private static async ValueTask> GetActionSetsAsync(
Document document,
- CodeActionOptionsProvider options,
+ CodeActionOptionsProvider fallbackOptions,
ICodeFixService codeFixService,
ICodeRefactoringService codeRefactoringService,
LSP.Range selection,
@@ -254,10 +254,10 @@ private static async ValueTask> GetAct
var codeFixes = await UnifiedSuggestedActionsSource.GetFilterAndOrderCodeFixesAsync(
document.Project.Solution.Workspace, codeFixService, document, textSpan,
CodeActionRequestPriority.None,
- options, isBlocking: false, addOperationScope: _ => null, cancellationToken).ConfigureAwait(false);
+ fallbackOptions, isBlocking: false, addOperationScope: _ => null, cancellationToken).ConfigureAwait(false);
var codeRefactorings = await UnifiedSuggestedActionsSource.GetFilterAndOrderCodeRefactoringsAsync(
- document.Project.Solution.Workspace, codeRefactoringService, document, textSpan, CodeActionRequestPriority.None, options, isBlocking: false,
+ document.Project.Solution.Workspace, codeRefactoringService, document, textSpan, CodeActionRequestPriority.None, fallbackOptions, isBlocking: false,
addOperationScope: _ => null, filterOutsideSelection: false, cancellationToken).ConfigureAwait(false);
var actionSets = UnifiedSuggestedActionsSource.FilterAndOrderActionSets(
diff --git a/src/EditorFeatures/Core/Options/CompletionViewOptions.cs b/src/EditorFeatures/Core/Options/CompletionViewOptions.cs
index 71bd290d76c9b..0666f6428af73 100644
--- a/src/EditorFeatures/Core/Options/CompletionViewOptions.cs
+++ b/src/EditorFeatures/Core/Options/CompletionViewOptions.cs
@@ -11,21 +11,8 @@
namespace Microsoft.CodeAnalysis.Completion
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class CompletionViewOptions : IOptionProvider
+ internal sealed class CompletionViewOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public CompletionViewOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- ShowCompletionItemFilters,
- HighlightMatchingPortionsOfCompletionListItems,
- EnableArgumentCompletionSnippets,
- BlockForCompletionItems);
-
private const string FeatureName = "CompletionOptions";
public static readonly PerLanguageOption2 HighlightMatchingPortionsOfCompletionListItems =
diff --git a/src/EditorFeatures/Core/Options/ExtensionManagerOptions.cs b/src/EditorFeatures/Core/Options/ExtensionManagerOptions.cs
index 20b38e3a0c629..8e2fb3f1ae0dd 100644
--- a/src/EditorFeatures/Core/Options/ExtensionManagerOptions.cs
+++ b/src/EditorFeatures/Core/Options/ExtensionManagerOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Options
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class ExtensionManagerOptions : IOptionProvider
+ internal sealed class ExtensionManagerOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public ExtensionManagerOptions()
- {
- }
-
- public ImmutableArray Options { get; } = ImmutableArray.Create(
- DisableCrashingExtensions);
-
public static readonly Option2 DisableCrashingExtensions = new(
nameof(ExtensionManagerOptions), nameof(DisableCrashingExtensions), defaultValue: true);
}
diff --git a/src/EditorFeatures/Core/Options/LegacyGlobalOptionsWorkspaceService.cs b/src/EditorFeatures/Core/Options/LegacyGlobalOptionsWorkspaceService.cs
index 2b63d91443dbb..d7df3989986c8 100644
--- a/src/EditorFeatures/Core/Options/LegacyGlobalOptionsWorkspaceService.cs
+++ b/src/EditorFeatures/Core/Options/LegacyGlobalOptionsWorkspaceService.cs
@@ -5,7 +5,11 @@
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Formatting;
+using Microsoft.CodeAnalysis.CodeGeneration;
+using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
+using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
+using Microsoft.CodeAnalysis.InlineHints;
namespace Microsoft.CodeAnalysis.Options
{
@@ -15,19 +19,85 @@ namespace Microsoft.CodeAnalysis.Options
[ExportWorkspaceService(typeof(ILegacyGlobalOptionsWorkspaceService)), Shared]
internal sealed class LegacyGlobalOptionsWorkspaceService : ILegacyGlobalOptionsWorkspaceService
{
- public IGlobalOptionService GlobalOptions { get; }
+ private readonly IGlobalOptionService _globalOptions;
+ private readonly CodeActionOptionsStorage.Provider _provider;
+
+ private static readonly Option2 s_generateOverridesOption = new(
+ "GenerateOverridesOptions", "SelectAll", defaultValue: true,
+ storageLocation: new RoamingProfileStorageLocation($"TextEditor.Specific.GenerateOverridesOptions.SelectAll"));
+
+ private static readonly PerLanguageOption2 s_generateOperators = new(
+ "GenerateEqualsAndGetHashCodeFromMembersOptions",
+ "GenerateOperators", defaultValue: false,
+ storageLocation: new RoamingProfileStorageLocation(
+ "TextEditor.%LANGUAGE%.Specific.GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators"));
+
+ private static readonly PerLanguageOption2 s_implementIEquatable = new(
+ "GenerateEqualsAndGetHashCodeFromMembersOptions",
+ "ImplementIEquatable", defaultValue: false,
+ storageLocation: new RoamingProfileStorageLocation(
+ "TextEditor.%LANGUAGE%.Specific.GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable"));
+
+ private static readonly PerLanguageOption2 s_addNullChecks = new(
+ "GenerateConstructorFromMembersOptions",
+ "AddNullChecks", defaultValue: false,
+ storageLocation: new RoamingProfileStorageLocation(
+ $"TextEditor.%LANGUAGE%.Specific.GenerateConstructorFromMembersOptions.AddNullChecks"));
+
+ internal static readonly PerLanguageOption2 AddNullChecksToConstructorsGeneratedFromMembers = new(
+ "GenerateConstructorFromMembersOptions",
+ "AddNullChecks", defaultValue: false,
+ storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.GenerateConstructorFromMembersOptions.AddNullChecks"));
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LegacyGlobalOptionsWorkspaceService(IGlobalOptionService globalOptions)
{
- GlobalOptions = globalOptions;
+ _globalOptions = globalOptions;
+ _provider = _globalOptions.CreateProvider();
+ }
+
+ public bool GenerateOverrides
+ {
+ get => _globalOptions.GetOption(s_generateOverridesOption);
+ set => _globalOptions.SetGlobalOption(new OptionKey(s_generateOverridesOption), value);
}
public bool RazorUseTabs
- => GlobalOptions.GetOption(RazorLineFormattingOptionsStorage.UseTabs);
+ => _globalOptions.GetOption(RazorLineFormattingOptionsStorage.UseTabs);
public int RazorTabSize
- => GlobalOptions.GetOption(RazorLineFormattingOptionsStorage.TabSize);
+ => _globalOptions.GetOption(RazorLineFormattingOptionsStorage.TabSize);
+
+ /// TODO: remove. https://github.com/dotnet/roslyn/issues/57283
+ public bool InlineHintsOptionsDisplayAllOverride
+ {
+ get => _globalOptions.GetOption(InlineHintsGlobalStateOption.DisplayAllOverride);
+ set => _globalOptions.SetGlobalOption(new OptionKey(InlineHintsGlobalStateOption.DisplayAllOverride), value);
+ }
+
+ public CleanCodeGenerationOptionsProvider CleanCodeGenerationOptionsProvider
+ => _provider;
+
+ public AutoFormattingOptions GetAutoFormattingOptions(HostLanguageServices languageServices)
+ => _globalOptions.GetAutoFormattingOptions(languageServices.Language);
+
+ public bool GetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language)
+ => _globalOptions.GetOption(s_implementIEquatable, language);
+
+ public void SetGenerateEqualsAndGetHashCodeFromMembersGenerateOperators(string language, bool value)
+ => _globalOptions.SetGlobalOption(new OptionKey(s_generateOperators, language), value);
+
+ public bool GetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language)
+ => _globalOptions.GetOption(s_implementIEquatable, language);
+
+ public void SetGenerateEqualsAndGetHashCodeFromMembersImplementIEquatable(string language, bool value)
+ => _globalOptions.SetGlobalOption(new OptionKey(s_implementIEquatable, language), value);
+
+ public bool GetGenerateConstructorFromMembersOptionsAddNullChecks(string language)
+ => _globalOptions.GetOption(s_addNullChecks, language);
+
+ public void SetGenerateConstructorFromMembersOptionsAddNullChecks(string language, bool value)
+ => _globalOptions.SetGlobalOption(new OptionKey(s_addNullChecks, language), value);
}
}
diff --git a/src/EditorFeatures/Core/Options/NavigationBarViewOptions.cs b/src/EditorFeatures/Core/Options/NavigationBarViewOptions.cs
index 3334ded376ec7..b0f41b0ab1f37 100644
--- a/src/EditorFeatures/Core/Options/NavigationBarViewOptions.cs
+++ b/src/EditorFeatures/Core/Options/NavigationBarViewOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Options
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class NavigationBarViewOptions : IOptionProvider
+ internal sealed class NavigationBarViewOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public NavigationBarViewOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- ShowNavigationBar);
-
private const string FeatureName = "NavigationBarOptions";
public static readonly PerLanguageOption ShowNavigationBar = new(FeatureName, nameof(ShowNavigationBar), defaultValue: true);
diff --git a/src/EditorFeatures/Core/Options/SignatureHelpViewOptions.cs b/src/EditorFeatures/Core/Options/SignatureHelpViewOptions.cs
index 027bc6995ca6f..0383174fb5338 100644
--- a/src/EditorFeatures/Core/Options/SignatureHelpViewOptions.cs
+++ b/src/EditorFeatures/Core/Options/SignatureHelpViewOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Options
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class SignatureHelpViewOptions : IOptionProvider
+ internal sealed class SignatureHelpViewOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public SignatureHelpViewOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- ShowSignatureHelp);
-
private const string FeatureName = "SignatureHelpOptions";
public static readonly PerLanguageOption2 ShowSignatureHelp = new(FeatureName, nameof(ShowSignatureHelp), defaultValue: true);
diff --git a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs
index 774f444b5b832..4f1ac82bfd641 100644
--- a/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs
+++ b/src/EditorFeatures/Core/Organizing/OrganizeDocumentCommandHandler.cs
@@ -133,13 +133,15 @@ public bool ExecuteCommand(SortAndRemoveUnnecessaryImportsCommandArgs args, Comm
return true;
}
- private static void SortImports(ITextBuffer subjectBuffer, IUIThreadOperationContext operationContext)
+ private void SortImports(ITextBuffer subjectBuffer, IUIThreadOperationContext operationContext)
{
var cancellationToken = operationContext.UserCancellationToken;
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
- var newDocument = Formatter.OrganizeImportsAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
+ var organizeImportsService = document.GetRequiredLanguageService();
+ var options = document.GetOrganizeImportsOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
+ var newDocument = organizeImportsService.OrganizeImportsAsync(document, options, cancellationToken).WaitAndGetResult(cancellationToken);
if (document != newDocument)
{
ApplyTextChange(document, newDocument);
@@ -155,8 +157,10 @@ private void SortAndRemoveUnusedImports(ITextBuffer subjectBuffer, IUIThreadOper
if (document != null)
{
var formattingOptions = document.SupportsSyntaxTree ? document.GetSyntaxFormattingOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken) : null;
- var newDocument = document.GetLanguageService().RemoveUnnecessaryImportsAsync(document, formattingOptions, cancellationToken).WaitAndGetResult(cancellationToken);
- newDocument = Formatter.OrganizeImportsAsync(newDocument, cancellationToken).WaitAndGetResult(cancellationToken);
+ var newDocument = document.GetRequiredLanguageService().RemoveUnnecessaryImportsAsync(document, formattingOptions, cancellationToken).WaitAndGetResult(cancellationToken);
+ var organizeImportsService = document.GetRequiredLanguageService();
+ var options = document.GetOrganizeImportsOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
+ newDocument = organizeImportsService.OrganizeImportsAsync(newDocument, options, cancellationToken).WaitAndGetResult(cancellationToken);
if (document != newDocument)
{
ApplyTextChange(document, newDocument);
diff --git a/src/EditorFeatures/Core/Remote/RemoteHostOptions.cs b/src/EditorFeatures/Core/Remote/RemoteHostOptions.cs
index bcb8aa2c30ee9..5507591d18825 100644
--- a/src/EditorFeatures/Core/Remote/RemoteHostOptions.cs
+++ b/src/EditorFeatures/Core/Remote/RemoteHostOptions.cs
@@ -12,8 +12,7 @@
namespace Microsoft.CodeAnalysis.Remote
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class RemoteHostOptions : IOptionProvider
+ internal sealed class RemoteHostOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
private const string FeatureName = "InternalFeatureOnOffOptions";
@@ -41,17 +40,5 @@ internal sealed class RemoteHostOptions : IOptionProvider
public static readonly Option2 OOPCoreClrFeatureFlag = new(
FeatureName, nameof(OOPCoreClrFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.ServiceHubCore"));
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- SolutionChecksumMonitorBackOffTimeSpanInMS,
- OOP64Bit,
- OOPServerGCFeatureFlag,
- OOPCoreClrFeatureFlag);
-
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public RemoteHostOptions()
- {
- }
}
}
diff --git a/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs
index 2f0fc7ff4f41c..ea6a7ae15209a 100644
--- a/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs
+++ b/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs
@@ -14,20 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.Shared.Options
///
/// options to indicate whether a certain component in Roslyn is enabled or not
///
- [ExportGlobalOptionProvider, Shared]
- internal sealed class EditorComponentOnOffOptions : IOptionProvider
+ internal sealed class EditorComponentOnOffOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public EditorComponentOnOffOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- Adornment,
- Tagger,
- CodeRefactorings);
-
private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Components\";
private const string FeatureName = "EditorComponentOnOffOptions";
diff --git a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs
index 32d34894b342a..d6b62ab0819eb 100644
--- a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs
+++ b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs
@@ -11,35 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class FeatureOnOffOptions : IOptionProvider
+ internal sealed class FeatureOnOffOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public FeatureOnOffOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- EndConstruct,
- AutomaticInsertionOfAbstractOrInterfaceMembers,
- LineSeparator,
- Outlining,
- KeywordHighlighting,
- ReferenceHighlighting,
- AutoInsertBlockCommentStartString,
- PrettyListing,
- RenameTrackingPreview,
- RenameTracking,
- RefactoringVerification,
- AddImportsOnPaste,
- OfferRemoveUnusedReferences,
- OfferRemoveUnusedReferencesFeatureFlag,
- ShowInheritanceMargin,
- InheritanceMarginCombinedWithIndicatorMargin,
- AutomaticallyCompleteStatementOnSemicolon,
- SkipAnalyzersForImplicitlyTriggeredBuilds);
-
private const string FeatureName = "FeatureOnOffOptions";
public static readonly PerLanguageOption2 EndConstruct = new(FeatureName, "EndConstruct", defaultValue: true,
diff --git a/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs
index cba47eeb815c3..6c155b5490a5e 100644
--- a/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs
+++ b/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs
@@ -12,29 +12,8 @@
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class InternalFeatureOnOffOptions : IOptionProvider
+ internal sealed class InternalFeatureOnOffOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public InternalFeatureOnOffOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- BraceMatching,
- Classification,
- SemanticColorizer,
- SyntacticColorizer,
- AutomaticLineEnder,
- SmartIndenter,
- Squiggles,
- FormatOnSave,
- RenameTracking,
- EventHookup,
- Snippets,
- BackgroundAnalysisMemoryMonitor);
-
private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\";
private const string FeatureName = "InternalFeatureOnOffOptions";
diff --git a/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs b/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs
index 57d2a41895f51..20204663b8ed3 100644
--- a/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs
+++ b/src/EditorFeatures/Core/SplitComment/SplitCommentCommandHandler.cs
@@ -138,7 +138,7 @@ private static bool MatchesCommentStart(string commentStart, ITextSnapshotLine l
return true;
}
- private static async Task<(Span replacementSpan, string replacementText)?> SplitCommentAsync(
+ private async Task<(Span replacementSpan, string replacementText)?> SplitCommentAsync(
ITextView textView,
Document document,
SnapshotSpan selectionSpan,
@@ -169,7 +169,7 @@ private static bool MatchesCommentStart(string commentStart, ITextSnapshotLine l
var textSnapshot = selectionSpan.Snapshot;
var triviaLine = textSnapshot.GetLineFromPosition(trivia.SpanStart);
- var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
+ var options = await document.GetLineFormattingOptionsAsync(_globalOptions, cancellationToken).ConfigureAwait(false);
var replacementSpan = GetReplacementSpan(triviaLine, selectionSpan);
var replacementText = GetReplacementText(textView, options, triviaLine, trivia, selectionSpan.Start);
return (replacementSpan, replacementText);
@@ -187,7 +187,7 @@ private static bool IsFollowedByComment(SnapshotPoint point, ISplitCommentServic
}
private static string GetReplacementText(
- ITextView textView, DocumentOptionSet options, ITextSnapshotLine triviaLine, SyntaxTrivia trivia, int position)
+ ITextView textView, LineFormattingOptions options, ITextSnapshotLine triviaLine, SyntaxTrivia trivia, int position)
{
// We're inside a comment. Instead of inserting just a newline here, insert
// 1. a newline
@@ -199,12 +199,9 @@ private static string GetReplacementText(
var commentStartColumn = triviaLine.GetColumnFromLineOffset(trivia.SpanStart - triviaLine.Start, textView.Options);
- var useTabs = options.GetOption(FormattingOptions.UseTabs);
- var tabSize = options.GetOption(FormattingOptions.TabSize);
-
var prefix = GetCommentPrefix(triviaLine.Snapshot, trivia, position);
- var replacementText = options.GetOption(FormattingOptions.NewLine) +
- commentStartColumn.CreateIndentationString(useTabs, tabSize) +
+ var replacementText = options.NewLine +
+ commentStartColumn.CreateIndentationString(options.UseTabs, options.TabSize) +
prefix +
GetWhitespaceAfterCommentPrefix(trivia, triviaLine, prefix, position);
diff --git a/src/EditorFeatures/Core/SplitComment/SplitCommentOptions.cs b/src/EditorFeatures/Core/SplitComment/SplitCommentOptions.cs
index e00bdc8b827f2..dd8d89b5be12c 100644
--- a/src/EditorFeatures/Core/SplitComment/SplitCommentOptions.cs
+++ b/src/EditorFeatures/Core/SplitComment/SplitCommentOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class SplitCommentOptions : IOptionProvider
+ internal sealed class SplitCommentOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public SplitCommentOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- Enabled);
-
public static PerLanguageOption2 Enabled =
new PerLanguageOption2(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments"));
diff --git a/src/EditorFeatures/Core/Suggestions/SuggestionsOptions.cs b/src/EditorFeatures/Core/Suggestions/SuggestionsOptions.cs
index b347b4c7a07e8..dde68b6524996 100644
--- a/src/EditorFeatures/Core/Suggestions/SuggestionsOptions.cs
+++ b/src/EditorFeatures/Core/Suggestions/SuggestionsOptions.cs
@@ -11,18 +11,8 @@
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class SuggestionsOptions : IOptionProvider
+ internal sealed class SuggestionsOptions
{
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public SuggestionsOptions()
- {
- }
-
- ImmutableArray IOptionProvider.Options { get; } = ImmutableArray.Create(
- AsynchronousQuickActionsDisableFeatureFlag);
-
private const string FeatureName = "SuggestionsOptions";
public static readonly Option2 Asynchronous = new(FeatureName, nameof(Asynchronous), defaultValue: null,
diff --git a/src/EditorFeatures/Core/Suggestions/SuggestionsOptionsProvider.cs b/src/EditorFeatures/Core/Suggestions/SuggestionsOptionsProvider.cs
deleted file mode 100644
index 6fc82433450b6..0000000000000
--- a/src/EditorFeatures/Core/Suggestions/SuggestionsOptionsProvider.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Immutable;
-using System.Composition;
-using Microsoft.CodeAnalysis.Host.Mef;
-using Microsoft.CodeAnalysis.Options;
-using Microsoft.CodeAnalysis.Options.Providers;
-
-namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
-{
- [ExportGlobalOptionProvider, Shared]
- internal sealed class SuggestionsOptionsProvider : IOptionProvider
- {
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public SuggestionsOptionsProvider()
- {
- }
-
- public ImmutableArray Options { get; } = ImmutableArray.Create(
- SuggestionsOptions.Asynchronous,
- SuggestionsOptions.AsynchronousQuickActionsDisableFeatureFlag);
- }
-}
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/ChangeSignature/ChangeSignatureTestState.cs b/src/EditorFeatures/DiagnosticsTestUtilities/ChangeSignature/ChangeSignatureTestState.cs
index f2c748ac30d8c..2a9e0f8425070 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/ChangeSignature/ChangeSignatureTestState.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/ChangeSignature/ChangeSignatureTestState.cs
@@ -17,6 +17,7 @@
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic;
@@ -81,14 +82,14 @@ public TestChangeSignatureOptionsService TestChangeSignatureOptionsService
public async Task ChangeSignatureAsync()
{
- var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CodeActionOptions.DefaultProvider, CancellationToken.None).ConfigureAwait(false);
+ var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, Workspace.GlobalOptions.CreateProvider(), CancellationToken.None).ConfigureAwait(false);
var options = AbstractChangeSignatureService.GetChangeSignatureOptions(context);
return await ChangeSignatureService.ChangeSignatureWithContextAsync(context, options, CancellationToken.None);
}
public async Task GetParameterConfigurationAsync()
{
- var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CodeActionOptions.DefaultProvider, CancellationToken.None);
+ var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, Workspace.GlobalOptions.CreateProvider(), CancellationToken.None);
if (context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext)
{
return changeSignatureAnalyzedSucceedContext.ParameterConfiguration;
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs
index e1247941c7252..48b1f7fb7d9f0 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs
@@ -185,13 +185,7 @@ protected TestWorkspace CreateWorkspaceFromOptions(string workspaceMarkupOrCode,
}
#if !CODE_STYLE
- workspace.ApplyOptions(parameters.options);
-
- if (parameters.globalOptions != null)
- {
- workspace.ApplyOptions(parameters.globalOptions);
- parameters.globalOptions.SetGlobalOptions(workspace.GlobalOptions);
- }
+ parameters.globalOptions?.SetGlobalOptions(workspace.GlobalOptions);
#endif
return workspace;
}
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs
index 237301cd76638..54e87a92da82d 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs
@@ -76,7 +76,7 @@ public Test()
internal OptionsCollection Options => _sharedState.Options;
#if !CODE_STYLE
- internal CodeActionOptions CodeActionOptions
+ internal CodeActionOptionsProvider CodeActionOptions
{
get => _sharedState.CodeActionOptions;
set => _sharedState.CodeActionOptions = value;
@@ -109,7 +109,7 @@ protected override AnalyzerOptions GetAnalyzerOptions(Project project)
=> new WorkspaceAnalyzerOptions(base.GetAnalyzerOptions(project), project.Solution, _sharedState.GetIdeAnalyzerOptions(project));
protected override CodeFixContext CreateCodeFixContext(Document document, TextSpan span, ImmutableArray diagnostics, Action> registerCodeFix, CancellationToken cancellationToken)
- => new(document, span, diagnostics, registerCodeFix, new DelegatingCodeActionOptionsProvider(_ => _sharedState.CodeActionOptions), isBlocking: false, cancellationToken);
+ => new(document, span, diagnostics, registerCodeFix, _sharedState.CodeActionOptions, isBlocking: false, cancellationToken);
protected override FixAllContext CreateFixAllContext(
Document? document,
@@ -130,7 +130,7 @@ protected override FixAllContext CreateFixAllContext(
codeActionEquivalenceKey,
diagnosticIds,
fixAllDiagnosticProvider,
- new DelegatingCodeActionOptionsProvider(_ => _sharedState.CodeActionOptions)),
+ _sharedState.CodeActionOptions),
new ProgressTracker(), cancellationToken);
#endif
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/SharedVerifierState.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/SharedVerifierState.cs
index b5a4734c2b482..bbda01e197957 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/SharedVerifierState.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/SharedVerifierState.cs
@@ -48,7 +48,7 @@ public SharedVerifierState(AnalyzerTest test, string defaultFileE
internal OptionsCollection Options { get; }
#if !CODE_STYLE
- internal CodeActionOptions CodeActionOptions { get; set; } = CodeActionOptions.Default;
+ internal CodeActionOptionsProvider CodeActionOptions { get; set; } = CodeAnalysis.CodeActions.CodeActionOptions.DefaultProvider;
internal IdeAnalyzerOptions? IdeAnalyzerOptions { get; set; }
internal IdeAnalyzerOptions GetIdeAnalyzerOptions(Project project)
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs
index e36e580967cbf..435d68794fe4b 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/MoveType/AbstractMoveTypeTest.cs
@@ -145,7 +145,7 @@ private async Task> TestOperationAsync(
expectedChangedDocumentId: null);
}
- protected async Task TestMoveTypeToNewFileAsync(
+ private protected async Task TestMoveTypeToNewFileAsync(
string originalCode,
string expectedSourceTextAfterRefactoring,
string expectedDocumentName,
@@ -153,15 +153,13 @@ protected async Task TestMoveTypeToNewFileAsync(
ImmutableArray destinationDocumentContainers = default,
bool expectedCodeAction = true,
int index = 0,
- Action onAfterWorkspaceCreated = null)
+ OptionsCollection options = null)
{
- var testOptions = new TestParameters(index: index);
+ var testOptions = new TestParameters(index: index, options: options);
if (expectedCodeAction)
{
using var workspace = CreateWorkspaceFromOptions(originalCode, testOptions);
- onAfterWorkspaceCreated?.Invoke(workspace);
-
// replace with default values on null.
destinationDocumentContainers = destinationDocumentContainers.NullToEmpty();
diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs b/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs
index 36fc2c6eb2e45..0f6a3e7056eae 100644
--- a/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs
+++ b/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs
@@ -7,6 +7,7 @@
using System;
using System.Collections.Immutable;
using System.Linq;
+using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NamingStyles;
diff --git a/src/EditorFeatures/Test/Formatting/InferredIndentationTests.cs b/src/EditorFeatures/Test/Formatting/InferredIndentationTests.cs
index b736bf02f43fe..4d7f129f93f1d 100644
--- a/src/EditorFeatures/Test/Formatting/InferredIndentationTests.cs
+++ b/src/EditorFeatures/Test/Formatting/InferredIndentationTests.cs
@@ -5,6 +5,7 @@
#nullable disable
using System.Linq;
+using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
@@ -22,9 +23,9 @@ public async Task BlankFileMatchesWorkspaceSettings()
{
using var testWorkspace = CreateWithLines(
"");
- var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetOptionsAsync();
+ var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetLineFormattingOptionsAsync(testWorkspace.GlobalOptions, CancellationToken.None);
- Assert.Equal(FormattingOptions.UseTabs.DefaultValue, options.GetOption(FormattingOptions.UseTabs));
+ Assert.Equal(FormattingOptions.UseTabs.DefaultValue, options.UseTabs);
}
[Fact]
@@ -35,9 +36,9 @@ public async Task SingleLineWithTab()
"{",
"\tvoid M() { }",
"}");
- var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetOptionsAsync();
+ var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetLineFormattingOptionsAsync(testWorkspace.GlobalOptions, CancellationToken.None);
- Assert.True(options.GetOption(FormattingOptions.UseTabs));
+ Assert.True(options.UseTabs);
}
[Fact]
@@ -48,10 +49,10 @@ public async Task SingleLineWithFourSpaces()
"{",
" void M() { }",
"}");
- var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetOptionsAsync();
+ var options = await testWorkspace.CurrentSolution.Projects.Single().Documents.Single().GetLineFormattingOptionsAsync(testWorkspace.GlobalOptions, CancellationToken.None);
- Assert.False(options.GetOption(FormattingOptions.UseTabs));
- Assert.Equal(4, options.GetOption(FormattingOptions.IndentationSize));
+ Assert.False(options.UseTabs);
+ Assert.Equal(4, options.IndentationSize);
}
private static TestWorkspace CreateWithLines(params string[] lines)
diff --git a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
index 60c41b52ea6e9..2b9987550081d 100644
--- a/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
+++ b/src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.cs
@@ -10,6 +10,8 @@
using System.Security;
using System.Threading;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.MetadataAsSource;
@@ -78,7 +80,11 @@ public Task GenerateSourceAsync(ISymbol symbol, Project? p
return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, signaturesOnly, MetadataAsSourceOptions.GetDefault(project.LanguageServices));
}
- public async Task GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool signaturesOnly = true)
+ public async Task GenerateSourceAsync(
+ string? symbolMetadataName = null,
+ Project? project = null,
+ bool signaturesOnly = true,
+ bool fileScopedNamespaces = false)
{
symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName;
project ??= this.DefaultProject;
@@ -112,8 +118,24 @@ public async Task GenerateSourceAsync(string? symbolMetada
}
}
+ var options = MetadataAsSourceOptions.GetDefault(project.LanguageServices);
+
+ if (fileScopedNamespaces)
+ {
+ options = options with
+ {
+ GenerationOptions = options.GenerationOptions with
+ {
+ GenerationOptions = new CSharpCodeGenerationOptions
+ {
+ NamespaceDeclarations = new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)
+ }
+ }
+ };
+ }
+
// Generate and hold onto the result so it can be disposed of with this context
- var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, signaturesOnly, MetadataAsSourceOptions.GetDefault(project.LanguageServices));
+ var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, signaturesOnly, options);
return result;
}
@@ -131,9 +153,9 @@ public static void VerifyResult(MetadataAsSourceFile file, string expected)
Assert.Equal(expectedSpan.End, actualSpan.End);
}
- public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool signaturesOnly = true)
+ public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool signaturesOnly = true, bool fileScopedNamespaces = false)
{
- var result = await GenerateSourceAsync(symbolMetadataName, project, signaturesOnly);
+ var result = await GenerateSourceAsync(symbolMetadataName, project, signaturesOnly, fileScopedNamespaces);
VerifyResult(result, expected);
}
diff --git a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs
index 017800d47dcef..a90d5d8174946 100644
--- a/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs
+++ b/src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs
@@ -19,6 +19,9 @@
using VB = Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using System.Threading;
+using Microsoft.CodeAnalysis.MetadataAsSource;
+using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
+using Microsoft.CodeAnalysis.CodeCleanup;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
@@ -984,10 +987,6 @@ public async Task TestTypeInFileScopedNamespace1()
using var context = TestContext.Create(
LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10");
- context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption(
- CSharpCodeStyleOptions.NamespaceDeclarations,
- new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)));
-
await context.GenerateAndVerifySourceAsync("N.C",
$@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
@@ -998,7 +997,8 @@ namespace N;
public class [|C|]
{{
public C();
-}}");
+}}",
+ fileScopedNamespaces: true);
}
[WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")]
@@ -1010,10 +1010,6 @@ public async Task TestTypeInFileScopedNamespace2()
using var context = TestContext.Create(
LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "9");
- context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption(
- CSharpCodeStyleOptions.NamespaceDeclarations,
- new CodeStyleOption2(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)));
-
await context.GenerateAndVerifySourceAsync("N.C",
$@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
@@ -1025,7 +1021,7 @@ public class [|C|]
{{
public C();
}}
-}}");
+}}", fileScopedNamespaces: true);
}
[WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")]
@@ -1037,10 +1033,6 @@ public async Task TestTypeInFileScopedNamespace3()
using var context = TestContext.Create(
LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10");
- context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption(
- CSharpCodeStyleOptions.NamespaceDeclarations,
- new CodeStyleOption2(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent)));
-
await context.GenerateAndVerifySourceAsync("N.C",
$@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
diff --git a/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb b/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb
index 3f8c543568135..ebdb2c335fe71 100644
--- a/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb
+++ b/src/EditorFeatures/Test2/Expansion/AbstractExpansionTest.vb
@@ -4,6 +4,7 @@
Imports System.Threading
Imports Microsoft.CodeAnalysis
+Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeCleanup
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
@@ -28,7 +29,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Expansion
Dim root = Await document.GetSyntaxRootAsync()
- Dim cleanupOptions = Await document.GetCodeCleanupOptionsAsync(fallbackOptions:=Nothing, CancellationToken.None)
+ Dim cleanupOptions = CodeCleanupOptions.GetDefault(document.Project.LanguageServices)
If hostDocument.AnnotatedSpans.ContainsKey("Expand") Then
For Each span In hostDocument.AnnotatedSpans("Expand")
diff --git a/src/EditorFeatures/TestUtilities/Completion/AbstractArgumentProviderTests`1.cs b/src/EditorFeatures/TestUtilities/Completion/AbstractArgumentProviderTests`1.cs
index ac23d353e45b4..222c32d6dc623 100644
--- a/src/EditorFeatures/TestUtilities/Completion/AbstractArgumentProviderTests`1.cs
+++ b/src/EditorFeatures/TestUtilities/Completion/AbstractArgumentProviderTests`1.cs
@@ -73,12 +73,11 @@ private protected async Task VerifyDefaultValueAsync(
Assert.IsType(GetArgumentProviderType(), provider);
var root = await document.GetRequiredSyntaxRootAsync(CancellationToken.None);
- var documentOptions = await document.GetOptionsAsync(CancellationToken.None);
var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None);
var parameter = GetParameterSymbolInfo(workspace, semanticModel, root, position, CancellationToken.None);
Contract.ThrowIfNull(parameter);
- var context = new ArgumentContext(provider, documentOptions, semanticModel, position, parameter, previousDefaultValue, CancellationToken.None);
+ var context = new ArgumentContext(provider, semanticModel, position, parameter, previousDefaultValue, CancellationToken.None);
await provider.ProvideArgumentAsync(context);
Assert.Equal(expectedDefaultValue, context.DefaultValue);
diff --git a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs
index c11adfcd4ee34..36fa5d9e91d55 100644
--- a/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs
+++ b/src/EditorFeatures/TestUtilities/Completion/AbstractCompletionProviderTests.cs
@@ -14,6 +14,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
+using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
@@ -127,14 +128,15 @@ private protected abstract Task BaseVerifyWorkerAsync(
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit,
- List matchingFilters, CompletionItemFlags? flags, bool skipSpeculation = false);
+ List matchingFilters, CompletionItemFlags? flags, CompletionOptions options,
+ bool skipSpeculation = false);
internal Task GetCompletionListAsync(
CompletionService service,
Document document,
int position,
RoslynCompletion.CompletionTrigger triggerInfo,
- CompletionOptions? options = null)
+ CompletionOptions options = null)
=> service.GetCompletionsAsync(document, position, options ?? GetCompletionOptions(), OptionValueSet.Empty, triggerInfo, GetRoles(document));
private protected async Task CheckResultsAsync(
@@ -144,8 +146,12 @@ private protected async Task CheckResultsAsync(
bool? hasSuggestionModeItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription,
bool? isComplexTextEdit,
- List matchingFilters, CompletionItemFlags? flags)
+ List matchingFilters,
+ CompletionItemFlags? flags,
+ CompletionOptions options)
{
+ options ??= GetCompletionOptions();
+
var code = (await document.GetTextAsync()).ToString();
var trigger = RoslynCompletion.CompletionTrigger.Invoke;
@@ -155,7 +161,6 @@ private protected async Task CheckResultsAsync(
trigger = RoslynCompletion.CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1));
}
- var options = GetCompletionOptions();
var displayOptions = SymbolDescriptionOptions.Default;
var completionService = GetCompletionService(document.Project);
var completionList = await GetCompletionListAsync(completionService, document, position, trigger, options);
@@ -241,7 +246,7 @@ private async Task VerifyAsync(
SourceCodeKind? sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionModeItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit,
- List matchingFilters, CompletionItemFlags? flags, bool skipSpeculation = false)
+ List matchingFilters, CompletionItemFlags? flags, CompletionOptions options, bool skipSpeculation = false)
{
foreach (var sourceKind in sourceCodeKind.HasValue ? new[] { sourceCodeKind.Value } : new[] { SourceCodeKind.Regular, SourceCodeKind.Script })
{
@@ -259,7 +264,7 @@ await VerifyWorkerAsync(
sourceKind, usePreviousCharAsTrigger, checkForAbsence, glyph,
matchPriority, hasSuggestionModeItem, displayTextSuffix, displayTextPrefix,
inlineDescription, isComplexTextEdit, matchingFilters, flags,
- skipSpeculation: skipSpeculation).ConfigureAwait(false);
+ options, skipSpeculation: skipSpeculation).ConfigureAwait(false);
}
}
@@ -336,7 +341,7 @@ private protected async Task VerifyItemExistsAsync(
int? glyph = null, int? matchPriority = null, bool? hasSuggestionModeItem = null,
string displayTextSuffix = null, string displayTextPrefix = null, string inlineDescription = null,
bool? isComplexTextEdit = null, List matchingFilters = null,
- CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence: false,
@@ -344,7 +349,7 @@ await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull,
hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix,
displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription,
isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters,
- flags: flags, skipSpeculation: skipSpeculation);
+ flags: flags, options, skipSpeculation: skipSpeculation);
}
private protected async Task VerifyItemIsAbsentAsync(
@@ -352,32 +357,33 @@ private protected async Task VerifyItemIsAbsentAsync(
SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false,
bool? hasSuggestionModeItem = null, string displayTextSuffix = null,
string displayTextPrefix = null, string inlineDescription = null,
- bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null)
+ bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null)
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind,
usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null,
hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix,
displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription,
- isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags);
+ isComplexTextEdit: isComplexTextEdit, matchingFilters: matchingFilters, flags: flags, options);
}
- protected async Task VerifyAnyItemExistsAsync(
+ private protected async Task VerifyAnyItemExistsAsync(
string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false,
bool? hasSuggestionModeItem = null, string displayTextSuffix = null, string displayTextPrefix = null,
- string inlineDescription = null)
+ string inlineDescription = null, CompletionOptions options = null)
{
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null,
sourceCodeKind, usePreviousCharAsTrigger: usePreviousCharAsTrigger,
checkForAbsence: false, glyph: null, matchPriority: null,
hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix,
displayTextPrefix: displayTextPrefix, inlineDescription: inlineDescription,
- isComplexTextEdit: null, matchingFilters: null, flags: null);
+ isComplexTextEdit: null, matchingFilters: null, flags: null, options);
}
- protected async Task VerifyNoItemsExistAsync(
+ private protected async Task VerifyNoItemsExistAsync(
string markup, SourceCodeKind? sourceCodeKind = null,
bool usePreviousCharAsTrigger = false, bool? hasSuggestionModeItem = null,
- string displayTextSuffix = null, string inlineDescription = null)
+ string displayTextSuffix = null, string inlineDescription = null, CompletionOptions options = null)
{
await VerifyAsync(
markup, expectedItemOrNull: null, expectedDescriptionOrNull: null,
@@ -385,7 +391,7 @@ await VerifyAsync(
checkForAbsence: true, glyph: null, matchPriority: null,
hasSuggestionModeItem: hasSuggestionModeItem, displayTextSuffix: displayTextSuffix,
displayTextPrefix: null, inlineDescription: inlineDescription,
- isComplexTextEdit: null, matchingFilters: null, flags: null);
+ isComplexTextEdit: null, matchingFilters: null, flags: null, options);
}
internal abstract Type GetCompletionProviderType();
@@ -407,6 +413,7 @@ private protected virtual async Task VerifyWorkerAsync(
string displayTextSuffix, string displayTextPrefix,
string inlineDescription, bool? isComplexTextEdit,
List matchingFilters, CompletionItemFlags? flags,
+ CompletionOptions options,
bool skipSpeculation = false)
{
using var workspaceFixture = GetOrCreateWorkspaceFixture();
@@ -419,7 +426,7 @@ await CheckResultsAsync(
expectedDescriptionOrNull, usePreviousCharAsTrigger,
checkForAbsence, glyph, matchPriority,
hasSuggestionModeItem, displayTextSuffix, displayTextPrefix,
- inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
if (!skipSpeculation && await CanUseSpeculativeSemanticModelAsync(document1, position))
{
@@ -428,7 +435,7 @@ await CheckResultsAsync(
document2, position, expectedItemOrNull, expectedDescriptionOrNull,
usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority,
hasSuggestionModeItem, displayTextSuffix, displayTextPrefix,
- inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
}
@@ -914,7 +921,7 @@ private protected async Task VerifyAtPositionAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence,
int? glyph, int? matchPriority, bool? hasSuggestionItem,
string displayTextSuffix, string displayTextPrefix, string inlineDescription = null,
- bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ bool? isComplexTextEdit = null, List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
code = code.Substring(0, position) + insertText + code.Substring(position);
position += insertText.Length;
@@ -923,7 +930,7 @@ await BaseVerifyWorkerAsync(code, position,
expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, skipSpeculation: skipSpeculation);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation);
}
private protected async Task VerifyAtPositionAsync(
@@ -932,13 +939,13 @@ private protected async Task VerifyAtPositionAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null, CompletionOptions options = null, bool skipSpeculation = false)
{
await VerifyAtPositionAsync(
code, position, string.Empty, usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix,
- inlineDescription, isComplexTextEdit, matchingFilters, flags, skipSpeculation: skipSpeculation);
+ inlineDescription, isComplexTextEdit, matchingFilters, flags, options, skipSpeculation: skipSpeculation);
}
private protected async Task VerifyAtEndOfFileAsync(
@@ -947,7 +954,8 @@ private protected async Task VerifyAtEndOfFileAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null)
+ List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null)
{
// only do this if the placeholder was at the end of the text.
if (code.Length != position)
@@ -962,7 +970,7 @@ await BaseVerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph,
matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix,
- inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync(
@@ -971,13 +979,15 @@ private protected async Task VerifyAtPosition_ItemPartiallyWrittenAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null, bool skipSpeculation = false)
+ List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null, bool skipSpeculation = false)
{
await VerifyAtPositionAsync(
code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, skipSpeculation: skipSpeculation);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options,
+ skipSpeculation: skipSpeculation);
}
private protected async Task VerifyAtEndOfFileAsync(
@@ -986,12 +996,13 @@ private protected async Task VerifyAtEndOfFileAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null)
+ List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null)
{
await VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind,
checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix,
- displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags);
+ displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags, options);
}
private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
@@ -1000,13 +1011,14 @@ private protected async Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph,
int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix,
string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null,
- List matchingFilters = null, CompletionItemFlags? flags = null)
+ List matchingFilters = null, CompletionItemFlags? flags = null,
+ CompletionOptions options = null)
{
await VerifyAtEndOfFileAsync(
code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence,
glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription,
- isComplexTextEdit, matchingFilters, flags);
+ isComplexTextEdit, matchingFilters, flags, options);
}
protected void VerifyTextualTriggerCharacter(
diff --git a/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs b/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs
index fdc228081db66..a78b7a2ffe961 100644
--- a/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs
+++ b/src/EditorFeatures/TestUtilities/ExtractInterface/AbstractExtractInterfaceTests.cs
@@ -98,7 +98,7 @@ private static async Task TestExtractInterfaceCommandAsync(
using var testState = ExtractInterfaceTestState.Create(markup, languageName, compilationOptions,
options: new OptionsCollection(languageName)
{
- { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Silent }
+ { CodeStyleOptions2.AccessibilityModifiersRequired, AccessibilityModifiersRequired.Never, NotificationOption2.Silent }
});
var result = await testState.ExtractViaCommandAsync();
diff --git a/src/EditorFeatures/TestUtilities/ExtractInterface/ExtractInterfaceTestState.cs b/src/EditorFeatures/TestUtilities/ExtractInterface/ExtractInterfaceTestState.cs
index 3ec9a60bec796..da77cb8bc205f 100644
--- a/src/EditorFeatures/TestUtilities/ExtractInterface/ExtractInterfaceTestState.cs
+++ b/src/EditorFeatures/TestUtilities/ExtractInterface/ExtractInterfaceTestState.cs
@@ -15,6 +15,7 @@
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Notification;
+using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
@@ -85,7 +86,7 @@ public Task GetTypeAnalysisResultAsync(TypeD
ExtractFromDocument,
_testDocument.CursorPosition.Value,
typeDiscoveryRule,
- CodeActionOptions.DefaultProvider,
+ Workspace.GlobalOptions.CreateProvider(),
CancellationToken.None);
}
@@ -94,7 +95,7 @@ public Task ExtractViaCommandAsync()
return ExtractInterfaceService.ExtractInterfaceAsync(
ExtractFromDocument,
_testDocument.CursorPosition.Value,
- CodeActionOptions.DefaultProvider,
+ Workspace.GlobalOptions.CreateProvider(),
(errorMessage, severity) =>
{
this.ErrorMessage = errorMessage;
@@ -108,7 +109,7 @@ public async Task ExtractViaCodeAction()
var actions = await ExtractInterfaceService.GetExtractInterfaceCodeActionAsync(
ExtractFromDocument,
new TextSpan(_testDocument.CursorPosition.Value, 1),
- CodeActionOptions.DefaultProvider,
+ Workspace.GlobalOptions.CreateProvider(),
CancellationToken.None);
var action = actions.Single();
diff --git a/src/EditorFeatures/TestUtilities/ExtractInterface/TestExtractInterfaceOptions.cs b/src/EditorFeatures/TestUtilities/ExtractInterface/TestExtractInterfaceOptions.cs
index f9aff7552cbe8..1db5a8c70d8bf 100644
--- a/src/EditorFeatures/TestUtilities/ExtractInterface/TestExtractInterfaceOptions.cs
+++ b/src/EditorFeatures/TestUtilities/ExtractInterface/TestExtractInterfaceOptions.cs
@@ -50,6 +50,7 @@ public Task GetExtractInterfaceOptionsAsync(
string defaultNamespace,
string generatedNameTypeParameterSuffix,
string languageName,
+ CleanCodeGenerationOptionsProvider fallbackOptions,
CancellationToken cancellationToken)
{
this.AllExtractableMembers = extractableMembers;
@@ -66,7 +67,7 @@ public Task GetExtractInterfaceOptionsAsync(
interfaceName: ChosenInterfaceName ?? defaultInterfaceName,
fileName: ChosenFileName ?? defaultInterfaceName,
location: SameFile ? ExtractInterfaceOptionsResult.ExtractLocation.SameFile : ExtractInterfaceOptionsResult.ExtractLocation.NewFile,
- CodeActionOptions.DefaultProvider);
+ fallbackOptions);
return Task.FromResult(result);
}
diff --git a/src/EditorFeatures/TestUtilities/Formatting/AbstractNewDocumentFormattingServiceTests.cs b/src/EditorFeatures/TestUtilities/Formatting/AbstractNewDocumentFormattingServiceTests.cs
index 83c83a9ba035a..e22b231b1aab5 100644
--- a/src/EditorFeatures/TestUtilities/Formatting/AbstractNewDocumentFormattingServiceTests.cs
+++ b/src/EditorFeatures/TestUtilities/Formatting/AbstractNewDocumentFormattingServiceTests.cs
@@ -5,7 +5,9 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeCleanup;
+using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
@@ -20,59 +22,25 @@ public abstract class AbstractNewDocumentFormattingServiceTests
protected abstract string Language { get; }
protected abstract TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions);
- internal Task TestAsync(string testCode, string expected)
+ internal async Task TestAsync(string testCode, string expected, OptionsCollection? options = null, ParseOptions? parseOptions = null)
{
- return TestCoreAsync