diff --git a/Roslyn.sln b/Roslyn.sln index 3f58a48bea12a..7fa920356be86 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -460,6 +460,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Workspace", "Workspace", "{ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities", "src\EditorFeatures\DiagnosticsTestUtilities\Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj", "{B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities", "src\CodeStyle\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj", "{2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution src\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems*{0141285d-8f6c-42c7-baf3-3c0ccd61c716}*SharedItemsImports = 5 @@ -1207,6 +1209,10 @@ Global {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E}.Release|Any CPU.Build.0 = Release|Any CPU + {2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1421,6 +1427,7 @@ Global {7A69EA65-4411-4CD0-B439-035E720C1BD3} = {DF17AF27-AA02-482B-8946-5CA8A50D5A2B} {9C1BE25C-5926-4E56-84AE-D2242CB0627E} = {DF17AF27-AA02-482B-8946-5CA8A50D5A2B} {B64766CD-1A1F-4C1B-B11F-C30F82B8E41E} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} + {2D5E2DE4-5DA8-41C1-A14F-49855DCCE9C5} = {DC014586-8D07-4DE6-B28E-C0540C59C085} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {604E6B91-7BC0-4126-AE07-D4D2FEFC3D29} diff --git a/src/Analyzers/CSharp/Analyzers/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs index 6f5759d7c5417..3607f887c7b52 100644 --- a/src/Analyzers/CSharp/Analyzers/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersDiagnosticAnalyzer.cs @@ -4,17 +4,12 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] @@ -29,14 +24,14 @@ public CSharpAddAccessibilityModifiersDiagnosticAnalyzer() protected override void ProcessCompilationUnit( SyntaxTreeAnalysisContext context, - CodeStyleOption option, CompilationUnitSyntax compilationUnit) + CodeStyleOption2 option, CompilationUnitSyntax compilationUnit) { ProcessMembers(context, option, compilationUnit.Members); } private void ProcessMembers( SyntaxTreeAnalysisContext context, - CodeStyleOption option, + CodeStyleOption2 option, SyntaxList members) { foreach (var memberDeclaration in members) @@ -47,7 +42,7 @@ private void ProcessMembers( private void ProcessMemberDeclaration( SyntaxTreeAnalysisContext context, - CodeStyleOption option, MemberDeclarationSyntax member) + CodeStyleOption2 option, MemberDeclarationSyntax member) { if (member.IsKind(SyntaxKind.NamespaceDeclaration, out NamespaceDeclarationSyntax namespaceDeclaration)) { diff --git a/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs index 0f3bf29304ef7..06785af8cefd8 100644 --- a/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/AddBraces/CSharpAddBracesDiagnosticAnalyzer.cs @@ -5,19 +5,13 @@ using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using FormattingRangeHelper = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces { [DiagnosticAnalyzer(LanguageNames.CSharp)] diff --git a/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs index f133313180e03..190c19264a9d6 100644 --- a/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs @@ -6,16 +6,11 @@ using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; diff --git a/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs index 450c353d1fe08..2f5a2f6cebd85 100644 --- a/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs @@ -3,17 +3,12 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.OrderModifiers; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs index 0c2a3b3dce90d..a95858a446810 100644 --- a/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs @@ -2,17 +2,12 @@ // 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.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues { [DiagnosticAnalyzer(LanguageNames.CSharp)] diff --git a/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs index 331465188ffbe..22deca161bb99 100644 --- a/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseDefaultLiteral/CSharpUseDefaultLiteralDiagnosticAnalyzer.cs @@ -3,17 +3,12 @@ // 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral { [DiagnosticAnalyzer(LanguageNames.CSharp)] diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs index da67ab88a74b5..573fa2d138ce1 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.cs @@ -3,15 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForAccessorsHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs index 7390d0ecaad27..5669e680be5bf 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs @@ -3,15 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForConstructorsHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs index cbf025b55bf50..bd0c6895bcb37 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConversionOperatorsHelper.cs @@ -3,15 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForConversionOperatorsHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs index 561c42842473b..fb3e1f26c4f34 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForIndexersHelper.cs @@ -4,16 +4,10 @@ using System; using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs index 7fe63df3f71e2..4b1c9e9e0e179 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForLocalFunctionHelper.cs @@ -3,16 +3,11 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForLocalFunctionHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs index eee9d6e4032b7..51c95512613fa 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForMethodsHelper.cs @@ -3,16 +3,11 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForMethodsHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs index f0ad8908264d7..605f9a1482723 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForOperatorsHelper.cs @@ -3,15 +3,10 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForOperatorsHelper : diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs index 86b4cf128837c..c590975fe39e7 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs @@ -4,16 +4,10 @@ using System; using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs index 959d4d8100c0b..95ffd6a727674 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper.cs @@ -3,21 +3,19 @@ // See the LICENSE file in the project root for more information. using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.CSharp.Syntax; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal abstract class UseExpressionBodyHelper { - public abstract Option> Option { get; } + public abstract Option2> Option { get; } public abstract LocalizableString UseExpressionBodyTitle { get; } public abstract LocalizableString UseBlockBodyTitle { get; } public abstract string DiagnosticId { get; } diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs index 691b278237e9f..e410ea5f4f315 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs @@ -5,17 +5,14 @@ using System; using System.Collections.Immutable; using System.Linq; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody @@ -28,7 +25,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody internal abstract class UseExpressionBodyHelper : UseExpressionBodyHelper where TDeclaration : SyntaxNode { - public override Option> Option { get; } + public override Option2> Option { get; } public override LocalizableString UseExpressionBodyTitle { get; } public override LocalizableString UseBlockBodyTitle { get; } public override string DiagnosticId { get; } @@ -38,7 +35,7 @@ protected UseExpressionBodyHelper( string diagnosticId, LocalizableString useExpressionBodyTitle, LocalizableString useBlockBodyTitle, - Option> option, + Option2> option, ImmutableArray syntaxKinds) { DiagnosticId = diagnosticId; @@ -61,7 +58,6 @@ protected static AccessorDeclarationSyntax GetSingleGetAccessor(AccessorListSynt return null; } - protected static BlockSyntax GetBodyFromSingleGetAccessor(AccessorListSyntax accessorList) => GetSingleGetAccessor(accessorList)?.Body; diff --git a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs index 30faffecfd136..99993af7388b0 100644 --- a/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseExpressionBody/UseExpressionBodyDiagnosticAnalyzer.cs @@ -6,12 +6,10 @@ using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody diff --git a/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs b/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs index 7ab8e7c35765b..85ac5061a1e70 100644 --- a/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs +++ b/src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpTypeStyleDiagnosticAnalyzerBase.cs @@ -4,18 +4,15 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle @@ -42,9 +39,9 @@ public override bool OpenFileOnly(OptionSet options) var whereApparentOption = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent).Notification; var wherePossibleOption = options.GetOption(CSharpCodeStyleOptions.VarElsewhere).Notification; - return !(forIntrinsicTypesOption == NotificationOption.Warning || forIntrinsicTypesOption == NotificationOption.Error || - whereApparentOption == NotificationOption.Warning || whereApparentOption == NotificationOption.Error || - wherePossibleOption == NotificationOption.Warning || wherePossibleOption == NotificationOption.Error); + return !(forIntrinsicTypesOption == NotificationOption2.Warning || forIntrinsicTypesOption == NotificationOption2.Error || + whereApparentOption == NotificationOption2.Warning || whereApparentOption == NotificationOption2.Error || + wherePossibleOption == NotificationOption2.Warning || wherePossibleOption == NotificationOption2.Error); } protected override void InitializeWorker(AnalysisContext context) diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs index 3e8c47668bdf4..af384809e342d 100644 --- a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.cs @@ -8,18 +8,13 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// diff --git a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs index 01c24c7a82e2d..0821ef1774e0a 100644 --- a/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzer.cs @@ -5,17 +5,12 @@ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// diff --git a/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs index 0d60df9f6c16b..e334bee84b2d2 100644 --- a/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs @@ -3,16 +3,11 @@ // See the LICENSE file in the project root for more information. using System.Threading; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UseThrowExpression; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseThrowExpression { [DiagnosticAnalyzer(LanguageNames.CSharp)] diff --git a/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs index 2ecead1166320..15d7465c27826 100644 --- a/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs @@ -5,15 +5,10 @@ using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.OrderModifiers; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [ExportCodeFixProvider(LanguageNames.CSharp), Shared] diff --git a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs index f1841256f3beb..e3b399585824c 100644 --- a/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; @@ -17,12 +18,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral { [ExportCodeFixProvider(LanguageNames.CSharp), Shared] diff --git a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs index 78da6d193bf7a..c9d7333931847 100644 --- a/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs +++ b/src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs @@ -3,18 +3,13 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers.CSharpAddAccessibilityModifiersDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers.CSharpAddAccessibilityModifiersCodeFixProvider>; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddAccessibilityModifiers { public class AddAccessibilityModifiersTests @@ -315,7 +310,7 @@ enum E }, Options = { - { CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, + { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } @@ -337,7 +332,7 @@ ref struct S1 { } }", Options = { - { CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, + { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } @@ -359,7 +354,7 @@ readonly struct S1 { } }", Options = { - { CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, + { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } @@ -375,7 +370,7 @@ internal class [|C1|] { }", class C1 { }", Options = { - { CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, + { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } diff --git a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs index b32aa2ee52cde..ea2b4bfdeadcb 100644 --- a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs +++ b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs @@ -4,6 +4,8 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; @@ -11,14 +13,6 @@ using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddBraces { public partial class AddBracesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -43,7 +37,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -67,7 +61,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -87,7 +81,7 @@ static void Main() return; } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -107,7 +101,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -127,7 +121,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -147,7 +141,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -168,7 +162,7 @@ static void Main() while (true); } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -196,7 +190,7 @@ public void Dispose() throw new NotImplementedException(); } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -231,7 +225,7 @@ public void Dispose() throw new NotImplementedException(); } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -252,7 +246,7 @@ static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -273,7 +267,7 @@ static void Main() return; } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -293,7 +287,7 @@ unsafe static void Main() } } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -662,12 +656,15 @@ static void Main() expectDiagnostic); } + +#pragma warning disable CA1200 // Avoid using cref tags with a prefix - Remove the suppression when https://github.com/dotnet/roslyn/issues/42611 is fixed. /// /// Verifies that the use of braces in a construct nested within the true portion of an if statement does /// not trigger the multiline behavior the else clause of a containing stetemnet for - /// . The else clause would only need braces if the true + /// . The else clause would only need braces if the true /// portion also used braces (which would be required if the true portion was considered multiline. /// +#pragma warning restore CA1200 // Avoid using cref tags with a prefix [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] @@ -1351,7 +1348,7 @@ static void Main() return; } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -1374,7 +1371,7 @@ static void Main() #endif } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -1399,7 +1396,7 @@ static void Main() return; } }", - new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption.Silent))); + new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] @@ -1832,11 +1829,11 @@ private async Task TestAsync(string initialMarkup, string expectedMarkup, Prefer { if (expectDiagnostic) { - await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption.Silent)); + await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent)); } else { - await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption.Silent))); + await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent))); } } } diff --git a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs index 5e898a9cc7adb..0e3dc5f5d5ed7 100644 --- a/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs +++ b/src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionTests.cs @@ -4,6 +4,8 @@ using System.Linq; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; @@ -14,14 +16,6 @@ Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression.ConvertSwitchStatementToExpressionDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression.ConvertSwitchStatementToExpressionCodeFixProvider>; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression { public class ConvertSwitchStatementToExpressionTests @@ -729,7 +723,7 @@ int M(int i) }, Options = { - { CSharpCodeStyleOptions.PreferSwitchExpression, true, NotificationOption.Warning }, + { CSharpCodeStyleOptions.PreferSwitchExpression, true, NotificationOption2.Warning }, }, }.RunAsync(); } @@ -1070,7 +1064,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1138,7 +1132,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1206,7 +1200,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1282,7 +1276,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1350,7 +1344,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1418,7 +1412,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1486,7 +1480,7 @@ public static void Test(string name) FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1533,7 +1527,7 @@ public static void Test() FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1578,7 +1572,7 @@ public static void Test() FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1624,7 +1618,7 @@ public static void Test() FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1670,7 +1664,7 @@ public static void Test() FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarForBuiltInTypes, false, NotificationOption2.Silent }, }, }.RunAsync(); } @@ -1716,7 +1710,7 @@ public static void Test() FixedCode = expected, Options = { - { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption.Silent }, + { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Silent }, }, }.RunAsync(); } diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs index 16f7287fca351..6e84cd52cf10a 100644 --- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs +++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs @@ -4,20 +4,15 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QualifyMemberAccess { public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -25,22 +20,22 @@ public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProvider internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpQualifyMemberAccessDiagnosticAnalyzer(), new CSharpQualifyMemberAccessCodeFixProvider()); - private Task TestAsyncWithOption(string code, string expected, PerLanguageOption> option) + private Task TestAsyncWithOption(string code, string expected, PerLanguageOption2> option) { - return TestAsyncWithOptionAndNotificationOption(code, expected, option, NotificationOption.Error); + return TestAsyncWithOptionAndNotificationOption(code, expected, option, NotificationOption2.Error); } - private Task TestAsyncWithOptionAndNotificationOption(string code, string expected, PerLanguageOption> option, NotificationOption notification) + private Task TestAsyncWithOptionAndNotificationOption(string code, string expected, PerLanguageOption2> option, NotificationOption2 notification) { return TestInRegularAndScriptAsync(code, expected, options: Option(option, true, notification)); } - private Task TestMissingAsyncWithOption(string code, PerLanguageOption> option) + private Task TestMissingAsyncWithOption(string code, PerLanguageOption2> option) { - return TestMissingAsyncWithOptionAndNotificationOption(code, option, NotificationOption.Error); + return TestMissingAsyncWithOptionAndNotificationOption(code, option, NotificationOption2.Error); } - private Task TestMissingAsyncWithOptionAndNotificationOption(string code, PerLanguageOption> option, NotificationOption notification) + private Task TestMissingAsyncWithOptionAndNotificationOption(string code, PerLanguageOption2> option, NotificationOption2 notification) => TestMissingInRegularAndScriptAsync(code, new TestParameters(options: Option(option, true, notification))); [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -66,7 +61,7 @@ void M() this.i = 1; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -92,7 +87,7 @@ void M() var x = this.i; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -118,7 +113,7 @@ void M(int ii) M(this.i); } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -144,7 +139,7 @@ void M() var s = this.i.ToString(); } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -170,7 +165,7 @@ void M() var x = this.s?.ToString(); } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -202,7 +197,7 @@ void M() this.i = 1; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -226,7 +221,7 @@ void M() var test = new System.Collections.Generic.List { this.i }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -250,7 +245,7 @@ void M() var test = new System.Collections.Generic.List { this.i }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -268,7 +263,7 @@ void M() c.[|i|] = 1; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -285,7 +280,7 @@ void M() [|i|] = 1; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -301,7 +296,7 @@ void M() var test = new System.Collections.Generic.List { [|foo|] }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -317,7 +312,7 @@ void M() var test = new System.Collections.Generic.List { [|foo|] }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } @@ -334,7 +329,7 @@ void M() var test = new System.Collections.Generic.Dictionary { { 2, [|foo|] } }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -353,7 +348,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -374,7 +369,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -395,7 +390,7 @@ void M(Class c) }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -421,7 +416,7 @@ void M() this.i = 1; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -447,7 +442,7 @@ void M() var x = this.i; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -466,7 +461,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -487,7 +482,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -508,7 +503,7 @@ void M(Class c) }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -543,7 +538,7 @@ void M(Class c) }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -562,7 +557,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -583,7 +578,7 @@ void M(Class c) } } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -604,7 +599,7 @@ void M(Class c) }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] @@ -639,7 +634,7 @@ void M(Class c) }; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -665,7 +660,7 @@ void M(int ii) M(this.i); } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -691,7 +686,7 @@ void M() var s = this.i.ToString(); } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -717,7 +712,7 @@ void M() var x = this.s?.ToString(); } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -749,7 +744,7 @@ void M() this.i = 1; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -766,7 +761,7 @@ void M(Class c) c.[|i|] = 1; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -783,7 +778,7 @@ void M() [|i|] = 1; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -805,7 +800,7 @@ void M(int i) this.M(0); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -825,7 +820,7 @@ int M() { return this.M(); }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -845,7 +840,7 @@ string M() { var s = this.M().ToString(); }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -865,7 +860,7 @@ string M() { return this.M()?.ToString(); }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -895,7 +890,7 @@ void Handler(object sender, EventArgs args) e += this.Handler; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -925,7 +920,7 @@ void Handler(object sender, EventArgs args) e += new EventHandler(this.Handler); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -961,7 +956,7 @@ void M() this.Method(); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -976,7 +971,7 @@ void M(Class c) c.[|M|](); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -995,7 +990,7 @@ void M() [|Method|](); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1011,7 +1006,7 @@ void M() var test = new System.Collections.Generic.List { [|foo|] }; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1027,7 +1022,7 @@ void M() var test = new System.Collections.Generic.List { [|Local()|] }; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1043,7 +1038,7 @@ void M() var test = new System.Collections.Generic.List { [|foo|] }; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1059,7 +1054,7 @@ void M() var test = new System.Collections.Generic.List { [|Local()|] }; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1075,7 +1070,7 @@ void M() [|Local|](); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] @@ -1097,7 +1092,7 @@ void Method2(Func LocalFunction) { } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] @@ -1116,7 +1111,7 @@ void Method() var dict = new Dictionary, int>() { { [|LocalFunction|], 1 } }; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] @@ -1134,7 +1129,7 @@ void Method() [|LocalFunction|](); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1164,7 +1159,7 @@ void Handler(object sender, EventArgs args) this.e += Handler; } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1212,7 +1207,7 @@ void Handler(object sender, EventArgs args) this.e += Handler; } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1242,7 +1237,7 @@ void OnSomeEvent() this.e(this, new EventArgs()); } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1272,7 +1267,7 @@ void OnSomeEvent() this.e.Invoke(this, new EventArgs()); } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1302,7 +1297,7 @@ void OnSomeEvent() this.e?.Invoke(this, new EventArgs()); } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1338,7 +1333,7 @@ void Handler(object sender, EventArgs args) this.e += Handler; } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1361,7 +1356,7 @@ void Handler(object sender, EventArgs args) { } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] @@ -1380,7 +1375,7 @@ void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] @@ -1405,7 +1400,7 @@ void M() this.Property = 1; } }", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Silent); +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] @@ -1430,7 +1425,7 @@ void M() this.Property = 1; } }", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Suggestion); +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] @@ -1455,7 +1450,7 @@ void M() this.Property = 1; } }", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Warning); +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] @@ -1480,7 +1475,7 @@ void M() this.Property = 1; } }", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Error); +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] @@ -1512,7 +1507,7 @@ void Error() func(1); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] @@ -1532,7 +1527,7 @@ void Error() func(1); } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] @@ -1548,7 +1543,7 @@ class Derived : Base { void M() { [|base.field|] = 0; } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] @@ -1564,7 +1559,7 @@ class Derived : Base { protected override int Property { get { return [|base.Property|]; } } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] @@ -1580,7 +1575,7 @@ class Derived : Base { protected override void M() { [|base.M()|]; } }", -CodeStyleOptions.QualifyMethodAccess); +CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] @@ -1600,7 +1595,7 @@ protected override event EventHandler Event remove { } } }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1613,7 +1608,7 @@ await TestMissingAsyncWithOption( public int Foo { get; set; } public static string Bar = nameof([|Foo|]); }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1626,7 +1621,7 @@ await TestMissingAsyncWithOption( public int Foo { get; set; } public string Bar = nameof([|Foo|]); }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1642,7 +1637,7 @@ static void Main(string[] args) System.Console.WriteLine(nameof([|Foo|])); } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1658,7 +1653,7 @@ static void Main(string[] args) System.Console.WriteLine(nameof([|Foo|])); } }", -CodeStyleOptions.QualifyFieldAccess); +CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1676,7 +1671,7 @@ static Program() Bar = nameof([|Foo|]); } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1690,7 +1685,7 @@ await TestMissingAsyncWithOption( private string Field = nameof([|Bar|]); }", -CodeStyleOptions.QualifyEventAccess); +CodeStyleOptions2.QualifyEventAccess); } [WorkItem(32093, "https://github.com/dotnet/roslyn/issues/32093")] @@ -1710,7 +1705,7 @@ public Derived() {} } ", - CodeStyleOptions.QualifyFieldAccess); + CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1728,7 +1723,7 @@ await TestAsyncWithOption( public string Foo { get; set; } public string Bar { get => this.Foo; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1746,7 +1741,7 @@ await TestAsyncWithOption( public string Foo { get; set; } public string Bar { get { return this.Foo; } => Foo; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] @@ -1764,7 +1759,7 @@ await TestAsyncWithOption( public string Foo { get; set; } public string Bar { get { return Foo; } => this.Foo; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1788,7 +1783,7 @@ void M() var test = new System.Collections.Generic.List { this.Foo }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] @@ -1812,7 +1807,7 @@ void M() var test = new System.Collections.Generic.List { this.Foo }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] @@ -1831,7 +1826,7 @@ public void Bar() }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] @@ -1850,7 +1845,7 @@ public void Bar() }; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] @@ -1871,7 +1866,7 @@ class Program { int Goo { get; set; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] @@ -1892,7 +1887,7 @@ class Program [My(nameof([|Goo|]))] int Goo { get; set; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] @@ -1914,7 +1909,7 @@ class Program public int Bar = 0 ; public int Goo { get; set; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] @@ -1934,7 +1929,7 @@ class Program { int Goo { [My(nameof([|Goo|]))]get; set; } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] @@ -1955,7 +1950,7 @@ class Program int Goo { get; set; } void M([My(nameof([|Goo|]))]int i) { } }", -CodeStyleOptions.QualifyPropertyAccess); +CodeStyleOptions2.QualifyPropertyAccess); } } } diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs index 04ada69bd6246..28614834b8391 100644 --- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs +++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs @@ -3,16 +3,11 @@ // See the LICENSE file in the project root for more information. using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QualifyMemberAccess { public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -97,7 +92,7 @@ void N() await TestInRegularAndScriptAsync( initialMarkup: input, expectedMarkup: expected, - options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Suggestion)); + options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Suggestion)); } } } diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs index e5939cae38f34..67a6efb8d3c0f 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs @@ -2,28 +2,21 @@ // 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestHelpers; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public class RemoveUnusedParametersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -31,9 +24,9 @@ public class RemoveUnusedParametersTests : AbstractCSharpDiagnosticProviderBased internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); - private IDictionary NonPublicMethodsOnly => - Option(CodeStyleOptions.UnusedParameters, - new CodeStyleOption(UnusedParametersPreference.NonPublicMethods, NotificationOption.Suggestion)); + private IOptionsCollection NonPublicMethodsOnly => + Option(CodeStyleOptions2.UnusedParameters, + new CodeStyleOption2(UnusedParametersPreference.NonPublicMethods, NotificationOption2.Suggestion)); // Ensure that we explicitly test missing UnusedParameterDiagnosticId, which has no corresponding code fix (non-fixable diagnostic). private Task TestDiagnosticMissingAsync(string initialMarkup, ParseOptions parseOptions = null) @@ -42,11 +35,11 @@ private Task TestDiagnosticsWithAsync(string initialMarkup, ParseOptions parseOp => TestDiagnosticsAsync(initialMarkup, options: null, parseOptions, expectedDiagnostics); private Task TestDiagnosticsAsync(string initialMarkup, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options: null, parseOptions: null, expectedDiagnostics); - private Task TestDiagnosticMissingAsync(string initialMarkup, IDictionary options, ParseOptions parseOptions = null) + private Task TestDiagnosticMissingAsync(string initialMarkup, IOptionsCollection options, ParseOptions parseOptions = null) => TestDiagnosticMissingAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true)); - private Task TestDiagnosticsAsync(string initialMarkup, IDictionary options, params DiagnosticDescription[] expectedDiagnostics) + private Task TestDiagnosticsAsync(string initialMarkup, IOptionsCollection options, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, options, parseOptions: null, expectedDiagnostics); - private Task TestDiagnosticsAsync(string initialMarkup, IDictionary options, ParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics) + private Task TestDiagnosticsAsync(string initialMarkup, IOptionsCollection options, ParseOptions parseOptions, params DiagnosticDescription[] expectedDiagnostics) => TestDiagnosticsAsync(initialMarkup, new TestParameters(parseOptions, options: options, retainNonFixableDiagnostics: true), expectedDiagnostics); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] @@ -112,7 +105,7 @@ await TestDiagnosticsAsync( public async Task Parameter_Unused_UnusedExpressionAssignment_PreferNone() { var unusedValueAssignmentOptionSuppressed = Option(CSharpCodeStyleOptions.UnusedValueAssignment, - new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.None)); + new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.None)); await TestDiagnosticMissingAsync( @"class C @@ -1351,8 +1344,8 @@ IEnumerable LocalFunc(T value) [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter() { - var options = Option(CodeStyleOptions.UnusedParameters, - new CodeStyleOption(default, NotificationOption.Suggestion)); + var options = Option(CodeStyleOptions2.UnusedParameters, + new CodeStyleOption2(default, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; @@ -1382,8 +1375,8 @@ private void myAction() { } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)] public async Task RegressionTest_ShouldReportUnusedParameter_02() { - var options = Option(CodeStyleOptions.UnusedParameters, - new CodeStyleOption((UnusedParametersPreference)2, NotificationOption.Suggestion)); + var options = Option(CodeStyleOptions2.UnusedParameters, + new CodeStyleOption2((UnusedParametersPreference)2, NotificationOption2.Suggestion)); await TestDiagnosticMissingAsync( @"using System; diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs index aa00f2053745c..6d2e473e0e633 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs @@ -2,38 +2,31 @@ // 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.Collections.Generic; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestHelpers; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public partial class RemoveUnusedValueAssignmentTests : RemoveUnusedValuesTestsBase { - protected override IDictionary PreferNone => + private protected override IOptionsCollection PreferNone => Option(CSharpCodeStyleOptions.UnusedValueAssignment, - new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.None)); + new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.None)); - protected override IDictionary PreferDiscard => + private protected override IOptionsCollection PreferDiscard => Option(CSharpCodeStyleOptions.UnusedValueAssignment, - new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.Suggestion)); + new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion)); - protected override IDictionary PreferUnusedLocal => + private protected override IOptionsCollection PreferUnusedLocal => Option(CSharpCodeStyleOptions.UnusedValueAssignment, - new CodeStyleOption(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Suggestion)); + new CodeStyleOption2(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task Initialization_Suppressed() @@ -94,8 +87,8 @@ int M() [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task Initialization_ConstantValue_RemoveUnsuedParametersSuppressed() { - var removeUnusedParametersSuppressed = Option(CodeStyleOptions.UnusedParameters, - new CodeStyleOption(UnusedParametersPreference.NonPublicMethods, NotificationOption.None)); + var removeUnusedParametersSuppressed = Option(CodeStyleOptions2.UnusedParameters, + new CodeStyleOption2(UnusedParametersPreference.NonPublicMethods, NotificationOption2.None)); await TestInRegularAndScriptAsync( @"class C @@ -120,8 +113,8 @@ int M() [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task Initialization_ConstantValue_RemoveUnsuedParametersNotApplicable() { - var removeUnusedParametersNotApplicable = Option(CodeStyleOptions.UnusedParameters, - new CodeStyleOption(UnusedParametersPreference.NonPublicMethods, NotificationOption.Silent)); + var removeUnusedParametersNotApplicable = Option(CodeStyleOptions2.UnusedParameters, + new CodeStyleOption2(UnusedParametersPreference.NonPublicMethods, NotificationOption2.Silent)); await TestInRegularAndScriptAsync( @"class C diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs index fcc3f077124a7..82c763bc44e31 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs @@ -2,37 +2,30 @@ // 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.Collections.Generic; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public partial class RemoveUnusedValueExpressionStatementTests : RemoveUnusedValuesTestsBase { - protected override IDictionary PreferNone => + private protected override IOptionsCollection PreferNone => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, - new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.None)); + new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.None)); - protected override IDictionary PreferDiscard => + private protected override IOptionsCollection PreferDiscard => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, - new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.Silent)); + new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent)); - protected override IDictionary PreferUnusedLocal => + private protected override IOptionsCollection PreferUnusedLocal => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, - new CodeStyleOption(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Silent)); + new CodeStyleOption2(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Suppressed() diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.cs index 23c08d12a6c09..6056642ed0c39 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.cs @@ -2,18 +2,12 @@ // 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; -#endif +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { @@ -22,11 +16,11 @@ public abstract class RemoveUnusedValuesTestsBase : AbstractCSharpDiagnosticProv internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new CSharpRemoveUnusedValuesCodeFixProvider()); - protected abstract IDictionary PreferNone { get; } - protected abstract IDictionary PreferDiscard { get; } - protected abstract IDictionary PreferUnusedLocal { get; } + private protected abstract IOptionsCollection PreferNone { get; } + private protected abstract IOptionsCollection PreferDiscard { get; } + private protected abstract IOptionsCollection PreferUnusedLocal { get; } - protected IDictionary GetOptions(string optionName) + private protected IOptionsCollection GetOptions(string optionName) { switch (optionName) { @@ -41,9 +35,9 @@ protected IDictionary GetOptions(string optionName) } } - protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, IDictionary options, ParseOptions parseOptions = null) + private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, IOptionsCollection options, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options, parseOptions: parseOptions)); - protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) + private protected Task TestMissingInRegularAndScriptAsync(string initialMarkup, string optionName, ParseOptions parseOptions = null) => TestMissingInRegularAndScriptAsync(initialMarkup, GetOptions(optionName), parseOptions); protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, string optionName, ParseOptions parseOptions = null) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: GetOptions(optionName), parseOptions: parseOptions); diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs index fda1be9d1e777..21d8854fb577a 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.cs @@ -5,23 +5,17 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForAccessorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -29,19 +23,19 @@ public class UseExpressionBodyForAccessorsTests : AbstractCSharpDiagnosticProvid internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement)); - private IDictionary UseExpressionBodyIncludingPropertiesAndIndexers => + private IOptionsCollection UseExpressionBodyIncludingPropertiesAndIndexers => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); - private IDictionary UseBlockBodyIncludingPropertiesAndIndexers => + private IOptionsCollection UseBlockBodyIncludingPropertiesAndIndexers => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement), @@ -311,7 +305,7 @@ int Goo [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { - var whenOnSingleLineWithNoneEnforcement = new CodeStyleOption(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption.None); + var whenOnSingleLineWithNoneEnforcement = new CodeStyleOption2(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None); var options = OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, whenOnSingleLineWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, whenOnSingleLineWithNoneEnforcement), diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs index d218f8154ae45..ed425a00a9f10 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConstructorsAnalyzerTests.cs @@ -6,21 +6,16 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConstructorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -28,10 +23,10 @@ public class UseExpressionBodyForConstructorsAnalyzerTests : AbstractCSharpDiagn internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs index 5c075f0c43be7..67ea45a6f91a8 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs @@ -5,20 +5,14 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConversionOperatorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -26,10 +20,10 @@ public class UseExpressionBodyForConversionOperatorsAnalyzerTests : AbstractCSha internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs index 26d80f0ce24da..137ebb06caef9 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForIndexersAnalyzerTests.cs @@ -5,21 +5,15 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForIndexersAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -27,17 +21,17 @@ public class UseExpressionBodyForIndexersAnalyzerTests : AbstractCSharpDiagnosti internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBodyExceptAccessor => + private IOptionsCollection UseBlockBodyExceptAccessor => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs index 24d200a51ad1f..9a57226f72f21 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForLocalFunctionsAnalyzerTests.cs @@ -5,20 +5,14 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForLocalFunctionsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -26,13 +20,13 @@ public class UseExpressionBodyForLocalFunctionsAnalyzerTests : AbstractCSharpDia internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyWhenOnSingleLine => + private IOptionsCollection UseExpressionBodyWhenOnSingleLine => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs index 149a47e6e8599..64f2eda64d7ea 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForMethodsAnalyzerTests.cs @@ -2,26 +2,19 @@ // 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForMethodsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -29,25 +22,25 @@ public class UseExpressionBodyForMethodsAnalyzerTests : AbstractCSharpDiagnostic internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public void TestOptionSerialization1() { // Verify that bool-options can migrate to ExpressionBodyPreference-options. - var option = new CodeStyleOption(false, NotificationOption.Silent); + var option = new CodeStyleOption2(false, NotificationOption2.Silent); var serialized = option.ToXElement(); - var deserialized = CodeStyleOption.FromXElement(serialized); + var deserialized = CodeStyleOption2.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.Never, deserialized.Value); - option = new CodeStyleOption(true, NotificationOption.Silent); + option = new CodeStyleOption2(true, NotificationOption2.Silent); serialized = option.ToXElement(); - deserialized = CodeStyleOption.FromXElement(serialized); + deserialized = CodeStyleOption2.FromXElement(serialized); Assert.Equal(ExpressionBodyPreference.WhenPossible, deserialized.Value); } @@ -56,23 +49,23 @@ public void TestOptionSerialization1() public void TestOptionSerialization2() { // Verify that ExpressionBodyPreference-options can migrate to bool-options. - var option = new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.Silent); + var option = new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.Silent); var serialized = option.ToXElement(); - var deserialized = CodeStyleOption.FromXElement(serialized); + var deserialized = CodeStyleOption2.FromXElement(serialized); Assert.False(deserialized.Value); - option = new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.Silent); + option = new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent); serialized = option.ToXElement(); - deserialized = CodeStyleOption.FromXElement(serialized); + deserialized = CodeStyleOption2.FromXElement(serialized); Assert.True(deserialized.Value); // This new values can't actually translate back to a bool. So we'll just get the default // value for this option. - option = new CodeStyleOption(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption.Silent); + option = new CodeStyleOption2(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent); serialized = option.ToXElement(); - deserialized = CodeStyleOption.FromXElement(serialized); + deserialized = CodeStyleOption2.FromXElement(serialized); Assert.Equal(default, deserialized.Value); } @@ -88,15 +81,15 @@ public void TestOptionEditorConfig1() var option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("false:error", null); Assert.Equal(ExpressionBodyPreference.Never, option.Value); - Assert.Equal(NotificationOption.Error, option.Notification); + Assert.Equal(NotificationOption2.Error, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("true:warning", null); Assert.Equal(ExpressionBodyPreference.WhenPossible, option.Value); - Assert.Equal(NotificationOption.Warning, option.Notification); + Assert.Equal(NotificationOption2.Warning, option.Notification); option = CSharpCodeStyleOptions.ParseExpressionBodyPreference("when_on_single_line:suggestion", null); Assert.Equal(ExpressionBodyPreference.WhenOnSingleLine, option.Value); - Assert.Equal(NotificationOption.Suggestion, option.Notification); + Assert.Equal(NotificationOption2.Suggestion, option.Notification); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs index 1c9a21f9d101b..c48075d5ebf23 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForOperatorsAnalyzerTests.cs @@ -2,23 +2,16 @@ // 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForOperatorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -26,10 +19,10 @@ public class UseExpressionBodyForOperatorsAnalyzerTests : AbstractCSharpDiagnost internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs index 7593a082a1a86..b5cbe264ce1ac 100644 --- a/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs @@ -6,21 +6,15 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForPropertiesAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -28,17 +22,17 @@ public class UseExpressionBodyForPropertiesAnalyzerTests : AbstractCSharpDiagnos internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider()); - private IDictionary UseExpressionBody => + private IOptionsCollection UseExpressionBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBody => + private IOptionsCollection UseBlockBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBodyExceptAccessor => + private IOptionsCollection UseBlockBodyExceptAccessor => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs index 597be7e107cfe..8835e23d25a47 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs @@ -2,25 +2,18 @@ // 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -28,48 +21,41 @@ public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBase internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider()); - private readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); - private readonly CodeStyleOption offWithSilent = new CodeStyleOption(false, NotificationOption.Silent); - private readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); - private readonly CodeStyleOption offWithInfo = new CodeStyleOption(false, NotificationOption.Suggestion); - private readonly CodeStyleOption onWithWarning = new CodeStyleOption(true, NotificationOption.Warning); - private readonly CodeStyleOption offWithWarning = new CodeStyleOption(false, NotificationOption.Warning); - private readonly CodeStyleOption onWithError = new CodeStyleOption(true, NotificationOption.Error); - private readonly CodeStyleOption offWithError = new CodeStyleOption(false, NotificationOption.Error); + private readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); + private readonly CodeStyleOption2 offWithSilent = new CodeStyleOption2(false, NotificationOption2.Silent); + private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); + private readonly CodeStyleOption2 offWithInfo = new CodeStyleOption2(false, NotificationOption2.Suggestion); + private readonly CodeStyleOption2 onWithWarning = new CodeStyleOption2(true, NotificationOption2.Warning); + private readonly CodeStyleOption2 offWithWarning = new CodeStyleOption2(false, NotificationOption2.Warning); + private readonly CodeStyleOption2 onWithError = new CodeStyleOption2(true, NotificationOption2.Error); + private readonly CodeStyleOption2 offWithError = new CodeStyleOption2(false, NotificationOption2.Error); // specify all options explicitly to override defaults. - private IDictionary ExplicitTypeEverywhere() => OptionsSet( + private IOptionsCollection ExplicitTypeEverywhere() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - private IDictionary ExplicitTypeExceptWhereApparent() => OptionsSet( + private IOptionsCollection ExplicitTypeExceptWhereApparent() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - private IDictionary ExplicitTypeForBuiltInTypesOnly() => OptionsSet( + private IOptionsCollection ExplicitTypeForBuiltInTypesOnly() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - private IDictionary ExplicitTypeEnforcements() => OptionsSet( + private IOptionsCollection ExplicitTypeEnforcements() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithWarning), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - private IDictionary ExplicitTypeSilentEnforcement() => OptionsSet( + private IOptionsCollection ExplicitTypeSilentEnforcement() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithSilent), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent)); - private IDictionary Options(OptionKey option, object value) - { - var options = new Dictionary(); - options.Add(option, value); - return options; - } - #region Error Cases [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] diff --git a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs index 07e074245c456..792232725642e 100644 --- a/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseImplicitTypeTests.cs @@ -7,20 +7,15 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType { @@ -29,49 +24,46 @@ public partial class UseImplicitTypeTests : AbstractCSharpDiagnosticProviderBase internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseImplicitTypeDiagnosticAnalyzer(), new UseImplicitTypeCodeFixProvider()); - private static readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); - private static readonly CodeStyleOption offWithSilent = new CodeStyleOption(false, NotificationOption.Silent); - private static readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); - private static readonly CodeStyleOption offWithInfo = new CodeStyleOption(false, NotificationOption.Suggestion); - private static readonly CodeStyleOption onWithWarning = new CodeStyleOption(true, NotificationOption.Warning); - private static readonly CodeStyleOption offWithWarning = new CodeStyleOption(false, NotificationOption.Warning); - private static readonly CodeStyleOption onWithError = new CodeStyleOption(true, NotificationOption.Error); - private static readonly CodeStyleOption offWithError = new CodeStyleOption(false, NotificationOption.Error); + private static readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); + private static readonly CodeStyleOption2 offWithSilent = new CodeStyleOption2(false, NotificationOption2.Silent); + private static readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); + private static readonly CodeStyleOption2 offWithInfo = new CodeStyleOption2(false, NotificationOption2.Suggestion); + private static readonly CodeStyleOption2 onWithWarning = new CodeStyleOption2(true, NotificationOption2.Warning); + private static readonly CodeStyleOption2 offWithWarning = new CodeStyleOption2(false, NotificationOption2.Warning); + private static readonly CodeStyleOption2 onWithError = new CodeStyleOption2(true, NotificationOption2.Error); + private static readonly CodeStyleOption2 offWithError = new CodeStyleOption2(false, NotificationOption2.Error); // specify all options explicitly to override defaults. - public IDictionary ImplicitTypeEverywhere() => OptionsSet( + internal IOptionsCollection ImplicitTypeEverywhere() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - private IDictionary ImplicitTypeWhereApparent() => OptionsSet( + private IOptionsCollection ImplicitTypeWhereApparent() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - private IDictionary ImplicitTypeWhereApparentAndForIntrinsics() => OptionsSet( + private IOptionsCollection ImplicitTypeWhereApparentAndForIntrinsics() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - public IDictionary ImplicitTypeButKeepIntrinsics() => OptionsSet( + internal IOptionsCollection ImplicitTypeButKeepIntrinsics() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo)); - private IDictionary ImplicitTypeEnforcements() => OptionsSet( + private IOptionsCollection ImplicitTypeEnforcements() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithWarning), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithError), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - private IDictionary ImplicitTypeSilentEnforcement() => OptionsSet( + private IOptionsCollection ImplicitTypeSilentEnforcement() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent)); - private static IDictionary Options(OptionKey option, object value) - => new Dictionary { { option, value } }; - [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)] public async Task NotOnFieldDeclaration() { diff --git a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs index 142bfa1446287..fd1453e861dbf 100644 --- a/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs +++ b/src/Analyzers/CSharp/Tests/UsePatternMatching/CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs @@ -5,7 +5,9 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UsePatternMatching; using Microsoft.CodeAnalysis.Diagnostics; @@ -14,14 +16,6 @@ using Roslyn.Test.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching { public partial class CSharpIsAndCastCheckDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest @@ -587,7 +581,7 @@ void M() } } }"; - var warningOption = new CodeStyleOption(true, NotificationOption.Warning); + var warningOption = new CodeStyleOption2(true, NotificationOption2.Warning); var options = Option(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, warningOption); var testParameters = new TestParameters(options: options, parseOptions: TestOptions.Regular8); diff --git a/src/Analyzers/Core/Analyzers/AbstractBuiltInCodeStyleDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AbstractBuiltInCodeStyleDiagnosticAnalyzer.cs index 05bad3555efa1..d609e7189befa 100644 --- a/src/Analyzers/Core/Analyzers/AbstractBuiltInCodeStyleDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/AbstractBuiltInCodeStyleDiagnosticAnalyzer.cs @@ -8,13 +8,11 @@ using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -#else -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CodeStyle diff --git a/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs index d9f59c4559772..0f087b26f3cd2 100644 --- a/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersDiagnosticAnalyzer.cs @@ -5,10 +5,6 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers { internal abstract class AbstractAddAccessibilityModifiersDiagnosticAnalyzer @@ -17,7 +13,7 @@ internal abstract class AbstractAddAccessibilityModifiersDiagnosticAnalyzer option, TCompilationUnitSyntax compilationUnitSyntax); + protected abstract void ProcessCompilationUnit(SyntaxTreeAnalysisContext context, CodeStyleOption2 option, TCompilationUnitSyntax compilationUnitSyntax); } } diff --git a/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs index fba3bfd8bafca..34c4cafe1f8c8 100644 --- a/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/FileHeaders/AbstractFileHeaderDiagnosticAnalyzer.cs @@ -9,10 +9,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.FileHeaders { internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer @@ -20,7 +16,7 @@ internal abstract class AbstractFileHeaderDiagnosticAnalyzer : AbstractBuiltInCo protected AbstractFileHeaderDiagnosticAnalyzer(string language) : base( IDEDiagnosticIds.FileHeaderMismatch, - CodeStyleOptions.FileHeaderTemplate, + CodeStyleOptions2.FileHeaderTemplate, language, new LocalizableResourceString(nameof(AnalyzersResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.A_source_file_is_missing_a_required_header), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) @@ -55,7 +51,7 @@ private void HandleSyntaxTree(SyntaxTreeAnalysisContext context) return; } - if (!context.Options.TryGetEditorConfigOption(CodeStyleOptions.FileHeaderTemplate, tree, out string fileHeaderTemplate) + if (!context.Options.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out string fileHeaderTemplate) || string.IsNullOrEmpty(fileHeaderTemplate)) { return; diff --git a/src/Analyzers/Core/Analyzers/Helpers/AnalyzerHelper.cs b/src/Analyzers/Core/Analyzers/Helpers/AnalyzerHelper.cs index 44cafb5465b91..340c5fa405c20 100644 --- a/src/Analyzers/Core/Analyzers/Helpers/AnalyzerHelper.cs +++ b/src/Analyzers/Core/Analyzers/Helpers/AnalyzerHelper.cs @@ -4,18 +4,19 @@ #nullable enable +using Microsoft.CodeAnalysis.Options; + #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; +using TOption = Microsoft.CodeAnalysis.Options.IOption2; #else -using System.Threading; -using Microsoft.CodeAnalysis.Options; +using TOption = Microsoft.CodeAnalysis.Options.IOption; #endif namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { - public static T GetOption(this SemanticModelAnalysisContext context, Option option) + public static T GetOption(this SemanticModelAnalysisContext context, Option2 option) { var analyzerOptions = context.Options; var syntaxTree = context.SemanticModel.SyntaxTree; @@ -24,7 +25,7 @@ public static T GetOption(this SemanticModelAnalysisContext context, Option(this SyntaxNodeAnalysisContext context, Option option) + public static T GetOption(this SyntaxNodeAnalysisContext context, Option2 option) { var analyzerOptions = context.Options; var syntaxTree = context.Node.SyntaxTree; @@ -33,7 +34,7 @@ public static T GetOption(this SyntaxNodeAnalysisContext context, Option o return GetOption(analyzerOptions, option, syntaxTree, cancellationToken); } - public static T GetOption(this SyntaxTreeAnalysisContext context, Option option) + public static T GetOption(this SyntaxTreeAnalysisContext context, Option2 option) { var analyzerOptions = context.Options; var syntaxTree = context.Tree; @@ -42,7 +43,7 @@ public static T GetOption(this SyntaxTreeAnalysisContext context, Option o return GetOption(analyzerOptions, option, syntaxTree, cancellationToken); } - public static T GetOption(this OperationAnalysisContext context, Option option) + public static T GetOption(this OperationAnalysisContext context, Option2 option) { var analyzerOptions = context.Options; var syntaxTree = context.Operation.Syntax.SyntaxTree; @@ -51,7 +52,7 @@ public static T GetOption(this OperationAnalysisContext context, Option op return GetOption(analyzerOptions, option, syntaxTree, cancellationToken); } - public static T GetOption(this SemanticModelAnalysisContext context, PerLanguageOption option, string? language) + public static T GetOption(this SemanticModelAnalysisContext context, PerLanguageOption2 option, string? language) { var analyzerOptions = context.Options; var syntaxTree = context.SemanticModel.SyntaxTree; @@ -60,7 +61,7 @@ public static T GetOption(this SemanticModelAnalysisContext context, PerLangu return GetOption(analyzerOptions, option, language, syntaxTree, cancellationToken); } - public static T GetOption(this SyntaxNodeAnalysisContext context, PerLanguageOption option, string? language) + public static T GetOption(this SyntaxNodeAnalysisContext context, PerLanguageOption2 option, string? language) { var analyzerOptions = context.Options; var syntaxTree = context.Node.SyntaxTree; @@ -69,7 +70,7 @@ public static T GetOption(this SyntaxNodeAnalysisContext context, PerLanguage return GetOption(analyzerOptions, option, language, syntaxTree, cancellationToken); } - public static T GetOption(this SyntaxTreeAnalysisContext context, PerLanguageOption option, string? language) + public static T GetOption(this SyntaxTreeAnalysisContext context, PerLanguageOption2 option, string? language) { var analyzerOptions = context.Options; var syntaxTree = context.Tree; @@ -78,7 +79,7 @@ public static T GetOption(this SyntaxTreeAnalysisContext context, PerLanguage return GetOption(analyzerOptions, option, language, syntaxTree, cancellationToken); } - public static T GetOption(this OperationAnalysisContext context, PerLanguageOption option, string? language) + public static T GetOption(this OperationAnalysisContext context, PerLanguageOption2 option, string? language) { var analyzerOptions = context.Options; var syntaxTree = context.Operation.Syntax.SyntaxTree; @@ -87,7 +88,7 @@ public static T GetOption(this OperationAnalysisContext context, PerLanguageO return GetOption(analyzerOptions, option, language, syntaxTree, cancellationToken); } - public static bool TryGetEditorConfigOption(this AnalyzerOptions analyzerOptions, IOption option, SyntaxTree syntaxTree, out T value) + public static bool TryGetEditorConfigOption(this AnalyzerOptions analyzerOptions, TOption option, SyntaxTree syntaxTree, out T value) { var configOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); return configOptions.TryGetEditorConfigOption(option, out value); diff --git a/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs b/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs index 25683466748a9..433ad65938fa8 100644 --- a/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs +++ b/src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs @@ -7,12 +7,7 @@ using System.Collections.Immutable; using System.Diagnostics; using System.Linq; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif namespace Microsoft.CodeAnalysis.Diagnostics { @@ -23,10 +18,10 @@ namespace Microsoft.CodeAnalysis.Diagnostics /// internal static class IDEDiagnosticIdToOptionMappingHelper { - private static readonly ConcurrentDictionary> s_diagnosticIdToOptionMap = new ConcurrentDictionary>(); - private static readonly ConcurrentDictionary>> s_diagnosticIdToLanguageSpecificOptionsMap = new ConcurrentDictionary>>(); + private static readonly ConcurrentDictionary> s_diagnosticIdToOptionMap = new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary>> s_diagnosticIdToLanguageSpecificOptionsMap = new ConcurrentDictionary>>(); - public static bool TryGetMappedOptions(string diagnosticId, string language, out ImmutableHashSet options) + public static bool TryGetMappedOptions(string diagnosticId, string language, out ImmutableHashSet options) => s_diagnosticIdToOptionMap.TryGetValue(diagnosticId, out options) || (s_diagnosticIdToLanguageSpecificOptionsMap.TryGetValue(language, out var map) && map.TryGetValue(diagnosticId, out options)); @@ -36,7 +31,7 @@ public static void AddOptionMapping(string diagnosticId, ImmutableHashSet().ToImmutableHashSet(); + var options = perLanguageOptions.Cast().ToImmutableHashSet(); AddOptionMapping(s_diagnosticIdToOptionMap, diagnosticId, options); } public static void AddOptionMapping(string diagnosticId, ImmutableHashSet languageSpecificOptions, string language) @@ -45,12 +40,12 @@ public static void AddOptionMapping(string diagnosticId, ImmutableHashSet new ConcurrentDictionary>()); - var options = languageSpecificOptions.Cast().ToImmutableHashSet(); + var map = s_diagnosticIdToLanguageSpecificOptionsMap.GetOrAdd(language, _ => new ConcurrentDictionary>()); + var options = languageSpecificOptions.Cast().ToImmutableHashSet(); AddOptionMapping(map, diagnosticId, options); } - private static void AddOptionMapping(ConcurrentDictionary> map, string diagnosticId, ImmutableHashSet options) + private static void AddOptionMapping(ConcurrentDictionary> map, string diagnosticId, ImmutableHashSet options) { // Verify that the option is either being added for the first time, or the existing option is already the same. // Latter can happen in tests as we re-instantiate the analyzer for every test, which attempts to add the mapping every time. diff --git a/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs index 9c77c21308ff7..595ad5de6c71f 100644 --- a/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs @@ -10,10 +10,6 @@ using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] @@ -23,7 +19,7 @@ internal sealed class MakeFieldReadonlyDiagnosticAnalyzer public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, - CodeStyleOptions.PreferReadonly, + CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -217,9 +213,9 @@ private static bool IsInAnonymousFunctionOrLocalFunction(IOperation operation) return false; } - private static CodeStyleOption GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) + private static CodeStyleOption2 GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) { - return options.GetOption(CodeStyleOptions.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); + return options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); } } } diff --git a/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs b/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs index 6783b0709208c..403865ef52f99 100644 --- a/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs +++ b/src/Analyzers/Core/Analyzers/NamingStyle/NamingStyleDiagnosticAnalyzerBase.cs @@ -7,18 +7,11 @@ using System.Collections.Immutable; using System.Linq; using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal abstract class NamingStyleDiagnosticAnalyzerBase diff --git a/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs index b66a4661bed10..d01c0d17f729a 100644 --- a/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/OrderModifiers/AbstractOrderModifiersDiagnosticAnalyzer.cs @@ -6,25 +6,20 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; -using Microsoft.CodeAnalysis.Text; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif +using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.OrderModifiers { internal abstract class AbstractOrderModifiersDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; - private readonly Option> _option; + private readonly Option2> _option; private readonly AbstractOrderModifiersHelpers _helpers; protected AbstractOrderModifiersDiagnosticAnalyzer( ISyntaxFacts syntaxFacts, - Option> option, + Option2> option, AbstractOrderModifiersHelpers helpers, string language) : base(IDEDiagnosticIds.OrderModifiersDiagnosticId, diff --git a/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs index a1e3dde0680ba..fc3984d175b70 100644 --- a/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs @@ -6,13 +6,11 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.QualifyMemberAccess @@ -28,7 +26,7 @@ internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer< { protected AbstractQualifyMemberAccessDiagnosticAnalyzer() : base(IDEDiagnosticIds.AddQualificationDiagnosticId, - options: ImmutableHashSet.Create(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.QualifyPropertyAccess, CodeStyleOptions.QualifyMethodAccess, CodeStyleOptions.QualifyEventAccess), + options: ImmutableHashSet.Create(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess), new LocalizableResourceString(nameof(AnalyzersResources.Member_access_should_be_qualified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Add_this_or_Me_qualification), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -36,15 +34,15 @@ protected AbstractQualifyMemberAccessDiagnosticAnalyzer() public override bool OpenFileOnly(OptionSet options) { - var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions.QualifyFieldAccess, GetLanguageName()).Notification; - var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions.QualifyPropertyAccess, GetLanguageName()).Notification; - var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions.QualifyMethodAccess, GetLanguageName()).Notification; - var qualifyEventAccessOption = options.GetOption(CodeStyleOptions.QualifyEventAccess, GetLanguageName()).Notification; - - return !(qualifyFieldAccessOption == NotificationOption.Warning || qualifyFieldAccessOption == NotificationOption.Error || - qualifyPropertyAccessOption == NotificationOption.Warning || qualifyPropertyAccessOption == NotificationOption.Error || - qualifyMethodAccessOption == NotificationOption.Warning || qualifyMethodAccessOption == NotificationOption.Error || - qualifyEventAccessOption == NotificationOption.Warning || qualifyEventAccessOption == NotificationOption.Error); + var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, GetLanguageName()).Notification; + var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions2.QualifyPropertyAccess, GetLanguageName()).Notification; + var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, GetLanguageName()).Notification; + var qualifyEventAccessOption = options.GetOption(CodeStyleOptions2.QualifyEventAccess, GetLanguageName()).Notification; + + return !(qualifyFieldAccessOption == NotificationOption2.Warning || qualifyFieldAccessOption == NotificationOption2.Error || + qualifyPropertyAccessOption == NotificationOption2.Warning || qualifyPropertyAccessOption == NotificationOption2.Error || + qualifyMethodAccessOption == NotificationOption2.Warning || qualifyMethodAccessOption == NotificationOption2.Error || + qualifyEventAccessOption == NotificationOption2.Warning || qualifyEventAccessOption == NotificationOption2.Error); } protected abstract string GetLanguageName(); @@ -174,24 +172,24 @@ static bool IsStaticMemberOrIsLocalFunctionHelper(ISymbol symbol) internal static class QualifyMembersHelpers { - public static PerLanguageOption> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind) + public static PerLanguageOption2> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind) { switch (symbolKind) { case SymbolKind.Field: - return CodeStyleOptions.QualifyFieldAccess; + return CodeStyleOptions2.QualifyFieldAccess; case SymbolKind.Property: - return CodeStyleOptions.QualifyPropertyAccess; + return CodeStyleOptions2.QualifyPropertyAccess; case SymbolKind.Method: - return CodeStyleOptions.QualifyMethodAccess; + return CodeStyleOptions2.QualifyMethodAccess; case SymbolKind.Event: - return CodeStyleOptions.QualifyEventAccess; + return CodeStyleOptions2.QualifyEventAccess; default: throw ExceptionUtilities.UnexpectedValue(symbolKind); } } - internal static PerLanguageOption> GetApplicableOptionFromSymbolKind(IOperation operation) + internal static PerLanguageOption2> GetApplicableOptionFromSymbolKind(IOperation operation) { switch (operation) { diff --git a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs index a32ae1896541b..652cce608e285 100644 --- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.BlockAnalyzer.cs @@ -9,20 +9,13 @@ using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -using System.Diagnostics.CodeAnalysis; - -#if CODE_STYLE -using AbstractBuiltInCodeStyleDiagnosticAnalyzer = Microsoft.CodeAnalysis.CodeStyle.AbstractBuiltInCodeStyleDiagnosticAnalyzer; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues { diff --git a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs index c9cf0b0477b08..d9f4fb0660fb1 100644 --- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.SymbolStartAnalyzer.cs @@ -15,10 +15,6 @@ using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues { internal abstract partial class AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer @@ -134,7 +130,7 @@ private void ReportUnusedParameterDiagnostic( } var location = parameter.Locations[0]; - var option = analyzerOptions.GetOption(CodeStyleOptions.UnusedParameters, parameter.Language, location.SourceTree, cancellationToken); + var option = analyzerOptions.GetOption(CodeStyleOptions2.UnusedParameters, parameter.Language, location.SourceTree, cancellationToken); 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 47dbd962c774f..73072d08cfdae 100644 --- a/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/RemoveUnusedParametersAndValues/AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs @@ -8,13 +8,8 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; -using Microsoft.CodeAnalysis.Shared.Extensions; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues { @@ -53,7 +48,7 @@ namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues /// Currently, we do not provide any code fix for removing unused parameters as it needs fixing the /// call sites and any automated fix can lead to subtle overload resolution differences, /// though this may change in future. - /// This diagnostic configuration is controlled by option. + /// This diagnostic configuration is controlled by option. /// internal abstract partial class AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { @@ -90,14 +85,14 @@ internal abstract partial class AbstractRemoveUnusedParametersAndValuesDiagnosti private static readonly PropertiesMap s_propertiesMap = CreatePropertiesMap(); protected AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer( - Option> unusedValueExpressionStatementOption, - Option> unusedValueAssignmentOption, + Option2> unusedValueExpressionStatementOption, + Option2> unusedValueAssignmentOption, string language) : base(ImmutableDictionary.Empty .Add(s_expressionValueIsUnusedRule, unusedValueExpressionStatementOption) .Add(s_valueAssignedIsUnusedRule, unusedValueAssignmentOption), ImmutableDictionary.Empty - .Add(s_unusedParameterRule, CodeStyleOptions.UnusedParameters), + .Add(s_unusedParameterRule, CodeStyleOptions2.UnusedParameters), language) { UnusedValueExpressionStatementOption = unusedValueExpressionStatementOption; @@ -108,8 +103,8 @@ protected AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer( protected abstract bool SupportsDiscard(SyntaxTree tree); protected abstract bool MethodHasHandlesClause(IMethodSymbol method); protected abstract bool IsIfConditionalDirective(SyntaxNode node); - private Option> UnusedValueExpressionStatementOption { get; } - private Option> UnusedValueAssignmentOption { get; } + private Option2> UnusedValueExpressionStatementOption { get; } + private Option2> UnusedValueAssignmentOption { get; } /// /// Indicates if we should bail from removable assignment analysis for the given @@ -203,7 +198,7 @@ private bool TryGetOptions( { options = null; - var unusedParametersOption = analyzerOptions.GetOption(CodeStyleOptions.UnusedParameters, language, syntaxTree, cancellationToken); + var unusedParametersOption = analyzerOptions.GetOption(CodeStyleOptions2.UnusedParameters, language, syntaxTree, cancellationToken); var (unusedValueExpressionStatementPreference, unusedValueExpressionStatementSeverity) = GetPreferenceAndSeverity(UnusedValueExpressionStatementOption); var (unusedValueAssignmentPreference, unusedValueAssignmentSeverity) = GetPreferenceAndSeverity(UnusedValueAssignmentOption); if (unusedParametersOption.Notification.Severity == ReportDiagnostic.Suppress && @@ -220,7 +215,7 @@ private bool TryGetOptions( // Local functions. (UnusedValuePreference preference, ReportDiagnostic severity) GetPreferenceAndSeverity( - Option> codeStyleOption) + Option2> codeStyleOption) { var option = analyzerOptions.GetOption(codeStyleOption, syntaxTree, cancellationToken); var preferenceOpt = option?.Value; diff --git a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs index 5a4a9cdb00381..8a83babbf6a5c 100644 --- a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionDiagnosticAnalyzer.cs @@ -9,10 +9,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.UseCoalesceExpression { /// @@ -30,7 +26,7 @@ internal abstract class AbstractUseCoalesceExpressionDiagnosticAnalyzer< { protected AbstractUseCoalesceExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCoalesceExpressionDiagnosticId, - CodeStyleOptions.PreferCoalesceExpression, + CodeStyleOptions2.PreferCoalesceExpression, new LocalizableResourceString(nameof(AnalyzersResources.Use_coalesce_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -52,7 +48,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var conditionalExpression = (TConditionalExpressionSyntax)context.Node; - var option = context.GetOption(CodeStyleOptions.PreferCoalesceExpression, conditionalExpression.Language); + var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language); if (!option.Value) { return; diff --git a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs index 287a3f88cb656..a8af96250e40b 100644 --- a/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCoalesceExpression/AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer.cs @@ -10,10 +10,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.UseCoalesceExpression { internal abstract class AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer< @@ -32,7 +28,7 @@ internal abstract class AbstractUseCoalesceExpressionForNullableDiagnosticAnalyz { protected AbstractUseCoalesceExpressionForNullableDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCoalesceExpressionForNullableDiagnosticId, - CodeStyleOptions.PreferCoalesceExpression, + CodeStyleOptions2.PreferCoalesceExpression, new LocalizableResourceString(nameof(AnalyzersResources.Use_coalesce_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } @@ -55,7 +51,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) var cancellationToken = context.CancellationToken; - var option = context.GetOption(CodeStyleOptions.PreferCoalesceExpression, conditionalExpression.Language); + var option = context.GetOption(CodeStyleOptions2.PreferCoalesceExpression, conditionalExpression.Language); if (!option.Value) { return; diff --git a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs index 5e3ab90dba36b..6483e944069e8 100644 --- a/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractUseCollectionInitializerDiagnosticAnalyzer.cs @@ -12,10 +12,6 @@ using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.UseCollectionInitializer { internal abstract partial class AbstractUseCollectionInitializerDiagnosticAnalyzer< @@ -42,7 +38,7 @@ public override DiagnosticAnalyzerCategory GetAnalyzerCategory() protected AbstractUseCollectionInitializerDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCollectionInitializerDiagnosticId, - CodeStyleOptions.PreferCollectionInitializer, + CodeStyleOptions2.PreferCollectionInitializer, new LocalizableResourceString(nameof(AnalyzersResources.Simplify_collection_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Collection_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -77,7 +73,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context, INamedTypeSymbol ien var language = objectCreationExpression.Language; var cancellationToken = context.CancellationToken; - var option = context.GetOption(CodeStyleOptions.PreferCollectionInitializer, language); + var option = context.GetOption(CodeStyleOptions2.PreferCollectionInitializer, language); if (!option.Value) { // not point in analyzing if the option is off. @@ -134,7 +130,7 @@ private void FadeOutCode( var syntaxTree = context.Node.SyntaxTree; var fadeOutCode = context.GetOption( - CodeStyleOptions.PreferCollectionInitializer_FadeOutCode, context.Node.Language); + CodeStyleOptions2.PreferCollectionInitializer_FadeOutCode, context.Node.Language); if (!fadeOutCode) { return; diff --git a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs index 549f39e6d31dd..176a326b204a6 100644 --- a/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseNullPropagation/AbstractUseNullPropagationDiagnosticAnalyzer.cs @@ -7,14 +7,10 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; -using System.Threading; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif namespace Microsoft.CodeAnalysis.UseNullPropagation { @@ -43,7 +39,7 @@ internal abstract class AbstractUseNullPropagationDiagnosticAnalyzer< { protected AbstractUseNullPropagationDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseNullPropagationDiagnosticId, - CodeStyleOptions.PreferNullPropagation, + CodeStyleOptions2.PreferNullPropagation, new LocalizableResourceString(nameof(AnalyzersResources.Use_null_propagation), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -92,7 +88,7 @@ private void AnalyzeSyntax( return; } - var option = context.GetOption(CodeStyleOptions.PreferNullPropagation, conditionalExpression.Language); + var option = context.GetOption(CodeStyleOptions2.PreferNullPropagation, conditionalExpression.Language); if (!option.Value) { return; diff --git a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs index 78b7333d341e1..bc83c46537b6d 100644 --- a/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs @@ -12,10 +12,6 @@ using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#endif - namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract partial class AbstractUseObjectInitializerDiagnosticAnalyzer< @@ -39,7 +35,7 @@ internal abstract partial class AbstractUseObjectInitializerDiagnosticAnalyzer< protected AbstractUseObjectInitializerDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseObjectInitializerDiagnosticId, - CodeStyleOptions.PreferObjectInitializer, + CodeStyleOptions2.PreferObjectInitializer, new LocalizableResourceString(nameof(AnalyzersResources.Simplify_object_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Object_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -63,7 +59,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context) var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node; var language = objectCreationExpression.Language; - var option = context.GetOption(CodeStyleOptions.PreferObjectInitializer, language); + var option = context.GetOption(CodeStyleOptions2.PreferObjectInitializer, language); if (!option.Value) { // not point in analyzing if the option is off. @@ -112,7 +108,7 @@ private void FadeOutCode( var syntaxTree = context.Node.SyntaxTree; var fadeOutCode = context.GetOption( - CodeStyleOptions.PreferObjectInitializer_FadeOutCode, context.Node.Language); + CodeStyleOptions2.PreferObjectInitializer_FadeOutCode, context.Node.Language); if (!fadeOutCode) { return; diff --git a/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs index c2c567ba36221..a375269c47454 100644 --- a/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseThrowExpression/AbstractUseThrowExpressionDiagnosticAnalyzer.cs @@ -6,15 +6,9 @@ using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; -using Microsoft.CodeAnalysis.Shared.Extensions; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif +using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseThrowExpression { @@ -40,9 +34,9 @@ namespace Microsoft.CodeAnalysis.UseThrowExpression internal abstract class AbstractUseThrowExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { - private readonly Option> _preferThrowExpressionOption; + private readonly Option2> _preferThrowExpressionOption; - protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option> preferThrowExpressionOption, string language) + protected AbstractUseThrowExpressionDiagnosticAnalyzer(Option2> preferThrowExpressionOption, string language) : base(IDEDiagnosticIds.UseThrowExpressionDiagnosticId, preferThrowExpressionOption, language, diff --git a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs index 75721c785b3a2..50c8fa5a4f97f 100644 --- a/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs @@ -20,10 +20,6 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using CodeStyleOptions = Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions; -#endif - namespace Microsoft.CodeAnalysis.FileHeaders { internal abstract class AbstractFileHeaderCodeFixProvider : CodeFixProvider @@ -62,7 +58,7 @@ private async Task GetTransformedSyntaxRootAsync(Document document, var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); - if (!document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions.FileHeaderTemplate, tree, out string fileHeaderTemplate) + if (!document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out string fileHeaderTemplate) || string.IsNullOrEmpty(fileHeaderTemplate)) { // This exception would show up as a gold bar, but as indicated we do not believe this is reachable. diff --git a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs index aefa1bf963111..305bcaccd21e7 100644 --- a/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/OrderModifiers/AbstractOrderModifiersCodeFixProvider.cs @@ -8,31 +8,26 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.OrderModifiers { internal abstract class AbstractOrderModifiersCodeFixProvider : SyntaxEditorBasedCodeFixProvider { private readonly ISyntaxFacts _syntaxFacts; - private readonly Option> _option; + private readonly Option2> _option; private readonly AbstractOrderModifiersHelpers _helpers; protected AbstractOrderModifiersCodeFixProvider( ISyntaxFacts syntaxFacts, - Option> option, + Option2> option, AbstractOrderModifiersHelpers helpers) { _syntaxFacts = syntaxFacts; diff --git a/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs index 03205577d9058..3dd32c18c2cb7 100644 --- a/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; @@ -24,12 +25,6 @@ using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues { /// diff --git a/src/Analyzers/VisualBasic/Analyzers/AddAccessibilityModifiers/VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/AddAccessibilityModifiers/VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer.vb index 814f1af97bfed..1d6c203ddd0bd 100644 --- a/src/Analyzers/VisualBasic/Analyzers/AddAccessibilityModifiers/VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/AddAccessibilityModifiers/VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer.vb @@ -4,18 +4,12 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.AddAccessibilityModifiers +Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Editing -Imports Microsoft.CodeAnalysis.Internal.Options -#Else -Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Editing -#End If - Namespace Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers Friend Class VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer @@ -25,20 +19,20 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers Protected Overrides Sub ProcessCompilationUnit( context As SyntaxTreeAnalysisContext, - [option] As CodeStyleOption(Of AccessibilityModifiersRequired), compilationUnit As CompilationUnitSyntax) + [option] As CodeStyleOption2(Of AccessibilityModifiersRequired), compilationUnit As CompilationUnitSyntax) ProcessMembers(context, [option], compilationUnit.Members) End Sub Private Sub ProcessMembers(context As SyntaxTreeAnalysisContext, - [option] As CodeStyleOption(Of AccessibilityModifiersRequired), members As SyntaxList(Of StatementSyntax)) + [option] As CodeStyleOption2(Of AccessibilityModifiersRequired), members As SyntaxList(Of StatementSyntax)) For Each member In members ProcessMember(context, [option], member) Next End Sub Private Sub ProcessMember(context As SyntaxTreeAnalysisContext, - [option] As CodeStyleOption(Of AccessibilityModifiersRequired), member As StatementSyntax) + [option] As CodeStyleOption2(Of AccessibilityModifiersRequired), member As StatementSyntax) If member.Kind() = SyntaxKind.NamespaceBlock Then diff --git a/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb index f8da7c251f1fc..1d10f7eeac06c 100644 --- a/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/OrderModifiers/VisualBasicOrderModifiersDiagnosticAnalyzer.vb @@ -4,15 +4,10 @@ Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.OrderModifiers +Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else -Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If - Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers Friend Class VisualBasicOrderModifiersDiagnosticAnalyzer diff --git a/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb b/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb index c03369c5b1b6f..86f256fc742f8 100644 --- a/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb +++ b/src/Analyzers/VisualBasic/Analyzers/RemoveUnusedParametersAndValues/VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer.vb @@ -5,13 +5,8 @@ Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues -Imports Microsoft.CodeAnalysis.VisualBasic.Syntax - -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues diff --git a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb index 021bfe123e225..030021133ea57 100644 --- a/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb +++ b/src/Analyzers/VisualBasic/CodeFixes/OrderModifiers/VisualBasicOrderModifiersCodeFixProvider.vb @@ -6,13 +6,8 @@ Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.OrderModifiers -Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices - -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If +Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers diff --git a/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb b/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb index 6767b6195ff0f..0689fd68b2e7c 100644 --- a/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb +++ b/src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.vb @@ -3,17 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers +Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -#Else -Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options -#End If - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAccessibilityModifiers Public Class AddAccessibilityModifiersTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest @@ -23,10 +18,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAccessibilityMo New VisualBasicAddAccessibilityModifiersCodeFixProvider()) End Function - Private ReadOnly Property OmitDefaultModifiers As IDictionary(Of OptionKey, Object) + Private ReadOnly Property OmitDefaultModifiers As IOptionsCollection Get Return OptionsSet( - SingleOption(CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption.Suggestion)) + SingleOption(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Suggestion)) End Get End Property diff --git a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb index 901468265417e..c7221094921ed 100644 --- a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb +++ b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests.vb @@ -3,17 +3,12 @@ ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes +Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.QualifyMemberAccess -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -#Else -Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options -#End If - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAccess Partial Public Class QualifyMemberAccessTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest @@ -23,19 +18,19 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAcces New VisualBasicQualifyMemberAccessCodeFixProvider()) End Function - Private Function TestAsyncWithOption(code As String, expected As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As Task - Return TestAsyncWithOptionAndNotification(code, expected, opt, NotificationOption.Error) + Private Function TestAsyncWithOption(code As String, expected As String, opt As PerLanguageOption2(Of CodeStyleOption2(Of Boolean))) As Task + Return TestAsyncWithOptionAndNotification(code, expected, opt, NotificationOption2.Error) End Function - Private Function TestAsyncWithOptionAndNotification(code As String, expected As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean)), notification As NotificationOption) As Task + Private Function TestAsyncWithOptionAndNotification(code As String, expected As String, opt As PerLanguageOption2(Of CodeStyleOption2(Of Boolean)), notification As NotificationOption2) As Task Return TestInRegularAndScriptAsync(code, expected, options:=[Option](opt, True, notification)) End Function - Private Function TestMissingAsyncWithOption(code As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As Task - Return TestMissingAsyncWithOptionAndNotification(code, opt, NotificationOption.Error) + Private Function TestMissingAsyncWithOption(code As String, opt As PerLanguageOption2(Of CodeStyleOption2(Of Boolean))) As Task + Return TestMissingAsyncWithOptionAndNotification(code, opt, NotificationOption2.Error) End Function - Private Function TestMissingAsyncWithOptionAndNotification(code As String, opt As PerLanguageOption(Of CodeStyleOption(Of Boolean)), notification As NotificationOption) As Task + Private Function TestMissingAsyncWithOptionAndNotification(code As String, opt As PerLanguageOption2(Of CodeStyleOption2(Of Boolean)), notification As NotificationOption2) As Task Return TestMissingInRegularAndScriptAsync(code, New TestParameters(options:=[Option](opt, True, notification))) End Function @@ -46,7 +41,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAcces Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Me.i = 1 : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -55,7 +50,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : Dim x = [|i|] : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Dim x = Me.i : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -64,7 +59,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M(ii As Integer) : M([|i|]) : End Sub : End Class", "Class C : Dim i As Integer : Sub M(ii As Integer) : M(Me.i) : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -73,7 +68,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Dim i As Integer : Sub M() : Dim s = [|i|].ToString() : End Sub : End Class", "Class C : Dim i As Integer : Sub M() : Dim s = Me.i.ToString() : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -82,7 +77,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Dim s As String : Sub M() : Dim x = [|s|]?.ToString() : End Sub : End Class", "Class C : Dim s As String : Sub M() : Dim x = Me.s?.ToString() : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -91,7 +86,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Property I As Integer : Sub M() : [|_I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me._I = 1 : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -119,7 +114,7 @@ Class Derived End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -141,7 +136,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -163,7 +158,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -171,7 +166,7 @@ CodeStyleOptions.QualifyFieldAccess) Public Async Function QualifyFieldAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Dim i As Integer : Sub M(c As C) : c.[|i|] = 1 : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -179,7 +174,7 @@ CodeStyleOptions.QualifyFieldAccess) Public Async Function QualifyFieldAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -187,7 +182,7 @@ CodeStyleOptions.QualifyFieldAccess) Public Async Function QualifyFieldAccess_NotSuggestedOnSharedWithMe() As Task Await TestMissingAsyncWithOption( "Class C : Shared i As Integer : Sub M() : Me.[|i|] = 1 : End Sub : End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -195,7 +190,7 @@ CodeStyleOptions.QualifyFieldAccess) Public Async Function QualifyFieldAccess_NotSuggestedInModule() As Task Await TestMissingAsyncWithOption( "Module C : Dim i As Integer : Sub M() : [|i|] = 1 : End Sub : End Module", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -208,7 +203,7 @@ CodeStyleOptions.QualifyFieldAccess) Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -221,7 +216,7 @@ CodeStyleOptions.QualifyFieldAccess) Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -230,7 +225,7 @@ CodeStyleOptions.QualifyFieldAccess) Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Me.i = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -239,7 +234,7 @@ CodeStyleOptions.QualifyPropertyAccess) Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : Dim x = [|i|] : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Dim x = Me.i : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -248,7 +243,7 @@ CodeStyleOptions.QualifyPropertyAccess) Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M(ii As Integer) : M([|i|]) : End Sub : End Class", "Class C : Property i As Integer : Sub M(ii As Integer) : M(Me.i) : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -257,7 +252,7 @@ CodeStyleOptions.QualifyPropertyAccess) Await TestAsyncWithOption( "Class C : Property i As Integer : Sub M() : Dim s = [|i|].ToString() : End Sub : End Class", "Class C : Property i As Integer : Sub M() : Dim s = Me.i.ToString() : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -266,7 +261,7 @@ CodeStyleOptions.QualifyPropertyAccess) Await TestAsyncWithOption( "Class C : Property s As String : Sub M() : Dim x = [|s|]?.ToString() : End Sub : End Class", "Class C : Property s As String : Sub M() : Dim x = Me.s?.ToString() : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -294,7 +289,7 @@ Class Derived End Sub End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -316,7 +311,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -338,7 +333,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -346,7 +341,7 @@ CodeStyleOptions.QualifyPropertyAccess) Public Async Function QualifyPropertyAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Property i As Integer : Sub M(c As C) : c.[|i|] = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -354,7 +349,7 @@ CodeStyleOptions.QualifyPropertyAccess) Public Async Function QualifyPropertyAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared Property i As Integer : Sub M() : [|i|] = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -363,7 +358,7 @@ CodeStyleOptions.QualifyPropertyAccess) Await TestAsyncWithOption( "Class C : Function M() As Integer : Return [|M|]() : End Function : End Class", "Class C : Function M() As Integer : Return Me.M() : End Function : End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -372,7 +367,7 @@ CodeStyleOptions.QualifyMethodAccess) Await TestAsyncWithOption( "Class C : Function M() As String : Return [|M|]().ToString() : End Function : End Class", "Class C : Function M() As String : Return Me.M().ToString() : End Function : End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -381,7 +376,7 @@ CodeStyleOptions.QualifyMethodAccess) Await TestAsyncWithOption( "Class C : Function M() As String : Return [|M|]()?.ToString() : End Function : End Class", "Class C : Function M() As String : Return Me.M()?.ToString() : End Function : End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -403,7 +398,7 @@ Class C AddHandler e, AddressOf Me.Handler End Sub End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -425,7 +420,7 @@ Class C AddHandler e, New EventHandler(AddressOf Me.Handler) End Sub End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -455,7 +450,7 @@ Class Derived End Sub End Class ", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -463,7 +458,7 @@ CodeStyleOptions.QualifyMethodAccess) Public Async Function QualifyMethodAccess_NotSuggestedOnInstance() As Task Await TestMissingAsyncWithOption( "Class C : Sub M(c As C) : c.[|M|]() : End Sub : End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -471,7 +466,7 @@ CodeStyleOptions.QualifyMethodAccess) Public Async Function QualifyMethodAccess_NotSuggestedOnShared() As Task Await TestMissingAsyncWithOption( "Class C : Shared Sub Method() : End Sub : Sub M() : [|Method|]() : End Sub : End Class", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -484,7 +479,7 @@ CodeStyleOptions.QualifyMethodAccess) Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -497,7 +492,7 @@ CodeStyleOptions.QualifyMethodAccess) Dim test = New System.Collections.Generic.List(Of Integer) With { [|i|] } End Sub End Module", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -519,7 +514,7 @@ Class C AddHandler Me.e, AddressOf Handler End Function End Class", -CodeStyleOptions.QualifyEventAccess) +CodeStyleOptions2.QualifyEventAccess) End Function @@ -547,7 +542,7 @@ Class Derived AddHandler Me.e, AddressOf Handler End Function End Class", -CodeStyleOptions.QualifyEventAccess) +CodeStyleOptions2.QualifyEventAccess) End Function @@ -563,7 +558,7 @@ Class C Sub Handler(sender As Object, args As EventArgs) End Function End Class", -CodeStyleOptions.QualifyEventAccess) +CodeStyleOptions2.QualifyEventAccess) End Function @@ -577,7 +572,7 @@ Class C AddHandler [|e|], AddressOf Handler End Function End Class", -CodeStyleOptions.QualifyEventAccess) +CodeStyleOptions2.QualifyEventAccess) End Function @@ -585,7 +580,7 @@ CodeStyleOptions.QualifyEventAccess) Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Silent) +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent) End Function @@ -593,7 +588,7 @@ CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Silent) Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Suggestion) +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion) End Function @@ -601,7 +596,7 @@ CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Suggestion) Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Warning) +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning) End Function @@ -609,7 +604,7 @@ CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Warning) Await TestAsyncWithOptionAndNotification( "Class C : Property I As Integer : Sub M() : [|I|] = 1 : End Sub : End Class", "Class C : Property I As Integer : Sub M() : Me.I = 1 : End Sub : End Class", -CodeStyleOptions.QualifyPropertyAccess, NotificationOption.Error) +CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error) End Function @@ -626,7 +621,7 @@ Class Derived End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -640,7 +635,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -658,7 +653,7 @@ Class Derived End Get End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -673,7 +668,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -692,7 +687,7 @@ Class Derived End Get End Class ", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -707,7 +702,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyMethodAccess) +CodeStyleOptions2.QualifyMethodAccess) End Function @@ -722,7 +717,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -734,7 +729,7 @@ Class C Private Shared Field As String = NameOf([|Value|]) End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -753,7 +748,7 @@ Public Class Derived MyBase.New(NameOf([|Foo|])) End Sub End Class", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -768,7 +763,7 @@ class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -783,7 +778,7 @@ class C End Sub End Class ", -CodeStyleOptions.QualifyFieldAccess) +CodeStyleOptions2.QualifyFieldAccess) End Function @@ -804,7 +799,7 @@ Class C Private Property Goo As String End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -825,7 +820,7 @@ Class C Private Property Goo As String End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -848,7 +843,7 @@ Class C Private Bar As Integer End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function @@ -871,7 +866,7 @@ Class C End Sub End Class ", -CodeStyleOptions.QualifyPropertyAccess) +CodeStyleOptions2.QualifyPropertyAccess) End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.vb b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.vb index e3ec81afba109..29acdd0936f74 100644 --- a/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.vb +++ b/src/Analyzers/VisualBasic/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.vb @@ -2,13 +2,8 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics - -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -#Else Imports Microsoft.CodeAnalysis.CodeStyle -#End If +Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.QualifyMemberAccess Partial Public Class QualifyMemberAccessTests @@ -85,7 +80,7 @@ End Class]]> Await TestInRegularAndScriptAsync( initialMarkup:=input, expectedMarkup:=expected, - options:=[Option](CodeStyleOptions.QualifyPropertyAccess, True, NotificationOption.Suggestion)) + options:=[Option](CodeStyleOptions2.QualifyPropertyAccess, True, NotificationOption2.Suggestion)) End Function End Class End Namespace diff --git a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.vb b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.vb index b62a3fb4e6235..6e885ca998874 100644 --- a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.vb +++ b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.vb @@ -2,37 +2,32 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -Imports Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Partial Public Class RemoveUnusedValueAssignmentTests Inherits RemoveUnusedValuesTestsBase - Protected Overrides ReadOnly Property PreferNone As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferNone As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.None)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.None)) End Get End Property - Protected Overrides ReadOnly Property PreferDiscard As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferDiscard As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption.Suggestion)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion)) End Get End Property - Protected Overrides ReadOnly Property PreferUnusedLocal As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferUnusedLocal As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueAssignment, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Suggestion)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion)) End Get End Property diff --git a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.vb b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.vb index dc3d57b066446..abd395c6f2392 100644 --- a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.vb +++ b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.vb @@ -2,37 +2,32 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -Imports Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else Imports Microsoft.CodeAnalysis.CodeStyle -Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Partial Public Class RemoveUnusedValueExpressionStatementTests Inherits RemoveUnusedValuesTestsBase - Protected Overrides ReadOnly Property PreferNone As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferNone As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.None)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.None)) End Get End Property - Protected Overrides ReadOnly Property PreferDiscard As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferDiscard As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption.Silent)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent)) End Get End Property - Protected Overrides ReadOnly Property PreferUnusedLocal As IDictionary(Of OptionKey, Object) + Private Protected Overrides ReadOnly Property PreferUnusedLocal As IOptionsCollection Get Return [Option](VisualBasicCodeStyleOptions.UnusedValueExpressionStatement, - New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Silent)) + New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent)) End Get End Property diff --git a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.vb b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.vb index 5f50c33b2f383..29597b214b5da 100644 --- a/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.vb +++ b/src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.vb @@ -5,14 +5,9 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics +Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Options -#Else -Imports Microsoft.CodeAnalysis.Options -#End If - Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public MustInherit Class RemoveUnusedValuesTestsBase Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest @@ -21,11 +16,11 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParame Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function - Protected MustOverride ReadOnly Property PreferNone As IDictionary(Of OptionKey, Object) - Protected MustOverride ReadOnly Property PreferDiscard As IDictionary(Of OptionKey, Object) - Protected MustOverride ReadOnly Property PreferUnusedLocal As IDictionary(Of OptionKey, Object) + Private Protected MustOverride ReadOnly Property PreferNone As IOptionsCollection + Private Protected MustOverride ReadOnly Property PreferDiscard As IOptionsCollection + Private Protected MustOverride ReadOnly Property PreferUnusedLocal As IOptionsCollection - Protected Overloads Function TestMissingInRegularAndScriptAsync(initialMarkup As String, options As IDictionary(Of OptionKey, Object)) As Task + Private Protected Overloads Function TestMissingInRegularAndScriptAsync(initialMarkup As String, options As IOptionsCollection) As Task Return TestMissingInRegularAndScriptAsync(initialMarkup, New TestParameters(options:=options)) End Function End Class diff --git a/src/CodeStyle/BannedSymbols.txt b/src/CodeStyle/BannedSymbols.txt index c606990637777..c51a56fbf653e 100644 --- a/src/CodeStyle/BannedSymbols.txt +++ b/src/CodeStyle/BannedSymbols.txt @@ -1,8 +1,7 @@ -P:Microsoft.CodeAnalysis.Project.LanguageServices; Use 'GetExtendedLanguageServices' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') -M:Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(System.String); Use 'GetExtendedLanguageServices' or directly get the language service by invoking 'GetLanguageService' or 'GetRequiredLanguageService' in CodeStyle layer (preprocessor variable 'CODE_STYLE') +P:Microsoft.CodeAnalysis.Project.LanguageServices; Use 'GetExtendedLanguageServices' instead +M:Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(System.String); Use 'GetExtendedLanguageServices' or directly get the language service by invoking 'GetLanguageService' or 'GetRequiredLanguageService' T:Microsoft.CodeAnalysis.Options.OptionSet; 'OptionSet' is not available in CodeStyle layer. Add a using/Imports statement defining 'OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions' when preprocessor variable 'CODE_STYLE' is defined -T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption`1; Use 'Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') -T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions; Use 'Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') -T:Microsoft.CodeAnalysis.Options.IOption; Use 'Microsoft.CodeAnalysis.Internal.Options.IOption' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') -T:Microsoft.CodeAnalysis.Options.OptionKey; Use 'Microsoft.CodeAnalysis.Internal.Options.OptionKey' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') -T:Microsoft.CodeAnalysis.CodeStyle.NotificationOption; Use 'Microsoft.CodeAnalysis.Internal.Options.NotificationOption' instead in CodeStyle layer (preprocessor variable 'CODE_STYLE') \ No newline at end of file +T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption`1; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption2' instead +T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions2' instead +T:Microsoft.CodeAnalysis.Options.OptionKey; Use 'Microsoft.CodeAnalysis.Options.OptionKey2' instead +T:Microsoft.CodeAnalysis.CodeStyle.NotificationOption; Use 'Microsoft.CodeAnalysis.CodeStyle.NotificationOption2' instead \ No newline at end of file diff --git a/src/CodeStyle/CSharp/Analyzers/PublicAPI.Shipped.txt b/src/CodeStyle/CSharp/Analyzers/PublicAPI.Shipped.txt index 70dcbbe5a8839..e69de29bb2d1d 100644 --- a/src/CodeStyle/CSharp/Analyzers/PublicAPI.Shipped.txt +++ b/src/CodeStyle/CSharp/Analyzers/PublicAPI.Shipped.txt @@ -1,56 +0,0 @@ -Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions -Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions.Ignore = 1 -> Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions -Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions.Remove = 2 -> Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions -Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions.Single = 0 -> Microsoft.CodeAnalysis.CSharp.Formatting.BinaryOperatorSpacingOptions -Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions -Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions -Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions.LeftMost = 0 -> Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions -Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions.NoIndent = 2 -> Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions -Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions.OneLess = 1 -> Microsoft.CodeAnalysis.CSharp.Formatting.LabelPositionOptions -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentBlock.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentBraces.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchCaseSection.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.IndentSwitchSection.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.LabelPositioning.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForCatch.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForClausesInQuery.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForElse.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForFinally.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInAnonymousTypes.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLineForMembersInObjectInit.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInAccessors.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInControlBlocks.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInMethods.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInProperties.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.NewLinesForBracesInTypes.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterCast.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterComma.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterDot.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterMethodCallName.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBeforeComma.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBeforeDot.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBeforeOpenSquareBracket.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinCastParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinExpressionParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinMethodCallParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinOtherParentheses.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpaceWithinSquareBrackets.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpacingAfterMethodDeclarationName.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.SpacingAroundBinaryOperator.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine.get -> Microsoft.CodeAnalysis.Internal.Options.Option -static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions.WrappingPreserveSingleLine.get -> Microsoft.CodeAnalysis.Internal.Options.Option diff --git a/src/CodeStyle/CSharp/Tests/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.cs b/src/CodeStyle/CSharp/Tests/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.cs new file mode 100644 index 0000000000000..3f3e1a76dfc44 --- /dev/null +++ b/src/CodeStyle/CSharp/Tests/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.cs @@ -0,0 +1,55 @@ +// 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.CodeStyle; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; +using Microsoft.CodeAnalysis.Options; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics +{ + public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest + { + internal (OptionKey2, object) SingleOption(Option2 option, T enabled) + => (new OptionKey2(option), enabled); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2 option, T value) + => (new OptionKey2(option, this.GetLanguage()), value); + + internal (OptionKey2, object) SingleOption(Option2> option, T enabled, NotificationOption2 notification) + => SingleOption(option, new CodeStyleOption2(enabled, notification)); + + internal (OptionKey2, object) SingleOption(Option2> option, CodeStyleOption2 codeStyle) + => (new OptionKey2(option), codeStyle); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2> option, T enabled, NotificationOption2 notification) + => SingleOption(option, new CodeStyleOption2(enabled, notification)); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2> option, CodeStyleOption2 codeStyle) + => SingleOption(option, codeStyle, language: GetLanguage()); + + internal static (OptionKey2, object) SingleOption(PerLanguageOption2> option, CodeStyleOption2 codeStyle, string language) + => (new OptionKey2(option, language), codeStyle); + + internal IOptionsCollection Option(Option2> option, T enabled, NotificationOption2 notification) + => OptionsSet(SingleOption(option, enabled, notification)); + + internal IOptionsCollection Option(Option2> option, CodeStyleOption2 codeStyle) + => OptionsSet(SingleOption(option, codeStyle)); + + internal IOptionsCollection Option(PerLanguageOption2> option, T enabled, NotificationOption2 notification) + => OptionsSet(SingleOption(option, enabled, notification)); + + internal IOptionsCollection Option(PerLanguageOption2> option, CodeStyleOption2 codeStyle) + => OptionsSet(SingleOption(option, codeStyle)); + + internal IOptionsCollection Option(Option2 option, T value) + => OptionsSet(SingleOption(option, value)); + + internal IOptionsCollection Option(PerLanguageOption2 option, T value) + => OptionsSet(SingleOption(option, value)); + + internal static IOptionsCollection OptionsSet(params (OptionKey2 key, object value)[] options) + => new OptionsCollection(LanguageNames.CSharp, options); + } +} diff --git a/src/CodeStyle/CSharp/Tests/Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests.csproj b/src/CodeStyle/CSharp/Tests/Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests.csproj index 054b433663e0f..a94b577d8c9af 100644 --- a/src/CodeStyle/CSharp/Tests/Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests.csproj +++ b/src/CodeStyle/CSharp/Tests/Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests.csproj @@ -30,6 +30,7 @@ + diff --git a/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj b/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj index 8513ea29d572b..aa0b94436864f 100644 --- a/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj +++ b/src/CodeStyle/Core/Analyzers/Microsoft.CodeAnalysis.CodeStyle.csproj @@ -22,31 +22,13 @@ + - - - - - - - - - - - - - - - - - - - diff --git a/src/CodeStyle/Core/Analyzers/Options/AnalyzerHelper.cs b/src/CodeStyle/Core/Analyzers/Options/AnalyzerHelper.cs index c6b5a3d97931b..7ded71055153e 100644 --- a/src/CodeStyle/Core/Analyzers/Options/AnalyzerHelper.cs +++ b/src/CodeStyle/Core/Analyzers/Options/AnalyzerHelper.cs @@ -5,13 +5,13 @@ #nullable enable using System.Threading; -using Microsoft.CodeAnalysis.Internal.Options; +using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { - public static T GetOption(this AnalyzerOptions analyzerOptions, IOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) + public static T GetOption(this AnalyzerOptions analyzerOptions, IOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (analyzerOptions.TryGetEditorConfigOption(option, syntaxTree, out var value)) { @@ -21,14 +21,14 @@ public static T GetOption(this AnalyzerOptions analyzerOptions, IOption optio return (T)option.DefaultValue!; } - public static T GetOption(this AnalyzerOptions analyzerOptions, Option option, SyntaxTree syntaxTree, CancellationToken cancellationToken) + public static T GetOption(this AnalyzerOptions analyzerOptions, Option2 option, SyntaxTree syntaxTree, CancellationToken cancellationToken) { return GetOption(analyzerOptions, option, language: null, syntaxTree, cancellationToken); } - public static T GetOption(this AnalyzerOptions analyzerOptions, PerLanguageOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) + public static T GetOption(this AnalyzerOptions analyzerOptions, PerLanguageOption2 option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { - return GetOption(analyzerOptions, (IOption)option, language, syntaxTree, cancellationToken); + return GetOption(analyzerOptions, (IOption2)option, language, syntaxTree, cancellationToken); } public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) diff --git a/src/CodeStyle/Core/Analyzers/PublicAPI.Shipped.txt b/src/CodeStyle/Core/Analyzers/PublicAPI.Shipped.txt index baf9a26a1bcba..e69de29bb2d1d 100644 --- a/src/CodeStyle/Core/Analyzers/PublicAPI.Shipped.txt +++ b/src/CodeStyle/Core/Analyzers/PublicAPI.Shipped.txt @@ -1,74 +0,0 @@ -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.CodeStyleOption(T value, Microsoft.CodeAnalysis.Internal.Options.NotificationOption notification) -> void -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Equals(Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption other) -> bool -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Notification.get -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Notification.set -> void -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.ToXElement() -> System.Xml.Linq.XElement -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Value.get -> T -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Value.set -> void -Microsoft.CodeAnalysis.Internal.Options.NotificationOption -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Name.get -> string -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Name.set -> void -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Severity.get -> Microsoft.CodeAnalysis.ReportDiagnostic -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Severity.set -> void -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Value.get -> Microsoft.CodeAnalysis.DiagnosticSeverity -Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Value.set -> void -Microsoft.CodeAnalysis.Formatting.FormattingOptions -Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle -Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Block = 1 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle -Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.None = 0 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle -Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart = 2 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle -Microsoft.CodeAnalysis.Internal.Options.IOption -Microsoft.CodeAnalysis.Internal.Options.IOption.DefaultValue.get -> object -Microsoft.CodeAnalysis.Internal.Options.IOption.Feature.get -> string -Microsoft.CodeAnalysis.Internal.Options.IOption.IsPerLanguage.get -> bool -Microsoft.CodeAnalysis.Internal.Options.IOption.Name.get -> string -Microsoft.CodeAnalysis.Internal.Options.IOption.StorageLocations.get -> System.Collections.Immutable.ImmutableArray -Microsoft.CodeAnalysis.Internal.Options.IOption.Type.get -> System.Type -Microsoft.CodeAnalysis.Internal.Options.Option -Microsoft.CodeAnalysis.Internal.Options.Option.DefaultValue.get -> T -Microsoft.CodeAnalysis.Internal.Options.Option.Feature.get -> string -Microsoft.CodeAnalysis.Internal.Options.Option.Name.get -> string -Microsoft.CodeAnalysis.Internal.Options.Option.Option(string feature, string name) -> void -Microsoft.CodeAnalysis.Internal.Options.Option.Option(string feature, string name, T defaultValue) -> void -Microsoft.CodeAnalysis.Internal.Options.Option.Option(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Internal.Options.OptionStorageLocation[] storageLocations) -> void -Microsoft.CodeAnalysis.Internal.Options.Option.StorageLocations.get -> System.Collections.Immutable.ImmutableArray -Microsoft.CodeAnalysis.Internal.Options.Option.Type.get -> System.Type -Microsoft.CodeAnalysis.Internal.Options.OptionKey -Microsoft.CodeAnalysis.Internal.Options.OptionKey.Equals(Microsoft.CodeAnalysis.Internal.Options.OptionKey other) -> bool -Microsoft.CodeAnalysis.Internal.Options.OptionKey.Language.get -> string -Microsoft.CodeAnalysis.Internal.Options.OptionKey.Option.get -> Microsoft.CodeAnalysis.Internal.Options.IOption -Microsoft.CodeAnalysis.Internal.Options.OptionKey.OptionKey(Microsoft.CodeAnalysis.Internal.Options.IOption option, string language = null) -> void -Microsoft.CodeAnalysis.Internal.Options.OptionStorageLocation -Microsoft.CodeAnalysis.Internal.Options.OptionStorageLocation.OptionStorageLocation() -> void -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.DefaultValue.get -> T -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.Feature.get -> string -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.Name.get -> string -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.PerLanguageOption(string feature, string name, T defaultValue) -> void -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.PerLanguageOption(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Internal.Options.OptionStorageLocation[] storageLocations) -> void -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.StorageLocations.get -> System.Collections.Immutable.ImmutableArray -Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.Type.get -> System.Type -override Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Equals(object obj) -> bool -override Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.GetHashCode() -> int -override Microsoft.CodeAnalysis.Internal.Options.NotificationOption.ToString() -> string -override Microsoft.CodeAnalysis.Internal.Options.Option.ToString() -> string -override Microsoft.CodeAnalysis.Internal.Options.OptionKey.Equals(object obj) -> bool -override Microsoft.CodeAnalysis.Internal.Options.OptionKey.GetHashCode() -> int -override Microsoft.CodeAnalysis.Internal.Options.OptionKey.ToString() -> string -override Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption.ToString() -> string -static Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.Default.get -> Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption -static Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption.FromXElement(System.Xml.Linq.XElement element) -> Microsoft.CodeAnalysis.Internal.Options.CodeStyleOption -static Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize.get -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine.get -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent.get -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize.get -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs.get -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption -static Microsoft.CodeAnalysis.Internal.Options.Option.implicit operator Microsoft.CodeAnalysis.Internal.Options.OptionKey(Microsoft.CodeAnalysis.Internal.Options.Option option) -> Microsoft.CodeAnalysis.Internal.Options.OptionKey -static Microsoft.CodeAnalysis.Internal.Options.OptionKey.operator !=(Microsoft.CodeAnalysis.Internal.Options.OptionKey left, Microsoft.CodeAnalysis.Internal.Options.OptionKey right) -> bool -static Microsoft.CodeAnalysis.Internal.Options.OptionKey.operator ==(Microsoft.CodeAnalysis.Internal.Options.OptionKey left, Microsoft.CodeAnalysis.Internal.Options.OptionKey right) -> bool -static readonly Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Error -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption -static readonly Microsoft.CodeAnalysis.Internal.Options.NotificationOption.None -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption -static readonly Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Silent -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption -static readonly Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Suggestion -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption -static readonly Microsoft.CodeAnalysis.Internal.Options.NotificationOption.Warning -> Microsoft.CodeAnalysis.Internal.Options.NotificationOption diff --git a/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt b/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt index 97fe5ed1ea323..5291c5f74d50c 100644 --- a/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt +++ b/src/CodeStyle/Core/Analyzers/PublicAPI.Unshipped.txt @@ -62,15 +62,6 @@ Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsVolatile(bool Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions -Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.CodeStyleOptions() -> void -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation.TryGetOption(System.Collections.Generic.IReadOnlyDictionary rawOptions, System.Type type, out object value) -> bool -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation2 -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation2.GetEditorConfigString(object value, Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions optionSet) -> string -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation2.GetEditorConfigStringValue(object value, Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions optionSet) -> string -Microsoft.CodeAnalysis.Internal.Options.IEditorConfigStorageLocation2.KeyName.get -> string -Microsoft.CodeAnalysis.Internal.Options.NamingStyleOptions override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.Equals(object obj) -> bool override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.GetHashCode() -> int override Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.ToString() -> string @@ -99,10 +90,3 @@ static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator +(M static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> bool static Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Internal.Editing.DeclarationModifiers -static Microsoft.CodeAnalysis.Internal.Options.NamingStyleOptions.GetNamingPreferencesOptionKey(string language) -> Microsoft.CodeAnalysis.Internal.Options.OptionKey -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.QualifyEventAccess -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.QualifyFieldAccess -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.QualifyMethodAccess -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> -static readonly Microsoft.CodeAnalysis.Internal.Options.CodeStyleOptions.QualifyPropertyAccess -> Microsoft.CodeAnalysis.Internal.Options.PerLanguageOption> diff --git a/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj b/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj new file mode 100644 index 0000000000000..a9b8da4848ed8 --- /dev/null +++ b/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj @@ -0,0 +1,37 @@ + + + + + Library + Microsoft.CodeAnalysis + net472 + $(DefineConstants),CODE_STYLE + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj b/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj index cb679dd82f41a..f7aaf0bcd9917 100644 --- a/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj +++ b/src/CodeStyle/Core/Tests/Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj @@ -15,10 +15,6 @@ - - - - @@ -36,12 +32,12 @@ - - + + - \ No newline at end of file + \ No newline at end of file diff --git a/src/CodeStyle/VisualBasic/Tests/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.vb b/src/CodeStyle/VisualBasic/Tests/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.vb new file mode 100644 index 0000000000000..4a41de2a3a790 --- /dev/null +++ b/src/CodeStyle/VisualBasic/Tests/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest_OptionHelpers.vb @@ -0,0 +1,68 @@ +' 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 Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +Imports Microsoft.CodeAnalysis.CodeStyle +Imports Microsoft.CodeAnalysis.Options + +Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics + + Partial Public MustInherit Class AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest + Friend Function SingleOption(Of T)(optionParam As Option2(Of T), enabled As T) As (OptionKey2, Object) + Return (New OptionKey2(optionParam), enabled) + End Function + + Friend Function SingleOption(Of T)(optionParam As PerLanguageOption2(Of T), value As T) As (OptionKey2, Object) + Return (New OptionKey2(optionParam, Me.GetLanguage()), value) + End Function + + Friend Function SingleOption(Of T)(optionParam As Option2(Of CodeStyleOption2(Of T)), enabled As T, notification As NotificationOption2) As (OptionKey2, Object) + Return SingleOption(optionParam, New CodeStyleOption2(Of T)(enabled, notification)) + End Function + + Friend Function SingleOption(Of T)(optionParam As Option2(Of CodeStyleOption2(Of T)), codeStyle As CodeStyleOption2(Of T)) As (OptionKey2, Object) + Return (New OptionKey2(optionParam), codeStyle) + End Function + + Friend Function SingleOption(Of T)(optionParam As PerLanguageOption2(Of CodeStyleOption2(Of T)), enabled As T, notification As NotificationOption2) As (OptionKey2, Object) + Return SingleOption(optionParam, New CodeStyleOption2(Of T)(enabled, notification)) + End Function + + Friend Function SingleOption(Of T)(optionParam As PerLanguageOption2(Of CodeStyleOption2(Of T)), codeStyle As CodeStyleOption2(Of T)) As (OptionKey2, Object) + Return SingleOption(optionParam, codeStyle, language:=GetLanguage()) + End Function + + Friend Function SingleOption(Of T)(optionParam As PerLanguageOption2(Of CodeStyleOption2(Of T)), codeStyle As CodeStyleOption2(Of T), language As String) As (OptionKey2, Object) + Return (New OptionKey2(optionParam, language), codeStyle) + End Function + + Friend Function [Option](Of T)(optionParam As Option2(Of CodeStyleOption2(Of T)), enabled As T, notification As NotificationOption2) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, enabled, notification)) + End Function + + Friend Function [Option](Of T)(optionParam As Option2(Of CodeStyleOption2(Of T)), codeStyle As CodeStyleOption2(Of T)) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, codeStyle)) + End Function + + Friend Function [Option](Of T)(optionParam As PerLanguageOption2(Of CodeStyleOption2(Of T)), enabled As T, notification As NotificationOption2) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, enabled, notification)) + End Function + + Friend Function [Option](Of T)(optionParam As PerLanguageOption2(Of CodeStyleOption2(Of T)), codeStyle As CodeStyleOption2(Of T)) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, codeStyle)) + End Function + + Friend Function [Option](Of T)(optionParam As Option2(Of T), value As T) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, value)) + End Function + + Friend Function [Option](Of T)(optionParam As PerLanguageOption2(Of T), value As T) As IOptionsCollection + Return OptionsSet(SingleOption(optionParam, value)) + End Function + + Friend Shared Function OptionsSet(ParamArray options As (OptionKey2, Object)()) As IOptionsCollection + Return New OptionsCollection(LanguageNames.VisualBasic, options) + End Function + End Class +End Namespace diff --git a/src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj b/src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj index 47208c2c01ba1..5d284be6a7e2a 100644 --- a/src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj +++ b/src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj @@ -31,6 +31,7 @@ + diff --git a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs index 7424402229f5a..bba9b007401b3 100644 --- a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs +++ b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralOptions.cs @@ -13,8 +13,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral { internal class SplitStringLiteralOptions { - public static PerLanguageOption Enabled = - new PerLanguageOption(nameof(SplitStringLiteralOptions), nameof(Enabled), defaultValue: true, + public static PerLanguageOption2 Enabled = + new PerLanguageOption2(nameof(SplitStringLiteralOptions), nameof(Enabled), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitStringLiterals")); } diff --git a/src/EditorFeatures/CSharpTest/AddRequiredParentheses/AddRequiredParenthesesTests.cs b/src/EditorFeatures/CSharpTest/AddRequiredParentheses/AddRequiredParenthesesTests.cs index 0044440262e38..bc1f05e250ea0 100644 --- a/src/EditorFeatures/CSharpTest/AddRequiredParentheses/AddRequiredParenthesesTests.cs +++ b/src/EditorFeatures/CSharpTest/AddRequiredParentheses/AddRequiredParenthesesTests.cs @@ -21,10 +21,10 @@ public partial class AddRequiredParenthesesTests : AbstractCSharpDiagnosticProvi internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAddRequiredParenthesesDiagnosticAnalyzer(), new AddRequiredParenthesesCodeFixProvider()); - private Task TestMissingAsync(string initialMarkup, IDictionary options) + private Task TestMissingAsync(string initialMarkup, IOptionsCollection options) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options)); - private Task TestAsync(string initialMarkup, string expected, IDictionary options) + private Task TestAsync(string initialMarkup, string expected, IOptionsCollection options) => TestInRegularAndScript1Async(initialMarkup, expected, parameters: new TestParameters(options: options)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] diff --git a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs index 98114b0f873b9..0ac04fd03e94d 100644 --- a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs +++ b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs @@ -13,7 +13,6 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.RemoteHost; @@ -27,7 +26,7 @@ public partial class AbstractAddUsingTests : AbstractCSharpDiagnosticProviderBas internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAddImportCodeFixProvider()); - protected IDictionary SeparateGroups => Option(GenerationOptions.SeparateImportDirectiveGroups, true); + private protected IOptionsCollection SeparateGroups => Option(GenerationOptions.SeparateImportDirectiveGroups, true); protected async Task TestAsync( string initialMarkup, @@ -45,7 +44,7 @@ internal async Task TestAsync( string expectedMarkup, int index = 0, CodeActionPriority? priority = null, - IDictionary options = null) + IOptionsCollection options = null) { await TestAsync(initialMarkup, expectedMarkup, index, priority, options, outOfProcess: false); await TestAsync(initialMarkup, expectedMarkup, index, priority, options, outOfProcess: true); @@ -56,7 +55,7 @@ internal async Task TestAsync( string expectedMarkup, int index, CodeActionPriority? priority, - IDictionary options, + IOptionsCollection options, bool outOfProcess) { await TestInRegularAndScript1Async( diff --git a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs index afefe3bf95a88..ded481f08d150 100644 --- a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs +++ b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs @@ -28,9 +28,9 @@ private Task TestAsync( bool systemSpecialCase, int index = 0) { - return TestInRegularAndScriptAsync(initialMarkup, expected, index: index, options: new Dictionary + return TestInRegularAndScriptAsync(initialMarkup, expected, index: index, options: new Dictionary { - { new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), systemSpecialCase } + { new OptionKey2(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), systemSpecialCase } }); } diff --git a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs index 75eadf7856708..0e2dbe32437c3 100644 --- a/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs +++ b/src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticBraceCompletionTests.cs @@ -546,9 +546,9 @@ public void man() } } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } + { CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -621,9 +621,9 @@ class Goo { public int bar; }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } + { CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -692,9 +692,9 @@ public void man() } } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } + { CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -753,9 +753,9 @@ public void man() } } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } + { CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -814,9 +814,9 @@ public void man() } } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, false } + { CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, false } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -879,10 +879,10 @@ public void X() } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -909,9 +909,9 @@ public class C1 { } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -944,9 +944,9 @@ public class C1 } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -987,9 +987,9 @@ public class C1 } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Block } }; using var session = CreateSession(code, optionSet); Assert.NotNull(session); @@ -1000,7 +1000,7 @@ public class C1 CheckReturn(session.Session, 8, expectedAfterReturn); } - internal Holder CreateSession(string code, Dictionary optionSet = null) + internal Holder CreateSession(string code, Dictionary optionSet = null) { return CreateSession( TestWorkspace.CreateCSharp(code), diff --git a/src/EditorFeatures/CSharpTest/CodeActions/EncapsulateField/EncapsulateFieldTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/EncapsulateField/EncapsulateFieldTests.cs index 6c36e83082ba9..dd4f3e6d0f2b4 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/EncapsulateField/EncapsulateFieldTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/EncapsulateField/EncapsulateFieldTests.cs @@ -22,7 +22,7 @@ public class EncapsulateFieldTests : AbstractCSharpCodeActionTest protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new EncapsulateFieldRefactoringProvider(); - private IDictionary AllOptionsOff => + private IDictionary AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); @@ -31,9 +31,9 @@ internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, - int index = 0, IDictionary options = null) + int index = 0, IDictionary options = null) { - options = options ?? new Dictionary(); + options = options ?? new Dictionary(); foreach (var kvp in AllOptionsOff) { options.Add(kvp); @@ -210,8 +210,8 @@ void baz() "; await TestInRegularAndScriptAsync(text, expected, options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent))); } [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] @@ -1356,7 +1356,7 @@ public int Class } } } -", options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error)); +", options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); } [WorkItem(7090, "https://github.com/dotnet/roslyn/issues/7090")] @@ -1384,7 +1384,7 @@ public int I this.i = value; } } -}", options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error)); +}", options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); } [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)] diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractLocalFunctionTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractLocalFunctionTests.cs index 908b2e2a39e1a..284dbcc769e02 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractLocalFunctionTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractLocalFunctionTests.cs @@ -81,7 +81,7 @@ static bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -108,7 +108,7 @@ bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.FalseWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -1467,7 +1467,7 @@ static string NewMethod(int i) return v; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSuggestionEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -1514,7 +1514,7 @@ static string NewMethod(int i) return v; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSuggestionEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3241,7 +3241,7 @@ bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3268,7 +3268,7 @@ bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3295,7 +3295,7 @@ static bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3322,7 +3322,7 @@ static bool NewMethod(bool b) return b != true; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement), parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3370,7 +3370,7 @@ double NewMethod() _seconds = value * 3600; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3418,7 +3418,7 @@ double NewMethod() _seconds = value * 3600; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3463,7 +3463,7 @@ static void NewMethod(double value) } } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3508,7 +3508,7 @@ void NewMethod(double value) } } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3563,7 +3563,7 @@ void NewMethod(int index) testArr[index] = value; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3618,7 +3618,7 @@ string NewMethod(int index) testArr[index] = value; } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3673,7 +3673,7 @@ void NewMethod(int index) } } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -3728,7 +3728,7 @@ void NewMethod(int index, string value) } } } -}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.TrueWithSilentEnforcement)); +}", CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractLocalFunction)] @@ -4249,7 +4249,7 @@ bool NewMethod() "; - await TestInRegularAndScriptAsync(input, expected, CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.FalseWithSilentEnforcement)); + await TestInRegularAndScriptAsync(input, expected, CodeActionIndex, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement)); } [WorkItem(40654, "https://github.com/dotnet/roslyn/issues/40654")] diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractMethodTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractMethodTests.cs index acb29e5ef1d82..827890b3e1889 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractMethodTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ExtractMethod/ExtractMethodTests.cs @@ -1493,7 +1493,7 @@ private static string NewMethod(int i) return v; } -}", options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSuggestionEnforcement)); +}", options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [WorkItem(15219, "https://github.com/dotnet/roslyn/issues/15219")] @@ -1541,7 +1541,7 @@ private static string NewMethod(int i) return v; } -}", options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSuggestionEnforcement)); +}", options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [Fact] @@ -3221,7 +3221,7 @@ private static bool NewMethod(bool b) { return b != true; } -}", options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.FalseWithSuggestionEnforcement)); +}", options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSuggestionEnforcement)); } [Fact, WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946"), Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] diff --git a/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs index 28a06fd2c67b7..85082055a9766 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs @@ -27,22 +27,15 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspa protected override ImmutableArray MassageActions(ImmutableArray actions) => GetNestedActions(actions); - private readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); + private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); // specify all options explicitly to override defaults. - private IDictionary ImplicitTypingEverywhere() => + private IDictionary ImplicitTypingEverywhere() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - internal IDictionary OptionSet(OptionKey option, object value) - { - var options = new Dictionary(); - options.Add(option, value); - return options; - } - [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)] public async Task TestEmptySpan1() { diff --git a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs index 77c919c5b0525..fd39703a14cf3 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs @@ -883,7 +883,7 @@ await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { - w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions.InsertFinalNewLine, true))); + w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true))); }); } @@ -924,7 +924,7 @@ await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { - w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions.InsertFinalNewLine, false))); + w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false))); }); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs index f6dcf045f267d..65a825eb7d28a 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs @@ -2345,19 +2345,19 @@ await TestAsync( options: AllCodeStyleOff); } - private IDictionary AllCodeStyleOff => + private IDictionary AllCodeStyleOff => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary PreferExpressionBodiedAccessors => + private IDictionary PreferExpressionBodiedAccessors => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary PreferExpressionBodiedProperties => + private IDictionary PreferExpressionBodiedProperties => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); - private IDictionary PreferExpressionBodiedAccessorsAndProperties => + private IDictionary PreferExpressionBodiedAccessorsAndProperties => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs index 6012159c83812..a74c1ee480537 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs @@ -1844,7 +1844,7 @@ public static void Set(int value) }"); } - private IDictionary PreferExpressionBodiedMethods => + private IDictionary PreferExpressionBodiedMethods => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); } } diff --git a/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs b/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs index 2f29504f30a5f..e9bc24c53f409 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs +++ b/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs @@ -2,82 +2,81 @@ // 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.Collections.Generic; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; -using Microsoft.CodeAnalysis.Options; +using static Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.AbstractCodeActionOrUserDiagnosticTest; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions { internal static class UseVarTestExtensions { - private static readonly CodeStyleOption onWithNone = new CodeStyleOption(true, NotificationOption.None); - private static readonly CodeStyleOption offWithNone = new CodeStyleOption(false, NotificationOption.None); - private static readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); - private static readonly CodeStyleOption offWithSilent = new CodeStyleOption(false, NotificationOption.Silent); - private static readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); - private static readonly CodeStyleOption offWithInfo = new CodeStyleOption(false, NotificationOption.Suggestion); - private static readonly CodeStyleOption onWithWarning = new CodeStyleOption(true, NotificationOption.Warning); - private static readonly CodeStyleOption offWithWarning = new CodeStyleOption(false, NotificationOption.Warning); - private static readonly CodeStyleOption offWithError = new CodeStyleOption(false, NotificationOption.Error); - private static readonly CodeStyleOption onWithError = new CodeStyleOption(true, NotificationOption.Error); + private static readonly CodeStyleOption2 onWithNone = new CodeStyleOption2(true, NotificationOption2.None); + private static readonly CodeStyleOption2 offWithNone = new CodeStyleOption2(false, NotificationOption2.None); + private static readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); + private static readonly CodeStyleOption2 offWithSilent = new CodeStyleOption2(false, NotificationOption2.Silent); + private static readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); + private static readonly CodeStyleOption2 offWithInfo = new CodeStyleOption2(false, NotificationOption2.Suggestion); + private static readonly CodeStyleOption2 onWithWarning = new CodeStyleOption2(true, NotificationOption2.Warning); + private static readonly CodeStyleOption2 offWithWarning = new CodeStyleOption2(false, NotificationOption2.Warning); + private static readonly CodeStyleOption2 offWithError = new CodeStyleOption2(false, NotificationOption2.Error); + private static readonly CodeStyleOption2 onWithError = new CodeStyleOption2(true, NotificationOption2.Error); - public static IDictionary PreferExplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferExplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithError), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithError)); - public static IDictionary PreferImplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferImplicitTypeWithError(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithError), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithError), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithError)); - public static IDictionary PreferExplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferExplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithWarning), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithWarning), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithWarning)); - public static IDictionary PreferImplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferImplicitTypeWithWarning(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithWarning), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithWarning), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithWarning)); - public static IDictionary PreferExplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferExplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithInfo), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo)); - public static IDictionary PreferImplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferImplicitTypeWithInfo(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - public static IDictionary PreferExplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferExplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithSilent), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent)); - public static IDictionary PreferImplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferImplicitTypeWithSilent(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithSilent), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent)); - public static IDictionary PreferExplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferExplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, offWithNone), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithNone), test.SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, offWithNone)); - public static IDictionary PreferImplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) + public static IOptionsCollection PreferImplicitTypeWithNone(this AbstractCodeActionOrUserDiagnosticTest test) => AbstractCodeActionOrUserDiagnosticTest.OptionsSet( test.SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithNone), test.SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithNone), diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs index 5361d14133f57..3a7ab58fcbc8b 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/DeclarationNameCompletionProviderTests.cs @@ -1453,7 +1453,7 @@ public async Task CustomNamingStyleInsideClass() { var workspace = WorkspaceFixture.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( - new OptionKey(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), + new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" @@ -1477,7 +1477,7 @@ public async Task CustomNamingStyleInsideMethod() { var workspace = WorkspaceFixture.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( - new OptionKey(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), + new OptionKey2(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp), NamesEndWithSuffixPreferences()))); var markup = @" diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs index 7ea202e7d2c8f..af14e4a3af57b 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/PartialMethodCompletionProviderTests.cs @@ -487,7 +487,7 @@ public async Task ExpressionBodyMethod() var workspace = WorkspaceFixture.GetWorkspace(ExportProvider); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options.WithChangedOption( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, - new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.Silent)))); + new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent)))); var text = @"using System; partial class Bar diff --git a/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs b/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs index 77dbb9762dbb6..eaaccecbb1fe2 100644 --- a/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs +++ b/src/EditorFeatures/CSharpTest/ConvertAutoPropertyToFullProperty/ConvertAutoPropertyToFullPropertyTests_OptionSets.cs @@ -19,41 +19,41 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAutoPropertyToFu { public partial class ConvertAutoPropertyToFullPropertyTests : AbstractCSharpCodeActionTest { - private IDictionary PreferExpressionBodiedAccessorsWhenPossible + private IDictionary PreferExpressionBodiedAccessorsWhenPossible => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); - private IDictionary PreferExpressionBodiedAccessorsWhenOnSingleLine + private IDictionary PreferExpressionBodiedAccessorsWhenOnSingleLine => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement)); - private IDictionary DoNotPreferExpressionBodiedAccessors + private IDictionary DoNotPreferExpressionBodiedAccessors => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine + private IDictionary DoNotPreferExpressionBodiedAccessorsAndPropertyOpenBraceOnSameLine => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), - SingleOption(CSharpFormattingOptions.NewLinesForBracesInProperties, false)); + SingleOption(CSharpFormattingOptions2.NewLinesForBracesInProperties, false)); - private IDictionary DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine + private IDictionary DoNotPreferExpressionBodiedAccessorsAndAccessorOpenBraceOnSameLine => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), - SingleOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, false)); + SingleOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors, false)); - private IDictionary PreferExpressionBodiesOnAccessorsAndMethods + private IDictionary PreferExpressionBodiesOnAccessorsAndMethods => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary UseCustomFieldName + private IDictionary UseCustomFieldName => OptionsSet( SingleOption(NamingStyleOptions.NamingPreferences, CreateCustomFieldNamingStylePreference()), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseUnderscorePrefixedFieldName + private IDictionary UseUnderscorePrefixedFieldName => OptionsSet( SingleOption(NamingStyleOptions.NamingPreferences, CreateUnderscorePrefixedFieldNamingStylePreference()), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseCustomStaticFieldName + private IDictionary UseCustomStaticFieldName => OptionsSet( SingleOption(NamingStyleOptions.NamingPreferences, CreateCustomStaticFieldNamingStylePreference()), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); diff --git a/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs b/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs index 86fd75af4bc27..68e6b6ca9a1ef 100644 --- a/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs +++ b/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs @@ -23,9 +23,9 @@ protected override CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters) => new CSharpConvertForEachToForCodeRefactoringProvider(); - private readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); + private readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); - private IDictionary ImplicitTypeEverywhere => OptionsSet( + private IDictionary ImplicitTypeEverywhere => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent)); diff --git a/src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs b/src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs index f90b3bd5c7e94..cc2af730f58c7 100644 --- a/src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs +++ b/src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs @@ -22,9 +22,9 @@ public class ConvertForToForEachTests : AbstractCSharpCodeActionTest protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertForToForEachCodeRefactoringProvider(); - private readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); + private readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); - private IDictionary ImplicitTypeEverywhere() => OptionsSet( + private IDictionary ImplicitTypeEverywhere() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent)); diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs b/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs index f9cb2e7c89dc0..2e8333e8a07d3 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest.cs @@ -2,16 +2,12 @@ // 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.Collections.Generic; -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; -using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics { - public abstract class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest : AbstractDiagnosticProviderBasedUserDiagnosticTest + public abstract partial class AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest : AbstractDiagnosticProviderBasedUserDiagnosticTest { protected override ParseOptions GetScriptOptions() => Options.Script; diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests.cs index 5e94bf1c71a9d..ab42c416ab484 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests.cs @@ -2732,7 +2732,7 @@ class Base protected int I; }", index: 1, -options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error)); +options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] @@ -2981,7 +2981,7 @@ class Base public int I { get; protected set; } }", index: 1, -options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); +options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] @@ -3060,7 +3060,7 @@ class Base protected int I { get; set; } }", index: 1, -options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); +options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -3091,7 +3091,7 @@ public T(System.Int32 i) } }", index: 1, -options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Error)); +options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error)); } #endregion diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.cs index 96c87f4a74755..5f3fb9562c0fa 100644 --- a/src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.cs +++ b/src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.cs @@ -20,24 +20,24 @@ public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProvider internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider()); - private readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); - private readonly CodeStyleOption offWithInfo = new CodeStyleOption(false, NotificationOption.Suggestion); + private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); + private readonly CodeStyleOption2 offWithInfo = new CodeStyleOption2(false, NotificationOption2.Suggestion); - private IDictionary NoFrameworkType => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage())); + private IDictionary NoFrameworkType => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage())); - private IDictionary FrameworkTypeEverywhere => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage())); + private IDictionary FrameworkTypeEverywhere => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage())); - private IDictionary FrameworkTypeInDeclaration => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage())); + private IDictionary FrameworkTypeInDeclaration => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage())); - private IDictionary FrameworkTypeInMemberAccess => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage())); + private IDictionary FrameworkTypeInMemberAccess => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage())); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] public async Task NotWhenOptionsAreNotSet() diff --git a/src/EditorFeatures/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs b/src/EditorFeatures/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs index 3c55df7d23903..b561b4912417f 100644 --- a/src/EditorFeatures/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs +++ b/src/EditorFeatures/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs @@ -21,10 +21,10 @@ public class ValidateRegexStringTests : AbstractCSharpDiagnosticProviderBasedUse internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRegexDiagnosticAnalyzer(), null); - private IDictionary OptionOn() + private IDictionary OptionOn() { - var optionsSet = new Dictionary(); - optionsSet.Add(new OptionKey(RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp), true); + var optionsSet = new Dictionary(); + optionsSet.Add(new OptionKey2(RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp), true); return optionsSet; } diff --git a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs index 3cd314190eacc..584fd9f71d6ec 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs @@ -24,13 +24,13 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class FormattingEngineTests : CSharpFormattingEngineTestBase { - private static Dictionary SmartIndentButDoNotFormatWhileTyping() + private static Dictionary SmartIndentButDoNotFormatWhileTyping() { - return new Dictionary + return new Dictionary { - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart }, - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false }, - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart }, + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false }, + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }, }; } @@ -510,7 +510,7 @@ public void M() var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(FormattingOptions.AllowDisjointSpanMerging, true))); + .WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true))); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); @@ -1165,9 +1165,9 @@ class C1 class C1 { }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FormattingOptions.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } + { new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None } }; AssertFormatAfterTypeChar(code, expected, optionSet); } @@ -1196,9 +1196,9 @@ class C } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); @@ -1228,9 +1228,9 @@ class C } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); @@ -1260,9 +1260,9 @@ static void Main() } }"; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); @@ -1318,9 +1318,9 @@ class C } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnSemicolon, LanguageNames.CSharp), false } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnSemicolon, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); @@ -1350,9 +1350,9 @@ class C } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } + { new OptionKey2(FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected, optionSet); @@ -1378,9 +1378,9 @@ public int P { } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(BraceCompletionOptions.Enable, LanguageNames.CSharp), false } + { new OptionKey2(BraceCompletionOptions.Enable, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected); @@ -1408,9 +1408,9 @@ public int P } "; - var optionSet = new Dictionary + var optionSet = new Dictionary { - { new OptionKey(BraceCompletionOptions.Enable, LanguageNames.CSharp), false } + { new OptionKey2(BraceCompletionOptions.Enable, LanguageNames.CSharp), false } }; AssertFormatAfterTypeChar(code, expected); @@ -2145,7 +2145,7 @@ public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst() AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true)); } - private void AssertFormatAfterTypeChar(string code, string expected, Dictionary changedOptionSet = null) + private void AssertFormatAfterTypeChar(string code, string expected, Dictionary changedOptionSet = null) { using var workspace = TestWorkspace.CreateCSharp(code); if (changedOptionSet != null) diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs index 1788898a83841..527476bbc5e2e 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs @@ -102,7 +102,7 @@ protected async Task GetSmartTokenFormatterIndentationAsync( // create tree service using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, useTabs))); + .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); if (baseIndentation.HasValue) { diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs index 40e1b5e120427..6ee89654aa567 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterEnterOnTokenTests.cs @@ -13,7 +13,8 @@ using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; -using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; +using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; +using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs index 6da660ef0f29c..32b3b6fcb0f5a 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartIndenterTests.cs @@ -10,7 +10,8 @@ using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; -using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; +using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; +using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs index 4329a85ffc234..b3c355dc0667d 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs @@ -3472,7 +3472,7 @@ internal static void AutoFormatToken(string markup, string expected, bool useTab using var workspace = TestWorkspace.CreateCSharp(markup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, useTabs))); + .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var subjectDocument = workspace.Documents.Single(); @@ -3518,7 +3518,7 @@ private async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected using var workspace = TestWorkspace.CreateCSharp(initialMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, useTabs))); + .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var tuple = GetService(workspace); var testDocument = workspace.Documents.Single(); diff --git a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs index 035937aeaa623..06a337ad0c28c 100644 --- a/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs +++ b/src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatTokenTests.cs @@ -639,7 +639,7 @@ private async Task AssertSmartTokenFormatterOpenBraceAsync( using var workspace = TestWorkspace.CreateCSharp(code); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, useTabs))); + .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var buffer = workspace.Documents.First().GetTextBuffer(); diff --git a/src/EditorFeatures/CSharpTest/GenerateConstructor/GenerateConstructorTests.cs b/src/EditorFeatures/CSharpTest/GenerateConstructor/GenerateConstructorTests.cs index 3c416e445b2a9..8b1a458f2229c 100644 --- a/src/EditorFeatures/CSharpTest/GenerateConstructor/GenerateConstructorTests.cs +++ b/src/EditorFeatures/CSharpTest/GenerateConstructor/GenerateConstructorTests.cs @@ -428,7 +428,7 @@ public D(int x) this.X = x; } }", - options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error)); + options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); } [WorkItem(539444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] @@ -560,7 +560,7 @@ public D(int x) this.X = x; } }", - options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error)); + options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error)); } [WorkItem(539444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] @@ -724,7 +724,7 @@ public D(int x) public int X { get; private set; } }", - options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); + options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [WorkItem(539444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] @@ -856,7 +856,7 @@ public D(int x) this.X = x; } }", - options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); + options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [WorkItem(539444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] @@ -943,7 +943,7 @@ public D(int x) this.X = x; } }", - options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); + options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [WorkItem(539444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539444")] diff --git a/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.cs b/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.cs index be0989b829302..c39573ea7edfd 100644 --- a/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.cs +++ b/src/EditorFeatures/CSharpTest/GenerateFromMembers/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.cs @@ -488,7 +488,7 @@ public Z(int a, string b{|Navigation:)|} public int A { get; private set; } public string B { get; private set; } -}", options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error)); +}", options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] @@ -815,7 +815,7 @@ public Program(int field{|Navigation:)|} this._field = field; } }", -options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement)); +options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [WorkItem(13944, "https://github.com/dotnet/roslyn/issues/13944")] @@ -839,7 +839,7 @@ protected Contribution(string title, int number{|Navigation:)|} public string Title { get; } public int Number { get; } }", -options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement)); +options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [WorkItem(13944, "https://github.com/dotnet/roslyn/issues/13944")] @@ -852,7 +852,7 @@ await TestMissingInRegularAndScriptAsync( [|public abstract string Title { get; } public int Number { get; }|] }", -new TestParameters(options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement))); +new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] @@ -1039,7 +1039,7 @@ public Z(int a, string b{|Navigation:)|} chosenSymbols: new string[] { "a", "b" }, optionsCallback: options => options[0].Value = true, parameters: new TestParameters(options: - Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions.FalseWithSilentEnforcement))); + Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] @@ -1074,7 +1074,7 @@ public Z(int a, int? b{|Navigation:)|} chosenSymbols: new string[] { "a", "b" }, optionsCallback: options => options[0].Value = true, parameters: new TestParameters(options: - Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions.FalseWithSilentEnforcement))); + Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] @@ -1115,7 +1115,7 @@ public Z(int a, string b{|Navigation:)|} optionsCallback: options => options[0].Value = true, parameters: new TestParameters( parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6), - options: Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions.FalseWithSilentEnforcement))); + options: Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] @@ -1211,7 +1211,7 @@ protected C(int prop{|Navigation:)|} public int Prop { get; set; } }", -options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement)); +options: Option(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.TrueWithSuggestionEnforcement)); } [WorkItem(17643, "https://github.com/dotnet/roslyn/issues/17643")] diff --git a/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs b/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs index 57775429116c8..35bb50caf0ff2 100644 --- a/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs +++ b/src/EditorFeatures/CSharpTest/GenerateVariable/GenerateVariableTests.cs @@ -33,17 +33,17 @@ public class GenerateVariableTests : AbstractCSharpDiagnosticProviderBasedUserDi internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpGenerateVariableCodeFixProvider()); - private readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); + private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); // specify all options explicitly to override defaults. - private IDictionary ImplicitTypingEverywhere() => OptionsSet( + private IDictionary ImplicitTypingEverywhere() => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - internal IDictionary OptionSet(OptionKey option, object value) + internal IDictionary OptionSet(OptionKey2 option, object value) { - var options = new Dictionary(); + var options = new Dictionary(); options.Add(option, value); return options; } diff --git a/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests.cs b/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests.cs index 78a7b65a6751c..d1d3a156aae43 100644 --- a/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests.cs +++ b/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests.cs @@ -25,7 +25,7 @@ public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProvi internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); - private IDictionary AllOptionsOff => + private IDictionary AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), @@ -38,10 +38,10 @@ internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, int index = 0, - IDictionary options = null, + IDictionary options = null, ParseOptions parseOptions = null) { - options = options ?? new Dictionary(); + options = options ?? new Dictionary(); foreach (var kvp in AllOptionsOff) { options.Add(kvp); @@ -1240,8 +1240,8 @@ public override int M } } }", options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] @@ -1277,8 +1277,8 @@ public override int M } } }", options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] @@ -1333,8 +1333,8 @@ public override int this[int i] } } }", options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] @@ -1370,8 +1370,8 @@ public override int this[int i] } } }", options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] @@ -1396,8 +1396,8 @@ class T : A { public override int M { get => throw new System.NotImplementedException(); } }", options: OptionsSet( - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption.Silent), - SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption.Silent))); + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption2.Silent), + SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent))); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] diff --git a/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs b/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs index 156393d56e632..a9de219e33b5c 100644 --- a/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs +++ b/src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests_ThroughMember.cs @@ -22,7 +22,7 @@ public sealed class ImplementAbstractClassTests_ThroughMemberTests : AbstractCSh internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); - private IDictionary AllOptionsOff => + private IDictionary AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), @@ -34,10 +34,10 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, - IDictionary options = null, + IDictionary options = null, ParseOptions parseOptions = null) { - options ??= new Dictionary(); + options ??= new Dictionary(); foreach (var kvp in AllOptionsOff) { options.Add(kvp); diff --git a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs index f9d97c1bfded3..7bfe56bd5c260 100644 --- a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs +++ b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs @@ -26,7 +26,7 @@ public partial class ImplementInterfaceTests : AbstractCSharpDiagnosticProviderB internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementInterfaceCodeFixProvider()); - private IDictionary AllOptionsOff => + private IDictionary AllOptionsOff => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), @@ -35,7 +35,7 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary AllOptionsOn => + private IDictionary AllOptionsOn => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), @@ -44,7 +44,7 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary AccessorOptionsOn => + private IDictionary AccessorOptionsOn => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), diff --git a/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs b/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs index 771c3c821c81f..0142bf308391c 100644 --- a/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs +++ b/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs @@ -646,7 +646,7 @@ public C(string s) S = s; } }", parameters: new TestParameters(options: - Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions.FalseWithSilentEnforcement))); + Option(CSharpCodeStyleOptions.PreferThrowExpression, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] @@ -1481,8 +1481,8 @@ static void Main(String bar) }", index: 1, parameters: new TestParameters( options: Option( - CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, - CodeStyleOptions.FalseWithSuggestionEnforcement))); + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, + CodeStyleOptions2.FalseWithSuggestionEnforcement))); } [WorkItem(19172, "https://github.com/dotnet/roslyn/issues/19172")] @@ -1513,7 +1513,7 @@ public C(string s) } }", parameters: new TestParameters(options: - Option(CSharpCodeStyleOptions.PreferBraces, new CodeStyleOption((PreferBracesPreference)preferBraces, NotificationOption.Silent)))); + Option(CSharpCodeStyleOptions.PreferBraces, new CodeStyleOption2((PreferBracesPreference)preferBraces, NotificationOption2.Silent)))); } [WorkItem(19956, "https://github.com/dotnet/roslyn/issues/19956")] diff --git a/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs b/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs index 62b57800b911b..f00ba15f15350 100644 --- a/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs +++ b/src/EditorFeatures/CSharpTest/InitializeParameter/InitializeMemberFromParameterTests.cs @@ -1464,9 +1464,9 @@ public C([|string p__End, string p_test_t|]) }", parameters: new TestParameters(options: options.MergeStyles(options.PropertyNamesArePascalCase, options.ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix, LanguageNames.CSharp))); } - private TestParameters OmitIfDefault_Warning => new TestParameters(options: Option(CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption.Warning)); - private TestParameters Never_Warning => new TestParameters(options: Option(CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption.Warning)); - private TestParameters Always_Warning => new TestParameters(options: Option(CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption.Warning)); + 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)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)] public async Task TestCreateFieldWithTopLevelNullability() @@ -1558,7 +1558,7 @@ public C(string s) { } public string S { get; } -}", options: this.Option(CSharpFormattingOptions.NewLinesForBracesInMethods, false)); +}", options: this.Option(CSharpFormattingOptions2.NewLinesForBracesInMethods, false)); } } } diff --git a/src/EditorFeatures/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs b/src/EditorFeatures/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs index 8d1f9d200de08..8c5045d8874b0 100644 --- a/src/EditorFeatures/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs +++ b/src/EditorFeatures/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs @@ -327,8 +327,8 @@ void M() var {|Rename:dateTime|} = new DateTime(); } }", options: OptionsSet( - (CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSuggestionEnforcement), - (CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSuggestionEnforcement))); + (CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSuggestionEnforcement), + (CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] diff --git a/src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs b/src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs index 9ceb5ad674f0e..1908975e0d4cf 100644 --- a/src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs +++ b/src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs @@ -72,7 +72,7 @@ void M() }", new TestParameters( parseOptions: CSharp8ParseOptions, - options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions.FalseWithSilentEnforcement))); + options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] diff --git a/src/EditorFeatures/CSharpTest/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProviderTests.cs b/src/EditorFeatures/CSharpTest/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProviderTests.cs index b16b484274511..e264350024a05 100644 --- a/src/EditorFeatures/CSharpTest/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProviderTests.cs @@ -22,17 +22,17 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MisplacedUsingDirective /// public class MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { - internal static readonly CodeStyleOption OutsidePreferPreservationOption = - new CodeStyleOption(AddImportPlacement.OutsideNamespace, NotificationOption.None); + internal static readonly CodeStyleOption2 OutsidePreferPreservationOption = + new CodeStyleOption2(AddImportPlacement.OutsideNamespace, NotificationOption2.None); - internal static readonly CodeStyleOption InsidePreferPreservationOption = - new CodeStyleOption(AddImportPlacement.InsideNamespace, NotificationOption.None); + internal static readonly CodeStyleOption2 InsidePreferPreservationOption = + new CodeStyleOption2(AddImportPlacement.InsideNamespace, NotificationOption2.None); - internal static readonly CodeStyleOption InsideNamespaceOption = - new CodeStyleOption(AddImportPlacement.InsideNamespace, NotificationOption.Error); + internal static readonly CodeStyleOption2 InsideNamespaceOption = + new CodeStyleOption2(AddImportPlacement.InsideNamespace, NotificationOption2.Error); - internal static readonly CodeStyleOption OutsideNamespaceOption = - new CodeStyleOption(AddImportPlacement.OutsideNamespace, NotificationOption.Error); + internal static readonly CodeStyleOption2 OutsideNamespaceOption = + new CodeStyleOption2(AddImportPlacement.OutsideNamespace, NotificationOption2.Error); protected const string ClassDefinition = @"public class TestClass @@ -54,25 +54,25 @@ public class MisplacedUsingDirectivesInCompilationUnitCodeFixProviderTests : Abs protected const string DelegateDefinition = @"public delegate void TestDelegate();"; - private protected Task TestDiagnosticMissingAsync(string initialMarkup, CodeStyleOption preferredPlacementOption) + private protected Task TestDiagnosticMissingAsync(string initialMarkup, CodeStyleOption2 preferredPlacementOption) { - var options = new Dictionary { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption } }; + var options = OptionsSet(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption); return TestDiagnosticMissingAsync(initialMarkup, new TestParameters(options: options)); } - private protected Task TestMissingAsync(string initialMarkup, CodeStyleOption preferredPlacementOption) + private protected Task TestMissingAsync(string initialMarkup, CodeStyleOption2 preferredPlacementOption) { - var options = new Dictionary { { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption } }; + var options = OptionsSet(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption); return TestMissingAsync(initialMarkup, new TestParameters(options: options)); } - private protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, CodeStyleOption preferredPlacementOption, bool placeSystemNamespaceFirst) + private protected Task TestInRegularAndScriptAsync(string initialMarkup, string expectedMarkup, CodeStyleOption2 preferredPlacementOption, bool placeSystemNamespaceFirst) { - var options = new Dictionary - { - { CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, preferredPlacementOption }, - { new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), placeSystemNamespaceFirst } - }; + var options = OptionsSet + ( + (new OptionKey2(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement), preferredPlacementOption), + (new OptionKey2(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp), placeSystemNamespaceFirst) + ); return TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: options); } diff --git a/src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs b/src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs index b35d3f8e21755..5e72fb41eb5da 100644 --- a/src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs +++ b/src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs @@ -85,7 +85,7 @@ void M() [|this|].SomeProperty = 1; } }", - options: Option(CodeStyleOptions.QualifyPropertyAccess, false, NotificationOption.Warning), + options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } @@ -420,8 +420,8 @@ void N() "; var options = OptionsSet( - SingleOption(CodeStyleOptions.QualifyPropertyAccess, false, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Suggestion)); + SingleOption(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion)); await TestInRegularAndScriptAsync( initialMarkup: input, diff --git a/src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs b/src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs index e803f742edbf4..5cf5309bb9ecd 100644 --- a/src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs +++ b/src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs @@ -3682,7 +3682,7 @@ public void z() { [|this|].x = 4; } -}", new TestParameters(options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -3814,7 +3814,7 @@ class C public void z() { } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -3857,7 +3857,7 @@ class C public void z() { } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] @@ -3897,7 +3897,7 @@ await TestMissingInRegularAndScriptAsync( public void z() { } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] @@ -3949,7 +3949,7 @@ public void z(System.Int32 y) { System.Int32 z = 9; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -3965,7 +3965,7 @@ public void z([|System.Int32|] y) { System.Int32 z = 9; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -3981,7 +3981,7 @@ public void z(System.Int32 y) { [|System.Int32|] z = 9; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -4064,7 +4064,7 @@ public void z() { var sss = [|Int32|].MaxValue; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] @@ -4078,7 +4078,7 @@ public void z() { var sss = [|System.Int32|].MaxValue; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption.Error))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(965208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965208")] @@ -5871,34 +5871,34 @@ private async Task TestWithPredefinedTypeOptionsAsync(string code, string expect await TestInRegularAndScriptAsync(code, expected, index: index, options: PreferIntrinsicTypeEverywhere); } - private IDictionary PreferIntrinsicTypeEverywhere => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithError, GetLanguage())); + private IDictionary PreferIntrinsicTypeEverywhere => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithError, GetLanguage())); - private IDictionary PreferIntrinsicTypeEverywhereAsWarning => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Warning), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithWarning, GetLanguage())); + private IDictionary PreferIntrinsicTypeEverywhereAsWarning => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Warning), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithWarning, GetLanguage())); - private IDictionary PreferIntrinsicTypeInDeclaration => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.offWithSilent, GetLanguage())); + private IDictionary PreferIntrinsicTypeInDeclaration => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.offWithSilent, GetLanguage())); - private IDictionary PreferIntrinsicTypeInMemberAccess => OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, true, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, this.offWithSilent, GetLanguage())); + private IDictionary PreferIntrinsicTypeInMemberAccess => OptionsSet( + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, true, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, this.offWithSilent, GetLanguage())); - private IDictionary PreferImplicitTypeEverywhere => OptionsSet( + private IDictionary PreferImplicitTypeEverywhere => OptionsSet( SingleOption(CSharpCodeStyleOptions.VarElsewhere, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo), SingleOption(CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo)); - private readonly CodeStyleOption onWithSilent = new CodeStyleOption(true, NotificationOption.Silent); - private readonly CodeStyleOption offWithSilent = new CodeStyleOption(false, NotificationOption.Silent); - private readonly CodeStyleOption onWithInfo = new CodeStyleOption(true, NotificationOption.Suggestion); - private readonly CodeStyleOption offWithInfo = new CodeStyleOption(false, NotificationOption.Suggestion); - private readonly CodeStyleOption onWithWarning = new CodeStyleOption(true, NotificationOption.Warning); - private readonly CodeStyleOption offWithWarning = new CodeStyleOption(false, NotificationOption.Warning); - private readonly CodeStyleOption onWithError = new CodeStyleOption(true, NotificationOption.Error); - private readonly CodeStyleOption offWithError = new CodeStyleOption(false, NotificationOption.Error); + private readonly CodeStyleOption2 onWithSilent = new CodeStyleOption2(true, NotificationOption2.Silent); + private readonly CodeStyleOption2 offWithSilent = new CodeStyleOption2(false, NotificationOption2.Silent); + private readonly CodeStyleOption2 onWithInfo = new CodeStyleOption2(true, NotificationOption2.Suggestion); + private readonly CodeStyleOption2 offWithInfo = new CodeStyleOption2(false, NotificationOption2.Suggestion); + private readonly CodeStyleOption2 onWithWarning = new CodeStyleOption2(true, NotificationOption2.Warning); + private readonly CodeStyleOption2 offWithWarning = new CodeStyleOption2(false, NotificationOption2.Warning); + private readonly CodeStyleOption2 onWithError = new CodeStyleOption2(true, NotificationOption2.Error); + private readonly CodeStyleOption2 offWithError = new CodeStyleOption2(false, NotificationOption2.Error); } } diff --git a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs index 60d0604c1104e..ab45f5ed660d0 100644 --- a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs @@ -18,7 +18,8 @@ using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; -using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; +using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; +using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { diff --git a/src/EditorFeatures/CSharpTest/Squiggles/ErrorSquiggleProducerTests.cs b/src/EditorFeatures/CSharpTest/Squiggles/ErrorSquiggleProducerTests.cs index 69c821beb3337..70f6782da4af2 100644 --- a/src/EditorFeatures/CSharpTest/Squiggles/ErrorSquiggleProducerTests.cs +++ b/src/EditorFeatures/CSharpTest/Squiggles/ErrorSquiggleProducerTests.cs @@ -104,10 +104,10 @@ void Test() "; using var workspace = TestWorkspace.Create(workspaceXml); - var options = new Dictionary(); + var options = new Dictionary(); var language = workspace.Projects.Single().Language; - var preferIntrinsicPredefinedTypeOption = new OptionKey(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language); - var preferIntrinsicPredefinedTypeOptionValue = new CodeStyleOption(value: true, notification: NotificationOption.Error); + var preferIntrinsicPredefinedTypeOption = new OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language); + var preferIntrinsicPredefinedTypeOptionValue = new CodeStyleOption2(value: true, notification: NotificationOption2.Error); options.Add(preferIntrinsicPredefinedTypeOption, preferIntrinsicPredefinedTypeOptionValue); workspace.ApplyOptions(options); diff --git a/src/EditorFeatures/CSharpTest/UseAutoProperty/UseAutoPropertyTests.cs b/src/EditorFeatures/CSharpTest/UseAutoProperty/UseAutoPropertyTests.cs index 363ff2236193a..1e1e46f6f5768 100644 --- a/src/EditorFeatures/CSharpTest/UseAutoProperty/UseAutoPropertyTests.cs +++ b/src/EditorFeatures/CSharpTest/UseAutoProperty/UseAutoPropertyTests.cs @@ -2312,7 +2312,7 @@ await TestInRegularAndScriptAsync( @"public class Foo { public object O { get; } -}", options: Option(FormattingOptions.UseTabs, true)); +}", options: Option(FormattingOptions2.UseTabs, true)); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] @@ -2329,7 +2329,7 @@ await TestInRegularAndScriptAsync( @"public class Foo { public object O { get; } -}", options: Option(FormattingOptions.UseTabs, false)); +}", options: Option(FormattingOptions2.UseTabs, false)); } [WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")] diff --git a/src/EditorFeatures/CSharpTest/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs b/src/EditorFeatures/CSharpTest/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs index ffed85c5fab22..9dbc71ae08e54 100644 --- a/src/EditorFeatures/CSharpTest/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs +++ b/src/EditorFeatures/CSharpTest/UseConditionalExpression/UseConditionalExpressionForAssignmentTests.cs @@ -23,12 +23,12 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider => (new CSharpUseConditionalExpressionForAssignmentDiagnosticAnalyzer(), new CSharpUseConditionalExpressionForAssignmentCodeRefactoringProvider()); - private static readonly Dictionary s_preferImplicitTypeAlways = new Dictionary - { - { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement }, - { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement }, - { CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement }, - }; + private static readonly IDictionary s_preferImplicitTypeAlways = OptionsSet + ( + (CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement), + (CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement), + (CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement) + ); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleAssignment() @@ -496,9 +496,7 @@ void M() { var i = true ? 0 : 1; } -}", options: new Dictionary { - { CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement } -}); +}", options: Option(CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] @@ -528,9 +526,7 @@ void M() { int i = true ? 0 : 1; } -}", options: new Dictionary { - { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement } -}); +}", options: Option(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] @@ -560,9 +556,7 @@ void M() { int i = true ? 0 : 1; } -}", options: new Dictionary { - { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement } -}); +}", options: Option(CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] diff --git a/src/EditorFeatures/CSharpTest/UseExplicitTupleName/UseExplicitTupleNameTests.cs b/src/EditorFeatures/CSharpTest/UseExplicitTupleName/UseExplicitTupleNameTests.cs index d6b67c02772d8..e36299e52a9f6 100644 --- a/src/EditorFeatures/CSharpTest/UseExplicitTupleName/UseExplicitTupleNameTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExplicitTupleName/UseExplicitTupleNameTests.cs @@ -210,7 +210,7 @@ void M() (int i, string s) v1 = default((int, string)); var v2 = v1.[|Item1|]; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferExplicitTupleNames, false, NotificationOption.Warning))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] @@ -225,7 +225,7 @@ void M() (int i, string s) v1 = default((int, string)); var v2 = v1.[|i|]; } -}", new TestParameters(options: Option(CodeStyleOptions.PreferExplicitTupleNames, false, NotificationOption.Warning))); +}", new TestParameters(options: Option(CodeStyleOptions2.PreferExplicitTupleNames, false, NotificationOption2.Warning))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTupleName)] diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs index 5f248ba4f2eed..061f44d2adb34 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs @@ -21,45 +21,45 @@ public class UseExpressionBodyForAccessorsRefactoringTests : AbstractCSharpCodeA protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties => + private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => + private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None))); - private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties => + private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => + private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None))); - private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties => + private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => + private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None))); - private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties => + private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => + private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None))); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyIfPropertyWantsBlockAndAccessorWantsExpression() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs index 401c62167580d..5865b78c02e4e 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs @@ -20,17 +20,17 @@ public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCo protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs index bd539b920ee4e..347d5c51c99eb 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs @@ -20,17 +20,17 @@ public class UseExpressionBodyForConversionOperatorsRefactoringTests : AbstractC protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs index dcbe60a085f10..0e55e8bf247a2 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs @@ -21,17 +21,17 @@ public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeAc protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs index 1f4c635660321..e50577623f48e 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForLocalFunctionsRefactoringTests.cs @@ -21,17 +21,17 @@ public class UseExpressionBodyForLocalFunctionsRefactoringTests : AbstractCSharp protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + Option(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs index 1d71f8e38bdbc..1207045661bb8 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs @@ -21,17 +21,17 @@ public class UseExpressionBodyForMethodsRefactoringTests : AbstractCSharpCodeAct protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs index b55499ecaefb5..8dcabcc05e675 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs @@ -20,17 +20,17 @@ public class UseExpressionBodyForOperatorsRefactoringTests : AbstractCSharpCodeA protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)); + private IDictionary UseExpressionBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => - this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)); + private IDictionary UseBlockBodyDisabledDiagnostic => + this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs index c7ed2547924ec..23c75793852c6 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs @@ -22,45 +22,45 @@ public class UseExpressionBodyForPropertiesRefactoringTests : AbstractCSharpCode protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); - private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties => + private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => + private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None))); - private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties => + private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => + private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None))); - private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties => + private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); - private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => + private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.None))); - private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties => + private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties => OptionsSet( this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement), this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement)); - private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => + private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties_DisabledDiagnostic => OptionsSet( - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None)), - this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.None))); + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None)), + this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.None))); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs index 07369ba276011..fe2b79c7820a5 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasAnalyzerTests.cs @@ -20,10 +20,10 @@ public class UseExpressionBodyForLambdasAnalyzerTests : AbstractCSharpDiagnostic internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyForLambdaDiagnosticAnalyzer(), new UseExpressionBodyForLambdaCodeFixProvider()); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs index bb393aa21a933..bb2430d697b64 100644 --- a/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs +++ b/src/EditorFeatures/CSharpTest/UseExpressionBodyForLambda/UseExpressionBodyForLambdasRefactoringTests.cs @@ -20,16 +20,16 @@ public class UseExpressionBodyForLambdasRefactoringTests : AbstractCSharpCodeAct protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyForLambdaCodeRefactoringProvider(); - private IDictionary UseExpressionBody => + private IDictionary UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement); - private IDictionary UseExpressionBodyDisabledDiagnostic => + private IDictionary UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); - private IDictionary UseBlockBody => + private IDictionary UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement); - private IDictionary UseBlockBodyDisabledDiagnostic => + private IDictionary UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, CSharpCodeStyleOptions.NeverWithSilentEnforcement); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] diff --git a/src/EditorFeatures/CSharpTest/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs b/src/EditorFeatures/CSharpTest/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs index 6be76e712f50a..5314784c97308 100644 --- a/src/EditorFeatures/CSharpTest/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs +++ b/src/EditorFeatures/CSharpTest/UseSimpleUsingStatement/UseSimpleUsingStatementTests.cs @@ -68,7 +68,7 @@ void M() }", new TestParameters( parseOptions: CSharp8ParseOptions, - options: Option(CSharpCodeStyleOptions.PreferSimpleUsingStatement, CodeStyleOptions.FalseWithSilentEnforcement))); + options: Option(CSharpCodeStyleOptions.PreferSimpleUsingStatement, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)] diff --git a/src/EditorFeatures/CSharpTest/ValidateFormatString/ValidateFormatStringTests.cs b/src/EditorFeatures/CSharpTest/ValidateFormatString/ValidateFormatStringTests.cs index 3b83feff9d505..5ceb908e97e06 100644 --- a/src/EditorFeatures/CSharpTest/ValidateFormatString/ValidateFormatStringTests.cs +++ b/src/EditorFeatures/CSharpTest/ValidateFormatString/ValidateFormatStringTests.cs @@ -21,19 +21,19 @@ public class ValidateFormatStringTests : AbstractCSharpDiagnosticProviderBasedUs internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpValidateFormatStringDiagnosticAnalyzer(), null); - private IDictionary CSharpOptionOffVBOptionOn() + private IDictionary CSharpOptionOffVBOptionOn() { - var optionsSet = new Dictionary(); - optionsSet.Add(new OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), false); - optionsSet.Add(new OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), true); + var optionsSet = new Dictionary(); + optionsSet.Add(new OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), false); + optionsSet.Add(new OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), true); return optionsSet; } - private IDictionary CSharpOptionOnVBOptionOff() + private IDictionary CSharpOptionOnVBOptionOff() { - var optionsSet = new Dictionary(); - optionsSet.Add(new OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), true); - optionsSet.Add(new OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), false); + var optionsSet = new Dictionary(); + optionsSet.Add(new OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), true); + optionsSet.Add(new OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), false); return optionsSet; } diff --git a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs index 46778961701a6..ab3d20d61ef64 100644 --- a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs +++ b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs @@ -1199,7 +1199,7 @@ public void TestSolutionWithOptions() workspace.AddTestProject(project1); var solution = workspace.CurrentSolution; - var optionKey = new OptionKey(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); + var optionKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); var optionValue = solution.Options.GetOption(optionKey); Assert.Equal(BackgroundAnalysisScope.Default, optionValue); @@ -1233,7 +1233,7 @@ public void TestOptionChangedHandlerInvokedAfterCurrentSolutionChanged(bool test var beforeSolutionForPrimaryWorkspace = primaryWorkspace.CurrentSolution; var beforeSolutionForSecondaryWorkspace = secondaryWorkspace.CurrentSolution; - var optionKey = new OptionKey(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); + var optionKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); Assert.Equal(BackgroundAnalysisScope.Default, primaryWorkspace.Options.GetOption(optionKey)); Assert.Equal(BackgroundAnalysisScope.Default, secondaryWorkspace.Options.GetOption(optionKey)); @@ -1274,7 +1274,7 @@ static void VerifyCurrentSolutionAndOptionChange(Workspace workspace, Solution b Assert.NotEqual(beforeOptionChangedSolution, currentSolution); // Verify workspace.CurrentSolution has changed option. - var optionKey = new OptionKey(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); + var optionKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp); Assert.Equal(BackgroundAnalysisScope.Default, beforeOptionChangedSolution.Options.GetOption(optionKey)); Assert.Equal(BackgroundAnalysisScope.ActiveFile, currentSolution.Options.GetOption(optionKey)); } diff --git a/src/EditorFeatures/CSharpTest/Wrapping/AbstractWrappingTests.cs b/src/EditorFeatures/CSharpTest/Wrapping/AbstractWrappingTests.cs index 4bd05ed943c37..c4ffa69476bdc 100644 --- a/src/EditorFeatures/CSharpTest/Wrapping/AbstractWrappingTests.cs +++ b/src/EditorFeatures/CSharpTest/Wrapping/AbstractWrappingTests.cs @@ -17,10 +17,10 @@ public abstract class AbstractWrappingTests : AbstractCSharpCodeActionTest protected sealed override ImmutableArray MassageActions(ImmutableArray actions) => FlattenActions(actions); - protected static Dictionary GetIndentionColumn(int column) - => new Dictionary + private protected static Dictionary GetIndentionColumn(int column) + => new Dictionary { - { FormattingOptions.PreferredWrappingColumn, column } + { FormattingOptions2.PreferredWrappingColumn, column } }; protected Task TestAllWrappingCasesAsync( @@ -30,9 +30,9 @@ protected Task TestAllWrappingCasesAsync( return TestAllWrappingCasesAsync(input, options: null, outputs); } - protected Task TestAllWrappingCasesAsync( + private protected Task TestAllWrappingCasesAsync( string input, - IDictionary options, + IDictionary options, params string[] outputs) { var parameters = new TestParameters(options: options); diff --git a/src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs b/src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs index f2573e94e04bd..f455275932daf 100644 --- a/src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs +++ b/src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.cs @@ -19,12 +19,12 @@ public class BinaryExpressionWrappingTests : AbstractWrappingTests protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); - private IDictionary EndOfLine => Option( - CodeStyleOptions.OperatorPlacementWhenWrapping, + private IDictionary EndOfLine => Option( + CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine); - private IDictionary BeginningOfLine => Option( - CodeStyleOptions.OperatorPlacementWhenWrapping, + private IDictionary BeginningOfLine => Option( + CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine); private Task TestEndOfLine(string markup, string expected) diff --git a/src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTaggerProvider.cs b/src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTaggerProvider.cs index 5b906b38b3947..ee42039793b06 100644 --- a/src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTaggerProvider.cs +++ b/src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTaggerProvider.cs @@ -38,7 +38,7 @@ internal partial class LineSeparatorTaggerProvider : AsynchronousTaggerProvider< { private readonly IEditorFormatMap _editorFormatMap; - protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.LineSeparator); + protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.LineSeparator); private readonly object _lineSeperatorTagGate = new object(); private LineSeparatorTag _lineSeparatorTag; diff --git a/src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightingViewTaggerProvider.cs index 19691d42b0c56..d7cfd38802b7b 100644 --- a/src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightingViewTaggerProvider.cs @@ -29,7 +29,7 @@ internal class BraceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvi { private readonly IBraceMatchingService _braceMatcherService; - protected override IEnumerable> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.BraceMatching); + protected override IEnumerable> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.BraceMatching); [ImportingConstructor] public BraceHighlightingViewTaggerProvider( diff --git a/src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationViewTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationViewTaggerProvider.cs index f722e34603e0d..5f007c75959ba 100644 --- a/src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationViewTaggerProvider.cs @@ -41,7 +41,7 @@ internal partial class SemanticClassificationViewTaggerProvider : AsynchronousVi // We want to track text changes so that we can try to only reclassify a method body if // all edits were contained within one. protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.TrackTextChanges; - protected override IEnumerable> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.SemanticColorizer); + protected override IEnumerable> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.SemanticColorizer); [ImportingConstructor] public SemanticClassificationViewTaggerProvider( diff --git a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsClassificationTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsClassificationTaggerProvider.cs index 654fd3d8106d7..cb60f070c7648 100644 --- a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsClassificationTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsClassificationTaggerProvider.cs @@ -32,13 +32,13 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics [TagType(typeof(ClassificationTag))] internal partial class DiagnosticsClassificationTaggerProvider : AbstractDiagnosticsTaggerProvider { - private static readonly IEnumerable> s_tagSourceOptions = new[] { EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Classification, ServiceComponentOnOffOptions.DiagnosticProvider }; + private static readonly IEnumerable> s_tagSourceOptions = new[] { EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Classification, ServiceComponentOnOffOptions.DiagnosticProvider }; private readonly ClassificationTypeMap _typeMap; private readonly ClassificationTag _classificationTag; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; - protected override IEnumerable> Options => s_tagSourceOptions; + protected override IEnumerable> Options => s_tagSourceOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] diff --git a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSquiggleTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSquiggleTaggerProvider.cs index 4a862e37556f8..ecd38e6612ee9 100644 --- a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSquiggleTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSquiggleTaggerProvider.cs @@ -27,10 +27,10 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics [TagType(typeof(IErrorTag))] internal partial class DiagnosticsSquiggleTaggerProvider : AbstractDiagnosticsAdornmentTaggerProvider { - private static readonly IEnumerable> s_tagSourceOptions = + private static readonly IEnumerable> s_tagSourceOptions = ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles, ServiceComponentOnOffOptions.DiagnosticProvider); - protected override IEnumerable> Options => s_tagSourceOptions; + protected override IEnumerable> Options => s_tagSourceOptions; [ImportingConstructor] public DiagnosticsSquiggleTaggerProvider( diff --git a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs index cd2f705a02e9c..7019da01f8ed7 100644 --- a/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/Diagnostics/DiagnosticsSuggestionTaggerProvider.cs @@ -25,10 +25,10 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics internal partial class DiagnosticsSuggestionTaggerProvider : AbstractDiagnosticsAdornmentTaggerProvider { - private static readonly IEnumerable> s_tagSourceOptions = + private static readonly IEnumerable> s_tagSourceOptions = ImmutableArray.Create(EditorComponentOnOffOptions.Tagger, InternalFeatureOnOffOptions.Squiggles, ServiceComponentOnOffOptions.DiagnosticProvider); - protected override IEnumerable> Options => s_tagSourceOptions; + protected override IEnumerable> Options => s_tagSourceOptions; [ImportingConstructor] public DiagnosticsSuggestionTaggerProvider( diff --git a/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs b/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs index 5551e9d6abbdd..763c8934d443a 100644 --- a/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.cs @@ -36,7 +36,7 @@ internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; - protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); + protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] public HighlighterViewTaggerProvider( diff --git a/src/EditorFeatures/Core/Options/ColorSchemeOptions.cs b/src/EditorFeatures/Core/Options/ColorSchemeOptions.cs index 3fe264ebee704..c037a24d8d9e7 100644 --- a/src/EditorFeatures/Core/Options/ColorSchemeOptions.cs +++ b/src/EditorFeatures/Core/Options/ColorSchemeOptions.cs @@ -14,12 +14,12 @@ internal static class ColorSchemeOptions { internal const string ColorSchemeSettingKey = "TextEditor.Roslyn.ColorScheme"; - public static readonly Option ColorScheme = new Option(nameof(ColorSchemeOptions), + public static readonly Option2 ColorScheme = new Option2(nameof(ColorSchemeOptions), nameof(ColorScheme), defaultValue: SchemeName.VisualStudio2019, storageLocations: new RoamingProfileStorageLocation(ColorSchemeSettingKey)); - public static readonly Option LegacyUseEnhancedColors = new Option(nameof(ColorSchemeOptions), + public static readonly Option2 LegacyUseEnhancedColors = new Option2(nameof(ColorSchemeOptions), nameof(LegacyUseEnhancedColors), defaultValue: UseEnhancedColors.Default, storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages")); diff --git a/src/EditorFeatures/Core/Options/SignatureHelpOptions.cs b/src/EditorFeatures/Core/Options/SignatureHelpOptions.cs index 8b75733da6d85..b46504da12c01 100644 --- a/src/EditorFeatures/Core/Options/SignatureHelpOptions.cs +++ b/src/EditorFeatures/Core/Options/SignatureHelpOptions.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Editor.Options { internal static class SignatureHelpOptions { - public static readonly PerLanguageOption ShowSignatureHelp = new PerLanguageOption(nameof(SignatureHelpOptions), nameof(ShowSignatureHelp), defaultValue: true); + public static readonly PerLanguageOption2 ShowSignatureHelp = new PerLanguageOption2(nameof(SignatureHelpOptions), nameof(ShowSignatureHelp), defaultValue: true); } [ExportOptionProvider, Shared] diff --git a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs index f208cfef1eecb..9982e8eaf4f3c 100644 --- a/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs +++ b/src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.cs @@ -42,7 +42,7 @@ internal partial class ReferenceHighlightingViewTaggerProvider : AsynchronousVie // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; - protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.ReferenceHighlighting); + protected override IEnumerable> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.ReferenceHighlighting); [ImportingConstructor] public ReferenceHighlightingViewTaggerProvider( diff --git a/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs b/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs index 087a9242ae282..77a01574710a1 100644 --- a/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs +++ b/src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs @@ -14,7 +14,7 @@ namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextBufferExtensions { - internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option option) + internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option2 option) { var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); @@ -26,7 +26,7 @@ internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option return option.DefaultValue; } - internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption option) + internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption2 option) { // Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is. try diff --git a/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs index 6504c965447da..8bd1670a46215 100644 --- a/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs +++ b/src/EditorFeatures/Core/Shared/Options/ComponentOnOffOptions.cs @@ -16,16 +16,16 @@ internal static class EditorComponentOnOffOptions { private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Components\"; - public static readonly Option Adornment = new Option(nameof(EditorComponentOnOffOptions), nameof(Adornment), defaultValue: true, + public static readonly Option2 Adornment = new Option2(nameof(EditorComponentOnOffOptions), nameof(Adornment), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Adornment")); - public static readonly Option Tagger = new Option(nameof(EditorComponentOnOffOptions), nameof(Tagger), defaultValue: true, + public static readonly Option2 Tagger = new Option2(nameof(EditorComponentOnOffOptions), nameof(Tagger), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Tagger")); - public static readonly Option CodeRefactorings = new Option(nameof(EditorComponentOnOffOptions), nameof(CodeRefactorings), defaultValue: true, + public static readonly Option2 CodeRefactorings = new Option2(nameof(EditorComponentOnOffOptions), nameof(CodeRefactorings), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Code Refactorings")); - public static readonly Option ShowCodeRefactoringsWhenQueriedForCodeFixes = new Option( + public static readonly Option2 ShowCodeRefactoringsWhenQueriedForCodeFixes = new Option2( nameof(EditorComponentOnOffOptions), nameof(ShowCodeRefactoringsWhenQueriedForCodeFixes), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ShowCodeRefactoringsWhenQueriedForCodeFixes))); } diff --git a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs index b8749491390a9..d7e2354361720 100644 --- a/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs +++ b/src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs @@ -13,50 +13,50 @@ namespace Microsoft.CodeAnalysis.Editor.Shared.Options { internal static class FeatureOnOffOptions { - public static readonly PerLanguageOption EndConstruct = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true, + public static readonly PerLanguageOption2 EndConstruct = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert")); // This value is only used by Visual Basic, and so is using the old serialization name that was used by VB. - public static readonly PerLanguageOption AutomaticInsertionOfAbstractOrInterfaceMembers = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true, + public static readonly PerLanguageOption2 AutomaticInsertionOfAbstractOrInterfaceMembers = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert")); - public static readonly PerLanguageOption LineSeparator = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false, + public static readonly PerLanguageOption2 LineSeparator = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator")); - public static readonly PerLanguageOption Outlining = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true, + public static readonly PerLanguageOption2 Outlining = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining")); - public static readonly PerLanguageOption KeywordHighlighting = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true, + public static readonly PerLanguageOption2 KeywordHighlighting = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting")); - public static readonly PerLanguageOption ReferenceHighlighting = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true, + public static readonly PerLanguageOption2 ReferenceHighlighting = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting")); - public static readonly PerLanguageOption FormatOnPaste = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(FormatOnPaste), defaultValue: true, + public static readonly PerLanguageOption2 FormatOnPaste = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(FormatOnPaste), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.FormatOnPaste")); - public static readonly PerLanguageOption AutoXmlDocCommentGeneration = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, + public static readonly PerLanguageOption2 AutoXmlDocCommentGeneration = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation")); - public static readonly PerLanguageOption AutoInsertBlockCommentStartString = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true, + public static readonly PerLanguageOption2 AutoInsertBlockCommentStartString = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String")); - public static readonly PerLanguageOption PrettyListing = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true, + public static readonly PerLanguageOption2 PrettyListing = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing")); - public static readonly PerLanguageOption AutoFormattingOnTyping = new PerLanguageOption( + public static readonly PerLanguageOption2 AutoFormattingOnTyping = new PerLanguageOption2( nameof(FeatureOnOffOptions), nameof(AutoFormattingOnTyping), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Typing")); - public static readonly PerLanguageOption AutoFormattingOnCloseBrace = new PerLanguageOption( + public static readonly PerLanguageOption2 AutoFormattingOnCloseBrace = new PerLanguageOption2( nameof(FeatureOnOffOptions), nameof(AutoFormattingOnCloseBrace), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Close Brace")); - public static readonly PerLanguageOption AutoFormattingOnSemicolon = new PerLanguageOption( + public static readonly PerLanguageOption2 AutoFormattingOnSemicolon = new PerLanguageOption2( nameof(FeatureOnOffOptions), nameof(AutoFormattingOnSemicolon), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Semicolon")); - public static readonly PerLanguageOption RenameTrackingPreview = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true, + public static readonly PerLanguageOption2 RenameTrackingPreview = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true, storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview")); /// @@ -65,7 +65,7 @@ internal static class FeatureOnOffOptions /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// - public static readonly PerLanguageOption RenameTracking = new PerLanguageOption(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true); + public static readonly PerLanguageOption2 RenameTracking = new PerLanguageOption2(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true); /// /// This option is currently used by Roslyn, but we might want to implement it in the @@ -73,22 +73,22 @@ internal static class FeatureOnOffOptions /// maintain any customized value for this setting, even through versions that have not /// implemented this feature yet. /// - public static readonly PerLanguageOption RefactoringVerification = new PerLanguageOption( + public static readonly PerLanguageOption2 RefactoringVerification = new PerLanguageOption2( nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false); - public static readonly PerLanguageOption StreamingGoToImplementation = new PerLanguageOption( + public static readonly PerLanguageOption2 StreamingGoToImplementation = new PerLanguageOption2( nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true); - public static readonly Option NavigateToDecompiledSources = new Option( + public static readonly Option2 NavigateToDecompiledSources = new Option2( nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}")); - public static readonly Option UseEnhancedColors = new Option( + public static readonly Option2 UseEnhancedColors = new Option2( nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1, storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages")); // Note: no storage location since this is intentionally a session variable - public static readonly Option AcceptedDecompilerDisclaimer = new Option( + public static readonly Option2 AcceptedDecompilerDisclaimer = new Option2( nameof(FeatureOnOffOptions), nameof(AcceptedDecompilerDisclaimer), defaultValue: false); } diff --git a/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs b/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs index 464db3f939515..c8dd6396eecb7 100644 --- a/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs +++ b/src/EditorFeatures/Core/Shared/Options/InternalFeatureOnOffOptions.cs @@ -13,63 +13,63 @@ internal static class InternalFeatureOnOffOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; - public static readonly Option BraceMatching = new Option(nameof(InternalFeatureOnOffOptions), nameof(BraceMatching), defaultValue: true, + public static readonly Option2 BraceMatching = new Option2(nameof(InternalFeatureOnOffOptions), nameof(BraceMatching), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Brace Matching")); - public static readonly Option Classification = new Option(nameof(InternalFeatureOnOffOptions), nameof(Classification), defaultValue: true, + public static readonly Option2 Classification = new Option2(nameof(InternalFeatureOnOffOptions), nameof(Classification), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Classification")); - public static readonly Option SemanticColorizer = new Option(nameof(InternalFeatureOnOffOptions), nameof(SemanticColorizer), defaultValue: true, + public static readonly Option2 SemanticColorizer = new Option2(nameof(InternalFeatureOnOffOptions), nameof(SemanticColorizer), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Semantic Colorizer")); - public static readonly Option SyntacticColorizer = new Option(nameof(InternalFeatureOnOffOptions), nameof(SyntacticColorizer), defaultValue: true, + public static readonly Option2 SyntacticColorizer = new Option2(nameof(InternalFeatureOnOffOptions), nameof(SyntacticColorizer), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Syntactic Colorizer")); - public static readonly Option AutomaticPairCompletion = new Option(nameof(InternalFeatureOnOffOptions), nameof(AutomaticPairCompletion), defaultValue: true, + public static readonly Option2 AutomaticPairCompletion = new Option2(nameof(InternalFeatureOnOffOptions), nameof(AutomaticPairCompletion), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Pair Completion")); - public static readonly Option AutomaticLineEnder = new Option(nameof(InternalFeatureOnOffOptions), nameof(AutomaticLineEnder), defaultValue: true, + public static readonly Option2 AutomaticLineEnder = new Option2(nameof(InternalFeatureOnOffOptions), nameof(AutomaticLineEnder), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Automatic Line Ender")); - public static readonly Option SmartIndenter = new Option(nameof(InternalFeatureOnOffOptions), nameof(SmartIndenter), defaultValue: true, + public static readonly Option2 SmartIndenter = new Option2(nameof(InternalFeatureOnOffOptions), nameof(SmartIndenter), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Smart Indenter")); - public static readonly Option CompletionSet = new Option(nameof(InternalFeatureOnOffOptions), nameof(CompletionSet), defaultValue: true, + public static readonly Option2 CompletionSet = new Option2(nameof(InternalFeatureOnOffOptions), nameof(CompletionSet), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Completion Set")); - public static readonly Option KeywordHighlight = new Option(nameof(InternalFeatureOnOffOptions), nameof(KeywordHighlight), defaultValue: true, + public static readonly Option2 KeywordHighlight = new Option2(nameof(InternalFeatureOnOffOptions), nameof(KeywordHighlight), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Keyword Highlight")); - public static readonly Option QuickInfo = new Option(nameof(InternalFeatureOnOffOptions), nameof(QuickInfo), defaultValue: true, + public static readonly Option2 QuickInfo = new Option2(nameof(InternalFeatureOnOffOptions), nameof(QuickInfo), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Quick Info")); - public static readonly Option Squiggles = new Option(nameof(InternalFeatureOnOffOptions), nameof(Squiggles), defaultValue: true, + public static readonly Option2 Squiggles = new Option2(nameof(InternalFeatureOnOffOptions), nameof(Squiggles), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Squiggles")); - public static readonly Option FormatOnSave = new Option(nameof(InternalFeatureOnOffOptions), nameof(FormatOnSave), defaultValue: true, + public static readonly Option2 FormatOnSave = new Option2(nameof(InternalFeatureOnOffOptions), nameof(FormatOnSave), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "FormatOnSave")); - public static readonly Option RenameTracking = new Option(nameof(InternalFeatureOnOffOptions), nameof(RenameTracking), defaultValue: true, + public static readonly Option2 RenameTracking = new Option2(nameof(InternalFeatureOnOffOptions), nameof(RenameTracking), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Rename Tracking")); - public static readonly Option EventHookup = new Option(nameof(InternalFeatureOnOffOptions), nameof(EventHookup), defaultValue: true, + public static readonly Option2 EventHookup = new Option2(nameof(InternalFeatureOnOffOptions), nameof(EventHookup), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Event Hookup")); /// Due to https://github.com/dotnet/roslyn/issues/5393, the name "Snippets" is unusable for serialization. /// (Summary: Some builds incorrectly set it without providing a way to clear it so it exists in many registries.) - public static readonly Option Snippets = new Option(nameof(InternalFeatureOnOffOptions), nameof(Snippets), defaultValue: true, + public static readonly Option2 Snippets = new Option2(nameof(InternalFeatureOnOffOptions), nameof(Snippets), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Snippets2")); - public static readonly Option TodoComments = new Option(nameof(InternalFeatureOnOffOptions), nameof(TodoComments), defaultValue: true, + public static readonly Option2 TodoComments = new Option2(nameof(InternalFeatureOnOffOptions), nameof(TodoComments), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Todo Comments")); - public static readonly Option DesignerAttributes = new Option(nameof(InternalFeatureOnOffOptions), nameof(DesignerAttributes), defaultValue: true, + public static readonly Option2 DesignerAttributes = new Option2(nameof(InternalFeatureOnOffOptions), nameof(DesignerAttributes), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Designer Attribute")); - public static readonly Option BackgroundAnalysisMemoryMonitor = new Option(nameof(InternalFeatureOnOffOptions), "FullSolutionAnalysisMemoryMonitor", defaultValue: true, + public static readonly Option2 BackgroundAnalysisMemoryMonitor = new Option2(nameof(InternalFeatureOnOffOptions), "FullSolutionAnalysisMemoryMonitor", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Full Solution Analysis Memory Monitor")); - public static readonly Option ProjectReferenceConversion = new Option(nameof(InternalFeatureOnOffOptions), nameof(ProjectReferenceConversion), defaultValue: true, + public static readonly Option2 ProjectReferenceConversion = new Option2(nameof(InternalFeatureOnOffOptions), nameof(ProjectReferenceConversion), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project Reference Conversion")); } diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs index b3915702212bf..0ca760978fb75 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs @@ -473,8 +473,8 @@ private async Task RecomputeTagsAsync( private bool ShouldSkipTagProduction() { - var options = _dataSource.Options ?? SpecializedCollections.EmptyEnumerable>(); - var perLanguageOptions = _dataSource.PerLanguageOptions ?? SpecializedCollections.EmptyEnumerable>(); + var options = _dataSource.Options ?? SpecializedCollections.EmptyEnumerable>(); + var perLanguageOptions = _dataSource.PerLanguageOptions ?? SpecializedCollections.EmptyEnumerable>(); return options.Any(option => !_subjectBuffer.GetFeatureOnOffOption(option)) || perLanguageOptions.Any(option => !_subjectBuffer.GetFeatureOnOffOption(option)); diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs index e45d5ff0b56d1..127a78dce90bb 100644 --- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs +++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.cs @@ -71,8 +71,8 @@ internal abstract partial class AbstractAsynchronousTaggerProvider : Foreg /// An empty enumerable, or null, can be returned to indicate that this tagger should /// run unconditionally. /// - protected virtual IEnumerable> Options => SpecializedCollections.EmptyEnumerable>(); - protected virtual IEnumerable> PerLanguageOptions => SpecializedCollections.EmptyEnumerable>(); + protected virtual IEnumerable> Options => SpecializedCollections.EmptyEnumerable>(); + protected virtual IEnumerable> PerLanguageOptions => SpecializedCollections.EmptyEnumerable>(); /// /// This controls what delay tagger will use to let editor know about newly inserted tags diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.IOptionsCollection.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.IOptionsCollection.cs new file mode 100644 index 0000000000000..a25b4f212b9b8 --- /dev/null +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.IOptionsCollection.cs @@ -0,0 +1,16 @@ +// 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.Collections.Generic; +using Microsoft.CodeAnalysis.Options; + +namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +{ + public abstract partial class AbstractCodeActionOrUserDiagnosticTest + { + internal interface IOptionsCollection : IDictionary + { + } + } +} diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.OptionsDictionary.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.OptionsDictionary.cs new file mode 100644 index 0000000000000..8b69ad639ee2f --- /dev/null +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.OptionsDictionary.cs @@ -0,0 +1,95 @@ +// 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.Generic; +using System.Collections.Immutable; +using System.Linq; +using Roslyn.Utilities; +using Microsoft.CodeAnalysis.Options; +using System.Collections; + +namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +{ + public abstract partial class AbstractCodeActionOrUserDiagnosticTest + { + internal sealed class OptionsDictionary : IOptionsCollection + { + private readonly Dictionary _map; + public OptionsDictionary(params (OptionKey2 key, object value)[] options) + { + _map = new Dictionary(); + foreach (var option in options) + { + Add(option.key, option.value); + } + } + + public object this[OptionKey2 key] { get => _map[key]; set => _map[key] = value; } + + public ICollection Keys => _map.Keys; + + public ICollection Values => _map.Values; + + public int Count => _map.Count; + + public bool IsReadOnly => false; + + public void Add(OptionKey2 key, object value) + { + _map.Add(key, value); + } + + public void Add(KeyValuePair item) + { + _map.Add(item.Key, item.Value); + } + + public void Clear() + { + _map.Clear(); + } + + public bool Contains(KeyValuePair item) + { + return _map.Contains(item); + } + + public bool ContainsKey(OptionKey2 key) + { + return _map.ContainsKey(key); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + public IEnumerator> GetEnumerator() + { + return _map.GetEnumerator(); + } + + public bool Remove(OptionKey2 key) + { + return _map.Remove(key); + } + + public bool Remove(KeyValuePair item) + { + return _map.Remove(item.Key); + } + + public bool TryGetValue(OptionKey2 key, out object value) + { + return _map.TryGetValue(key, out value); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return _map.GetEnumerator(); + } + } + } +} diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs index 32689aabca54e..16346caa0b26d 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs @@ -5,16 +5,12 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; -using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; -using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; @@ -25,11 +21,12 @@ using Xunit; #if CODE_STYLE -using EditorConfigFileGenerator = Microsoft.CodeAnalysis.Options.EditorConfigFileGenerator; -using Microsoft.CodeAnalysis.Internal.Options; +using System.Diagnostics; +using System.IO; +using TestParametersOptions = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.IOptionsCollection; #else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; +using TestParametersOptions = System.Collections.Generic.IDictionary; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions @@ -39,7 +36,7 @@ public abstract partial class AbstractCodeActionOrUserDiagnosticTest { public struct TestParameters { - internal readonly IDictionary options; + internal readonly TestParametersOptions options; internal readonly object fixProviderData; internal readonly ParseOptions parseOptions; internal readonly CompilationOptions compilationOptions; @@ -52,7 +49,7 @@ public struct TestParameters internal TestParameters( ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, - IDictionary options = null, + TestParametersOptions options = null, object fixProviderData = null, int index = 0, CodeActionPriority? priority = null, @@ -74,7 +71,7 @@ internal TestParameters( public TestParameters WithParseOptions(ParseOptions parseOptions) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title); - public TestParameters WithOptions(IDictionary options) + internal TestParameters WithOptions(TestParametersOptions options) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title); public TestParameters WithFixProviderData(object fixProviderData) @@ -122,6 +119,7 @@ protected TestWorkspace CreateWorkspaceFromOptions( return workspace; } +#if CODE_STYLE private static void MakeProjectsAndDocumentsRooted(TestWorkspace workspace) { const string defaultRootFilePath = @"z:\"; @@ -160,7 +158,7 @@ private static void MakeProjectsAndDocumentsRooted(TestWorkspace workspace) return; } - private static void AddAnalyzerConfigDocumentWithOptions(TestWorkspace workspace, IDictionary options) + private void AddAnalyzerConfigDocumentWithOptions(TestWorkspace workspace, TestParametersOptions options) { Debug.Assert(options != null); var analyzerConfigText = GenerateAnalyzerConfigText(options); @@ -182,60 +180,18 @@ private static void AddAnalyzerConfigDocumentWithOptions(TestWorkspace workspace Assert.True(applied); return; - static string GenerateAnalyzerConfigText(IDictionary options) + string GenerateAnalyzerConfigText(TestParametersOptions options) { var textBuilder = new StringBuilder(); // Add an auto-generated header at the top so we can skip this file in expected baseline validation. textBuilder.AppendLine(AutoGeneratedAnalyzerConfigHeader); textBuilder.AppendLine(); - - foreach (var (optionKey, value) in options) - { - foreach (var location in optionKey.Option.StorageLocations) - { - if (location is IEditorConfigStorageLocation2 editorConfigStorageLocation) - { - var editorConfigString = editorConfigStorageLocation.GetEditorConfigString(value, null); - if (editorConfigString != null) - { - textBuilder.AppendLine(GetSectionHeader(optionKey)); - textBuilder.AppendLine(editorConfigString); - textBuilder.AppendLine(); - break; - } - - Assert.False(true, "Unexpected non-editorconfig option"); - } - else if (value is NamingStylePreferences namingStylePreferences) - { - textBuilder.AppendLine(GetSectionHeader(optionKey)); - EditorConfigFileGenerator.AppendNamingStylePreferencesToEditorConfig(namingStylePreferences, optionKey.Language, textBuilder); - textBuilder.AppendLine(); - break; - } - } - } - + textBuilder.AppendLine(options.GetEditorConfigText()); return textBuilder.ToString(); - - static string GetSectionHeader(OptionKey optionKey) - { - if (optionKey.Option.IsPerLanguage) - { - switch (optionKey.Language) - { - case LanguageNames.CSharp: - return "[*.cs]"; - case LanguageNames.VisualBasic: - return "[*.vb]"; - } - } - - return "[*]"; - } } } +#endif protected abstract TestWorkspace CreateWorkspaceFromFile(string initialMarkup, TestParameters parameters); @@ -345,7 +301,7 @@ internal Task TestInRegularAndScriptAsync( int index = 0, CodeActionPriority? priority = null, CompilationOptions compilationOptions = null, - IDictionary options = null, + TestParametersOptions options = null, object fixProviderData = null, ParseOptions parseOptions = null, string title = null) @@ -370,7 +326,7 @@ internal Task TestAsync( string initialMarkup, string expectedMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions = null, - int index = 0, IDictionary options = null, + int index = 0, TestParametersOptions options = null, object fixProviderData = null, CodeActionPriority? priority = null) { @@ -726,56 +682,7 @@ protected static ImmutableArray FlattenActions(ImmutableArray GetNestedActions(ImmutableArray codeActions) => codeActions.SelectMany(a => a.NestedCodeActions).ToImmutableArray(); - internal (OptionKey, object) SingleOption(Option option, T enabled) - => (new OptionKey(option), enabled); - - protected (OptionKey, object) SingleOption(PerLanguageOption option, T value) - => (new OptionKey(option, this.GetLanguage()), value); - - protected (OptionKey, object) SingleOption(Option> option, T enabled, NotificationOption notification) - => SingleOption(option, new CodeStyleOption(enabled, notification)); - - protected (OptionKey, object) SingleOption(Option> option, CodeStyleOption codeStyle) - => (new OptionKey(option), codeStyle); - - protected (OptionKey, object) SingleOption(PerLanguageOption> option, T enabled, NotificationOption notification) - => SingleOption(option, new CodeStyleOption(enabled, notification)); - - protected (OptionKey, object) SingleOption(PerLanguageOption> option, CodeStyleOption codeStyle) - => SingleOption(option, codeStyle, language: GetLanguage()); - - protected static (OptionKey, object) SingleOption(PerLanguageOption> option, CodeStyleOption codeStyle, string language) - => (new OptionKey(option, language), codeStyle); - - protected IDictionary Option(Option> option, T enabled, NotificationOption notification) - => OptionsSet(SingleOption(option, enabled, notification)); - protected IDictionary Option(Option> option, CodeStyleOption codeStyle) - => OptionsSet(SingleOption(option, codeStyle)); - - protected IDictionary Option(PerLanguageOption> option, T enabled, NotificationOption notification) - => OptionsSet(SingleOption(option, enabled, notification)); - - protected IDictionary Option(Option option, T value) - => OptionsSet(SingleOption(option, value)); - - protected IDictionary Option(PerLanguageOption option, T value) - => OptionsSet(SingleOption(option, value)); - - protected IDictionary Option(PerLanguageOption> option, CodeStyleOption codeStyle) - => OptionsSet(SingleOption(option, codeStyle)); - - internal static IDictionary OptionsSet( - params (OptionKey key, object value)[] options) - { - var result = new Dictionary(); - foreach (var option in options) - { - result.Add(option.key, option.value); - } - - return result; - } /// /// Tests all the code actions for the given string. Each code diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_OptionHelpers.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_OptionHelpers.cs new file mode 100644 index 0000000000000..72e9ed47ac66e --- /dev/null +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_OptionHelpers.cs @@ -0,0 +1,57 @@ +// 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; +using Microsoft.CodeAnalysis.CodeStyle; + +namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions +{ + public abstract partial class AbstractCodeActionOrUserDiagnosticTest + { + internal (OptionKey2, object) SingleOption(Option2 option, T enabled) + => (new OptionKey2(option), enabled); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2 option, T value) + => (new OptionKey2(option, this.GetLanguage()), value); + + internal (OptionKey2, object) SingleOption(Option2> option, T enabled, NotificationOption2 notification) + => (new OptionKey2(option), new CodeStyleOption2(enabled, notification)); + + internal (OptionKey2, object) SingleOption(Option2> option, CodeStyleOption2 codeStyle) + => (new OptionKey2(option), codeStyle); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2> option, T enabled, NotificationOption2 notification) + => (new OptionKey2(option, this.GetLanguage()), new CodeStyleOption2(enabled, notification)); + + internal (OptionKey2, object) SingleOption(PerLanguageOption2> option, CodeStyleOption2 codeStyle) + => (new OptionKey2(option, this.GetLanguage()), codeStyle); + + internal static (OptionKey2, object) SingleOption(PerLanguageOption2> option, CodeStyleOption2 codeStyle, string language) + => (new OptionKey2(option, language), codeStyle); + + internal IOptionsCollection Option(Option2> option, T enabled, NotificationOption2 notification) + => OptionsSet(SingleOption(option, enabled, notification)); + + internal IOptionsCollection Option(Option2> option, CodeStyleOption2 codeStyle) + => OptionsSet(SingleOption(option, codeStyle)); + + internal IOptionsCollection Option(PerLanguageOption2> option, T enabled, NotificationOption2 notification) + => OptionsSet(SingleOption(option, enabled, notification)); + + internal IOptionsCollection Option(Option2 option, T value) + => OptionsSet(SingleOption(option, value)); + + internal IOptionsCollection Option(PerLanguageOption2 option, T value) + => OptionsSet(SingleOption(option, value)); + + internal IOptionsCollection Option(PerLanguageOption2> option, CodeStyleOption2 codeStyle) + => OptionsSet(SingleOption(option, codeStyle)); + + internal IOptionsCollection OptionsSet(OptionKey2 option, object value) + => OptionsSet((option, value)); + + internal static IOptionsCollection OptionsSet(params (OptionKey2 key, object value)[] options) + => new OptionsDictionary(options); + } +} diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs index c98adf1ba1a0b..24a543c9b84b2 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CSharpCodeFixVerifier`2+Test.cs @@ -37,10 +37,10 @@ public Test() SolutionTransforms.Add((solution, projectId) => { - var parseOptions = (CSharpParseOptions)solution.GetRequiredProject(projectId).ParseOptions!; + var parseOptions = (CSharpParseOptions)solution.GetProject(projectId)!.ParseOptions!; solution = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion)); - var compilationOptions = solution.GetRequiredProject(projectId).CompilationOptions!; + var compilationOptions = solution.GetProject(projectId)!.CompilationOptions!; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(compilationOptions.SpecificDiagnosticOptions.SetItems(s_nullableWarnings)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions); @@ -92,7 +92,7 @@ private static ImmutableDictionary GetNullableWarnings /// Gets a collection of options to apply to for testing. Values may be added /// using a collection initializer. /// - public OptionsCollection Options { get; } = new OptionsCollection(LanguageNames.CSharp); + internal OptionsCollection Options { get; } = new OptionsCollection(LanguageNames.CSharp); public string? EditorConfig { get; set; } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CodeFixVerifierHelper.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CodeFixVerifierHelper.cs index a811ee1686ff4..96294b4cb55e4 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CodeFixVerifierHelper.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/CodeFixVerifierHelper.cs @@ -9,17 +9,12 @@ using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; -#if CODE_STYLE -using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { internal static class CodeFixVerifierHelper @@ -87,7 +82,7 @@ private static void VerifyMessageHelpLinkUri(DiagnosticAnalyzer analyzer) } } - public static (SourceText? analyzerConfig, IEnumerable> options) ConvertOptionsToAnalyzerConfig(string defaultFileExtension, string? explicitEditorConfig, OptionsCollection options) + public static (SourceText? analyzerConfig, IEnumerable> options) ConvertOptionsToAnalyzerConfig(string defaultFileExtension, string? explicitEditorConfig, OptionsCollection options) { if (options.Count == 0) { @@ -95,8 +90,7 @@ public static (SourceText? analyzerConfig, IEnumerable, OptionKey, object?>(option => option.Key, option => option.Value)); - var remainingOptions = new List>(); + var remainingOptions = new List>(); var analyzerConfig = new StringBuilder(); if (explicitEditorConfig is object) @@ -112,51 +106,23 @@ public static (SourceText? analyzerConfig, IEnumerable().FirstOrDefault(); - if (editorConfigStorageLocation is null) + if (value is NamingStylePreferences namingStylePreferences) { - remainingOptions.Add(KeyValuePairUtil.Create(key, value)); + EditorConfigFileGenerator.AppendNamingStylePreferencesToEditorConfig(namingStylePreferences, key.Language!, analyzerConfig); continue; } - analyzerConfig.AppendLine(editorConfigStorageLocation.GetEditorConfigString(value, optionSet)); - } - - return (SourceText.From(analyzerConfig.ToString(), Encoding.UTF8), remainingOptions); - } - - private sealed class OptionSetWrapper : OptionSet - { - private readonly Dictionary _options; - - public OptionSetWrapper(Dictionary options) - { - _options = options; - } - -#if CODE_STYLE - public override bool TryGetValue(string key, out string value) - { - throw new NotImplementedException(); - } -#else - public override object? GetOption(OptionKey optionKey) - { - if (!_options.TryGetValue(optionKey, out var value)) + var editorConfigStorageLocation = key.Option.StorageLocations.OfType().FirstOrDefault(); + if (editorConfigStorageLocation is null) { - value = optionKey.Option.DefaultValue; + remainingOptions.Add(KeyValuePairUtil.Create(key, value)); + continue; } - return value; + analyzerConfig.AppendLine(editorConfigStorageLocation.GetEditorConfigString(value, null!)); } - public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) - => throw new NotSupportedException(); - - internal override IEnumerable GetChangedOptions(OptionSet optionSet) - => SpecializedCollections.EmptyEnumerable(); - -#endif + return (SourceText.From(analyzerConfig.ToString(), Encoding.UTF8), remainingOptions); } } } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/OptionsCollection.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/OptionsCollection.cs index 71f7e817983c8..21d1ebab6358a 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/OptionsCollection.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/OptionsCollection.cs @@ -4,47 +4,69 @@ using System.Collections; using System.Collections.Generic; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; -#endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { - public sealed class OptionsCollection : IReadOnlyCollection> +#if CODE_STYLE + internal interface IOptionsCollection : IReadOnlyCollection> + { + string GetEditorConfigText(); + } +#endif + + internal sealed class OptionsCollection : IReadOnlyCollection> +#if CODE_STYLE + , IOptionsCollection +#endif { - private readonly Dictionary _options = new Dictionary(); + private readonly Dictionary _options = new Dictionary(); private readonly string _languageName; + private readonly string _defaultExtension; - public OptionsCollection(string languageName) + public OptionsCollection(string languageName, params (OptionKey2 key, object value)[] options) { _languageName = languageName; + _defaultExtension = languageName == LanguageNames.CSharp ? "cs" : "vb"; + + foreach (var (key, value) in options) + { + Add(key, value); + } + } public int Count => _options.Count; - public void Add(Option option, T value) - => _options.Add(new OptionKey(option), value); + public void Add(Option2 option, T value) + => _options.Add(new OptionKey2(option), value); - public void Add(Option> option, T value, NotificationOption notification) - => _options.Add(new OptionKey(option), new CodeStyleOption(value, notification)); + public void Add(Option2> option, T value, NotificationOption2 notification) + => _options.Add(new OptionKey2(option), new CodeStyleOption2(value, notification)); - public void Add(PerLanguageOption option, T value) - => _options.Add(new OptionKey(option, _languageName), value); + public void Add(PerLanguageOption2 option, T value) + => _options.Add(new OptionKey2(option, _languageName), value); - public void Add(PerLanguageOption> option, T value) + public void Add(PerLanguageOption2> option, T value) => Add(option, value, option.DefaultValue.Notification); - public void Add(PerLanguageOption> option, T value, NotificationOption notification) - => _options.Add(new OptionKey(option, _languageName), new CodeStyleOption(value, notification)); + public void Add(PerLanguageOption2> option, T value, NotificationOption2 notification) + => _options.Add(new OptionKey2(option, _languageName), new CodeStyleOption2(value, notification)); - public IEnumerator> GetEnumerator() + public void Add(OptionKey2 optionKey, T value) + => _options.Add(optionKey, value); + + public IEnumerator> GetEnumerator() => _options.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public string GetEditorConfigText() + { + var (text, _) = CodeFixVerifierHelper.ConvertOptionsToAnalyzerConfig(_defaultExtension, explicitEditorConfig: string.Empty, this); + return text.ToString(); + } } } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2+Test.cs b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2+Test.cs index 8daab14b945d1..ae2a26c16d481 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2+Test.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2+Test.cs @@ -8,7 +8,6 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Testing; @@ -28,7 +27,7 @@ public Test() SolutionTransforms.Add((solution, projectId) => { - var parseOptions = (VisualBasicParseOptions)solution.GetRequiredProject(projectId).ParseOptions!; + var parseOptions = (VisualBasicParseOptions)solution.GetProject(projectId)!.ParseOptions!; solution = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion)); var (analyzerConfigSource, remainingOptions) = CodeFixVerifierHelper.ConvertOptionsToAnalyzerConfig(DefaultFileExt, EditorConfig, Options); @@ -65,7 +64,7 @@ public Test() /// Gets a collection of options to apply to for testing. Values may be added /// using a collection initializer. /// - public OptionsCollection Options { get; } = new OptionsCollection(LanguageNames.VisualBasic); + internal OptionsCollection Options { get; } = new OptionsCollection(LanguageNames.VisualBasic); public string? EditorConfig { get; set; } diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs index 1b9c99e47a051..9eda24525ad95 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; @@ -17,14 +18,14 @@ using Roslyn.Utilities; using Xunit; +namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics +{ #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; + using TestParametersOptions = IOptionsCollection; #else -using Microsoft.CodeAnalysis.Options; + using TestParametersOptions = IDictionary; #endif -namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -{ public abstract partial class AbstractDiagnosticProviderBasedUserDiagnosticTest : AbstractUserDiagnosticTest { private readonly ConcurrentDictionary _analyzerAndFixerMap = @@ -172,9 +173,9 @@ internal async override Task> GetDiagnosticsAsync( return (resultDiagnostics, codeActions, actionToInvoke); } - protected async Task TestDiagnosticInfoAsync( + private protected async Task TestDiagnosticInfoAsync( string initialMarkup, - IDictionary options, + TestParametersOptions options, string diagnosticId, DiagnosticSeverity diagnosticSeverity, LocalizableString diagnosticMessage = null) @@ -183,11 +184,11 @@ protected async Task TestDiagnosticInfoAsync( await TestDiagnosticInfoAsync(initialMarkup, GetScriptOptions(), null, options, diagnosticId, diagnosticSeverity, diagnosticMessage); } - protected async Task TestDiagnosticInfoAsync( + private protected async Task TestDiagnosticInfoAsync( string initialMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions, - IDictionary options, + TestParametersOptions options, string diagnosticId, DiagnosticSeverity diagnosticSeverity, LocalizableString diagnosticMessage = null) diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest_ParenthesesOptions.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest_ParenthesesOptions.cs index f8c83823fc3c1..cec30e1519192 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest_ParenthesesOptions.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractDiagnosticProviderBasedUserDiagnosticTest_ParenthesesOptions.cs @@ -10,52 +10,56 @@ namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { +#if !CODE_STYLE + using IOptionsCollection = IDictionary; +#endif + public abstract partial class AbstractDiagnosticProviderBasedUserDiagnosticTest : AbstractUserDiagnosticTest { #region Parentheses options - private static readonly CodeStyleOption IgnorePreference = - new CodeStyleOption(ParenthesesPreference.AlwaysForClarity, NotificationOption.None); + private static readonly CodeStyleOption2 IgnorePreference = + new CodeStyleOption2(ParenthesesPreference.AlwaysForClarity, NotificationOption2.None); - private static readonly CodeStyleOption RequireForPrecedenceClarityPreference = - new CodeStyleOption(ParenthesesPreference.AlwaysForClarity, NotificationOption.Suggestion); + private static readonly CodeStyleOption2 RequireForPrecedenceClarityPreference = + new CodeStyleOption2(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Suggestion); - private static readonly CodeStyleOption RemoveIfUnnecessaryPreference = - new CodeStyleOption(ParenthesesPreference.NeverIfUnnecessary, NotificationOption.Suggestion); + private static readonly CodeStyleOption2 RemoveIfUnnecessaryPreference = + new CodeStyleOption2(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Suggestion); - private static IEnumerable>> GetAllExceptOtherParenthesesOptions() + private static IEnumerable>> GetAllExceptOtherParenthesesOptions() { - yield return CodeStyleOptions.ArithmeticBinaryParentheses; - yield return CodeStyleOptions.RelationalBinaryParentheses; - yield return CodeStyleOptions.OtherBinaryParentheses; + yield return CodeStyleOptions2.ArithmeticBinaryParentheses; + yield return CodeStyleOptions2.RelationalBinaryParentheses; + yield return CodeStyleOptions2.OtherBinaryParentheses; } - protected IDictionary RequireArithmeticBinaryParenthesesForClarity - => GetSingleRequireOption(CodeStyleOptions.ArithmeticBinaryParentheses); + private protected IOptionsCollection RequireArithmeticBinaryParenthesesForClarity + => GetSingleRequireOption(CodeStyleOptions2.ArithmeticBinaryParentheses); - protected IDictionary RequireRelationalBinaryParenthesesForClarity - => GetSingleRequireOption(CodeStyleOptions.RelationalBinaryParentheses); + private protected IOptionsCollection RequireRelationalBinaryParenthesesForClarity + => GetSingleRequireOption(CodeStyleOptions2.RelationalBinaryParentheses); - protected IDictionary RequireOtherBinaryParenthesesForClarity - => GetSingleRequireOption(CodeStyleOptions.OtherBinaryParentheses); + private protected IOptionsCollection RequireOtherBinaryParenthesesForClarity + => GetSingleRequireOption(CodeStyleOptions2.OtherBinaryParentheses); - private IEnumerable>> GetAllParenthesesOptions() - => GetAllExceptOtherParenthesesOptions().Concat(CodeStyleOptions.OtherParentheses); + private IEnumerable>> GetAllParenthesesOptions() + => GetAllExceptOtherParenthesesOptions().Concat(CodeStyleOptions2.OtherParentheses); - protected IDictionary IgnoreAllParentheses + private protected IOptionsCollection IgnoreAllParentheses => OptionsSet(GetAllParenthesesOptions().Select( o => SingleOption(o, IgnorePreference)).ToArray()); - protected IDictionary RemoveAllUnnecessaryParentheses + private protected IOptionsCollection RemoveAllUnnecessaryParentheses => OptionsSet(GetAllParenthesesOptions().Select( o => SingleOption(o, RemoveIfUnnecessaryPreference)).ToArray()); - protected IDictionary RequireAllParenthesesForClarity + private protected IOptionsCollection RequireAllParenthesesForClarity => OptionsSet(GetAllExceptOtherParenthesesOptions() .Select(o => SingleOption(o, RequireForPrecedenceClarityPreference)) - .Concat(SingleOption(CodeStyleOptions.OtherParentheses, RemoveIfUnnecessaryPreference)).ToArray()); + .Concat(SingleOption(CodeStyleOptions2.OtherParentheses, RemoveIfUnnecessaryPreference)).ToArray()); - private IDictionary GetSingleRequireOption(PerLanguageOption> option) + private IOptionsCollection GetSingleRequireOption(PerLanguageOption2> option) => OptionsSet(GetAllParenthesesOptions() .Where(o => o != option) .Select(o => SingleOption(o, RemoveIfUnnecessaryPreference)) diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.FixAllDiagnosticProvider.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.FixAllDiagnosticProvider.cs index d57e439688a90..90b6c2b7629ac 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.FixAllDiagnosticProvider.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.FixAllDiagnosticProvider.cs @@ -8,7 +8,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs index 95c66312507b3..ba99805c884be 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUserDiagnosticTest.cs @@ -21,12 +21,6 @@ using Roslyn.Utilities; using Xunit; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; -#endif - namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract partial class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest @@ -37,7 +31,7 @@ public abstract partial class AbstractUserDiagnosticTest : AbstractCodeActionOrU internal abstract Task> GetDiagnosticsAsync( TestWorkspace workspace, TestParameters parameters); - protected async Task TestDiagnosticsAsync( + private protected async Task TestDiagnosticsAsync( string initialMarkup, TestParameters parameters = default, params DiagnosticDescription[] expected) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); @@ -242,12 +236,12 @@ private static FixAllState GetFixAllState( : new FixAllState(fixAllProvider, document.Project, fixer, scope, equivalenceKey, diagnosticIds, fixAllDiagnosticProvider); } - protected Task TestActionCountInAllFixesAsync( + private protected Task TestActionCountInAllFixesAsync( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, - IDictionary options = null, + IOptionsCollection options = null, object fixProviderData = null) { return TestActionCountInAllFixesAsync( diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj b/src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj index b1baa3c88bdd5..6e649cfd4a5f9 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj +++ b/src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj @@ -52,7 +52,7 @@ - + diff --git a/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs b/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs index 91c1c29e5fa3b..7996f500afb6e 100644 --- a/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs +++ b/src/EditorFeatures/DiagnosticsTestUtilities/NamingStyles/NamingStylesTestOptionSets.cs @@ -3,33 +3,34 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; +using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.NamingStyles; using Roslyn.Utilities; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; -#endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles { +#if !CODE_STYLE + using IOptionsCollection = IDictionary; +#endif + public sealed class NamingStylesTestOptionSets { - private readonly OptionKey _optionKey; + private readonly string _languageName; + private readonly OptionKey2 _optionKey; public NamingStylesTestOptionSets(string languageName) { + _languageName = languageName; _optionKey = NamingStyleOptions.GetNamingPreferencesOptionKey(languageName); } - public IDictionary MergeStyles(IDictionary first, IDictionary second, string languageName) + internal IOptionsCollection MergeStyles(IOptionsCollection first, IOptionsCollection second, string languageName) { var firstPreferences = (NamingStylePreferences)first.First().Value; var secondPreferences = (NamingStylePreferences)second.First().Value; @@ -39,67 +40,67 @@ public IDictionary MergeStyles(IDictionary firstPreferences.NamingRules.AddRange(secondPreferences.NamingRules))); } - public IDictionary ClassNamesArePascalCase => + internal IOptionsCollection ClassNamesArePascalCase => Options(_optionKey, ClassNamesArePascalCaseOption()); - public IDictionary FieldNamesAreCamelCase => + internal IOptionsCollection FieldNamesAreCamelCase => Options(_optionKey, FieldNamesAreCamelCaseOption()); - public IDictionary FieldNamesAreCamelCaseWithUnderscorePrefix => + internal IOptionsCollection FieldNamesAreCamelCaseWithUnderscorePrefix => Options(_optionKey, FieldNamesAreCamelCaseWithUnderscorePrefixOption()); - public IDictionary FieldNamesAreCamelCaseWithFieldUnderscorePrefix => + internal IOptionsCollection FieldNamesAreCamelCaseWithFieldUnderscorePrefix => Options(_optionKey, FieldNamesAreCamelCaseWithFieldUnderscorePrefixOption()); - public IDictionary FieldNamesAreCamelCaseWithFieldUnderscorePrefixAndUnderscoreEndSuffix => + internal IOptionsCollection FieldNamesAreCamelCaseWithFieldUnderscorePrefixAndUnderscoreEndSuffix => Options(_optionKey, FieldNamesAreCamelCaseWithFieldUnderscorePrefixAndUnderscoreEndSuffixOption()); - public IDictionary MethodNamesArePascalCase => + internal IOptionsCollection MethodNamesArePascalCase => Options(_optionKey, MethodNamesArePascalCaseOption()); - public IDictionary ParameterNamesAreCamelCase => + internal IOptionsCollection ParameterNamesAreCamelCase => Options(_optionKey, ParameterNamesAreCamelCaseOption()); - public IDictionary ParameterNamesAreCamelCaseWithPUnderscorePrefix => + internal IOptionsCollection ParameterNamesAreCamelCaseWithPUnderscorePrefix => Options(_optionKey, ParameterNamesAreCamelCaseWithPUnderscorePrefixOption()); - public IDictionary ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix => + internal IOptionsCollection ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffix => Options(_optionKey, ParameterNamesAreCamelCaseWithPUnderscorePrefixAndUnderscoreEndSuffixOption()); - public IDictionary LocalNamesAreCamelCase => + internal IOptionsCollection LocalNamesAreCamelCase => Options(_optionKey, LocalNamesAreCamelCaseOption()); - public IDictionary LocalFunctionNamesAreCamelCase => + internal IOptionsCollection LocalFunctionNamesAreCamelCase => Options(_optionKey, LocalFunctionNamesAreCamelCaseOption()); - public IDictionary PropertyNamesArePascalCase => + internal IOptionsCollection PropertyNamesArePascalCase => Options(_optionKey, PropertyNamesArePascalCaseOption()); - public IDictionary InterfaceNamesStartWithI => + internal IOptionsCollection InterfaceNamesStartWithI => Options(_optionKey, InterfaceNamesStartWithIOption()); - public IDictionary TypeParameterNamesStartWithT => + internal IOptionsCollection TypeParameterNamesStartWithT => Options(_optionKey, TypeParameterNamesStartWithTOption()); - public IDictionary ConstantsAreUpperCase => + internal IOptionsCollection ConstantsAreUpperCase => Options(_optionKey, ConstantsAreUpperCaseOption()); - public IDictionary LocalsAreCamelCaseConstantsAreUpperCase => + internal IOptionsCollection LocalsAreCamelCaseConstantsAreUpperCase => Options(_optionKey, LocalsAreCamelCaseConstantsAreUpperCaseOption()); - public IDictionary AsyncFunctionNamesEndWithAsync => + internal IOptionsCollection AsyncFunctionNamesEndWithAsync => Options(_optionKey, AsyncFunctionNamesEndWithAsyncOption()); - public IDictionary MethodNamesWithAccessibilityArePascalCase(ImmutableArray accessibilities) => + internal IOptionsCollection MethodNamesWithAccessibilityArePascalCase(ImmutableArray accessibilities) => Options(_optionKey, MethodNamesArePascalCaseOption(accessibilities)); - internal IDictionary SymbolKindsArePascalCase(ImmutableArray symbolKinds) => + internal IOptionsCollection SymbolKindsArePascalCase(ImmutableArray symbolKinds) => Options(_optionKey, SymbolKindsArePascalCaseOption(symbolKinds)); - internal IDictionary SymbolKindsArePascalCaseEmpty() => + internal IOptionsCollection SymbolKindsArePascalCaseEmpty() => Options(_optionKey, SymbolKindsArePascalCaseOption(ImmutableArray.Empty)); - internal IDictionary SymbolKindsArePascalCase(object symbolOrTypeKind) => + internal IOptionsCollection SymbolKindsArePascalCase(object symbolOrTypeKind) => SymbolKindsArePascalCase(ImmutableArray.Create(ToSymbolKindOrTypeKind(symbolOrTypeKind))); internal static SymbolSpecification.SymbolKindOrTypeKind ToSymbolKindOrTypeKind(object symbolOrTypeKind) @@ -120,16 +121,25 @@ internal static SymbolSpecification.SymbolKindOrTypeKind ToSymbolKindOrTypeKind( } } - internal IDictionary AccessibilitiesArePascalCase(ImmutableArray accessibilities) => + internal IOptionsCollection AccessibilitiesArePascalCase(ImmutableArray accessibilities) => Options(_optionKey, AccessibilitiesArePascalCaseOption(accessibilities)); - private static IDictionary Options(OptionKey option, object value) +#if CODE_STYLE + private IOptionsCollection Options(OptionKey2 option, object value) + => Options(new[] { (option, value) }); + + private IOptionsCollection Options(params (OptionKey2 key, object value)[] options) + => new OptionsCollection(_languageName, options); + +#else + private static IOptionsCollection Options(OptionKey2 option, object value) { - return new Dictionary + return new Dictionary { { option, value } }; } +#endif private static NamingStylePreferences ClassNamesArePascalCaseOption() { diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs index 86fa79820a2d0..f102754a70c18 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.CSharp.cs @@ -951,7 +951,7 @@ await TestAddPropertyAsync(input, expected, parameters: Parameters(Parameter(typeof(int), "i")), getStatements: "return String.Empty;", isIndexer: true, - options: new Dictionary { + options: new Dictionary { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }); diff --git a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs index fd635314a03d0..c7719bf67bb3c 100644 --- a/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs +++ b/src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs @@ -342,7 +342,7 @@ internal static async Task TestAddPropertyAsync( ImmutableArray> parameters = default, bool isIndexer = false, CodeGenerationOptions codeGenerationOptions = null, - IDictionary options = null) + IDictionary options = null) { // This assumes that tests will not use place holders for get/set statements at the same time if (getStatements != null) diff --git a/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs b/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs index 88e8461f9c656..6aae6a25593e6 100644 --- a/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDConfigurationTests.cs @@ -25,12 +25,12 @@ public class IDEDiagnosticIDConfigurationTests // For example: "dotnet_style_object_initializer = true:suggestion # Optional comment" private static readonly Regex s_optionBasedEntryPattern = new Regex(@"([\w ]+)=([\w ]+):[ ]*([\w]+)([ ]*[;#].*)?"); - private static ImmutableArray<(string diagnosticId, ImmutableHashSet codeStyleOptions)> GetIDEDiagnosticIdsAndOptions( + private static ImmutableArray<(string diagnosticId, ImmutableHashSet codeStyleOptions)> GetIDEDiagnosticIdsAndOptions( string languageName) { const string diagnosticIdPrefix = "IDE"; - var diagnosticIdAndOptions = new List<(string diagnosticId, ImmutableHashSet options)>(); + var diagnosticIdAndOptions = new List<(string diagnosticId, ImmutableHashSet options)>(); var uniqueDiagnosticIds = new HashSet(); foreach (var assembly in MefHostServices.DefaultAssemblies) { @@ -51,7 +51,7 @@ public class IDEDiagnosticIDConfigurationTests if (!IDEDiagnosticIdToOptionMappingHelper.TryGetMappedOptions(diagnosticId, languageName, out var options)) { - options = ImmutableHashSet.Empty; + options = ImmutableHashSet.Empty; } if (uniqueDiagnosticIds.Add(diagnosticId)) diff --git a/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb index f8ac90bbcd304..ac499e262f35d 100644 --- a/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/AbstractSimplificationTests.vb @@ -16,7 +16,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification <[UseExportProvider]> Public MustInherit Class AbstractSimplificationTests - Protected Async Function TestAsync(definition As XElement, expected As XElement, Optional options As Dictionary(Of OptionKey, Object) = Nothing, Optional csharpParseOptions As CSharpParseOptions = Nothing) As System.Threading.Tasks.Task + Private Protected Async Function TestAsync(definition As XElement, expected As XElement, Optional options As Dictionary(Of OptionKey2, Object) = Nothing, Optional csharpParseOptions As CSharpParseOptions = Nothing) As System.Threading.Tasks.Task Using workspace = TestWorkspace.Create(definition) Dim finalWorkspace = workspace @@ -30,7 +30,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Using End Function - Protected Async Function TestAsync(workspace As TestWorkspace, expected As XElement, Optional options As Dictionary(Of OptionKey, Object) = Nothing) As System.Threading.Tasks.Task + Private Protected Async Function TestAsync(workspace As TestWorkspace, expected As XElement, Optional options As Dictionary(Of OptionKey2, Object) = Nothing) As System.Threading.Tasks.Task Dim hostDocument = workspace.Documents.Single() Dim spansToAddSimplifierAnnotation = hostDocument.AnnotatedSpans.Where(Function(kvp) kvp.Key.StartsWith("Simplify", StringComparison.Ordinal)) @@ -57,7 +57,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification listOfLabelToAddSimplifierAnnotationSpans As IEnumerable(Of KeyValuePair(Of String, ImmutableArray(Of TextSpan))), explicitSpansToSimplifyWithin As ImmutableArray(Of TextSpan), expected As XElement, - options As Dictionary(Of OptionKey, Object)) As System.Threading.Tasks.Task + options As Dictionary(Of OptionKey2, Object)) As System.Threading.Tasks.Task Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single() Dim root = Await document.GetSyntaxRootAsync() diff --git a/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb b/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb index e97ffdc77edda..90fc0be533c87 100644 --- a/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb +++ b/src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.vb @@ -2,7 +2,6 @@ ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. -Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.CSharp.CodeStyle Imports Microsoft.CodeAnalysis.Options @@ -11,7 +10,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification Public Class SimplificationTests Inherits AbstractSimplificationTests - Private Shared ReadOnly DoNotPreferBraces As Dictionary(Of OptionKey, Object) = New Dictionary(Of OptionKey, Object) From {{New OptionKey(CSharpCodeStyleOptions.PreferBraces), New CodeStyleOption(Of PreferBracesPreference)(PreferBracesPreference.None, NotificationOption.Silent)}} + Private Shared ReadOnly DoNotPreferBraces As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CSharpCodeStyleOptions.PreferBraces), New CodeStyleOption2(Of PreferBracesPreference)(PreferBracesPreference.None, NotificationOption2.Silent)}} Public Async Function TestCSharp_DoNotSimplifyIfBlock() As Task diff --git a/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb b/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb index 49d608e6d3bab..2ab0f9b9eae76 100644 --- a/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb +++ b/src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.vb @@ -70,7 +70,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Module - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -102,7 +102,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Module - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -167,7 +167,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Class - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -204,7 +204,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Module - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -255,7 +255,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Class - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -305,7 +305,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Module - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -358,7 +358,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Module - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -409,7 +409,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification End Class - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -469,7 +469,7 @@ class D : C }]]> - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -524,7 +524,7 @@ End Class ]]> - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -570,7 +570,7 @@ Namespace X End Namespace - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -620,7 +620,7 @@ Namespace Y End Namespace - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {} Await TestAsync(input, expected, simplificationOptionSet) End Function diff --git a/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb b/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb index 9ab242b5d91cd..4d63da85fe453 100644 --- a/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb +++ b/src/EditorFeatures/Test2/Simplification/TypeNameSimplifierTest.vb @@ -1470,10 +1470,10 @@ class C1 Public Async Function TestCSharpSimplifyToVarLocalDeclaration() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From { - {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From { + {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement} } Dim input = @@ -1508,10 +1508,10 @@ class Program Public Async Function TestCSharpSimplifyToVarForeachDecl() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From { - {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From { + {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement} } Dim input = @@ -1548,10 +1548,10 @@ class Program Public Async Function TestCSharpSimplifyToVarCorrect() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From { - {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From { + {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement} } Dim input = @@ -1618,10 +1618,10 @@ class Program Public Async Function TestCSharpSimplifyToVarCorrect_QualifiedTypeNames() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From { - {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions.TrueWithSilentEnforcement}, - {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions.TrueWithSilentEnforcement} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From { + {CSharpCodeStyleOptions.VarForBuiltInTypes, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSilentEnforcement}, + {CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSilentEnforcement} } Dim input = @@ -1668,7 +1668,7 @@ class Program Public Async Function TestCSharpSimplifyToVarDontSimplify() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {} Dim input = @@ -2025,7 +2025,7 @@ class E Public Async Function TestDoNotSimplifyToGenericName() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {} Dim input = @@ -2086,7 +2086,7 @@ class E Public Async Function TestDontSimplifyAllNodes_SimplifyNestedType() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {} Dim input = @@ -2524,7 +2524,7 @@ class C } ]]> - Dim simplificationOptionSet = New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.QualifyFieldAccess, LanguageNames.CSharp), New CodeStyleOption(Of Boolean)(True, NotificationOption.Error)}} + Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}} Await TestAsync(input, expected, simplificationOptionSet) End Function @@ -3167,7 +3167,7 @@ class C } ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption.Silent)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Silent)) End Function @@ -3203,7 +3203,7 @@ class C } ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption.Suggestion)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Suggestion)) End Function @@ -3239,7 +3239,7 @@ class C } ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption.Warning)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Warning)) End Function @@ -3275,7 +3275,7 @@ class C } ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption.Error)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.CSharp, NotificationOption2.Error)) End Function #End Region @@ -4829,7 +4829,7 @@ End Class Public Async Function TestVisualBasic_DoNotSimplifyToGenericName() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {} Dim input = @@ -4882,7 +4882,7 @@ End Class Public Async Function TestVisualBasic_TestDontSimplifyAllNodes_SimplifyNestedType() As Task - Dim simplificationOption = New Dictionary(Of OptionKey, Object) From {} + Dim simplificationOption = New Dictionary(Of OptionKey2, Object) From {} Dim input = @@ -5744,7 +5744,7 @@ Class C End Class ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption.Silent)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Silent)) End Function @@ -5776,7 +5776,7 @@ Class C End Class ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption.Suggestion)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Suggestion)) End Function @@ -5808,7 +5808,7 @@ Class C End Class ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption.Warning)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Warning)) End Function @@ -5840,7 +5840,7 @@ Class C End Class ]]> - Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption.Error)) + Await TestAsync(input, expected, QualifyPropertyAccessOptionWithNotification(LanguageNames.VisualBasic, NotificationOption2.Error)) End Function @@ -5953,27 +5953,27 @@ End Class #Region "Helpers" - Protected Function QualifyFieldAccessOption(languageName As String) As Dictionary(Of OptionKey, Object) - Return New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.QualifyFieldAccess, languageName), New CodeStyleOption(Of Boolean)(True, NotificationOption.Error)}} + Private Protected Function QualifyFieldAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object) + Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyFieldAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}} End Function - Protected Function QualifyPropertyAccessOption(languageName As String) As Dictionary(Of OptionKey, Object) - Return QualifyPropertyAccessOptionWithNotification(languageName, NotificationOption.Error) + Private Protected Function QualifyPropertyAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object) + Return QualifyPropertyAccessOptionWithNotification(languageName, NotificationOption2.Error) End Function - Protected Function QualifyMethodAccessOption(languageName As String) As Dictionary(Of OptionKey, Object) - Return New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.QualifyMethodAccess, languageName), New CodeStyleOption(Of Boolean)(True, NotificationOption.Error)}} + Private Protected Function QualifyMethodAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object) + Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyMethodAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}} End Function - Protected Function QualifyEventAccessOption(languageName As String) As Dictionary(Of OptionKey, Object) - Return New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.QualifyEventAccess, languageName), New CodeStyleOption(Of Boolean)(True, NotificationOption.Error)}} + Private Protected Function QualifyEventAccessOption(languageName As String) As Dictionary(Of OptionKey2, Object) + Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyEventAccess, languageName), New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error)}} End Function - Protected Function QualifyPropertyAccessOptionWithNotification(languageName As String, notification As NotificationOption) As Dictionary(Of OptionKey, Object) - Return New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.QualifyPropertyAccess, languageName), New CodeStyleOption(Of Boolean)(True, notification)}} + Private Protected Function QualifyPropertyAccessOptionWithNotification(languageName As String, notification As NotificationOption2) As Dictionary(Of OptionKey2, Object) + Return New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.QualifyPropertyAccess, languageName), New CodeStyleOption2(Of Boolean)(True, notification)}} End Function - Shared DontPreferIntrinsicPredefinedTypeKeywordInDeclaration As Dictionary(Of OptionKey, Object) = New Dictionary(Of OptionKey, Object) From {{New OptionKey(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic), CodeStyleOption(Of Boolean).Default}} + Shared DontPreferIntrinsicPredefinedTypeKeywordInDeclaration As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic), CodeStyleOption2(Of Boolean).Default}} #End Region diff --git a/src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.cs b/src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.cs index 1b13e2dd84165..3ae3cddacf40a 100644 --- a/src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.cs +++ b/src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticBraceCompletionTests.cs @@ -147,7 +147,7 @@ internal void Type(IBraceCompletionSession session, string text) } } - internal Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary changedOptionSet = null) + internal Holder CreateSession(TestWorkspace workspace, char opening, char closing, Dictionary changedOptionSet = null) { var threadingContext = workspace.ExportProvider.GetExportedValue(); var undoManager = workspace.ExportProvider.GetExportedValue(); diff --git a/src/EditorFeatures/TestUtilities/Extensions/WorkspaceExtensions.cs b/src/EditorFeatures/TestUtilities/Extensions/WorkspaceExtensions.cs index 228ee6711e903..0c5ad947f2a2f 100644 --- a/src/EditorFeatures/TestUtilities/Extensions/WorkspaceExtensions.cs +++ b/src/EditorFeatures/TestUtilities/Extensions/WorkspaceExtensions.cs @@ -2,21 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Collections.Generic; +using System.Linq; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public static class WorkspaceExtensions { - public static void ApplyOptions(this Workspace workspace, IDictionary options) + public static void ApplyOptions(this Workspace workspace, IDictionary? options) + => workspace.ApplyOptions(options?.Select(kvp => (kvp.Key, kvp.Value))); + + internal static void ApplyOptions(this Workspace workspace, IDictionary? options) + => workspace.ApplyOptions(options?.Select(kvp => ((OptionKey)kvp.Key, kvp.Value))); + + private static void ApplyOptions(this Workspace workspace, IEnumerable<(OptionKey key, object value)>? options) { if (options != null) { var optionSet = workspace.Options; foreach (var option in options) { - optionSet = optionSet.WithChangedOption(option.Key, option.Value); + optionSet = optionSet.WithChangedOption(option.key, option.value); } workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)); diff --git a/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs b/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs index d14b38e17f152..81752809be0ee 100644 --- a/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs +++ b/src/EditorFeatures/TestUtilities/Formatting/CoreFormatterTestsBase.cs @@ -88,7 +88,7 @@ protected void TestIndentation(TestWorkspace workspace, int indentationLine, int Assert.Equal(expectedIndentation, actualIndentation); } - protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption option, bool enabled)[] options) + private protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption2 option, bool enabled)[] options) { using var workspace = CreateWorkspace(codeWithMarker); diff --git a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj index 0193a094651ac..8f6d7a998072a 100644 --- a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj +++ b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj @@ -102,7 +102,7 @@ - + diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb index 40deada0d9b38..52ef69b0dfbd4 100644 --- a/src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb +++ b/src/EditorFeatures/VisualBasicTest/CodeActions/EncapsulateField/EncapsulateFieldTests.vb @@ -338,7 +338,7 @@ Class C End Property End Class.ConvertTestSourceTag() - Await TestInRegularAndScriptAsync(text, expected, options:=[Option](CodeStyleOptions.QualifyFieldAccess, True, NotificationOption.Error)) + Await TestInRegularAndScriptAsync(text, expected, options:=[Option](CodeStyleOptions2.QualifyFieldAccess, True, NotificationOption2.Error)) End Function @@ -633,7 +633,7 @@ Class C End Property End Class ", -options:=[Option](CodeStyleOptions.QualifyFieldAccess, True, NotificationOption.Error)) +options:=[Option](CodeStyleOptions2.QualifyFieldAccess, True, NotificationOption2.Error)) End Function End Class End Namespace diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb index b4be17b788a7d..e482f47024aa8 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb @@ -2,14 +2,12 @@ ' 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.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics -Imports Microsoft.CodeAnalysis.CodeActions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics - Public MustInherit Class AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest + Partial Public MustInherit Class AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Inherits AbstractDiagnosticProviderBasedUserDiagnosticTest Private ReadOnly _compilationOptions As VisualBasicCompilationOptions = @@ -27,15 +25,13 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics End Function Friend Overloads Async Function TestAsync( - initialMarkup As XElement, expected As XElement, Optional index As Integer = 0, - Optional priority As CodeActionPriority? = Nothing) As Threading.Tasks.Task + initialMarkup As XElement, expected As XElement, Optional index As Integer = 0) As Threading.Tasks.Task Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag() Dim expectedStr = expected.ConvertTestSourceTag() Await MyBase.TestAsync(initialMarkupStr, expectedStr, parseOptions:=_compilationOptions.ParseOptions, compilationOptions:=_compilationOptions, - index:=index, - priority:=priority) + index:=index) End Function Protected Overloads Async Function TestMissingAsync(initialMarkup As XElement) As Threading.Tasks.Task diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests.vb index 9c0a15546fba2..dc391ca32a965 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests.vb @@ -1459,7 +1459,7 @@ Friend Class T End Class .NormalizedValue, index:=1, -options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Error)) +options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Error)) End Function diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.vb index 77be4b703bc5f..c31ee85df5579 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.vb @@ -15,43 +15,43 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Prefer Partial Public Class PreferFrameworkTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest - Private ReadOnly onWithInfo As New CodeStyleOption(Of Boolean)(True, NotificationOption.Suggestion) - Private ReadOnly offWithInfo As New CodeStyleOption(Of Boolean)(False, NotificationOption.Suggestion) + Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion) + Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion) Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(), New PreferFrameworkTypeCodeFixProvider()) End Function - Private ReadOnly Property NoFrameworkType As IDictionary(Of OptionKey, Object) + Private ReadOnly Property NoFrameworkType As IDictionary(Of OptionKey2, Object) Get Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo, GetLanguage())) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo, GetLanguage())) End Get End Property - Private ReadOnly Property FrameworkTypeEverywhere As IDictionary(Of OptionKey, Object) + Private ReadOnly Property FrameworkTypeEverywhere As IDictionary(Of OptionKey2, Object) Get Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo, GetLanguage())) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo, GetLanguage())) End Get End Property - Private ReadOnly Property FrameworkTypeInDeclaration As IDictionary(Of OptionKey, Object) + Private ReadOnly Property FrameworkTypeInDeclaration As IDictionary(Of OptionKey2, Object) Get Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo, GetLanguage())) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo, GetLanguage())) End Get End Property - Private ReadOnly Property FrameworkTypeInMemberAccess As IDictionary(Of OptionKey, Object) + Private ReadOnly Property FrameworkTypeInMemberAccess As IDictionary(Of OptionKey2, Object) Get Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo, GetLanguage())) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo, GetLanguage())) End Get End Property diff --git a/src/EditorFeatures/VisualBasicTest/EmbeddedLanguages/ValidateRegexStringTests.vb b/src/EditorFeatures/VisualBasicTest/EmbeddedLanguages/ValidateRegexStringTests.vb index 5b2ed4fa7aa00..3038e6b5cc8c5 100644 --- a/src/EditorFeatures/VisualBasicTest/EmbeddedLanguages/ValidateRegexStringTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EmbeddedLanguages/ValidateRegexStringTests.vb @@ -18,9 +18,9 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EmbeddedLanguages Return (New VisualBasicRegexDiagnosticAnalyzer(), Nothing) End Function - Private Function OptionOn() As IDictionary(Of OptionKey, Object) - Dim values = New Dictionary(Of OptionKey, Object) - values.Add(New OptionKey(RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic), True) + Private Function OptionOn() As IDictionary(Of OptionKey2, Object) + Dim values = New Dictionary(Of OptionKey2, Object) + values.Add(New OptionKey2(RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic), True) Return values End Function diff --git a/src/EditorFeatures/VisualBasicTest/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.vb b/src/EditorFeatures/VisualBasicTest/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.vb index 5f4684e7f69a6..ce85cdf0b646c 100644 --- a/src/EditorFeatures/VisualBasicTest/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.vb +++ b/src/EditorFeatures/VisualBasicTest/GenerateConstructorFromMembers/GenerateConstructorFromMembersTests.vb @@ -366,8 +366,8 @@ End Class", chosenSymbols:={"i"}) Public Async Function TestWithDialog1WithNullCheck() As Task - Dim options = New Dictionary(Of OptionKey, Object) - options(New OptionKey(GenerateConstructorFromMembersOptions.AddNullChecks, language:=LanguageNames.VisualBasic)) = True + Dim options = New Dictionary(Of OptionKey2, Object) + options(New OptionKey2(GenerateConstructorFromMembersOptions.AddNullChecks, language:=LanguageNames.VisualBasic)) = True Dim parameters = New TestParameters() parameters = parameters.WithOptions(options) diff --git a/src/EditorFeatures/VisualBasicTest/InitializeParameter/InitializeMemberFromParameterTests.vb b/src/EditorFeatures/VisualBasicTest/InitializeParameter/InitializeMemberFromParameterTests.vb index 8af8f89e24c69..6e67046dfd91e 100644 --- a/src/EditorFeatures/VisualBasicTest/InitializeParameter/InitializeMemberFromParameterTests.vb +++ b/src/EditorFeatures/VisualBasicTest/InitializeParameter/InitializeMemberFromParameterTests.vb @@ -698,19 +698,19 @@ End Structure Private ReadOnly Property OmitIfDefault_Warning As TestParameters Get - Return New TestParameters(options:=[Option](CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption.Warning)) + Return New TestParameters(options:=[Option](CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault, NotificationOption2.Warning)) End Get End Property Private ReadOnly Property Never_Warning As TestParameters Get - Return New TestParameters(options:=[Option](CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption.Warning)) + Return New TestParameters(options:=[Option](CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Never, NotificationOption2.Warning)) End Get End Property Private ReadOnly Property Always_Warning As TestParameters Get - Return New TestParameters(options:=[Option](CodeStyleOptions.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption.Warning)) + Return New TestParameters(options:=[Option](CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.Always, NotificationOption2.Warning)) End Get End Property End Class diff --git a/src/EditorFeatures/VisualBasicTest/SimplifyThisOrMe/SimplifyThisOrMeTests.vb b/src/EditorFeatures/VisualBasicTest/SimplifyThisOrMe/SimplifyThisOrMeTests.vb index 90c1d8134dbd7..89891bdf71fa9 100644 --- a/src/EditorFeatures/VisualBasicTest/SimplifyThisOrMe/SimplifyThisOrMeTests.vb +++ b/src/EditorFeatures/VisualBasicTest/SimplifyThisOrMe/SimplifyThisOrMeTests.vb @@ -66,7 +66,7 @@ End Class") Public Async Function TestAppropriateDiagnosticOnMissingQualifier() As Task Await TestDiagnosticInfoAsync( "Class C : Property SomeProperty As Integer : Sub M() : [|Me|].SomeProperty = 1 : End Sub : End Class", - options:=OptionsSet(SingleOption(CodeStyleOptions.QualifyPropertyAccess, False, NotificationOption.Error)), + options:=OptionsSet(SingleOption(CodeStyleOptions2.QualifyPropertyAccess, False, NotificationOption2.Error)), diagnosticId:=IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity:=DiagnosticSeverity.Error) End Function @@ -345,8 +345,8 @@ End Class]]> .ToString() Dim options = OptionsSet( - SingleOption(CodeStyleOptions.QualifyPropertyAccess, False, NotificationOption.Suggestion), - SingleOption(CodeStyleOptions.QualifyFieldAccess, True, NotificationOption.Suggestion)) + SingleOption(CodeStyleOptions2.QualifyPropertyAccess, False, NotificationOption2.Suggestion), + SingleOption(CodeStyleOptions2.QualifyFieldAccess, True, NotificationOption2.Suggestion)) Await TestInRegularAndScriptAsync( initialMarkup:=input, expectedMarkup:=expected, diff --git a/src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb b/src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb index aa3c7af310f7b..459d998a8d2b2 100644 --- a/src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb +++ b/src/EditorFeatures/VisualBasicTest/SimplifyTypeNames/SimplifyTypeNamesTests.vb @@ -21,32 +21,32 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SimplifyTypeNames New SimplifyTypeNamesCodeFixProvider()) End Function - Private Function PreferIntrinsicPredefinedTypeEverywhere() As IDictionary(Of OptionKey, Object) + Private Function PreferIntrinsicPredefinedTypeEverywhere() As IDictionary(Of OptionKey2, Object) Dim language = GetLanguage() Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithError, language)) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithError, language)) End Function - Private Function PreferIntrinsicPredefinedTypeInDeclaration() As IDictionary(Of OptionKey, Object) + Private Function PreferIntrinsicPredefinedTypeInDeclaration() As IDictionary(Of OptionKey2, Object) Dim language = GetLanguage() Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithSilent, language)) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithSilent, language)) End Function - Private Function PreferIntrinsicTypeInMemberAccess() As IDictionary(Of OptionKey, Object) + Private Function PreferIntrinsicTypeInMemberAccess() As IDictionary(Of OptionKey2, Object) Dim language = GetLanguage() Return OptionsSet( - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, True, NotificationOption.Error), - SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.offWithSilent, language)) + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, True, NotificationOption2.Error), + SingleOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.offWithSilent, language)) End Function - Private ReadOnly onWithError As New CodeStyleOption(Of Boolean)(True, NotificationOption.Error) - Private ReadOnly offWithSilent As New CodeStyleOption(Of Boolean)(False, NotificationOption.Silent) + Private ReadOnly onWithError As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Error) + Private ReadOnly offWithSilent As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Silent) Public Async Function TestGenericNames() As Task @@ -2190,7 +2190,7 @@ Class Program End Sub End Class - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Error))) End Function @@ -2205,7 +2205,7 @@ Class Program End Sub End Class - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Error))) End Function @@ -2220,7 +2220,7 @@ Class Program End Sub End Class - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Error))) End Function @@ -2303,7 +2303,7 @@ Module Program End Sub End Module - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Error))) End Function @@ -2318,7 +2318,7 @@ Module Program End Sub End Module - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Error))) End Function @@ -2331,7 +2331,7 @@ Module Program End Module - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Error))) End Function @@ -2364,7 +2364,7 @@ Module Program End Module - Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption.Error))) + Await TestMissingInRegularAndScriptAsync(source.Value, New TestParameters(options:=[Option](CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Error))) End Function diff --git a/src/EditorFeatures/VisualBasicTest/Squiggles/ErrorSquiggleProducerTests.vb b/src/EditorFeatures/VisualBasicTest/Squiggles/ErrorSquiggleProducerTests.vb index 62e6e4fb02153..06a95f685e2bf 100644 --- a/src/EditorFeatures/VisualBasicTest/Squiggles/ErrorSquiggleProducerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Squiggles/ErrorSquiggleProducerTests.vb @@ -104,10 +104,10 @@ End Class" }) Using workspace = TestWorkspace.CreateVisualBasic(content) - Dim options As New Dictionary(Of OptionKey, Object) + Dim options As New Dictionary(Of OptionKey2, Object) Dim language = workspace.Projects.Single().Language - Dim preferIntrinsicPredefinedTypeOption = New OptionKey(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language) - Dim preferIntrinsicPredefinedTypeOptionValue = New CodeStyleOption(Of Boolean)(value:=True, notification:=NotificationOption.Error) + Dim preferIntrinsicPredefinedTypeOption = New OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language) + Dim preferIntrinsicPredefinedTypeOptionValue = New CodeStyleOption2(Of Boolean)(value:=True, notification:=NotificationOption2.Error) options.Add(preferIntrinsicPredefinedTypeOption, preferIntrinsicPredefinedTypeOptionValue) workspace.ApplyOptions(options) diff --git a/src/EditorFeatures/VisualBasicTest/UseAutoProperty/UseAutoPropertyTests.vb b/src/EditorFeatures/VisualBasicTest/UseAutoProperty/UseAutoPropertyTests.vb index 2f9740d5cad53..d5fc588f83512 100644 --- a/src/EditorFeatures/VisualBasicTest/UseAutoProperty/UseAutoPropertyTests.vb +++ b/src/EditorFeatures/VisualBasicTest/UseAutoProperty/UseAutoPropertyTests.vb @@ -1126,7 +1126,7 @@ end class") End Class", "Public Class Foo Public ReadOnly Property O As Object -End Class", options:=[Option](FormattingOptions.UseTabs, True)) +End Class", options:=[Option](FormattingOptions2.UseTabs, True)) End Function @@ -1144,7 +1144,7 @@ End Class", options:=[Option](FormattingOptions.UseTabs, True)) End Class", "Public Class Foo Public ReadOnly Property O As Object -End Class", options:=[Option](FormattingOptions.UseTabs, False)) +End Class", options:=[Option](FormattingOptions2.UseTabs, False)) End Function diff --git a/src/EditorFeatures/VisualBasicTest/ValidateFormatString/ValidateFormatStringTests.vb b/src/EditorFeatures/VisualBasicTest/ValidateFormatString/ValidateFormatStringTests.vb index 2148b197afbca..1dc4d42e2c2f3 100644 --- a/src/EditorFeatures/VisualBasicTest/ValidateFormatString/ValidateFormatStringTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ValidateFormatString/ValidateFormatStringTests.vb @@ -18,21 +18,21 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ValidateFormatStri Return (New VisualBasicValidateFormatStringDiagnosticAnalyzer, Nothing) End Function - Private Function VBOptionOnCSharpOptionOff() As IDictionary(Of OptionKey, Object) - Dim optionsSet = New Dictionary(Of OptionKey, Object) From + Private Function VBOptionOnCSharpOptionOff() As IDictionary(Of OptionKey2, Object) + Dim optionsSet = New Dictionary(Of OptionKey2, Object) From { - {New OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), False}, - {New OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), True} + {New OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), False}, + {New OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), True} } Return optionsSet End Function - Private Function VBOptionOffCSharpOptionOn() As IDictionary(Of OptionKey, Object) - Dim optionsSet = New Dictionary(Of OptionKey, Object) From + Private Function VBOptionOffCSharpOptionOn() As IDictionary(Of OptionKey2, Object) + Dim optionsSet = New Dictionary(Of OptionKey2, Object) From { - {New OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), True}, - {New OptionKey(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), False} + {New OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp), True}, + {New OptionKey2(ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic), False} } Return optionsSet diff --git a/src/EditorFeatures/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb b/src/EditorFeatures/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb index 2dae76181d4fc..150d8f2ea2aa9 100644 --- a/src/EditorFeatures/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.vb @@ -16,9 +16,9 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Return FlattenActions(actions) End Function - Protected Shared Function GetIndentionColumn(column As Integer) As Dictionary(Of OptionKey, Object) - Return New Dictionary(Of OptionKey, Object) From { - {FormattingOptions.PreferredWrappingColumn, column} + Private Protected Shared Function GetIndentionColumn(column As Integer) As Dictionary(Of OptionKey2, Object) + Return New Dictionary(Of OptionKey2, Object) From { + {FormattingOptions2.PreferredWrappingColumn, column} } End Function @@ -29,9 +29,9 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Return TestAllWrappingCasesAsync(input, options:=Nothing, outputs) End Function - Protected Function TestAllWrappingCasesAsync( + Private Protected Function TestAllWrappingCasesAsync( input As String, - options As IDictionary(Of OptionKey, Object), + options As IDictionary(Of OptionKey2, Object), ParamArray outputs As String()) As Task Dim parameters = New TestParameters(options:=options) diff --git a/src/EditorFeatures/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb b/src/EditorFeatures/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb index bc38996f0ff1a..52fc90a05b22e 100644 --- a/src/EditorFeatures/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb @@ -15,12 +15,12 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Return New VisualBasicWrappingCodeRefactoringProvider() End Function - Private ReadOnly Property EndOfLine As IDictionary(Of OptionKey, Object) = [Option]( - CodeStyleOptions.OperatorPlacementWhenWrapping, + Private ReadOnly Property EndOfLine As IDictionary(Of OptionKey2, Object) = [Option]( + CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine) - Private ReadOnly Property BeginningOfLine As IDictionary(Of OptionKey, Object) = [Option]( - CodeStyleOptions.OperatorPlacementWhenWrapping, + Private ReadOnly Property BeginningOfLine As IDictionary(Of OptionKey2, Object) = [Option]( + CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine) Private Function TestEndOfLine(markup As String, expected As String) As Task diff --git a/src/Features/BannedSymbols.txt b/src/Features/BannedSymbols.txt new file mode 100644 index 0000000000000..41ed0451b2c94 --- /dev/null +++ b/src/Features/BannedSymbols.txt @@ -0,0 +1,4 @@ +T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption`1; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption2' instead +T:Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions; Use 'Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions2' instead +T:Microsoft.CodeAnalysis.Options.PerLanguageOption`1; Use 'Microsoft.CodeAnalysis.Options.PerLanguageOption2' instead +T:Microsoft.CodeAnalysis.Options.Option`1; Use 'Microsoft.CodeAnalysis.Options.Option2' instead diff --git a/src/Features/CSharp/Portable/Completion/CSharpCompletionOptions.cs b/src/Features/CSharp/Portable/Completion/CSharpCompletionOptions.cs index 78024cbadcf9b..83aac68a6b9a2 100644 --- a/src/Features/CSharp/Portable/Completion/CSharpCompletionOptions.cs +++ b/src/Features/CSharp/Portable/Completion/CSharpCompletionOptions.cs @@ -10,9 +10,9 @@ namespace Microsoft.CodeAnalysis.CSharp.Completion internal static class CSharpCompletionOptions { [Obsolete("This option is superceded by CompletionOptions.EnterKeyBehavior")] - public static readonly Option AddNewLineOnEnterAfterFullyTypedWord = new Option(nameof(CSharpCompletionOptions), nameof(AddNewLineOnEnterAfterFullyTypedWord), defaultValue: false); + public static readonly Option2 AddNewLineOnEnterAfterFullyTypedWord = new Option2(nameof(CSharpCompletionOptions), nameof(AddNewLineOnEnterAfterFullyTypedWord), defaultValue: false); [Obsolete("This option is superceded by CompletionOptions.SnippetsBehavior")] - public static readonly Option IncludeSnippets = new Option(nameof(CSharpCompletionOptions), nameof(IncludeSnippets), defaultValue: true); + public static readonly Option2 IncludeSnippets = new Option2(nameof(CSharpCompletionOptions), nameof(IncludeSnippets), defaultValue: true); } } diff --git a/src/Features/CSharp/Portable/Diagnostics/Analyzers/CSharpSimplifyTypeNamesDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/Diagnostics/Analyzers/CSharpSimplifyTypeNamesDiagnosticAnalyzer.cs index 128bb249ee835..4c78b07415c7e 100644 --- a/src/Features/CSharp/Portable/Diagnostics/Analyzers/CSharpSimplifyTypeNamesDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/Diagnostics/Analyzers/CSharpSimplifyTypeNamesDiagnosticAnalyzer.cs @@ -124,12 +124,12 @@ internal override bool CanSimplifyTypeNameExpression( } // set proper diagnostic ids. - if (replacementSyntax.HasAnnotations(nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration))) + if (replacementSyntax.HasAnnotations(nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration))) { inDeclaration = true; diagnosticId = IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId; } - else if (replacementSyntax.HasAnnotations(nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))) + else if (replacementSyntax.HasAnnotations(nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))) { inDeclaration = false; diagnosticId = IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId; diff --git a/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs b/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs index 20ea9bcf4bd38..3e28eb8985558 100644 --- a/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs +++ b/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs @@ -323,7 +323,7 @@ private static (AddImportPlacement placement, bool preferPreservation) Determine var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement); var placement = codeStyleOption.Value; - var preferPreservation = codeStyleOption.Notification == NotificationOption.None; + var preferPreservation = codeStyleOption.Notification == NotificationOption2.None; if (preferPreservation || placement == AddImportPlacement.OutsideNamespace) { diff --git a/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs index f1d16b5ce95d0..7bedd8e6b3783 100644 --- a/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/MisplacedUsingDirectives/MisplacedUsingDirectivesDiagnosticAnalyzer.cs @@ -89,7 +89,7 @@ private static bool ShouldSuppressDiagnostic(CompilationUnitSyntax compilationUn private static void ReportDiagnostics( SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, - IEnumerable usingDirectives, CodeStyleOption option) + IEnumerable usingDirectives, CodeStyleOption2 option) { foreach (var usingDirective in usingDirectives) { diff --git a/src/Features/CSharp/Portable/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs index fa7f9131108e9..2ad0a70ef9b6e 100644 --- a/src/Features/CSharp/Portable/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer.cs @@ -21,7 +21,7 @@ internal class CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer { public CSharpUseCompoundCoalesceAssignmentDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId, - CodeStyleOptions.PreferCompoundAssignment, + CodeStyleOptions2.PreferCompoundAssignment, new LocalizableResourceString(nameof(FeaturesResources.Use_compound_assignment), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { } @@ -38,7 +38,7 @@ private void AnalyzeCoalesceExpression(SyntaxNodeAnalysisContext context) var semanticModel = context.SemanticModel; var coalesceExpression = (BinaryExpressionSyntax)context.Node; - var option = context.GetOption(CodeStyleOptions.PreferCompoundAssignment, coalesceExpression.Language); + var option = context.GetOption(CodeStyleOptions2.PreferCompoundAssignment, coalesceExpression.Language); // Bail immediately if the user has disabled this feature. if (!option.Value) diff --git a/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.cs b/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.cs index 021da049af014..04333cf1659c2 100644 --- a/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.cs +++ b/src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.cs @@ -22,7 +22,7 @@ protected override void DiagnosticAnalyzerInitialize(AnalysisContext context) protected override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; - private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption option) + private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption2 option) { var declaration = (LambdaExpressionSyntax)context.Node; var diagnostic = AnalyzeSyntax(context.SemanticModel, option, declaration, context.CancellationToken); @@ -33,7 +33,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption option, + SemanticModel semanticModel, CodeStyleOption2 option, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { if (CanOfferUseExpressionBody(option.Value, declaration)) diff --git a/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs b/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs index ae998a1dd83ce..babff3a37a7e3 100644 --- a/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs +++ b/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.Result.cs @@ -22,7 +22,7 @@ public enum ResultKind public readonly struct Result { public readonly ResultKind Kind; - public readonly CodeStyleOption Option; + public readonly CodeStyleOption2 Option; public readonly IInvocationOperation InvocationOperation; public readonly InvocationExpressionSyntax Invocation; public readonly IMethodSymbol SliceLikeMethod; @@ -31,7 +31,7 @@ public readonly struct Result public readonly IOperation Op2; public Result( - ResultKind kind, CodeStyleOption option, + ResultKind kind, CodeStyleOption2 option, IInvocationOperation invocationOperation, InvocationExpressionSyntax invocation, IMethodSymbol sliceLikeMethod, MemberInfo memberInfo, IOperation op1, IOperation op2) diff --git a/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs index 921266f56ceae..35d88f80711c1 100644 --- a/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs @@ -92,7 +92,7 @@ private void AnalyzeInvocation( return null; } - CodeStyleOption option = null; + CodeStyleOption2 option = null; if (analyzerOptionsOpt != null) { // Check if we're at least on C# 8, and that the user wants these operators. diff --git a/src/Features/CSharp/Portable/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs index d77d88b0c85b8..002293bde93cb 100644 --- a/src/Features/CSharp/Portable/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs @@ -46,7 +46,7 @@ private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnal RoslynDebug.Assert(context.Compilation is object); var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( - CodeStyleOptions.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); + CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameReducer.CanSimplifyTupleElementName(argument, parseOptions)) { @@ -80,7 +80,7 @@ private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAn RoslynDebug.Assert(context.Compilation is object); var preference = options.GetOption( - CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); + CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameReducer.CanSimplifyAnonymousTypeMemberName(anonCtor)) { diff --git a/src/Features/CSharp/Portable/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs b/src/Features/CSharp/Portable/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs index e6f38146a85b0..34e4cdaa40526 100644 --- a/src/Features/CSharp/Portable/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs +++ b/src/Features/CSharp/Portable/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs @@ -19,7 +19,7 @@ internal class CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer public CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseIsNullCheckDiagnosticId, - CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, + CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpFeaturesResources.Use_is_null_check, new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -43,7 +43,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) return; } - var option = context.Options.GetOption(CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language, syntaxTree, cancellationToken); + var option = context.Options.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language, syntaxTree, cancellationToken); if (!option.Value) { return; diff --git a/src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs b/src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs index 944500efe36ef..44131b2e0e086 100644 --- a/src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs @@ -15,7 +15,7 @@ internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInC protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, LocalizableString title, LocalizableString message) : base(descriptorId, - options: ImmutableHashSet.Create(CodeStyleOptions.ArithmeticBinaryParentheses, CodeStyleOptions.RelationalBinaryParentheses, CodeStyleOptions.OtherBinaryParentheses, CodeStyleOptions.OtherParentheses), + options: ImmutableHashSet.Create(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message) { } @@ -25,22 +25,22 @@ protected AbstractParenthesesDiagnosticAnalyzer(ImmutableArray> GetLanguageOption(PrecedenceKind precedenceKind) + protected PerLanguageOption2> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: - return CodeStyleOptions.ArithmeticBinaryParentheses; + return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: - return CodeStyleOptions.RelationalBinaryParentheses; + return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: - return CodeStyleOptions.OtherBinaryParentheses; + return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: - return CodeStyleOptions.OtherParentheses; + return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); diff --git a/src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.cs b/src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.cs index 92fac9433969f..fd223bb9f7b27 100644 --- a/src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.cs @@ -39,7 +39,7 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); - if (document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions.FileHeaderTemplate, tree, out string fileHeaderTemplate) + if (document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out string fileHeaderTemplate) && !string.IsNullOrEmpty(fileHeaderTemplate)) { // If we have a defined file header template, allow the analyzer and code fix to handle it diff --git a/src/Features/Core/Portable/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs b/src/Features/Core/Portable/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs index cf9a399df38d0..8f2a0cc6a27fb 100644 --- a/src/Features/Core/Portable/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.AddRequiredParentheses @@ -29,8 +30,8 @@ static AbstractAddRequiredParenthesesDiagnosticAnalyzer() { var options = new[] { - CodeStyleOptions.ArithmeticBinaryParentheses, CodeStyleOptions.OtherBinaryParentheses, - CodeStyleOptions.OtherParentheses, CodeStyleOptions.RelationalBinaryParentheses + CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, + CodeStyleOptions2.OtherParentheses, CodeStyleOptions2.RelationalBinaryParentheses }; var includeArray = new[] { false, true }; @@ -52,7 +53,7 @@ static AbstractAddRequiredParenthesesDiagnosticAnalyzer() } } - private static string GetEquivalenceKey(Options.PerLanguageOption> parentPrecedence) + private static string GetEquivalenceKey(PerLanguageOption2> parentPrecedence) => parentPrecedence.Name; private static ImmutableDictionary GetProperties(bool includeInFixAll, string equivalenceKey) diff --git a/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Analysis.cs b/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Analysis.cs index ee236f309fc0b..667bedc38cc36 100644 --- a/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Analysis.cs +++ b/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.Analysis.cs @@ -5,7 +5,6 @@ using System; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CodeStyle { @@ -51,7 +50,7 @@ public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() /// To that end, we don't let the subclass have direct access to the real . Instead, we pass this type to the subclass for it /// register with. We then check if the registration should proceed given the + /// cref="CodeStyleOption2{T}"/> /// and the current being processed. If not, we don't do the /// actual registration. /// @@ -73,21 +72,21 @@ public void RegisterCompilationStartAction(Action c => analyze(c.Compilation, _this)); } - public void RegisterCodeBlockAction(Action> analyze) + public void RegisterCodeBlockAction(Action> analyze) { var provider = _codeStyleProvider; _context.RegisterCodeBlockAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } - public void RegisterSemanticModelAction(Action> analyze) + public void RegisterSemanticModelAction(Action> analyze) { var provider = _codeStyleProvider; _context.RegisterSemanticModelAction( c => AnalyzeIfEnabled(provider, c, analyze, c.Options, c.SemanticModel.SyntaxTree, c.CancellationToken)); } - public void RegisterSyntaxTreeAction(Action> analyze) + public void RegisterSyntaxTreeAction(Action> analyze) { var provider = _codeStyleProvider; _context.RegisterSyntaxTreeAction( @@ -95,7 +94,7 @@ public void RegisterSyntaxTreeAction(Action> analyze, + Action> analyze, params OperationKind[] operationKinds) { var provider = _codeStyleProvider; @@ -105,7 +104,7 @@ public void RegisterOperationAction( } public void RegisterSyntaxNodeAction( - Action> analyze, + Action> analyze, params TSyntaxKind[] syntaxKinds) where TSyntaxKind : struct { var provider = _codeStyleProvider; @@ -115,7 +114,7 @@ public void RegisterSyntaxNodeAction( } private static void AnalyzeIfEnabled( - TCodeStyleProvider provider, TContext context, Action> analyze, + TCodeStyleProvider provider, TContext context, Action> analyze, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionValue = options.GetOption(provider._option, syntaxTree, cancellationToken); diff --git a/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.cs b/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.cs index d6a79bc708074..5226ec10dd85a 100644 --- a/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.cs +++ b/src/Features/Core/Portable/CodeStyle/AbstractCodeStyleProvider.cs @@ -33,14 +33,14 @@ internal abstract partial class AbstractCodeStyleProvider< TOptionKind, TCodeStyleProvider> where TCodeStyleProvider : AbstractCodeStyleProvider, new() { - private readonly Option> _option; + private readonly Option2> _option; private readonly string _language; private readonly string _descriptorId; private readonly LocalizableString _title; private readonly LocalizableString _message; protected AbstractCodeStyleProvider( - Option> option, + Option2> option, string language, string descriptorId, LocalizableString title, @@ -58,7 +58,7 @@ protected AbstractCodeStyleProvider( /// handle ReportDiagnostic.Default and will map that back to the appropriate value in that /// case. /// - protected static ReportDiagnostic GetOptionSeverity(CodeStyleOption optionValue) + protected static ReportDiagnostic GetOptionSeverity(CodeStyleOption2 optionValue) { var severity = optionValue.Notification.Severity; return severity == ReportDiagnostic.Default diff --git a/src/Features/Core/Portable/Completion/CompletionOptions.cs b/src/Features/Core/Portable/Completion/CompletionOptions.cs index 18311b8f3184c..1f0f1b3e7e8dc 100644 --- a/src/Features/Core/Portable/Completion/CompletionOptions.cs +++ b/src/Features/Core/Portable/Completion/CompletionOptions.cs @@ -12,52 +12,52 @@ namespace Microsoft.CodeAnalysis.Completion internal static class CompletionOptions { // This is serialized by the Visual Studio-specific LanguageSettingsPersister - public static readonly PerLanguageOption HideAdvancedMembers = new PerLanguageOption(nameof(CompletionOptions), nameof(HideAdvancedMembers), defaultValue: false); + public static readonly PerLanguageOption2 HideAdvancedMembers = new PerLanguageOption2(nameof(CompletionOptions), nameof(HideAdvancedMembers), defaultValue: false); // This is serialized by the Visual Studio-specific LanguageSettingsPersister - public static readonly PerLanguageOption TriggerOnTyping = new PerLanguageOption(nameof(CompletionOptions), nameof(TriggerOnTyping), defaultValue: true); + public static readonly PerLanguageOption2 TriggerOnTyping = new PerLanguageOption2(nameof(CompletionOptions), nameof(TriggerOnTyping), defaultValue: true); - public static readonly PerLanguageOption TriggerOnTypingLetters = new PerLanguageOption(nameof(CompletionOptions), nameof(TriggerOnTypingLetters), defaultValue: true, + public static readonly PerLanguageOption2 TriggerOnTypingLetters = new PerLanguageOption2(nameof(CompletionOptions), nameof(TriggerOnTypingLetters), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.TriggerOnTypingLetters")); - public static readonly PerLanguageOption TriggerOnDeletion = new PerLanguageOption(nameof(CompletionOptions), nameof(TriggerOnDeletion), defaultValue: null, + public static readonly PerLanguageOption2 TriggerOnDeletion = new PerLanguageOption2(nameof(CompletionOptions), nameof(TriggerOnDeletion), defaultValue: null, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.TriggerOnDeletion")); - public static readonly PerLanguageOption EnterKeyBehavior = - new PerLanguageOption(nameof(CompletionOptions), nameof(EnterKeyBehavior), defaultValue: EnterKeyRule.Default, + public static readonly PerLanguageOption2 EnterKeyBehavior = + new PerLanguageOption2(nameof(CompletionOptions), nameof(EnterKeyBehavior), defaultValue: EnterKeyRule.Default, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.EnterKeyBehavior")); - public static readonly PerLanguageOption SnippetsBehavior = - new PerLanguageOption(nameof(CompletionOptions), nameof(SnippetsBehavior), defaultValue: SnippetsRule.Default, + public static readonly PerLanguageOption2 SnippetsBehavior = + new PerLanguageOption2(nameof(CompletionOptions), nameof(SnippetsBehavior), defaultValue: SnippetsRule.Default, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SnippetsBehavior")); // Dev15 options - public static readonly PerLanguageOption ShowCompletionItemFilters = new PerLanguageOption(nameof(CompletionOptions), nameof(ShowCompletionItemFilters), defaultValue: true, + public static readonly PerLanguageOption2 ShowCompletionItemFilters = new PerLanguageOption2(nameof(CompletionOptions), nameof(ShowCompletionItemFilters), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowCompletionItemFilters")); - public static readonly PerLanguageOption HighlightMatchingPortionsOfCompletionListItems = new PerLanguageOption(nameof(CompletionOptions), nameof(HighlightMatchingPortionsOfCompletionListItems), defaultValue: true, + public static readonly PerLanguageOption2 HighlightMatchingPortionsOfCompletionListItems = new PerLanguageOption2(nameof(CompletionOptions), nameof(HighlightMatchingPortionsOfCompletionListItems), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.HighlightMatchingPortionsOfCompletionListItems")); - public static readonly PerLanguageOption BlockForCompletionItems = new PerLanguageOption( + public static readonly PerLanguageOption2 BlockForCompletionItems = new PerLanguageOption2( nameof(CompletionOptions), nameof(BlockForCompletionItems), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{BlockForCompletionItems}")); - public static readonly PerLanguageOption ShowNameSuggestions = - new PerLanguageOption(nameof(CompletionOptions), nameof(ShowNameSuggestions), defaultValue: true, + public static readonly PerLanguageOption2 ShowNameSuggestions = + new PerLanguageOption2(nameof(CompletionOptions), nameof(ShowNameSuggestions), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowNameSuggestions")); //Dev16 options // Use tri-value so the default state can be used to turn on the feature with experimentation service. - public static readonly PerLanguageOption ShowItemsFromUnimportedNamespaces = - new PerLanguageOption(nameof(CompletionOptions), nameof(ShowItemsFromUnimportedNamespaces), defaultValue: null, + public static readonly PerLanguageOption2 ShowItemsFromUnimportedNamespaces = + new PerLanguageOption2(nameof(CompletionOptions), nameof(ShowItemsFromUnimportedNamespaces), defaultValue: null, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowItemsFromUnimportedNamespaces")); // Use tri-value so the default state can be used to turn on the feature with experimentation service. - public static readonly PerLanguageOption TriggerInArgumentLists = - new PerLanguageOption(nameof(CompletionOptions), nameof(TriggerInArgumentLists), defaultValue: null, + public static readonly PerLanguageOption2 TriggerInArgumentLists = + new PerLanguageOption2(nameof(CompletionOptions), nameof(TriggerInArgumentLists), defaultValue: null, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.TriggerInArgumentLists")); - public static IEnumerable> GetDev15CompletionOptions() + public static IEnumerable> GetDev15CompletionOptions() { yield return ShowCompletionItemFilters; yield return HighlightMatchingPortionsOfCompletionListItems; @@ -66,7 +66,7 @@ public static IEnumerable> GetDev15CompletionOptions() internal static class CompletionControllerOptions { - public static readonly Option FilterOutOfScopeLocals = new Option(nameof(CompletionControllerOptions), nameof(FilterOutOfScopeLocals), defaultValue: true); - public static readonly Option ShowXmlDocCommentCompletion = new Option(nameof(CompletionControllerOptions), nameof(ShowXmlDocCommentCompletion), defaultValue: true); + public static readonly Option2 FilterOutOfScopeLocals = new Option2(nameof(CompletionControllerOptions), nameof(FilterOutOfScopeLocals), defaultValue: true); + public static readonly Option2 ShowXmlDocCommentCompletion = new Option2(nameof(CompletionControllerOptions), nameof(ShowXmlDocCommentCompletion), defaultValue: true); } } diff --git a/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs b/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs index ba0c3280ca6ea..855105bbb9e7c 100644 --- a/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs +++ b/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs @@ -11,7 +11,7 @@ internal static class CompletionServiceOptions /// /// Indicates if the completion is trigger by toggle the expander. /// - public static readonly Option IsExpandedCompletion - = new Option(nameof(CompletionServiceOptions), nameof(IsExpandedCompletion), defaultValue: false); + public static readonly Option2 IsExpandedCompletion + = new Option2(nameof(CompletionServiceOptions), nameof(IsExpandedCompletion), defaultValue: false); } } diff --git a/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs b/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs index d306aa2fe836b..0788aea94f2a2 100644 --- a/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs +++ b/src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs @@ -112,7 +112,7 @@ public static async ValueTask GetAnalyzerOptionSetAsync(this Analyzer return new AnalyzerConfigOptionSet(configOptions, optionSet); } - public static T GetOption(this AnalyzerOptions analyzerOptions, Option option, SyntaxTree syntaxTree, CancellationToken cancellationToken) + public static T GetOption(this AnalyzerOptions analyzerOptions, ILanguageSpecificOption option, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync(analyzerOptions, option, language: null, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) @@ -121,7 +121,7 @@ public static T GetOption(this AnalyzerOptions analyzerOptions, Option opt return optionAsync.AsTask().GetAwaiter().GetResult(); } - public static T GetOption(this AnalyzerOptions analyzerOptions, PerLanguageOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) + public static T GetOption(this AnalyzerOptions analyzerOptions, IPerLanguageOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync(analyzerOptions, option, language, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) diff --git a/src/Features/Core/Portable/Diagnostics/Analyzers/FxCopAnalyzersInstallOptions.cs b/src/Features/Core/Portable/Diagnostics/Analyzers/FxCopAnalyzersInstallOptions.cs index b2d7601840def..187253014939e 100644 --- a/src/Features/Core/Portable/Diagnostics/Analyzers/FxCopAnalyzersInstallOptions.cs +++ b/src/Features/Core/Portable/Diagnostics/Analyzers/FxCopAnalyzersInstallOptions.cs @@ -12,27 +12,27 @@ internal static class FxCopAnalyzersInstallOptions private const string LocalRegistryPath = @"Roslyn\Internal\FxCopAnalyzers\"; private const string LocalRegistryPath_CodeAnalysis2017 = @"Roslyn\Internal\Analyzers\AB\Vsix\"; - public static readonly Option LastDateTimeUsedSuggestionAction = new Option(nameof(FxCopAnalyzersInstallOptions), + public static readonly Option2 LastDateTimeUsedSuggestionAction = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(LastDateTimeUsedSuggestionAction), defaultValue: DateTime.MinValue.ToBinary(), storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(LastDateTimeUsedSuggestionAction))); - public static readonly Option UsedSuggestedActionCount = new Option(nameof(FxCopAnalyzersInstallOptions), nameof(UsedSuggestedActionCount), + public static readonly Option2 UsedSuggestedActionCount = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(UsedSuggestedActionCount), defaultValue: 0, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(UsedSuggestedActionCount))); - public static readonly Option NeverShowAgain_CodeAnalysis2017 = new Option(@"AnalyzerABTestOptions", @"NeverShowAgain", + public static readonly Option2 NeverShowAgain_CodeAnalysis2017 = new Option2(@"AnalyzerABTestOptions", @"NeverShowAgain", defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath_CodeAnalysis2017 + @"NeverShowAgain")); - public static readonly Option NeverShowAgain = new Option(nameof(FxCopAnalyzersInstallOptions), nameof(NeverShowAgain), + public static readonly Option2 NeverShowAgain = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(NeverShowAgain), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath_CodeAnalysis2017 + nameof(NeverShowAgain))); - public static readonly Option HasMetCandidacyRequirements = new Option(nameof(FxCopAnalyzersInstallOptions), nameof(HasMetCandidacyRequirements), + public static readonly Option2 HasMetCandidacyRequirements = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(HasMetCandidacyRequirements), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(HasMetCandidacyRequirements))); - public static readonly Option LastDateTimeInfoBarShown = new Option(nameof(FxCopAnalyzersInstallOptions), nameof(LastDateTimeInfoBarShown), + public static readonly Option2 LastDateTimeInfoBarShown = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(LastDateTimeInfoBarShown), defaultValue: DateTime.MinValue.ToBinary(), storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(LastDateTimeInfoBarShown))); - public static readonly Option VsixInstalled = new Option(nameof(FxCopAnalyzersInstallOptions), + public static readonly Option2 VsixInstalled = new Option2(nameof(FxCopAnalyzersInstallOptions), nameof(VsixInstalled), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(VsixInstalled))); } diff --git a/src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaCompletionProviderBase.cs b/src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaCompletionProviderBase.cs index 19952933e2501..f81fec6dc2b91 100644 --- a/src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaCompletionProviderBase.cs +++ b/src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaCompletionProviderBase.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal abstract class PythiaCompletionProviderBase : CommonCompletionProvider { - public static PerLanguageOption HideAdvancedMembersOption => CompletionOptions.HideAdvancedMembers; + public static PerLanguageOption2 HideAdvancedMembersOption => CompletionOptions.HideAdvancedMembers; public static CompletionItem CreateCommonCompletionItem( string displayText, diff --git a/src/Features/Core/Portable/ExtractMethod/ExtractMethodOptions.cs b/src/Features/Core/Portable/ExtractMethod/ExtractMethodOptions.cs index bf4057031cb6d..b440eeeb79803 100644 --- a/src/Features/Core/Portable/ExtractMethod/ExtractMethodOptions.cs +++ b/src/Features/Core/Portable/ExtractMethod/ExtractMethodOptions.cs @@ -10,10 +10,10 @@ namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class ExtractMethodOptions { - public static readonly PerLanguageOption AllowBestEffort = new PerLanguageOption(nameof(ExtractMethodOptions), nameof(AllowBestEffort), defaultValue: true, + public static readonly PerLanguageOption2 AllowBestEffort = new PerLanguageOption2(nameof(ExtractMethodOptions), nameof(AllowBestEffort), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Allow Best Effort")); - public static readonly PerLanguageOption DontPutOutOrRefOnStruct = new PerLanguageOption(nameof(ExtractMethodOptions), nameof(DontPutOutOrRefOnStruct), defaultValue: true, + public static readonly PerLanguageOption2 DontPutOutOrRefOnStruct = new PerLanguageOption2(nameof(ExtractMethodOptions), nameof(DontPutOutOrRefOnStruct), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Don't Put Out Or Ref On Strcut")); // NOTE: the spelling error is what we've shipped and thus should not change } } diff --git a/src/Features/Core/Portable/GenerateConstructorFromMembers/GenerateConstructorFromMembersOptions.cs b/src/Features/Core/Portable/GenerateConstructorFromMembers/GenerateConstructorFromMembersOptions.cs index c223cd684887f..c89b9dc546a46 100644 --- a/src/Features/Core/Portable/GenerateConstructorFromMembers/GenerateConstructorFromMembersOptions.cs +++ b/src/Features/Core/Portable/GenerateConstructorFromMembers/GenerateConstructorFromMembersOptions.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal static class GenerateConstructorFromMembersOptions { - public static readonly PerLanguageOption AddNullChecks = new PerLanguageOption( + public static readonly PerLanguageOption2 AddNullChecks = new PerLanguageOption2( nameof(GenerateConstructorFromMembersOptions), nameof(AddNullChecks), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( diff --git a/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs b/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs index f95b2d6f88007..1928d6c3f7e66 100644 --- a/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs +++ b/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs @@ -10,13 +10,13 @@ namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal static class GenerateEqualsAndGetHashCodeFromMembersOptions { - public static readonly PerLanguageOption GenerateOperators = new PerLanguageOption( + public static readonly PerLanguageOption2 GenerateOperators = new PerLanguageOption2( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(GenerateOperators), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}")); - public static readonly PerLanguageOption ImplementIEquatable = new PerLanguageOption( + public static readonly PerLanguageOption2 ImplementIEquatable = new PerLanguageOption2( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(ImplementIEquatable), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( diff --git a/src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs b/src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs index 602dc11cd0ab5..d25d41b8d123e 100644 --- a/src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs +++ b/src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.DisposePatternCodeAction.cs @@ -322,7 +322,7 @@ private async Task CreateDisposedValueFieldAsync( var rule = await document.GetApplicableNamingRuleAsync( SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); - var requireAccessiblity = options.GetOption(CodeStyleOptions.RequireAccessibilityModifiers); + var requireAccessiblity = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var boolType = compilation.GetSpecialType(SpecialType.System_Boolean); diff --git a/src/Features/Core/Portable/ImplementType/ImplementTypeOptions.cs b/src/Features/Core/Portable/ImplementType/ImplementTypeOptions.cs index ad43a1f5af6bb..add3547a08f0a 100644 --- a/src/Features/Core/Portable/ImplementType/ImplementTypeOptions.cs +++ b/src/Features/Core/Portable/ImplementType/ImplementTypeOptions.cs @@ -22,16 +22,16 @@ internal enum ImplementTypePropertyGenerationBehavior internal static class ImplementTypeOptions { - public static readonly PerLanguageOption InsertionBehavior = - new PerLanguageOption( + public static readonly PerLanguageOption2 InsertionBehavior = + new PerLanguageOption2( nameof(ImplementTypeOptions), nameof(InsertionBehavior), defaultValue: ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(InsertionBehavior)}")); - public static readonly PerLanguageOption PropertyGenerationBehavior = - new PerLanguageOption( + public static readonly PerLanguageOption2 PropertyGenerationBehavior = + new PerLanguageOption2( nameof(ImplementTypeOptions), nameof(PropertyGenerationBehavior), defaultValue: ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, diff --git a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs index a818e3f547d68..559b11dd0cedd 100644 --- a/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs +++ b/src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs @@ -98,7 +98,7 @@ protected override async Task> GetRefactoringsForSing var codeGenService = document.GetLanguageService(); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); - var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions.RequireAccessibilityModifiers); + var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var field = CreateField(requireAccessibilityModifiers, parameter, rules, parameterNameParts.BaseNameParts); var property = CreateProperty(requireAccessibilityModifiers, parameter, rules, parameterNameParts.BaseNameParts); @@ -115,7 +115,7 @@ protected override async Task> GetRefactoringsForSing } private IFieldSymbol CreateField( - CodeStyleOption requireAccessibilityModifiers, + CodeStyleOption2 requireAccessibilityModifiers, IParameterSymbol parameter, ImmutableArray rules, ImmutableArray parameterNameParts) @@ -163,7 +163,7 @@ private static string GenerateUniqueName(IParameterSymbol parameter, ImmutableAr } private IPropertySymbol CreateProperty( - CodeStyleOption requireAccessibilityModifiers, + CodeStyleOption2 requireAccessibilityModifiers, IParameterSymbol parameter, ImmutableArray rules, ImmutableArray parameterNameParts) diff --git a/src/Features/Core/Portable/Navigation/NavigationOptions.cs b/src/Features/Core/Portable/Navigation/NavigationOptions.cs index ffbaedaf0ca61..87beab2718e49 100644 --- a/src/Features/Core/Portable/Navigation/NavigationOptions.cs +++ b/src/Features/Core/Portable/Navigation/NavigationOptions.cs @@ -12,6 +12,6 @@ internal static class NavigationOptions /// This option can be passed to the APIs to request that a provisional (or preview) tab /// be used for any document that needs to be opened, if one is available. /// - public static readonly Option PreferProvisionalTab = new Option(nameof(NavigationOptions), nameof(PreferProvisionalTab), defaultValue: false); + public static readonly Option2 PreferProvisionalTab = new Option2(nameof(NavigationOptions), nameof(PreferProvisionalTab), defaultValue: false); } } diff --git a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeDiagnosticAnalyzerBase.cs b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeDiagnosticAnalyzerBase.cs index 089d94c3dd692..d6e6a245a5ac3 100644 --- a/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeDiagnosticAnalyzerBase.cs +++ b/src/Features/Core/Portable/PreferFrameworkType/PreferFrameworkTypeDiagnosticAnalyzerBase.cs @@ -4,9 +4,7 @@ #nullable enable -using System; using System.Collections.Immutable; -using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; @@ -21,27 +19,27 @@ internal abstract class PreferFrameworkTypeDiagnosticAnalyzerBase(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess), + options: ImmutableHashSet.Create(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess), new LocalizableResourceString(nameof(FeaturesResources.Use_framework_type), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Use_framework_type), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { } - private static PerLanguageOption> GetOptionForDeclarationContext - => CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration; + private static PerLanguageOption2> GetOptionForDeclarationContext + => CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration; - private static PerLanguageOption> GetOptionForMemberAccessContext - => CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; + private static PerLanguageOption2> GetOptionForMemberAccessContext + => CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; public override bool OpenFileOnly(OptionSet options) { var preferTypeKeywordInDeclarationOption = options.GetOption( - CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName()).Notification; + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName()).Notification; var preferTypeKeywordInMemberAccessOption = options.GetOption( - CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName()).Notification; + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName()).Notification; - return !(preferTypeKeywordInDeclarationOption == NotificationOption.Warning || preferTypeKeywordInDeclarationOption == NotificationOption.Error || - preferTypeKeywordInMemberAccessOption == NotificationOption.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption.Error); + return !(preferTypeKeywordInDeclarationOption == NotificationOption2.Warning || preferTypeKeywordInDeclarationOption == NotificationOption2.Error || + preferTypeKeywordInMemberAccessOption == NotificationOption2.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption2.Error); } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() @@ -121,7 +119,7 @@ private bool IsStylePreferred( private bool IsFrameworkTypePreferred( SyntaxNodeAnalysisContext context, - PerLanguageOption> option, + PerLanguageOption2> option, string language) { var optionValue = context.GetOption(option, language); @@ -132,7 +130,7 @@ private bool IsFrameworkTypePreferred( /// checks if style is preferred and the enforcement is not None. /// /// if predefined type is not preferred, it implies the preference is framework type. - private static bool OptionSettingPrefersFrameworkType(CodeStyleOption optionValue, ReportDiagnostic severity) + private static bool OptionSettingPrefersFrameworkType(CodeStyleOption2 optionValue, ReportDiagnostic severity) => !optionValue.Value && severity != ReportDiagnostic.Suppress; } } diff --git a/src/Features/Core/Portable/Shared/Options/ServiceComponentOnOffOptions.cs b/src/Features/Core/Portable/Shared/Options/ServiceComponentOnOffOptions.cs index 61f435523a857..3f147c0917381 100644 --- a/src/Features/Core/Portable/Shared/Options/ServiceComponentOnOffOptions.cs +++ b/src/Features/Core/Portable/Shared/Options/ServiceComponentOnOffOptions.cs @@ -11,6 +11,6 @@ namespace Microsoft.CodeAnalysis.Shared.Options /// internal static class ServiceComponentOnOffOptions { - public static readonly Option DiagnosticProvider = new Option(nameof(ServiceComponentOnOffOptions), nameof(DiagnosticProvider), defaultValue: true); + public static readonly Option2 DiagnosticProvider = new Option2(nameof(ServiceComponentOnOffOptions), nameof(DiagnosticProvider), defaultValue: true); } } diff --git a/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs b/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs index aaac74bf918f8..7321e589ada7e 100644 --- a/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs +++ b/src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs @@ -21,8 +21,10 @@ internal static class ServiceFeatureOnOffOptions /// /// This option is used by TypeScript. /// +#pragma warning disable RS0030 // Do not used banned APIs - to avoid a binary breaking API change. public static readonly PerLanguageOption RemoveDocumentDiagnosticsOnDocumentClose = new PerLanguageOption( "ServiceFeatureOnOffOptions", "RemoveDocumentDiagnosticsOnDocumentClose", defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveDocumentDiagnosticsOnDocumentClose")); +#pragma warning restore RS0030 // Do not used banned APIs } } diff --git a/src/Features/Core/Portable/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs b/src/Features/Core/Portable/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs index 5bfc6905f42dd..fe398677293bd 100644 --- a/src/Features/Core/Portable/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/SimplifyBooleanExpression/AbstractSimplifyConditionalDiagnosticAnalyzer.cs @@ -42,7 +42,7 @@ private static readonly ImmutableDictionary s_takeConditionAndWh protected AbstractSimplifyConditionalDiagnosticAnalyzer() : base(IDEDiagnosticIds.SimplifyConditionalExpressionDiagnosticId, - CodeStyleOptions.PreferSimplifiedBooleanExpressions, + CodeStyleOptions2.PreferSimplifiedBooleanExpressions, new LocalizableResourceString(nameof(FeaturesResources.Simplify_conditional_expression), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Conditional_expression_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { @@ -70,7 +70,7 @@ private void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext context) var cancellationToken = context.CancellationToken; var styleOption = options.GetOption( - CodeStyleOptions.PreferSimplifiedBooleanExpressions, + CodeStyleOptions2.PreferSimplifiedBooleanExpressions, semanticModel.Language, syntaxTree, cancellationToken); if (!styleOption.Value) { diff --git a/src/Features/Core/Portable/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs b/src/Features/Core/Portable/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs index 100abb5eab318..4ffafd53763ed 100644 --- a/src/Features/Core/Portable/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/SimplifyInterpolation/AbstractSimplifyInterpolationDiagnosticAnalyzer.cs @@ -19,7 +19,7 @@ internal abstract class AbstractSimplifyInterpolationDiagnosticAnalyzer< { protected AbstractSimplifyInterpolationDiagnosticAnalyzer() : base(IDEDiagnosticIds.SimplifyInterpolationId, - CodeStyleOptions.PreferSimplifiedInterpolation, + CodeStyleOptions2.PreferSimplifiedInterpolation, new LocalizableResourceString(nameof(FeaturesResources.Simplify_interpolation), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Interpolation_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { @@ -48,7 +48,7 @@ private void AnalyzeInterpolation(OperationAnalysisContext context) } var language = interpolation.Language; - var option = optionSet.GetOption(CodeStyleOptions.PreferSimplifiedInterpolation, language); + var option = optionSet.GetOption(CodeStyleOptions2.PreferSimplifiedInterpolation, language); if (!option.Value) { // No point in analyzing if the option is off. diff --git a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeDiagnosticAnalyzer.cs b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeDiagnosticAnalyzer.cs index 8d43317c23b74..5043b6fd3d147 100644 --- a/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/SimplifyThisOrMe/AbstractSimplifyThisOrMeDiagnosticAnalyzer.cs @@ -32,7 +32,7 @@ internal abstract class AbstractSimplifyThisOrMeDiagnosticAnalyzer< protected AbstractSimplifyThisOrMeDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveQualificationDiagnosticId, - ImmutableHashSet.Create(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.QualifyPropertyAccess, CodeStyleOptions.QualifyMethodAccess, CodeStyleOptions.QualifyEventAccess), + ImmutableHashSet.Create(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess), new LocalizableResourceString(nameof(FeaturesResources.Remove_qualification), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(WorkspacesResources.Name_can_be_simplified), WorkspacesResources.ResourceManager, typeof(WorkspacesResources))) { @@ -104,7 +104,7 @@ private void AnalyzeNode(SyntaxNodeAnalysisContext context) // used so we can provide a link in the preview to the options page. This value is // hard-coded there to be the one that will go to the code-style page. - builder["OptionName"] = nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); + builder["OptionName"] = nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration); builder["OptionLanguage"] = model.Language; var diagnostic = DiagnosticHelper.Create( diff --git a/src/Features/Core/Portable/SimplifyTypeNames/SimplifyTypeNamesDiagnosticAnalyzerBase.cs b/src/Features/Core/Portable/SimplifyTypeNames/SimplifyTypeNamesDiagnosticAnalyzerBase.cs index ada0583d84a35..9c9adcaa9cf5a 100644 --- a/src/Features/Core/Portable/SimplifyTypeNames/SimplifyTypeNamesDiagnosticAnalyzerBase.cs +++ b/src/Features/Core/Portable/SimplifyTypeNames/SimplifyTypeNamesDiagnosticAnalyzerBase.cs @@ -83,12 +83,12 @@ protected SimplifyTypeNamesDiagnosticAnalyzerBase() public bool OpenFileOnly(OptionSet options) { var preferTypeKeywordInDeclarationOption = options.GetOption( - CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName())!.Notification; + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName())!.Notification; var preferTypeKeywordInMemberAccessOption = options.GetOption( - CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName())!.Notification; + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName())!.Notification; - return !(preferTypeKeywordInDeclarationOption == NotificationOption.Warning || preferTypeKeywordInDeclarationOption == NotificationOption.Error || - preferTypeKeywordInMemberAccessOption == NotificationOption.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption.Error); + return !(preferTypeKeywordInDeclarationOption == NotificationOption2.Warning || preferTypeKeywordInDeclarationOption == NotificationOption2.Error || + preferTypeKeywordInMemberAccessOption == NotificationOption2.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption2.Error); } public sealed override void Initialize(AnalysisContext context) @@ -143,7 +143,7 @@ public bool TrySimplify(SemanticModel model, SyntaxNode node, [NotNullWhen(true) internal static Diagnostic CreateDiagnostic(SemanticModel model, OptionSet optionSet, TextSpan issueSpan, string diagnosticId, bool inDeclaration) { - PerLanguageOption> option; + PerLanguageOption2> option; DiagnosticDescriptor descriptor; ReportDiagnostic severity; switch (diagnosticId) @@ -160,8 +160,8 @@ internal static Diagnostic CreateDiagnostic(SemanticModel model, OptionSet optio case IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId: option = inDeclaration - ? CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration - : CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; + ? CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration + : CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; descriptor = s_descriptorPreferBuiltinOrFrameworkType; var optionValue = optionSet.GetOption(option, model.Language)!; @@ -173,7 +173,7 @@ internal static Diagnostic CreateDiagnostic(SemanticModel model, OptionSet optio var tree = model.SyntaxTree; var builder = ImmutableDictionary.CreateBuilder(); - builder["OptionName"] = nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one + builder["OptionName"] = nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one builder["OptionLanguage"] = model.Language; var diagnostic = DiagnosticHelper.Create(descriptor, tree.GetLocation(issueSpan), severity, additionalLocations: null, builder.ToImmutable()); diff --git a/src/Features/Core/Portable/SolutionCrawler/InternalSolutionCrawlerOptions.cs b/src/Features/Core/Portable/SolutionCrawler/InternalSolutionCrawlerOptions.cs index 93e91e4bbc2ae..8fd219b5d381d 100644 --- a/src/Features/Core/Portable/SolutionCrawler/InternalSolutionCrawlerOptions.cs +++ b/src/Features/Core/Portable/SolutionCrawler/InternalSolutionCrawlerOptions.cs @@ -10,28 +10,28 @@ internal static class InternalSolutionCrawlerOptions { private const string LocalRegistryPath = @"Roslyn\Internal\SolutionCrawler\"; - public static readonly Option SolutionCrawler = new Option(nameof(InternalSolutionCrawlerOptions), "Solution Crawler", defaultValue: true, + public static readonly Option2 SolutionCrawler = new Option2(nameof(InternalSolutionCrawlerOptions), "Solution Crawler", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Solution Crawler")); - public static readonly Option DirectDependencyPropagationOnly = new Option(nameof(InternalSolutionCrawlerOptions), "Project propagation only on direct dependency", defaultValue: true, + public static readonly Option2 DirectDependencyPropagationOnly = new Option2(nameof(InternalSolutionCrawlerOptions), "Project propagation only on direct dependency", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project propagation only on direct dependency")); - public static readonly Option ActiveFileWorkerBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "Active file worker backoff timespan in ms", defaultValue: 400, + public static readonly Option2 ActiveFileWorkerBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "Active file worker backoff timespan in ms", defaultValue: 400, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Active file worker backoff timespan in ms")); - public static readonly Option AllFilesWorkerBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "All files worker backoff timespan in ms", defaultValue: 1500, + public static readonly Option2 AllFilesWorkerBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "All files worker backoff timespan in ms", defaultValue: 1500, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "All files worker backoff timespan in ms")); - public static readonly Option EntireProjectWorkerBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "Entire project analysis worker backoff timespan in ms", defaultValue: 5000, + public static readonly Option2 EntireProjectWorkerBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "Entire project analysis worker backoff timespan in ms", defaultValue: 5000, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Entire project analysis worker backoff timespan in ms")); - public static readonly Option SemanticChangeBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "Semantic change backoff timespan in ms", defaultValue: 100, + public static readonly Option2 SemanticChangeBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "Semantic change backoff timespan in ms", defaultValue: 100, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Semantic change backoff timespan in ms")); - public static readonly Option ProjectPropagationBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "Project propagation backoff timespan in ms", defaultValue: 500, + public static readonly Option2 ProjectPropagationBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "Project propagation backoff timespan in ms", defaultValue: 500, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project propagation backoff timespan in ms")); - public static readonly Option PreviewBackOffTimeSpanInMS = new Option(nameof(InternalSolutionCrawlerOptions), "Preview backoff timespan in ms", defaultValue: 500, + public static readonly Option2 PreviewBackOffTimeSpanInMS = new Option2(nameof(InternalSolutionCrawlerOptions), "Preview backoff timespan in ms", defaultValue: 500, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Preview backoff timespan in ms")); } } diff --git a/src/Features/Core/Portable/Structure/BlockStructureOptions.cs b/src/Features/Core/Portable/Structure/BlockStructureOptions.cs index 55bb88f6d426a..bca9a5db6bb78 100644 --- a/src/Features/Core/Portable/Structure/BlockStructureOptions.cs +++ b/src/Features/Core/Portable/Structure/BlockStructureOptions.cs @@ -10,35 +10,35 @@ namespace Microsoft.CodeAnalysis.Structure { internal static class BlockStructureOptions { - public static readonly PerLanguageOption ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions)}")); - public static readonly PerLanguageOption ShowBlockStructureGuidesForDeclarationLevelConstructs = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowBlockStructureGuidesForDeclarationLevelConstructs = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs)}")); - public static readonly PerLanguageOption ShowBlockStructureGuidesForCodeLevelConstructs = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowBlockStructureGuidesForCodeLevelConstructs = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCodeLevelConstructs)}")); - public static readonly PerLanguageOption ShowOutliningForCommentsAndPreprocessorRegions = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowOutliningForCommentsAndPreprocessorRegions = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowOutliningForCommentsAndPreprocessorRegions), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCommentsAndPreprocessorRegions)}")); - public static readonly PerLanguageOption ShowOutliningForDeclarationLevelConstructs = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowOutliningForDeclarationLevelConstructs = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowOutliningForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForDeclarationLevelConstructs)}")); - public static readonly PerLanguageOption ShowOutliningForCodeLevelConstructs = new PerLanguageOption( + public static readonly PerLanguageOption2 ShowOutliningForCodeLevelConstructs = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(ShowOutliningForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCodeLevelConstructs)}")); - public static readonly PerLanguageOption CollapseRegionsWhenCollapsingToDefinitions = new PerLanguageOption( + public static readonly PerLanguageOption2 CollapseRegionsWhenCollapsingToDefinitions = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(CollapseRegionsWhenCollapsingToDefinitions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(CollapseRegionsWhenCollapsingToDefinitions)}")); - public static readonly PerLanguageOption MaximumBannerLength = new PerLanguageOption( + public static readonly PerLanguageOption2 MaximumBannerLength = new PerLanguageOption2( nameof(BlockStructureOptions), nameof(MaximumBannerLength), defaultValue: 80, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(MaximumBannerLength)}")); diff --git a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs index 93c89eb1405ab..bbb0a401c6a9f 100644 --- a/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs +++ b/src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyAnalyzer.cs @@ -24,7 +24,7 @@ internal abstract class AbstractUseAutoPropertyAnalyzer< FeaturesResources.ResourceManager, typeof(FeaturesResources)); protected AbstractUseAutoPropertyAnalyzer() - : base(IDEDiagnosticIds.UseAutoPropertyDiagnosticId, CodeStyleOptions.PreferAutoProperties, s_title, s_title) + : base(IDEDiagnosticIds.UseAutoPropertyDiagnosticId, CodeStyleOptions2.PreferAutoProperties, s_title, s_title) { } @@ -52,7 +52,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(CodeStyleOptions.PreferAutoProperties, semanticModel.Language); + var option = context.GetOption(CodeStyleOptions2.PreferAutoProperties, semanticModel.Language); if (!option.Value) { return; @@ -312,7 +312,7 @@ private void Process(AnalysisResult result, SemanticModelAnalysisContext context var additionalLocations = ImmutableArray.Create( propertyDeclaration.GetLocation(), variableDeclarator.GetLocation()); - var option = context.GetOption(CodeStyleOptions.PreferAutoProperties, propertyDeclaration.Language); + var option = context.GetOption(CodeStyleOptions2.PreferAutoProperties, propertyDeclaration.Language); if (option.Notification.Severity == ReportDiagnostic.Suppress) { // Avoid reporting diagnostics when the feature is disabled. This primarily avoids reporting the hidden diff --git a/src/Features/Core/Portable/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs index 8b1807992a344..9efd41c8274ee 100644 --- a/src/Features/Core/Portable/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseCompoundAssignment/AbstractUseCompoundAssignmentDiagnosticAnalyzer.cs @@ -39,7 +39,7 @@ protected AbstractUseCompoundAssignmentDiagnosticAnalyzer( ISyntaxFacts syntaxFacts, ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds) : base(IDEDiagnosticIds.UseCompoundAssignmentDiagnosticId, - CodeStyleOptions.PreferCompoundAssignment, + CodeStyleOptions2.PreferCompoundAssignment, new LocalizableResourceString( nameof(FeaturesResources.Use_compound_assignment), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { @@ -62,7 +62,7 @@ private void AnalyzeAssignment(SyntaxNodeAnalysisContext context) var cancellationToken = context.CancellationToken; var syntaxTree = assignment.SyntaxTree; - var option = context.GetOption(CodeStyleOptions.PreferCompoundAssignment, assignment.Language); + var option = context.GetOption(CodeStyleOptions2.PreferCompoundAssignment, assignment.Language); if (!option.Value) { // Bail immediately if the user has disabled this feature. diff --git a/src/Features/Core/Portable/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs index a5cbe3c5ea596..714a5e1714760 100644 --- a/src/Features/Core/Portable/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseConditionalExpression/AbstractUseConditionalExpressionDiagnosticAnalyzer.cs @@ -18,7 +18,7 @@ internal abstract class AbstractUseConditionalExpressionDiagnosticAnalyzer< : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TIfStatementSyntax : SyntaxNode { - private readonly PerLanguageOption> _option; + private readonly PerLanguageOption2> _option; public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; @@ -26,7 +26,7 @@ public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() protected AbstractUseConditionalExpressionDiagnosticAnalyzer( string descriptorId, LocalizableResourceString message, - PerLanguageOption> option) + PerLanguageOption2> option) : base(descriptorId, option, new LocalizableResourceString(nameof(FeaturesResources.Convert_to_conditional_expression), FeaturesResources.ResourceManager, typeof(FeaturesResources)), diff --git a/src/Features/Core/Portable/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs index 5aae8f065f93e..eaaa04aa5d787 100644 --- a/src/Features/Core/Portable/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseConditionalExpression/ForAssignment/AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer.cs @@ -17,7 +17,7 @@ protected AbstractUseConditionalExpressionForAssignmentDiagnosticAnalyzer( LocalizableResourceString message) : base(IDEDiagnosticIds.UseConditionalExpressionForAssignmentDiagnosticId, message, - CodeStyleOptions.PreferConditionalExpressionOverAssignment) + CodeStyleOptions2.PreferConditionalExpressionOverAssignment) { } diff --git a/src/Features/Core/Portable/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs index 53f4e6168a8f6..bc7ccd7531b74 100644 --- a/src/Features/Core/Portable/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.cs @@ -17,7 +17,7 @@ protected AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer( LocalizableResourceString message) : base(IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId, message, - CodeStyleOptions.PreferConditionalExpressionOverReturn) + CodeStyleOptions2.PreferConditionalExpressionOverReturn) { } diff --git a/src/Features/Core/Portable/UseConditionalExpression/UseConditionalExpressionOptions.cs b/src/Features/Core/Portable/UseConditionalExpression/UseConditionalExpressionOptions.cs index ec60239e7fb84..5e3090cb9028c 100644 --- a/src/Features/Core/Portable/UseConditionalExpression/UseConditionalExpressionOptions.cs +++ b/src/Features/Core/Portable/UseConditionalExpression/UseConditionalExpressionOptions.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionOptions { - public static readonly PerLanguageOption ConditionalExpressionWrappingLength = new PerLanguageOption( + public static readonly PerLanguageOption2 ConditionalExpressionWrappingLength = new PerLanguageOption2( nameof(UseConditionalExpressionOptions), nameof(ConditionalExpressionWrappingLength), defaultValue: 120, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ConditionalExpressionWrappingLength)}")); diff --git a/src/Features/Core/Portable/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs index da75153c5fc68..11c97f306188d 100644 --- a/src/Features/Core/Portable/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseExplicitTupleName/UseExplicitTupleNameDiagnosticAnalyzer.cs @@ -18,7 +18,7 @@ internal class UseExplicitTupleNameDiagnosticAnalyzer : AbstractBuiltInCodeStyle public UseExplicitTupleNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseExplicitTupleNameDiagnosticId, - CodeStyleOptions.PreferExplicitTupleNames, + CodeStyleOptions2.PreferExplicitTupleNames, title: new LocalizableResourceString(nameof(FeaturesResources.Use_explicitly_provided_tuple_name), FeaturesResources.ResourceManager, typeof(FeaturesResources)), messageFormat: new LocalizableResourceString(nameof(FeaturesResources.Prefer_explicitly_provided_tuple_element_name), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { @@ -32,7 +32,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(CodeStyleOptions.PreferExplicitTupleNames, context.Compilation.Language); + var option = context.GetOption(CodeStyleOptions2.PreferExplicitTupleNames, context.Compilation.Language); if (!option.Value) { return; diff --git a/src/Features/Core/Portable/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs index c118d7018d4b2..992c466304e05 100644 --- a/src/Features/Core/Portable/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseInferredMemberName/AbstractUseInferredMemberNameDiagnosticAnalyzer.cs @@ -16,7 +16,7 @@ internal abstract class AbstractUseInferredMemberNameDiagnosticAnalyzer : Abstra public AbstractUseInferredMemberNameDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId, - options: ImmutableHashSet.Create(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, CodeStyleOptions.PreferInferredTupleNames), + options: ImmutableHashSet.Create(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, CodeStyleOptions2.PreferInferredTupleNames), new LocalizableResourceString(nameof(FeaturesResources.Use_inferred_member_name), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.Member_name_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { diff --git a/src/Features/Core/Portable/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs index 811acac4ccaa5..0c64b73f98491 100644 --- a/src/Features/Core/Portable/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsDiagnosticAnalyzer.cs @@ -20,7 +20,7 @@ internal abstract class AbstractUseIsNullCheckForReferenceEqualsDiagnosticAnalyz { protected AbstractUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer(LocalizableString title) : base(IDEDiagnosticIds.UseIsNullCheckDiagnosticId, - CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, + CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, title, new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { @@ -63,7 +63,7 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, IMethodSymbol refe return; } - var option = context.GetOption(CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language); + var option = context.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language); if (!option.Value) { return; diff --git a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs b/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs index 9d5244b6ce056..db7ca87bde76b 100644 --- a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs @@ -15,7 +15,7 @@ internal class UseSystemHashCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDia { public UseSystemHashCodeDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSystemHashCode, - CodeStyleOptions.PreferSystemHashCode, + CodeStyleOptions2.PreferSystemHashCode, new LocalizableResourceString(nameof(FeaturesResources.Use_System_HashCode), FeaturesResources.ResourceManager, typeof(FeaturesResources)), new LocalizableResourceString(nameof(FeaturesResources.GetHashCode_implementation_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) { @@ -54,7 +54,7 @@ private void AnalyzeOperationBlock(Analyzer analyzer, OperationBlockAnalysisCont var syntaxTree = operation.Syntax.SyntaxTree; var cancellationToken = context.CancellationToken; - var option = context.Options.GetOption(CodeStyleOptions.PreferSystemHashCode, operation.Language, syntaxTree, cancellationToken); + var option = context.Options.GetOption(CodeStyleOptions2.PreferSystemHashCode, operation.Language, syntaxTree, cancellationToken); if (option?.Value != true) { return; diff --git a/src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOption.cs b/src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOption.cs index 9caee614fa8de..e4e7564919b5c 100644 --- a/src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOption.cs +++ b/src/Features/Core/Portable/ValidateFormatString/ValidateFormatStringOption.cs @@ -13,8 +13,8 @@ namespace Microsoft.CodeAnalysis.ValidateFormatString { internal class ValidateFormatStringOption { - public static PerLanguageOption ReportInvalidPlaceholdersInStringDotFormatCalls = - new PerLanguageOption( + public static PerLanguageOption2 ReportInvalidPlaceholdersInStringDotFormatCalls = + new PerLanguageOption2( nameof(ValidateFormatStringOption), nameof(ReportInvalidPlaceholdersInStringDotFormatCalls), defaultValue: true, diff --git a/src/Features/Core/Portable/Wrapping/BinaryExpression/BinaryExpressionCodeActionComputer.cs b/src/Features/Core/Portable/Wrapping/BinaryExpression/BinaryExpressionCodeActionComputer.cs index 69e2910d6dd7f..dc2d66d2bc485 100644 --- a/src/Features/Core/Portable/Wrapping/BinaryExpression/BinaryExpressionCodeActionComputer.cs +++ b/src/Features/Core/Portable/Wrapping/BinaryExpression/BinaryExpressionCodeActionComputer.cs @@ -53,7 +53,7 @@ public BinaryExpressionCodeActionComputer( : base(service, document, originalSourceText, options, cancellationToken) { _exprsAndOperators = exprsAndOperators; - _preference = options.GetOption(CodeStyleOptions.OperatorPlacementWhenWrapping); + _preference = options.GetOption(CodeStyleOptions2.OperatorPlacementWhenWrapping); var generator = SyntaxGenerator.GetGenerator(document); diff --git a/src/Features/Directory.Build.targets b/src/Features/Directory.Build.targets new file mode 100644 index 0000000000000..6099ced055532 --- /dev/null +++ b/src/Features/Directory.Build.targets @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb index 888f827632022..a94e150552a41 100644 --- a/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb +++ b/src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicSimplifyTypeNamesDiagnosticAnalyzer.vb @@ -104,10 +104,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames End If ' set proper diagnostic ids. - If replacementSyntax.HasAnnotations(NameOf(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration)) Then + If replacementSyntax.HasAnnotations(NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)) Then inDeclaration = True diagnosticId = IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId - ElseIf replacementSyntax.HasAnnotations(NameOf(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)) Then + ElseIf replacementSyntax.HasAnnotations(NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)) Then inDeclaration = False diagnosticId = IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId ElseIf expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then diff --git a/src/Features/VisualBasic/Portable/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb b/src/Features/VisualBasic/Portable/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb index 2ac6131c0f0b7..11e916de11d51 100644 --- a/src/Features/VisualBasic/Portable/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb +++ b/src/Features/VisualBasic/Portable/UseInferredMemberName/VisualBasicUseInferredMemberNameDiagnosticAnalyzer.vb @@ -51,7 +51,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName Dim argument = DirectCast(nameColonEquals.Parent, SimpleArgumentSyntax) Dim preference = options.GetOption( - CodeStyleOptions.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken) + CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken) If Not preference.Value OrElse Not VisualBasicInferredMemberNameReducer.CanSimplifyTupleName(argument, parseOptions) Then Return @@ -85,7 +85,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName End If Dim preference = options.GetOption( - CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken) + CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken) If Not preference.Value OrElse Not VisualBasicInferredMemberNameReducer.CanSimplifyNamedFieldInitializer(fieldInitializer) Then diff --git a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj index 1c43f16cdcb1e..fef75f9c26d5b 100644 --- a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj +++ b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj @@ -62,6 +62,7 @@ + diff --git a/src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs b/src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs index 503b3c33d77a8..582278788df67 100644 --- a/src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs +++ b/src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs @@ -10,6 +10,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCompletionOptions { - public static PerLanguageOption BlockForCompletionItems => Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems; + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption BlockForCompletionItems { get; } = ((PerLanguageOption)Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems)!; } } diff --git a/src/Tools/ExternalAccess/FSharp/Navigation/FSharpNavigationOptions.cs b/src/Tools/ExternalAccess/FSharp/Navigation/FSharpNavigationOptions.cs index 459b1c8bf19d7..ee5e7d7fa09da 100644 --- a/src/Tools/ExternalAccess/FSharp/Navigation/FSharpNavigationOptions.cs +++ b/src/Tools/ExternalAccess/FSharp/Navigation/FSharpNavigationOptions.cs @@ -9,6 +9,6 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { internal static class FSharpNavigationOptions { - public static Option PreferProvisionalTab => NavigationOptions.PreferProvisionalTab; + public static Option PreferProvisionalTab { get; } = (Option)NavigationOptions.PreferProvisionalTab; } } diff --git a/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs b/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs index 7b03d78d27dbb..66651c6e9cafc 100644 --- a/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs +++ b/src/VisualStudio/CSharp/Impl/Options/AutomationObject.cs @@ -145,46 +145,46 @@ public int HighlightReferences public int Indent_BlockContents { - get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); } - set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.IndentBlock); } + set { SetBooleanOption(CSharpFormattingOptions2.IndentBlock, value); } } public int Indent_Braces { - get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); } - set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.IndentBraces); } + set { SetBooleanOption(CSharpFormattingOptions2.IndentBraces, value); } } public int Indent_CaseContents { - get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); } - set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection); } + set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSection, value); } } public int Indent_CaseContentsWhenBlock { - get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock); } - set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock); } + set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock, value); } } public int Indent_CaseLabels { - get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); } - set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection); } + set { SetBooleanOption(CSharpFormattingOptions2.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { - var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); + var option = _workspace.Options.GetOption(CSharpFormattingOptions2.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options - .WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent))); + .WithChangedOption(CSharpFormattingOptions2.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent))); } } @@ -192,13 +192,13 @@ public int Indent_UnindentLabels { get { - return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); + return (int)_workspace.Options.GetOption(CSharpFormattingOptions2.LabelPositioning); } set { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options - .WithChangedOption(CSharpFormattingOptions.LabelPositioning, value))); + .WithChangedOption(CSharpFormattingOptions2.LabelPositioning, value))); } } @@ -222,92 +222,92 @@ public int SnippetsBehavior public int NewLines_AnonymousTypeInitializer_EachMember { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { - get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); } - set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForCatch); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForCatch, value); } } public int NewLines_Keywords_Else { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForElse); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForElse, value); } } public int NewLines_Keywords_Finally { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForFinally); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { - get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); } - set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery); } + set { SetBooleanOption(CSharpFormattingOptions2.NewLineForClausesInQuery, value); } } public int Refactoring_Verification_Enabled @@ -376,51 +376,51 @@ public int AddImport_SuggestForTypesInNuGetPackages public int Space_AfterBasesColon { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterCast, value); } } public int Space_AfterComma { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterComma, value); } } public int Space_AfterDot { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { - get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); } - set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } + set { SetBooleanOption(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { - var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); + var option = _workspace.Options.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } @@ -428,110 +428,110 @@ public int Space_AroundBinaryOperator { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options - .WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option))); + .WithChangedOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, option))); } } public int Space_BeforeBasesColon { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeComma, value); } } public int Space_BeforeDot { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { - get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); } - set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets); } + set { SetBooleanOption(CSharpFormattingOptions2.SpaceWithinSquareBrackets, value); } } public string Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration_CodeStyle { - get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } - set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } + set { SetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } } public string Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess_CodeStyle { - get { return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } - set { SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } + set { SetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } } public string Style_NamingPreferences @@ -556,26 +556,26 @@ public string Style_NamingPreferences public string Style_QualifyFieldAccess { - get { return GetXmlOption(CodeStyleOptions.QualifyFieldAccess); } - set { SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value); } + get { return GetXmlOption(CodeStyleOptions2.QualifyFieldAccess); } + set { SetXmlOption(CodeStyleOptions2.QualifyFieldAccess, value); } } public string Style_QualifyPropertyAccess { - get { return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess); } - set { SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value); } + get { return GetXmlOption(CodeStyleOptions2.QualifyPropertyAccess); } + set { SetXmlOption(CodeStyleOptions2.QualifyPropertyAccess, value); } } public string Style_QualifyMethodAccess { - get { return GetXmlOption(CodeStyleOptions.QualifyMethodAccess); } - set { SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value); } + get { return GetXmlOption(CodeStyleOptions2.QualifyMethodAccess); } + set { SetXmlOption(CodeStyleOptions2.QualifyMethodAccess, value); } } public string Style_QualifyEventAccess { - get { return GetXmlOption(CodeStyleOptions.QualifyEventAccess); } - set { SetXmlOption(CodeStyleOptions.QualifyEventAccess, value); } + get { return GetXmlOption(CodeStyleOptions2.QualifyEventAccess); } + set { SetXmlOption(CodeStyleOptions2.QualifyEventAccess, value); } } public string Style_PreferThrowExpression @@ -586,26 +586,26 @@ public string Style_PreferThrowExpression public string Style_PreferObjectInitializer { - get { return GetXmlOption(CodeStyleOptions.PreferObjectInitializer); } - set { SetXmlOption(CodeStyleOptions.PreferObjectInitializer, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferObjectInitializer); } + set { SetXmlOption(CodeStyleOptions2.PreferObjectInitializer, value); } } public string Style_PreferCollectionInitializer { - get { return GetXmlOption(CodeStyleOptions.PreferCollectionInitializer); } - set { SetXmlOption(CodeStyleOptions.PreferCollectionInitializer, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferCollectionInitializer); } + set { SetXmlOption(CodeStyleOptions2.PreferCollectionInitializer, value); } } public string Style_PreferCoalesceExpression { - get { return GetXmlOption(CodeStyleOptions.PreferCoalesceExpression); } - set { SetXmlOption(CodeStyleOptions.PreferCoalesceExpression, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferCoalesceExpression); } + set { SetXmlOption(CodeStyleOptions2.PreferCoalesceExpression, value); } } public string Style_PreferNullPropagation { - get { return GetXmlOption(CodeStyleOptions.PreferNullPropagation); } - set { SetXmlOption(CodeStyleOptions.PreferNullPropagation, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferNullPropagation); } + set { SetXmlOption(CodeStyleOptions2.PreferNullPropagation, value); } } public string Style_PreferInlinedVariableDeclaration @@ -616,20 +616,20 @@ public string Style_PreferInlinedVariableDeclaration public string Style_PreferExplicitTupleNames { - get { return GetXmlOption(CodeStyleOptions.PreferExplicitTupleNames); } - set { SetXmlOption(CodeStyleOptions.PreferExplicitTupleNames, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferExplicitTupleNames); } + set { SetXmlOption(CodeStyleOptions2.PreferExplicitTupleNames, value); } } public string Style_PreferInferredTupleNames { - get { return GetXmlOption(CodeStyleOptions.PreferInferredTupleNames); } - set { SetXmlOption(CodeStyleOptions.PreferInferredTupleNames, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferInferredTupleNames); } + set { SetXmlOption(CodeStyleOptions2.PreferInferredTupleNames, value); } } public string Style_PreferInferredAnonymousTypeMemberNames { - get { return GetXmlOption(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames); } - set { SetXmlOption(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames); } + set { SetXmlOption(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, value); } } [Obsolete("Use Style_UseImplicitTypeWherePossible, Style_UseImplicitTypeWhereApparent or Style_UseImplicitTypeForIntrinsicTypes", error: true)] @@ -725,76 +725,76 @@ public string Style_PreferBraces public string Style_PreferReadonly { - get { return GetXmlOption(CodeStyleOptions.PreferReadonly); } - set { SetXmlOption(CodeStyleOptions.PreferReadonly, value); } + get { return GetXmlOption(CodeStyleOptions2.PreferReadonly); } + set { SetXmlOption(CodeStyleOptions2.PreferReadonly, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { - return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); + return (int)_workspace.Options.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator); } set { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options - .WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value))); + .WithChangedOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator, value))); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { - get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); } - set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration); } + set { SetBooleanOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { - get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); } - set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine); } + set { SetBooleanOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { - get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); } - set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); } + get { return GetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine); } + set { SetBooleanOption(CSharpFormattingOptions2.WrappingPreserveSingleLine, value); } } - private int GetBooleanOption(Option key) + private int GetBooleanOption(Option2 key) { return _workspace.Options.GetOption(key) ? 1 : 0; } - private int GetBooleanOption(PerLanguageOption key) + private int GetBooleanOption(PerLanguageOption2 key) { return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } - private T GetOption(PerLanguageOption key) + private T GetOption(PerLanguageOption2 key) { return _workspace.Options.GetOption(key, LanguageNames.CSharp); } - private void SetBooleanOption(Option key, int value) + private void SetBooleanOption(Option2 key, int value) { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, value != 0))); } - private void SetBooleanOption(PerLanguageOption key, int value) + private void SetBooleanOption(PerLanguageOption2 key, int value) { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, LanguageNames.CSharp, value != 0))); } - private void SetOption(PerLanguageOption key, T value) + private void SetOption(PerLanguageOption2 key, T value) { _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, LanguageNames.CSharp, value))); } - private int GetBooleanOption(PerLanguageOption key) + private int GetBooleanOption(PerLanguageOption2 key) { var option = _workspace.Options.GetOption(key, LanguageNames.CSharp); if (!option.HasValue) @@ -805,33 +805,33 @@ private int GetBooleanOption(PerLanguageOption key) return option.Value ? 1 : 0; } - private string GetXmlOption(Option> option) + private string GetXmlOption(Option2> option) { return _workspace.Options.GetOption(option).ToXElement().ToString(); } - private void SetBooleanOption(PerLanguageOption key, int value) + private void SetBooleanOption(PerLanguageOption2 key, int value) { var boolValue = (value < 0) ? (bool?)null : (value > 0); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(key, LanguageNames.CSharp, boolValue))); } - private string GetXmlOption(PerLanguageOption> option) + private string GetXmlOption(PerLanguageOption2> option) { return _workspace.Options.GetOption(option, LanguageNames.CSharp).ToXElement().ToString(); } - private void SetXmlOption(Option> option, string value) + private void SetXmlOption(Option2> option, string value) { - var convertedValue = CodeStyleOption.FromXElement(XElement.Parse(value)); + var convertedValue = CodeStyleOption2.FromXElement(XElement.Parse(value)); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(option, convertedValue))); } - private void SetXmlOption(PerLanguageOption> option, string value) + private void SetXmlOption(PerLanguageOption2> option, string value) { - var convertedValue = CodeStyleOption.FromXElement(XElement.Parse(value)); + var convertedValue = CodeStyleOption2.FromXElement(XElement.Parse(value)); _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(option, LanguageNames.CSharp, convertedValue))); } diff --git a/src/VisualStudio/CSharp/Impl/Options/Formatting/CodeStylePage.cs b/src/VisualStudio/CSharp/Impl/Options/Formatting/CodeStylePage.cs index 16f5675c91e0d..f22f638b53f42 100644 --- a/src/VisualStudio/CSharp/Impl/Options/Formatting/CodeStylePage.cs +++ b/src/VisualStudio/CSharp/Impl/Options/Formatting/CodeStylePage.cs @@ -32,8 +32,8 @@ protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider s { var builder = ArrayBuilder<(string, ImmutableArray)>.GetInstance(); builder.AddRange(GridOptionPreviewControl.GetLanguageAgnosticEditorConfigOptions()); - builder.Add((CSharpVSResources.CSharp_Coding_Conventions, CSharpCodeStyleOptions.AllOptions)); - builder.Add((CSharpVSResources.CSharp_Formatting_Rules, CSharpFormattingOptions.AllOptions)); + builder.Add((CSharpVSResources.CSharp_Coding_Conventions, CSharpCodeStyleOptions.AllOptions.As())); + builder.Add((CSharpVSResources.CSharp_Formatting_Rules, CSharpFormattingOptions2.AllOptions.As())); return builder.ToImmutableAndFree(); } diff --git a/src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingOptionPageControl.xaml.cs b/src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingOptionPageControl.xaml.cs index ba51637f3540e..32d68f9a56919 100644 --- a/src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingOptionPageControl.xaml.cs +++ b/src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingOptionPageControl.xaml.cs @@ -34,7 +34,7 @@ public FormattingOptionPageControl(OptionStore optionStore) : base(optionStore) BindToOption(FormatWhenTypingCheckBox, FeatureOnOffOptions.AutoFormattingOnTyping, LanguageNames.CSharp); BindToOption(FormatOnCloseBraceCheckBox, FeatureOnOffOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp); BindToOption(FormatOnSemicolonCheckBox, FeatureOnOffOptions.AutoFormattingOnSemicolon, LanguageNames.CSharp); - BindToOption(FormatOnReturnCheckBox, FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp); + BindToOption(FormatOnReturnCheckBox, FormattingOptions2.AutoFormattingOnReturn, LanguageNames.CSharp); BindToOption(FormatOnPasteCheckBox, FeatureOnOffOptions.FormatOnPaste, LanguageNames.CSharp); } } diff --git a/src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.cs b/src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.cs index 262706ec12b94..966d72d09fef3 100644 --- a/src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.cs +++ b/src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.cs @@ -1660,13 +1660,13 @@ internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvide new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false), }; - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); // Use var CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); @@ -1675,27 +1675,27 @@ internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvide // Code block AddBracesOptions(optionStore, codeBlockPreferencesGroupTitle); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleUsingStatement, ServicesVSResources.Prefer_simple_using_statement, s_preferSimpleUsingStatement, s_preferSimpleUsingStatement, this, optionStore, codeBlockPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle)); AddParenthesesOptions(OptionStore); // Expression preferences - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSwitchExpression, CSharpVSResources.Prefer_switch_expression, s_preferSwitchExpression, s_preferSwitchExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, CSharpVSResources.Prefer_pattern_matching_over_is_with_cast_check, s_preferPatternMatchingOverIsWithCastCheck, s_preferPatternMatchingOverIsWithCastCheck, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, CSharpVSResources.Prefer_pattern_matching_over_as_with_null_check, s_preferPatternMatchingOverAsWithNullCheck, s_preferPatternMatchingOverAsWithNullCheck, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, ServicesVSResources.Prefer_simple_default_expression, s_preferSimpleDefaultExpression, s_preferSimpleDefaultExpression, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, ServicesVSResources.Prefer_local_function_over_anonymous_function, s_preferLocalFunctionOverAnonymousFunction, s_preferLocalFunctionOverAnonymousFunction, this, optionStore, expressionPreferencesGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferIndexOperator, ServicesVSResources.Prefer_index_operator, s_preferIndexOperator, s_preferIndexOperator, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferRangeOperator, ServicesVSResources.Prefer_range_operator, s_preferRangeOperator, s_preferRangeOperator, this, optionStore, expressionPreferencesGroupTitle)); @@ -1710,9 +1710,9 @@ internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvide // Null preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferThrowExpression, CSharpVSResources.Prefer_throw_expression, s_preferThrowExpression, s_preferThrowExpression, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferConditionalDelegateCall, CSharpVSResources.Prefer_conditional_delegate_call, s_preferConditionalDelegateCall, s_preferConditionalDelegateCall, this, optionStore, nullCheckingGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle)); - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle)); // Using directive preferences. CodeStyleItems.Add(new EnumCodeStyleOptionViewModel( @@ -1721,7 +1721,7 @@ internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvide s_usingDirectivePlacement, this, optionStore, usingsGroupTitle, usingDirectivePlacementPreferences)); // Modifier preferences. - CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle)); + CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferStaticLocalFunction, ServicesVSResources.Prefer_static_local_functions, s_preferStaticLocalFunction, s_preferStaticLocalFunction, this, optionStore, modifierGroupTitle)); // Parameter preferences @@ -1731,25 +1731,25 @@ internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvide private void AddParenthesesOptions(OptionStore optionStore) { AddParenthesesOption( - LanguageNames.CSharp, optionStore, CodeStyleOptions.ArithmeticBinaryParentheses, + LanguageNames.CSharp, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, CSharpVSResources.In_arithmetic_binary_operators, new[] { s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( - LanguageNames.CSharp, optionStore, CodeStyleOptions.OtherBinaryParentheses, + LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherBinaryParentheses, CSharpVSResources.In_other_binary_operators, new[] { s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( - LanguageNames.CSharp, optionStore, CodeStyleOptions.RelationalBinaryParentheses, + LanguageNames.CSharp, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, CSharpVSResources.In_relational_binary_operators, new[] { s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( - LanguageNames.CSharp, optionStore, CodeStyleOptions.OtherParentheses, + LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, new[] { s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary }, defaultAddForClarity: false); diff --git a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs index 182eae47a1695..583a6357386e3 100644 --- a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs +++ b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupCommandHandlerTests.cs @@ -886,7 +886,7 @@ void M() MyEvent +$$ } }"; - using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption.Error)); + using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption2.Error)); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); @@ -976,7 +976,7 @@ void M() MyEvent +$$ } }"; - using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption.Silent)); + using var testState = EventHookupTestState.CreateTestState(markup, QualifyMethodAccessWithNotification(NotificationOption2.Silent)); testState.SendTypeChar('='); testState.SendTab(); await testState.WaitForAsynchronousOperationsAsync(); @@ -998,7 +998,7 @@ private void C_MyEvent() testState.AssertCodeIs(expectedCode); } - private IDictionary QualifyMethodAccessWithNotification(NotificationOption notification) - => new Dictionary() { { new OptionKey(CodeStyleOptions.QualifyMethodAccess, LanguageNames.CSharp), new CodeStyleOption(true, notification) } }; + private IDictionary QualifyMethodAccessWithNotification(NotificationOption2 notification) + => new Dictionary() { { new OptionKey2(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.CSharp), new CodeStyleOption2(true, notification) } }; } } diff --git a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs index 2736b495dd031..abd14cd503ea5 100644 --- a/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs +++ b/src/VisualStudio/CSharp/Test/EventHookup/EventHookupTestState.cs @@ -24,7 +24,7 @@ internal sealed class EventHookupTestState : AbstractCommandHandlerTestState private readonly EventHookupCommandHandler _commandHandler; private readonly Mutex _testSessionHookupMutex; - public EventHookupTestState(XElement workspaceElement, IDictionary options) + public EventHookupTestState(XElement workspaceElement, IDictionary options) : base(workspaceElement, GetExtraParts()) { _commandHandler = new EventHookupCommandHandler( @@ -43,7 +43,7 @@ private static ComposableCatalog GetExtraParts() return ExportProviderCache.CreateTypeCatalog(new[] { typeof(EventHookupCommandHandler), typeof(EventHookupSessionManager) }); } - public static EventHookupTestState CreateTestState(string markup, IDictionary options = null) + public static EventHookupTestState CreateTestState(string markup, IDictionary options = null) { var workspaceXml = string.Format(@" diff --git a/src/VisualStudio/CSharp/Test/PersistentStorage/OptionServiceMock.cs b/src/VisualStudio/CSharp/Test/PersistentStorage/OptionServiceMock.cs index bb7aa498d98f9..fc177b3b1d0ca 100644 --- a/src/VisualStudio/CSharp/Test/PersistentStorage/OptionServiceMock.cs +++ b/src/VisualStudio/CSharp/Test/PersistentStorage/OptionServiceMock.cs @@ -36,11 +36,21 @@ public T GetOption(Option option) return (T)_optionsByOption[option]; } + public T GetOption(Option2 option) + { + return (T)_optionsByOption[option]; + } + public T GetOption(PerLanguageOption option, string languageName) { throw new NotImplementedException(); } + public T GetOption(PerLanguageOption2 option, string languageName) + { + throw new NotImplementedException(); + } + public SerializableOptionSet GetOptions() { throw new NotImplementedException(); diff --git a/src/VisualStudio/Core/Def/Implementation/PreviewPane/PreviewPaneService.cs b/src/VisualStudio/Core/Def/Implementation/PreviewPane/PreviewPaneService.cs index d557f1d3bf12b..ebcbfecd2241a 100644 --- a/src/VisualStudio/Core/Def/Implementation/PreviewPane/PreviewPaneService.cs +++ b/src/VisualStudio/Core/Def/Implementation/PreviewPane/PreviewPaneService.cs @@ -126,7 +126,7 @@ private Guid GetOptionPageGuidForOptionName(string optionName, string optionLang return Guid.Parse(Guids.VisualBasicOptionPageNamingStyleIdString); } } - else if (optionName == nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration)) + else if (optionName == nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)) { if (optionLanguage == LanguageNames.CSharp) { diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioNavigationOptions.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioNavigationOptions.cs index 008a40baed1dc..a8b0124619b8c 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioNavigationOptions.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioNavigationOptions.cs @@ -10,7 +10,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal static class VisualStudioNavigationOptions { - public static readonly PerLanguageOption NavigateToObjectBrowser = new PerLanguageOption(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false, + public static readonly PerLanguageOption2 NavigateToObjectBrowser = new PerLanguageOption2(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NavigateToObjectBrowser")); } } diff --git a/src/VisualStudio/Core/Def/SymbolSearch/AbstractDelayStartedService.cs b/src/VisualStudio/Core/Def/SymbolSearch/AbstractDelayStartedService.cs index 4f831b30cc839..da69f3373f2b3 100644 --- a/src/VisualStudio/Core/Def/SymbolSearch/AbstractDelayStartedService.cs +++ b/src/VisualStudio/Core/Def/SymbolSearch/AbstractDelayStartedService.cs @@ -27,18 +27,18 @@ internal abstract class AbstractDelayStartedService : ForegroundThreadAffinitize protected readonly Workspace Workspace; // Option that controls if this service is enabled or not (regardless of language). - private readonly Option _serviceOnOffOption; + private readonly Option2 _serviceOnOffOption; // Options that control if this service is enabled or not for a particular language. - private readonly ImmutableArray> _perLanguageOptions; + private readonly ImmutableArray> _perLanguageOptions; private bool _enabled = false; protected AbstractDelayStartedService( IThreadingContext threadingContext, Workspace workspace, - Option onOffOption, - params PerLanguageOption[] perLanguageOptions) + Option2 onOffOption, + params PerLanguageOption2[] perLanguageOptions) : base(threadingContext) { Workspace = workspace; diff --git a/src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs b/src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs index bcadf4301ff5b..6d078809cce98 100644 --- a/src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs +++ b/src/VisualStudio/Core/Impl/Options/AbstractOptionPageControl.cs @@ -61,7 +61,7 @@ private void InitializeStyles() Resources.Add(typeof(ComboBox), comboBoxStyle); } - protected void BindToOption(CheckBox checkbox, Option optionKey) + private protected void BindToOption(CheckBox checkbox, Option2 optionKey) { var binding = new Binding() { @@ -74,7 +74,7 @@ protected void BindToOption(CheckBox checkbox, Option optionKey) _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(CheckBox checkbox, PerLanguageOption optionKey, string languageName) + private protected void BindToOption(CheckBox checkbox, PerLanguageOption2 optionKey, string languageName) { var binding = new Binding() { @@ -87,7 +87,7 @@ protected void BindToOption(CheckBox checkbox, PerLanguageOption optionKey _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(TextBox textBox, Option optionKey) + private protected void BindToOption(TextBox textBox, Option2 optionKey) { var binding = new Binding() { @@ -100,7 +100,7 @@ protected void BindToOption(TextBox textBox, Option optionKey) _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(TextBox textBox, PerLanguageOption optionKey, string languageName) + private protected void BindToOption(TextBox textBox, PerLanguageOption2 optionKey, string languageName) { var binding = new Binding() { @@ -113,7 +113,7 @@ protected void BindToOption(TextBox textBox, PerLanguageOption optionKey, s _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(ComboBox comboBox, Option optionKey) + private protected void BindToOption(ComboBox comboBox, Option2 optionKey) { var binding = new Binding() { @@ -127,7 +127,7 @@ protected void BindToOption(ComboBox comboBox, Option optionKey) _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(ComboBox comboBox, PerLanguageOption optionKey, string languageName) + private protected void BindToOption(ComboBox comboBox, PerLanguageOption2 optionKey, string languageName) { var binding = new Binding() { @@ -141,7 +141,7 @@ protected void BindToOption(ComboBox comboBox, PerLanguageOption optionKey _bindingExpressions.Add(bindingExpression); } - protected void BindToOption(RadioButton radiobutton, PerLanguageOption optionKey, T optionValue, string languageName) + private protected void BindToOption(RadioButton radiobutton, PerLanguageOption2 optionKey, T optionValue, string languageName) { var binding = new Binding() { diff --git a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs index 72b401d8fb450..c61c774fa3809 100644 --- a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs @@ -214,7 +214,7 @@ private void UpdateDocument(string text) protected void AddParenthesesOption( string language, OptionStore optionStore, - PerLanguageOption> languageOption, + PerLanguageOption2> languageOption, string title, string[] examples, bool defaultAddForClarity) { var preferences = new List(); @@ -249,7 +249,7 @@ protected void AddUnusedParameterOption(string language, OptionStore optionStore }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel( - CodeStyleOptions.UnusedParameters, language, + CodeStyleOptions2.UnusedParameters, language, ServicesVSResources.Avoid_unused_parameters, enumValues, examples, this, optionStore, title, unusedParameterPreferences)); diff --git a/src/VisualStudio/Core/Impl/Options/GridOptionPreviewControl.xaml.cs b/src/VisualStudio/Core/Impl/Options/GridOptionPreviewControl.xaml.cs index 678b062a24373..38c0c40d4de63 100644 --- a/src/VisualStudio/Core/Impl/Options/GridOptionPreviewControl.xaml.cs +++ b/src/VisualStudio/Core/Impl/Options/GridOptionPreviewControl.xaml.cs @@ -56,8 +56,8 @@ internal GridOptionPreviewControl(IServiceProvider serviceProvider, internal static IEnumerable<(string feature, ImmutableArray options)> GetLanguageAgnosticEditorConfigOptions() { - yield return (WorkspacesResources.Core_EditorConfig_Options, FormattingOptions.AllOptions); - yield return (WorkspacesResources.dot_NET_Coding_Conventions, GenerationOptions.AllOptions.Concat(CodeStyleOptions.AllOptions)); + yield return (WorkspacesResources.Core_EditorConfig_Options, FormattingOptions2.AllOptions.As()); + yield return (WorkspacesResources.dot_NET_Coding_Conventions, GenerationOptions.AllOptions.AddRange(CodeStyleOptions2.AllOptions).As()); } private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) diff --git a/src/VisualStudio/Core/Impl/Options/OptionBinding.cs b/src/VisualStudio/Core/Impl/Options/OptionBinding.cs index 6e5e9873c3ba8..50a902120b5e6 100644 --- a/src/VisualStudio/Core/Impl/Options/OptionBinding.cs +++ b/src/VisualStudio/Core/Impl/Options/OptionBinding.cs @@ -10,11 +10,11 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options internal class OptionBinding : INotifyPropertyChanged { private readonly OptionStore _optionStore; - private readonly Option _key; + private readonly Option2 _key; public event PropertyChangedEventHandler PropertyChanged; - public OptionBinding(OptionStore optionStore, Option key) + public OptionBinding(OptionStore optionStore, Option2 key) { _optionStore = optionStore; _key = key; diff --git a/src/VisualStudio/Core/Impl/Options/OptionStore.cs b/src/VisualStudio/Core/Impl/Options/OptionStore.cs index db97232e7e6fb..a9730ec1d9448 100644 --- a/src/VisualStudio/Core/Impl/Options/OptionStore.cs +++ b/src/VisualStudio/Core/Impl/Options/OptionStore.cs @@ -27,7 +27,9 @@ public OptionStore(OptionSet optionSet, IEnumerable registeredOptions) public object GetOption(OptionKey optionKey) => _optionSet.GetOption(optionKey); public T GetOption(Option option) => _optionSet.GetOption(option); + internal T GetOption(Option2 option) => _optionSet.GetOption(option); public T GetOption(PerLanguageOption option, string language) => _optionSet.GetOption(option, language); + internal T GetOption(PerLanguageOption2 option, string language) => _optionSet.GetOption(option, language); public OptionSet GetOptions() => _optionSet; public void SetOption(OptionKey optionKey, object value) @@ -44,6 +46,13 @@ public void SetOption(Option option, T value) OnOptionChanged(new OptionKey(option)); } + internal void SetOption(Option2 option, T value) + { + _optionSet = _optionSet.WithChangedOption(option, value); + + OnOptionChanged(new OptionKey(option)); + } + public void SetOption(PerLanguageOption option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); @@ -51,6 +60,13 @@ public void SetOption(PerLanguageOption option, string language, T value) OnOptionChanged(new OptionKey(option, language)); } + internal void SetOption(PerLanguageOption2 option, string language, T value) + { + _optionSet = _optionSet.WithChangedOption(option, language, value); + + OnOptionChanged(new OptionKey(option, language)); + } + public IEnumerable GetRegisteredOptions() { return _registeredOptions; diff --git a/src/VisualStudio/Core/Impl/Options/PerLanguageOptionBinding.cs b/src/VisualStudio/Core/Impl/Options/PerLanguageOptionBinding.cs index 109dffd3879a4..91c14ed192e12 100644 --- a/src/VisualStudio/Core/Impl/Options/PerLanguageOptionBinding.cs +++ b/src/VisualStudio/Core/Impl/Options/PerLanguageOptionBinding.cs @@ -10,12 +10,12 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options internal class PerLanguageOptionBinding : INotifyPropertyChanged { private readonly OptionStore _optionStore; - private readonly PerLanguageOption _key; + private readonly PerLanguageOption2 _key; private readonly string _languageName; public event PropertyChangedEventHandler PropertyChanged; - public PerLanguageOptionBinding(OptionStore optionStore, PerLanguageOption key, string languageName) + public PerLanguageOptionBinding(OptionStore optionStore, PerLanguageOption2 key, string languageName) { _optionStore = optionStore; _key = key; diff --git a/src/VisualStudio/Core/Impl/Options/Style/EnumCodeStyleOptionViewModel.cs b/src/VisualStudio/Core/Impl/Options/Style/EnumCodeStyleOptionViewModel.cs index 50b0ae929dd7c..8ebd3eaafe488 100644 --- a/src/VisualStudio/Core/Impl/Options/Style/EnumCodeStyleOptionViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/Style/EnumCodeStyleOptionViewModel.cs @@ -36,7 +36,7 @@ static EnumCodeStyleOptionViewModel() private NotificationOptionViewModel _selectedNotificationPreference; public EnumCodeStyleOptionViewModel( - PerLanguageOption> option, + PerLanguageOption2> option, string language, string description, T[] enumValues, @@ -51,7 +51,7 @@ public EnumCodeStyleOptionViewModel( } public EnumCodeStyleOptionViewModel( - Option> option, + Option2> option, string description, T[] enumValues, string[] previews, diff --git a/src/VisualStudio/Core/Test.Next/Services/VisualStudioDiagnosticAnalyzerExecutorTests.cs b/src/VisualStudio/Core/Test.Next/Services/VisualStudioDiagnosticAnalyzerExecutorTests.cs index 08fb9c4493296..de4d48053c33a 100644 --- a/src/VisualStudio/Core/Test.Next/Services/VisualStudioDiagnosticAnalyzerExecutorTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/VisualStudioDiagnosticAnalyzerExecutorTests.cs @@ -17,6 +17,7 @@ using Microsoft.CodeAnalysis.Diagnostics.EngineV2; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Execution; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; @@ -80,7 +81,7 @@ End Sub { // set option workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(CodeStyleOptions.PreferNullPropagation, LanguageNames.VisualBasic, new CodeStyleOption(false, NotificationOption.Silent)))); + .WithChangedOption(CodeStyleOptions2.PreferNullPropagation, LanguageNames.VisualBasic, new CodeStyleOption2(false, NotificationOption2.Silent)))); var analyzerType = typeof(VisualBasicUseNullPropagationDiagnosticAnalyzer); var analyzerResult = await AnalyzeAsync(workspace, workspace.CurrentSolution.ProjectIds.First(), analyzerType); @@ -89,7 +90,7 @@ End Sub // set option workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(CodeStyleOptions.PreferNullPropagation, LanguageNames.VisualBasic, new CodeStyleOption(true, NotificationOption.Error)))); + .WithChangedOption(CodeStyleOptions2.PreferNullPropagation, LanguageNames.VisualBasic, new CodeStyleOption2(true, NotificationOption2.Error)))); analyzerResult = await AnalyzeAsync(workspace, workspace.CurrentSolution.ProjectIds.First(), analyzerType); var diagnostics = analyzerResult.GetDocumentDiagnostics(analyzerResult.DocumentIds.First(), AnalysisKind.Semantic); @@ -189,7 +190,7 @@ void Method() // set option workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, new CodeStyleOption(false, NotificationOption.Suggestion)))); + .WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent.ToPublicOption(), new CodeStyleOption(false, NotificationOption.Suggestion)))); // run analysis var project = workspace.CurrentSolution.Projects.First(); diff --git a/src/VisualStudio/Core/Test/CodeModel/AbstractCodeElementTests`1.vb b/src/VisualStudio/Core/Test/CodeModel/AbstractCodeElementTests`1.vb index 2650c71556aa0..45dd62cfd16d2 100644 --- a/src/VisualStudio/Core/Test/CodeModel/AbstractCodeElementTests`1.vb +++ b/src/VisualStudio/Core/Test/CodeModel/AbstractCodeElementTests`1.vb @@ -51,9 +51,9 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel End Using End Sub - Protected Overloads Async Function TestElementUpdate( + Private Protected Overloads Async Function TestElementUpdate( code As XElement, expectedCode As XElement, updater As Action(Of TCodeElement), - Optional options As IDictionary(Of OptionKey, Object) = Nothing) As Task + Optional options As IDictionary(Of OptionKey2, Object) = Nothing) As Task Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim workspace = state.Workspace If options IsNot Nothing Then @@ -773,9 +773,9 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel End Sub) End Function - Protected Overrides Async Function TestAddProperty( + Private Protected Overrides Async Function TestAddProperty( code As XElement, expectedCode As XElement, data As PropertyData, - Optional options As IDictionary(Of OptionKey, Object) = Nothing) As Task + Optional options As IDictionary(Of OptionKey2, Object) = Nothing) As Task Await TestElementUpdate(code, expectedCode, Sub(codeElement) Dim prop = AddProperty(codeElement, data) diff --git a/src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.vb b/src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.vb index e66474542c0a3..f23843e7a2dc4 100644 --- a/src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.vb +++ b/src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.vb @@ -64,8 +64,8 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Throw New NotImplementedException End Function - Protected Overridable Function TestAddProperty(code As XElement, expectedCode As XElement, data As PropertyData, - Optional options As IDictionary(Of OptionKey, Object) = Nothing) As Task + Private Protected Overridable Function TestAddProperty(code As XElement, expectedCode As XElement, data As PropertyData, + Optional options As IDictionary(Of OptionKey2, Object) = Nothing) As Task Throw New NotImplementedException End Function diff --git a/src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb b/src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb index b43fb14337147..9650ef9a5713d 100644 --- a/src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb +++ b/src/VisualStudio/Core/Test/CodeModel/CSharp/CodeClassTests.vb @@ -2203,7 +2203,7 @@ class C Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = "Name", .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, - New Dictionary(Of OptionKey, Object) From { + New Dictionary(Of OptionKey2, Object) From { {CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement}, {CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement} }) @@ -2254,7 +2254,7 @@ class C Await TestAddProperty( code, expected, New PropertyData With {.GetterName = "Name", .PutterName = Nothing, .Type = EnvDTE.vsCMTypeRef.vsCMTypeRefString}, - New Dictionary(Of OptionKey, Object) From { + New Dictionary(Of OptionKey2, Object) From { {CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement}, {CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement} }) diff --git a/src/VisualStudio/Core/Test/Options/BasicEditorConfigGeneratorTests.vb b/src/VisualStudio/Core/Test/Options/BasicEditorConfigGeneratorTests.vb index 35b3328d5ea40..601c8b2f30169 100644 --- a/src/VisualStudio/Core/Test/Options/BasicEditorConfigGeneratorTests.vb +++ b/src/VisualStudio/Core/Test/Options/BasicEditorConfigGeneratorTests.vb @@ -144,8 +144,8 @@ dotnet_naming_style.begins_with_i.capitalization = pascal_case Public Sub TestEditorConfigGeneratorToggleOptions() Using workspace = TestWorkspace.CreateVisualBasic("") - Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey(CodeStyleOptions.PreferExplicitTupleNames, LanguageNames.VisualBasic), - New CodeStyleOption(Of Boolean)(False, NotificationOption.[Error])) + Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey2(CodeStyleOptions2.PreferExplicitTupleNames, LanguageNames.VisualBasic), + New CodeStyleOption2(Of Boolean)(False, NotificationOption2.[Error])) Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories root = true diff --git a/src/VisualStudio/Core/Test/Options/CSharpEditorConfigGeneratorTests.vb b/src/VisualStudio/Core/Test/Options/CSharpEditorConfigGeneratorTests.vb index f6a1dc511abc0..777ddc6acee28 100644 --- a/src/VisualStudio/Core/Test/Options/CSharpEditorConfigGeneratorTests.vb +++ b/src/VisualStudio/Core/Test/Options/CSharpEditorConfigGeneratorTests.vb @@ -228,8 +228,8 @@ dotnet_naming_style.begins_with_i.capitalization = pascal_case Public Sub TestEditorConfigGeneratorToggleOptions() Using workspace = TestWorkspace.CreateCSharp("") - Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey(CodeStyleOptions.PreferExplicitTupleNames, LanguageNames.CSharp), - New CodeStyleOption(Of Boolean)(False, NotificationOption.[Error])) + Dim changedOptions = workspace.Options.WithChangedOption(New OptionKey2(CodeStyleOptions2.PreferExplicitTupleNames, LanguageNames.CSharp), + New CodeStyleOption2(Of Boolean)(False, NotificationOption2.[Error])) Dim expectedText = "# Remove the line below if you want to inherit .editorconfig settings from higher directories root = true diff --git a/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb b/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb index 5e02b9b92ddc8..2357fd1ad50b4 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/AutomationObject.vb @@ -134,127 +134,127 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Public Property Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration_CodeStyle As String Get - Return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration) + Return GetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value) + SetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value) End Set End Property Public Property Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess_CodeStyle As String Get - Return GetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess) + Return GetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value) + SetXmlOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value) End Set End Property Public Property Style_QualifyFieldAccess As String Get - Return GetXmlOption(CodeStyleOptions.QualifyFieldAccess) + Return GetXmlOption(CodeStyleOptions2.QualifyFieldAccess) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value) + SetXmlOption(CodeStyleOptions2.QualifyFieldAccess, value) End Set End Property Public Property Style_QualifyPropertyAccess As String Get - Return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess) + Return GetXmlOption(CodeStyleOptions2.QualifyPropertyAccess) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value) + SetXmlOption(CodeStyleOptions2.QualifyPropertyAccess, value) End Set End Property Public Property Style_QualifyMethodAccess As String Get - Return GetXmlOption(CodeStyleOptions.QualifyMethodAccess) + Return GetXmlOption(CodeStyleOptions2.QualifyMethodAccess) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value) + SetXmlOption(CodeStyleOptions2.QualifyMethodAccess, value) End Set End Property Public Property Style_QualifyEventAccess As String Get - Return GetXmlOption(CodeStyleOptions.QualifyEventAccess) + Return GetXmlOption(CodeStyleOptions2.QualifyEventAccess) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.QualifyEventAccess, value) + SetXmlOption(CodeStyleOptions2.QualifyEventAccess, value) End Set End Property Public Property Style_PreferObjectInitializer As String Get - Return GetXmlOption(CodeStyleOptions.PreferObjectInitializer) + Return GetXmlOption(CodeStyleOptions2.PreferObjectInitializer) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferObjectInitializer, value) + SetXmlOption(CodeStyleOptions2.PreferObjectInitializer, value) End Set End Property Public Property Style_PreferCollectionInitializer As String Get - Return GetXmlOption(CodeStyleOptions.PreferCollectionInitializer) + Return GetXmlOption(CodeStyleOptions2.PreferCollectionInitializer) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferCollectionInitializer, value) + SetXmlOption(CodeStyleOptions2.PreferCollectionInitializer, value) End Set End Property Public Property Style_PreferCoalesceExpression As String Get - Return GetXmlOption(CodeStyleOptions.PreferCoalesceExpression) + Return GetXmlOption(CodeStyleOptions2.PreferCoalesceExpression) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferCoalesceExpression, value) + SetXmlOption(CodeStyleOptions2.PreferCoalesceExpression, value) End Set End Property Public Property Style_PreferNullPropagation As String Get - Return GetXmlOption(CodeStyleOptions.PreferNullPropagation) + Return GetXmlOption(CodeStyleOptions2.PreferNullPropagation) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferNullPropagation, value) + SetXmlOption(CodeStyleOptions2.PreferNullPropagation, value) End Set End Property Public Property Style_PreferInferredTupleNames As String Get - Return GetXmlOption(CodeStyleOptions.PreferInferredTupleNames) + Return GetXmlOption(CodeStyleOptions2.PreferInferredTupleNames) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferInferredTupleNames, value) + SetXmlOption(CodeStyleOptions2.PreferInferredTupleNames, value) End Set End Property Public Property Style_PreferInferredAnonymousTypeMemberNames As String Get - Return GetXmlOption(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames) + Return GetXmlOption(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, value) + SetXmlOption(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, value) End Set End Property Public Property Style_PreferExplicitTupleNames As String Get - Return GetXmlOption(CodeStyleOptions.PreferExplicitTupleNames) + Return GetXmlOption(CodeStyleOptions2.PreferExplicitTupleNames) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferExplicitTupleNames, value) + SetXmlOption(CodeStyleOptions2.PreferExplicitTupleNames, value) End Set End Property Public Property Style_PreferReadonly As String Get - Return GetXmlOption(CodeStyleOptions.PreferReadonly) + Return GetXmlOption(CodeStyleOptions2.PreferReadonly) End Get Set(value As String) - SetXmlOption(CodeStyleOptions.PreferReadonly, value) + SetXmlOption(CodeStyleOptions2.PreferReadonly, value) End Set End Property @@ -294,20 +294,20 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options End Set End Property - Private Function GetBooleanOption(key As [PerLanguageOption](Of Boolean)) As Boolean + Private Function GetBooleanOption(key As [PerLanguageOption2](Of Boolean)) As Boolean Return _workspace.Options.GetOption(key, LanguageNames.VisualBasic) End Function - Private Function GetXmlOption(key As PerLanguageOption(Of CodeStyleOption(Of Boolean))) As String + Private Function GetXmlOption(key As PerLanguageOption2(Of CodeStyleOption2(Of Boolean))) As String Return _workspace.Options.GetOption(key, LanguageNames.VisualBasic).ToXElement().ToString() End Function - Private Sub SetBooleanOption(key As [PerLanguageOption](Of Boolean), value As Boolean) + Private Sub SetBooleanOption(key As [PerLanguageOption2](Of Boolean), value As Boolean) _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options _ .WithChangedOption(key, LanguageNames.VisualBasic, value))) End Sub - Private Function GetBooleanOption(key As PerLanguageOption(Of Boolean?)) As Integer + Private Function GetBooleanOption(key As PerLanguageOption2(Of Boolean?)) As Integer Dim [option] = _workspace.Options.GetOption(key, LanguageNames.VisualBasic) If Not [option].HasValue Then Return -1 @@ -316,14 +316,14 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Return If([option].Value, 1, 0) End Function - Private Sub SetBooleanOption(key As PerLanguageOption(Of Boolean?), value As Integer) + Private Sub SetBooleanOption(key As PerLanguageOption2(Of Boolean?), value As Integer) Dim boolValue As Boolean? = If(value < 0, Nothing, value > 0) _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options _ .WithChangedOption(key, LanguageNames.VisualBasic, boolValue))) End Sub - Private Sub SetXmlOption(key As PerLanguageOption(Of CodeStyleOption(Of Boolean)), value As String) - Dim convertedValue = CodeStyleOption(Of Boolean).FromXElement(XElement.Parse(value)) + Private Sub SetXmlOption(key As PerLanguageOption2(Of CodeStyleOption2(Of Boolean)), value As String) + Dim convertedValue = CodeStyleOption2(Of Boolean).FromXElement(XElement.Parse(value)) _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options _ .WithChangedOption(key, LanguageNames.VisualBasic, convertedValue))) End Sub diff --git a/src/VisualStudio/VisualBasic/Impl/Options/Formatting/CodeStylePage.vb b/src/VisualStudio/VisualBasic/Impl/Options/Formatting/CodeStylePage.vb index 8704eb35f77ec..496560e9f53bb 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/Formatting/CodeStylePage.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/Formatting/CodeStylePage.vb @@ -26,7 +26,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting Private Shared Function GetEditorConfigOptions() As ImmutableArray(Of (String, ImmutableArray(Of IOption))) Dim builder = ArrayBuilder(Of (String, ImmutableArray(Of IOption))).GetInstance() builder.AddRange(GridOptionPreviewControl.GetLanguageAgnosticEditorConfigOptions()) - builder.Add((BasicVSResources.VB_Coding_Conventions, VisualBasicCodeStyleOptions.AllOptions)) + builder.Add((BasicVSResources.VB_Coding_Conventions, VisualBasicCodeStyleOptions.AllOptions.As(Of IOption))) Return builder.ToImmutableAndFree() End Function diff --git a/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb b/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb index c9e516a7a6023..dd6b3bb6c4120 100644 --- a/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb +++ b/src/VisualStudio/VisualBasic/Impl/Options/StyleViewModel.vb @@ -700,41 +700,41 @@ End Class Dim parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon ' qualify with Me. group - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyFieldAccess, BasicVSResources.Qualify_field_access_with_Me, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyPropertyAccess, BasicVSResources.Qualify_property_access_with_Me, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyMethodAccess, BasicVSResources.Qualify_method_access_with_Me, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.QualifyEventAccess, BasicVSResources.Qualify_event_access_with_Me, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, BasicVSResources.Qualify_field_access_with_Me, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, BasicVSResources.Qualify_property_access_with_Me, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, BasicVSResources.Qualify_method_access_with_Me, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, BasicVSResources.Qualify_event_access_with_Me, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, Me, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)) ' predefined or framework type group - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, _intrinsicDeclarationPreviewTrue, _intrinsicDeclarationPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, _intrinsicMemberAccessPreviewTrue, _intrinsicMemberAccessPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, _intrinsicDeclarationPreviewTrue, _intrinsicDeclarationPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, _intrinsicMemberAccessPreviewTrue, _intrinsicMemberAccessPreviewFalse, Me, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)) AddParenthesesOptions(optionStore) ' Code block - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, Me, optionStore, codeBlockPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, Me, optionStore, codeBlockPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, Me, optionStore, codeBlockPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, Me, optionStore, codeBlockPreferencesGroupTitle)) ' expression preferences - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpressions, s_preferSimplifiedConditionalExpressions, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, Me, optionStore, expressionPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpressions, s_preferSimplifiedConditionalExpressions, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, Me, optionStore, expressionPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, Me, optionStore, expressionPreferencesGroupTitle)) AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle) ' nothing preferences - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, Me, optionStore, nothingPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, Me, optionStore, nothingPreferencesGroupTitle)) - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferIsNullCheckOverReferenceEqualityMethod, BasicVSResources.Prefer_Is_Nothing_for_reference_equality_checks, s_preferIsNothingCheckOverReferenceEquals, s_preferIsNothingCheckOverReferenceEquals, Me, optionStore, nothingPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, Me, optionStore, nothingPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, Me, optionStore, nothingPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, BasicVSResources.Prefer_Is_Nothing_for_reference_equality_checks, s_preferIsNothingCheckOverReferenceEquals, s_preferIsNothingCheckOverReferenceEquals, Me, optionStore, nothingPreferencesGroupTitle)) ' Field preferences - Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, Me, optionStore, fieldPreferencesGroupTitle)) + Me.CodeStyleItems.Add(New BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, Me, optionStore, fieldPreferencesGroupTitle)) ' Parameter preferences AddParameterOptions(optionStore, parameterPreferencesGroupTitle) @@ -742,25 +742,25 @@ End Class Private Sub AddParenthesesOptions(optionStore As OptionStore) AddParenthesesOption( - LanguageNames.VisualBasic, optionStore, CodeStyleOptions.ArithmeticBinaryParentheses, + LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, BasicVSResources.In_arithmetic_binary_operators, {s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( - LanguageNames.VisualBasic, optionStore, CodeStyleOptions.OtherBinaryParentheses, + LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherBinaryParentheses, BasicVSResources.In_other_binary_operators, {s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( - LanguageNames.VisualBasic, optionStore, CodeStyleOptions.RelationalBinaryParentheses, + LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, BasicVSResources.In_relational_binary_operators, {s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary}, defaultAddForClarity:=True) AddParenthesesOption( - LanguageNames.VisualBasic, optionStore, CodeStyleOptions.OtherParentheses, + LanguageNames.VisualBasic, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, {s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary}, defaultAddForClarity:=False) diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/ForceLowMemoryMode_Options.cs b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/ForceLowMemoryMode_Options.cs index e140aebdf788c..8b03b6dad3609 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/ForceLowMemoryMode_Options.cs +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/ForceLowMemoryMode_Options.cs @@ -2,20 +2,16 @@ // 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.Options; -using Microsoft.VisualStudio.LanguageServices.Implementation.Options; -using Microsoft.VisualStudio.Shell; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { internal sealed partial class ForceLowMemoryMode { - public static readonly Option Enabled = new Option(nameof(ForceLowMemoryMode), nameof(Enabled), defaultValue: false, + public static readonly Option2 Enabled = new Option2(nameof(ForceLowMemoryMode), nameof(Enabled), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\Enabled")); - public static readonly Option SizeInMegabytes = new Option(nameof(ForceLowMemoryMode), nameof(SizeInMegabytes), defaultValue: 500, + public static readonly Option2 SizeInMegabytes = new Option2(nameof(ForceLowMemoryMode), nameof(SizeInMegabytes), defaultValue: 500, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\ForceLowMemoryMode\SizeInMegabytes")); } } diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/InternalOptionsControl.cs b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/InternalOptionsControl.cs index 447c2cc752dc8..92f017414f20d 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/InternalOptionsControl.cs +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/InternalOptionsControl.cs @@ -187,22 +187,22 @@ private void BindToCheckBox(CheckBox checkBox, IOption option, string languageNa { if (languageName == null) { - BindToOption(checkBox, (Option)option); + BindToOption(checkBox, (Option2)option); return; } - BindToOption(checkBox, (PerLanguageOption)option, languageName); + BindToOption(checkBox, (PerLanguageOption2)option, languageName); } private void BindToTextBox(TextBox textBox, IOption option, string languageName = null) { if (languageName == null) { - BindToOption(textBox, (Option)option); + BindToOption(textBox, (Option2)option); return; } - BindToOption(textBox, (PerLanguageOption)option, languageName); + BindToOption(textBox, (PerLanguageOption2)option, languageName); } } } diff --git a/src/Workspaces/CSharp/Portable/CodeStyle/CSharpCodeStyleOptionsProvider.cs b/src/Workspaces/CSharp/Portable/CodeStyle/CSharpCodeStyleOptionsProvider.cs index 8450a9f849c51..25df57d70c7e4 100644 --- a/src/Workspaces/CSharp/Portable/CodeStyle/CSharpCodeStyleOptionsProvider.cs +++ b/src/Workspaces/CSharp/Portable/CodeStyle/CSharpCodeStyleOptionsProvider.cs @@ -18,6 +18,6 @@ public CSharpCodeStyleOptionsProvider() { } - public ImmutableArray Options { get; } = CSharpCodeStyleOptions.AllOptions; + public ImmutableArray Options { get; } = CSharpCodeStyleOptions.AllOptions.As(); } } diff --git a/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs new file mode 100644 index 0000000000000..34afad3fba3aa --- /dev/null +++ b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptions.cs @@ -0,0 +1,153 @@ +// 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.CSharp.Formatting +{ + /// + public static class CSharpFormattingOptions + { + /// + public static Option SpacingAfterMethodDeclarationName { get; } = (Option)CSharpFormattingOptions2.SpacingAfterMethodDeclarationName; + + /// + public static Option SpaceWithinMethodDeclarationParenthesis { get; } = (Option)CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis; + + /// + public static Option SpaceBetweenEmptyMethodDeclarationParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses; + + /// + public static Option SpaceAfterMethodCallName { get; } = (Option)CSharpFormattingOptions2.SpaceAfterMethodCallName; + + /// + public static Option SpaceWithinMethodCallParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceWithinMethodCallParentheses; + + /// + public static Option SpaceBetweenEmptyMethodCallParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses; + + /// + public static Option SpaceAfterControlFlowStatementKeyword { get; } = (Option)CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword; + + /// + public static Option SpaceWithinExpressionParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceWithinExpressionParentheses; + + /// + public static Option SpaceWithinCastParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceWithinCastParentheses; + + /// + public static Option SpaceWithinOtherParentheses { get; } = (Option)CSharpFormattingOptions2.SpaceWithinOtherParentheses; + + /// + public static Option SpaceAfterCast { get; } = (Option)CSharpFormattingOptions2.SpaceAfterCast; + + /// + public static Option SpacesIgnoreAroundVariableDeclaration { get; } = (Option)CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration; + + /// + public static Option SpaceBeforeOpenSquareBracket { get; } = (Option)CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket; + + /// + public static Option SpaceBetweenEmptySquareBrackets { get; } = (Option)CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets; + + /// + public static Option SpaceWithinSquareBrackets { get; } = (Option)CSharpFormattingOptions2.SpaceWithinSquareBrackets; + + /// + public static Option SpaceAfterColonInBaseTypeDeclaration { get; } = (Option)CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration; + + /// + public static Option SpaceAfterComma { get; } = (Option)CSharpFormattingOptions2.SpaceAfterComma; + + /// + public static Option SpaceAfterDot { get; } = (Option)CSharpFormattingOptions2.SpaceAfterDot; + + /// + public static Option SpaceAfterSemicolonsInForStatement { get; } = (Option)CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement; + + /// + public static Option SpaceBeforeColonInBaseTypeDeclaration { get; } = (Option)CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration; + + /// + public static Option SpaceBeforeComma { get; } = (Option)CSharpFormattingOptions2.SpaceBeforeComma; + + /// + public static Option SpaceBeforeDot { get; } = (Option)CSharpFormattingOptions2.SpaceBeforeDot; + + /// + public static Option SpaceBeforeSemicolonsInForStatement { get; } = (Option)CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement; + + /// + public static Option SpacingAroundBinaryOperator { get; } = (Option)CSharpFormattingOptions2.SpacingAroundBinaryOperator; + + /// + public static Option IndentBraces { get; } = (Option)CSharpFormattingOptions2.IndentBraces; + + /// + public static Option IndentBlock { get; } = (Option)CSharpFormattingOptions2.IndentBlock; + + /// + public static Option IndentSwitchSection { get; } = (Option)CSharpFormattingOptions2.IndentSwitchSection; + + /// + public static Option IndentSwitchCaseSection { get; } = (Option)CSharpFormattingOptions2.IndentSwitchCaseSection; + + /// + public static Option IndentSwitchCaseSectionWhenBlock { get; } = (Option)CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock; + + /// + public static Option LabelPositioning { get; } = (Option)CSharpFormattingOptions2.LabelPositioning; + + /// + public static Option WrappingPreserveSingleLine { get; } = (Option)CSharpFormattingOptions2.WrappingPreserveSingleLine; + + /// + public static Option WrappingKeepStatementsOnSingleLine { get; } = (Option)CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine; + + /// + public static Option NewLinesForBracesInTypes { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInTypes; + + /// + public static Option NewLinesForBracesInMethods { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInMethods; + + /// + public static Option NewLinesForBracesInProperties { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInProperties; + + /// + public static Option NewLinesForBracesInAccessors { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInAccessors; + + /// + public static Option NewLinesForBracesInAnonymousMethods { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods; + + /// + public static Option NewLinesForBracesInControlBlocks { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInControlBlocks; + + /// + public static Option NewLinesForBracesInAnonymousTypes { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes; + + /// + public static Option NewLinesForBracesInObjectCollectionArrayInitializers { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers; + + /// + public static Option NewLinesForBracesInLambdaExpressionBody { get; } = (Option)CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody; + + /// + public static Option NewLineForElse { get; } = (Option)CSharpFormattingOptions2.NewLineForElse; + + /// + public static Option NewLineForCatch { get; } = (Option)CSharpFormattingOptions2.NewLineForCatch; + + /// + public static Option NewLineForFinally { get; } = (Option)CSharpFormattingOptions2.NewLineForFinally; + + /// + public static Option NewLineForMembersInObjectInit { get; } = (Option)CSharpFormattingOptions2.NewLineForMembersInObjectInit; + + /// + public static Option NewLineForMembersInAnonymousTypes { get; } = (Option)CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes; + + /// + public static Option NewLineForClausesInQuery { get; } = (Option)CSharpFormattingOptions2.NewLineForClausesInQuery; + } +} diff --git a/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptionsProvider.cs b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptionsProvider.cs index f6ca87dc6e302..bdea893da3093 100644 --- a/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptionsProvider.cs +++ b/src/Workspaces/CSharp/Portable/Formatting/CSharpFormattingOptionsProvider.cs @@ -17,6 +17,6 @@ public CSharpFormattingOptionsProvider() { } - public ImmutableArray Options { get; } = CSharpFormattingOptions.AllOptions; + public ImmutableArray Options { get; } = CSharpFormattingOptions2.AllOptions.As(); } } diff --git a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/ExpressionSimplifier.cs b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/ExpressionSimplifier.cs index cc5168a1a3eb9..574d6e4410c4f 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/ExpressionSimplifier.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/ExpressionSimplifier.cs @@ -164,7 +164,7 @@ private static bool TryReduceMemberAccessExpression( replacementNode = replacementNode .WithAdditionalAnnotations(new SyntaxAnnotation( - nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))); + nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))); issueSpan = memberAccess.Span; // we want to show the whole expression as unnecessary diff --git a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs index 68c7b5c144f70..52f93d2fe7d4b 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs @@ -245,8 +245,8 @@ public override bool TrySimplify( // If not, we'll still fall through and see if we can convert it to Int32. var codeStyleOptionName = inDeclarationContext - ? nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration) - : nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); + ? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration) + : nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); var type = semanticModel.GetTypeInfo(name, cancellationToken).Type; if (type != null) diff --git a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/QualifiedCrefSimplifier.cs b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/QualifiedCrefSimplifier.cs index b1619a0a44262..c2da9cf10a96e 100644 --- a/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/QualifiedCrefSimplifier.cs +++ b/src/Workspaces/CSharp/Portable/Simplification/Simplifiers/QualifiedCrefSimplifier.cs @@ -70,7 +70,7 @@ public override bool TrySimplify( private static TypeCrefSyntax CreateReplacement(QualifiedCrefSyntax crefSyntax, SyntaxKind keywordKind) { - var annotation = new SyntaxAnnotation(nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)); + var annotation = new SyntaxAnnotation(nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)); var token = Token(crefSyntax.GetLeadingTrivia(), keywordKind, crefSyntax.GetTrailingTrivia()); return TypeCref(PredefinedType(token)).WithAdditionalAnnotations(annotation); } diff --git a/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs b/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs index 29c9da9c9a4fd..b0f300f7c3b36 100644 --- a/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs +++ b/src/Workspaces/CSharpTest/CodeStyle/CSharpEditorConfigCodeStyleParserTests.cs @@ -23,7 +23,7 @@ public class CSharpEditorConfigCodeStyleParserTests [InlineData(" before_and_after ", BinaryOperatorSpacingOptions.Single)] public void TestParseSpacingAroundBinaryOperator(string rawValue, BinaryOperatorSpacingOptions parsedValue) { - Assert.Equal(parsedValue, CSharpFormattingOptions.ParseEditorConfigSpacingAroundBinaryOperator(rawValue)); + Assert.Equal(parsedValue, CSharpFormattingOptions2.ParseEditorConfigSpacingAroundBinaryOperator(rawValue)); } [Theory] @@ -37,7 +37,7 @@ public void TestParseSpacingAroundBinaryOperator(string rawValue, BinaryOperator [InlineData(" one_less_than_current ", LabelPositionOptions.OneLess)] public void TestParseLabelPositioning(string rawValue, LabelPositionOptions parsedValue) { - Assert.Equal(parsedValue, CSharpFormattingOptions.ParseEditorConfigLabelPositioning(rawValue)); + Assert.Equal(parsedValue, CSharpFormattingOptions2.ParseEditorConfigLabelPositioning(rawValue)); } [Theory] @@ -51,7 +51,7 @@ public void TestParseLabelPositioning(string rawValue, LabelPositionOptions pars [InlineData("when_on_single_line : error", (int)ExpressionBodyPreference.WhenOnSingleLine, ReportDiagnostic.Error)] public void TestParseExpressionBodyPreference(string optionString, int parsedValue, ReportDiagnostic severity) { - var defaultValue = new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.Error); + var defaultValue = new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.Error); var codeStyleOption = CSharpCodeStyleOptions.ParseExpressionBodyPreference(optionString, defaultValue); Assert.NotSame(defaultValue, codeStyleOption); diff --git a/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs b/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs index c1e782b7086cc..a9e7e5eb7d86e 100644 --- a/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs +++ b/src/Workspaces/CSharpTest/Formatting/EditorConfigOptionParserTests.cs @@ -4,7 +4,7 @@ using Microsoft.CodeAnalysis.CSharp.Formatting; using Xunit; -using static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions; +using static Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions2; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { @@ -19,7 +19,7 @@ public class EditorConfigOptionParserTests InlineData("expressions , , , control_flow_statements", SpacingWithinParenthesesOption.ControlFlowStatements), InlineData("expressions , , , control_flow_statements", SpacingWithinParenthesesOption.Expressions), InlineData(", , , control_flow_statements", SpacingWithinParenthesesOption.ControlFlowStatements)] - static void TestParseParenthesesSpaceOptionsTrue(string value, CSharpFormattingOptions.SpacingWithinParenthesesOption parenthesesSpacingOption) + static void TestParseParenthesesSpaceOptionsTrue(string value, SpacingWithinParenthesesOption parenthesesSpacingOption) { Assert.True(DetermineIfSpaceOptionIsSet(value, parenthesesSpacingOption), $"Expected option {value} to be parsed as set."); diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs index 6fbc9e776ad0f..def1216f267c8 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/BatchFixAllProvider.cs @@ -11,7 +11,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; diff --git a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs index 637620051026e..906c28f26f070 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.DiagnosticProvider.cs @@ -7,10 +7,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes diff --git a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs index f3e47026ab3f2..97d993395f6a5 100644 --- a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs +++ b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption.cs @@ -3,194 +3,60 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Xml.Linq; -using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { - internal interface ICodeStyleOption - { - XElement ToXElement(); - object Value { get; } - NotificationOption Notification { get; } - ICodeStyleOption WithValue(object value); - ICodeStyleOption WithNotification(NotificationOption notification); - } - - /// - /// Represents a code style option and an associated notification option. Supports - /// being instantiated with T as a or an enum type. - /// - /// CodeStyleOption also has some basic support for migration a option - /// forward to an enum type option. Specifically, if a previously serialized - /// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false' - /// values will be migrated to have the 0-value of the enum, and 'true' values will be - /// migrated to have the 1-value of the enum. - /// - /// Similarly, enum-type code options will serialize out in a way that is compatible with - /// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1 - /// then those values will write back as false/true. - /// + /// public class CodeStyleOption : ICodeStyleOption, IEquatable> { + private readonly CodeStyleOption2 _codeStyleOptionImpl; public static CodeStyleOption Default => new CodeStyleOption(default, NotificationOption.Silent); - private const int SerializationVersion = 1; - - private NotificationOption _notification; + internal CodeStyleOption(CodeStyleOption2 codeStyleOptionImpl) + { + _codeStyleOptionImpl = codeStyleOptionImpl; + } public CodeStyleOption(T value, NotificationOption notification) + : this(new CodeStyleOption2(value, (NotificationOption2)notification)) { - Value = value; - _notification = notification ?? throw new ArgumentNullException(nameof(notification)); } - public T Value { get; set; } + public T Value + { + get => _codeStyleOptionImpl.Value; + set => _codeStyleOptionImpl.Value = value; + } object ICodeStyleOption.Value => this.Value; + NotificationOption2 ICodeStyleOption.Notification => _codeStyleOptionImpl.Notification; ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption((T)value, Notification); - ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption notification) => new CodeStyleOption(Value, notification); - - private int EnumValueAsInt32 => (int)(object)Value; + ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption(Value, (NotificationOption)notification); + ICodeStyleOption ICodeStyleOption.AsCodeStyleOption() + => this is TCodeStyleOption ? this : (ICodeStyleOption)_codeStyleOptionImpl; public NotificationOption Notification { - get => _notification; - set => _notification = value ?? throw new ArgumentNullException(nameof(value)); - } - - public XElement ToXElement() => - new XElement(nameof(CodeStyleOption), // `nameof()` returns just "CodeStyleOption" - new XAttribute(nameof(SerializationVersion), SerializationVersion), - new XAttribute("Type", GetTypeNameForSerialization()), - new XAttribute(nameof(Value), GetValueForSerialization()), - new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); - - private object GetValueForSerialization() - { - if (typeof(T) == typeof(string)) - { - return Value; - } - else if (typeof(T) == typeof(bool)) - { - return Value; - } - else if (IsZeroOrOneValueOfEnum()) - { - return EnumValueAsInt32 == 1; - } - else - { - return EnumValueAsInt32; - } + get => (NotificationOption)_codeStyleOptionImpl.Notification; + set => _codeStyleOptionImpl.Notification = (NotificationOption2)(value ?? throw new ArgumentNullException(nameof(value))); } - private string GetTypeNameForSerialization() - { - if (typeof(T) == typeof(string)) - { - return nameof(String); - } - if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum()) - { - return nameof(Boolean); - } - else - { - return nameof(Int32); - } - } + internal CodeStyleOption2 UnderlyingOption => _codeStyleOptionImpl; - private bool IsZeroOrOneValueOfEnum() - { - var intVal = EnumValueAsInt32; - return intVal == 0 || intVal == 1; - } + public XElement ToXElement() => _codeStyleOptionImpl.ToXElement(); public static CodeStyleOption FromXElement(XElement element) - { - var typeAttribute = element.Attribute("Type"); - var valueAttribute = element.Attribute(nameof(Value)); - var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); - var version = (int)element.Attribute(nameof(SerializationVersion)); - - if (typeAttribute == null || valueAttribute == null || severityAttribute == null) - { - // data from storage is corrupt, or nothing has been stored yet. - return Default; - } - - if (version != SerializationVersion) - { - return Default; - } - - var parser = GetParser(typeAttribute.Value); - var value = parser(valueAttribute.Value); - var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value); - - return new CodeStyleOption(value, severity switch - { - DiagnosticSeverity.Hidden => NotificationOption.Silent, - DiagnosticSeverity.Info => NotificationOption.Suggestion, - DiagnosticSeverity.Warning => NotificationOption.Warning, - DiagnosticSeverity.Error => NotificationOption.Error, - _ => throw new ArgumentException(nameof(element)), - }); - } - - private static Func GetParser(string type) - => type switch - { - nameof(Boolean) => - // Try to map a boolean value. Either map it to true/false if we're a - // CodeStyleOption or map it to the 0 or 1 value for an enum if we're - // a CodeStyleOption. - (Func)(v => Convert(bool.Parse(v))), - nameof(Int32) => v => Convert(int.Parse(v)), - nameof(String) => v => (T)(object)v, - _ => throw new ArgumentException(nameof(type)), - }; - - private static T Convert(bool b) - { - // If we had a bool and we wanted a bool, then just return this value. - if (typeof(T) == typeof(bool)) - { - return (T)(object)b; - } - - // Map booleans to the 1/0 value of the enum. - return b ? (T)(object)1 : (T)(object)0; - } - - private static T Convert(int i) - { - // We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default. - if (typeof(T) == typeof(bool)) - { - return (T)(object)(i == 1); - } - - // If had an int and we wanted an enum, then just return this value. - return (T)(object)(i); - } + => new CodeStyleOption(CodeStyleOption2.FromXElement(element)); public bool Equals(CodeStyleOption other) - => EqualityComparer.Default.Equals(Value, other.Value) && - Notification == other.Notification; + => _codeStyleOptionImpl.Equals(other?._codeStyleOptionImpl); public override bool Equals(object obj) => obj is CodeStyleOption option && Equals(option); public override int GetHashCode() - => unchecked((Notification.GetHashCode() * (int)0xA5555529) + Value.GetHashCode()); + => _codeStyleOptionImpl.GetHashCode(); } } diff --git a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption2_operators.cs b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption2_operators.cs new file mode 100644 index 0000000000000..eef1ce96089db --- /dev/null +++ b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOption2_operators.cs @@ -0,0 +1,30 @@ +// 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. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.CodeStyle +{ + internal partial class CodeStyleOption2 + { + [return: NotNullIfNotNull("option")] + public static explicit operator CodeStyleOption?(CodeStyleOption2? option) + { + if (option == null) + { + return null; + } + + return new CodeStyleOption(option.Value, (NotificationOption?)option.Notification); + } + + [return: NotNullIfNotNull("option")] + public static explicit operator CodeStyleOption2?(CodeStyleOption? option) + { + return option?.UnderlyingOption; + } + } +} diff --git a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptions.cs b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptions.cs index 74cda1aed1a7c..610dd49c447c0 100644 --- a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptions.cs +++ b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptions.cs @@ -4,436 +4,35 @@ #nullable enable -using System.Collections.Immutable; -using System.Diagnostics; -using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else using Microsoft.CodeAnalysis.Options; + namespace Microsoft.CodeAnalysis.CodeStyle -#endif { + /// public class CodeStyleOptions { - private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); - - internal static ImmutableArray AllOptions { get; } - - private static PerLanguageOption CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) - { - var option = new PerLanguageOption(nameof(CodeStyleOptions), group, name, defaultValue, storageLocations); - s_allOptionsBuilder.Add(option); - return option; - } - - private static Option CreateCommonOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) - { - var option = new Option(nameof(CodeStyleOptions), group, name, defaultValue, storageLocations); - s_allOptionsBuilder.Add(option); - return option; - } - - /// - /// When user preferences are not yet set for a style, we fall back to the default value. - /// One such default(s), is that the feature is turned on, so that codegen consumes it, - /// but with silent enforcement, so that the user is not prompted about their usage. - /// - internal static readonly CodeStyleOption TrueWithSilentEnforcement = new CodeStyleOption(value: true, notification: NotificationOption.Silent); - internal static readonly CodeStyleOption FalseWithSilentEnforcement = new CodeStyleOption(value: false, notification: NotificationOption.Silent); - internal static readonly CodeStyleOption TrueWithSuggestionEnforcement = new CodeStyleOption(value: true, notification: NotificationOption.Suggestion); - internal static readonly CodeStyleOption FalseWithSuggestionEnforcement = new CodeStyleOption(value: false, notification: NotificationOption.Suggestion); - - /// - /// This option says if we should simplify away the . or . in field access expressions. - /// - public static readonly PerLanguageOption> QualifyFieldAccess = CreateOption( - CodeStyleOptionGroups.ThisOrMe, nameof(QualifyFieldAccess), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_field"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyFieldAccess")}); - - /// - /// This option says if we should simplify away the . or . in property access expressions. - /// - public static readonly PerLanguageOption> QualifyPropertyAccess = CreateOption( - CodeStyleOptionGroups.ThisOrMe, nameof(QualifyPropertyAccess), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_property"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyPropertyAccess")}); - - /// - /// This option says if we should simplify away the . or . in method access expressions. - /// - public static readonly PerLanguageOption> QualifyMethodAccess = CreateOption( - CodeStyleOptionGroups.ThisOrMe, nameof(QualifyMethodAccess), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_method"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyMethodAccess")}); - - /// - /// This option says if we should simplify away the . or . in event access expressions. - /// - public static readonly PerLanguageOption> QualifyEventAccess = CreateOption( - CodeStyleOptionGroups.ThisOrMe, nameof(QualifyEventAccess), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_event"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyEventAccess")}); - - /// - /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations - /// - public static readonly PerLanguageOption> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( - CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), - defaultValue: TrueWithSilentEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_predefined_type_for_locals_parameters_members"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle")}); - - /// - /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression - /// - public static readonly PerLanguageOption> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( - CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), - defaultValue: TrueWithSilentEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_predefined_type_for_member_access"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle")}); - - internal static readonly PerLanguageOption> PreferObjectInitializer = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_object_initializer"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer")}); - - internal static readonly PerLanguageOption> PreferCollectionInitializer = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_collection_initializer"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer")}); - - // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? - internal static readonly PerLanguageOption PreferObjectInitializer_FadeOutCode = new PerLanguageOption( - nameof(CodeStyleOptions), nameof(PreferObjectInitializer_FadeOutCode), - defaultValue: false, - storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); - - internal static readonly PerLanguageOption PreferCollectionInitializer_FadeOutCode = new PerLanguageOption( - nameof(CodeStyleOptions), nameof(PreferCollectionInitializer_FadeOutCode), - defaultValue: false, - storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); - - internal static readonly PerLanguageOption> PreferSimplifiedBooleanExpressions = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_simplified_boolean_expressions"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions")}); - - internal static readonly PerLanguageOption OperatorPlacementWhenWrapping = - CreateOption(CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), - defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, - storageLocations: - new EditorConfigStorageLocation( - "dotnet_style_operator_placement_when_wrapping", - OperatorPlacementUtilities.Parse, - OperatorPlacementUtilities.GetEditorConfigString)); - - internal static readonly PerLanguageOption> PreferCoalesceExpression = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_coalesce_expression"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression") }); - - internal static readonly PerLanguageOption> PreferNullPropagation = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_null_propagation"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferNullPropagation") }); - - internal static readonly PerLanguageOption> PreferExplicitTupleNames = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_explicit_tuple_names"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames") }); - - internal static readonly PerLanguageOption> PreferAutoProperties = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), - defaultValue: TrueWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_auto_properties"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferAutoProperties") }); - - internal static readonly PerLanguageOption> PreferInferredTupleNames = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_inferred_tuple_names"), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}") }); - - internal static readonly PerLanguageOption> PreferInferredAnonymousTypeMemberNames = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_inferred_anonymous_type_member_names"), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}") }); - - internal static readonly PerLanguageOption> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_is_null_check_over_reference_equality_method"), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}") }); - - internal static readonly PerLanguageOption> PreferConditionalExpressionOverAssignment = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), - defaultValue: TrueWithSilentEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_conditional_expression_over_assignment"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment")}); - - internal static readonly PerLanguageOption> PreferConditionalExpressionOverReturn = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), - defaultValue: TrueWithSilentEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_conditional_expression_over_return"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn")}); - - internal static readonly PerLanguageOption> PreferCompoundAssignment = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, - nameof(PreferCompoundAssignment), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_compound_assignment"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment") }); + /// + public static readonly PerLanguageOption> QualifyFieldAccess = + CodeStyleOptions2.QualifyFieldAccess.ToPublicOption(); - internal static readonly PerLanguageOption> PreferSimplifiedInterpolation = CreateOption( - CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_simplified_interpolation"), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}") }); + /// + public static readonly PerLanguageOption> QualifyPropertyAccess = + CodeStyleOptions2.QualifyPropertyAccess.ToPublicOption(); - private static readonly CodeStyleOption s_preferNoneUnusedParametersPreference = - new CodeStyleOption(default, NotificationOption.None); - private static readonly CodeStyleOption s_preferAllMethodsUnusedParametersPreference = - new CodeStyleOption(UnusedParametersPreference.AllMethods, NotificationOption.Suggestion); + /// + public static readonly PerLanguageOption> QualifyMethodAccess = + CodeStyleOptions2.QualifyMethodAccess.ToPublicOption(); - // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption and CodeQualityOptions - // and moving this option to CodeQualityOptions. - internal static readonly PerLanguageOption> UnusedParameters = CreateOption( - CodeStyleOptionGroups.Parameter, - nameof(UnusedParameters), - defaultValue: s_preferAllMethodsUnusedParametersPreference, - storageLocations: new OptionStorageLocation[]{ - new EditorConfigStorageLocation>( - "dotnet_code_quality_unused_parameters", - ParseUnusedParametersPreference, - o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference.Value)), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference") }); + /// + public static readonly PerLanguageOption> QualifyEventAccess = + CodeStyleOptions2.QualifyEventAccess.ToPublicOption(); - private static readonly CodeStyleOption s_requireAccessibilityModifiersDefault = - new CodeStyleOption(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption.Silent); + /// + public static readonly PerLanguageOption> PreferIntrinsicPredefinedTypeKeywordInDeclaration = + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration.ToPublicOption(); - internal static readonly PerLanguageOption> RequireAccessibilityModifiers = - CreateOption( - CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), - defaultValue: s_requireAccessibilityModifiersDefault, - storageLocations: new OptionStorageLocation[]{ - new EditorConfigStorageLocation>( - "dotnet_style_require_accessibility_modifiers", - s => ParseAccessibilityModifiersRequired(s), - GetAccessibilityModifiersRequiredEditorConfigString), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")}); - - internal static readonly PerLanguageOption> PreferReadonly = CreateOption( - CodeStyleOptionGroups.Field, nameof(PreferReadonly), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_readonly_field"), - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferReadonly") }); - - internal static readonly Option FileHeaderTemplate = CreateCommonOption( - CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), - defaultValue: "", - EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); - - private static readonly BidirectionalMap s_accessibilityModifiersRequiredMap = - new BidirectionalMap(new[] - { - KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), - KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), - KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), - KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), - }); - - private static CodeStyleOption ParseAccessibilityModifiersRequired(string optionString) - { - if (TryGetCodeStyleValueAndOptionalNotification(optionString, - out var value, out var notificationOpt)) - { - if (value == "never") - { - // If they provide 'never', they don't need a notification level. - notificationOpt ??= NotificationOption.Silent; - } - - if (notificationOpt != null) - { - Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); - return new CodeStyleOption(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); - } - } - - return s_requireAccessibilityModifiersDefault; - } - - private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption option) - { - // If they provide 'never', they don't need a notification level. - if (option.Notification == null) - { - Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); - return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never); - } - - Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); - return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}:{option.Notification.ToEditorConfigString()}"; - } - - private static readonly CodeStyleOption s_alwaysForClarityPreference = - new CodeStyleOption(ParenthesesPreference.AlwaysForClarity, NotificationOption.Silent); - - private static readonly CodeStyleOption s_neverIfUnnecessaryPreference = - new CodeStyleOption(ParenthesesPreference.NeverIfUnnecessary, NotificationOption.Silent); - - private static PerLanguageOption> CreateParenthesesOption( - string fieldName, CodeStyleOption defaultValue, - string styleName) - { - return CreateOption( - CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, - storageLocations: new OptionStorageLocation[]{ - new EditorConfigStorageLocation>( - styleName, - s => ParseParenthesesPreference(s, defaultValue), - v => GetParenthesesPreferenceEditorConfigString(v)), - new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")}); - } - - internal static readonly PerLanguageOption> ArithmeticBinaryParentheses = - CreateParenthesesOption( - nameof(ArithmeticBinaryParentheses), - s_alwaysForClarityPreference, - "dotnet_style_parentheses_in_arithmetic_binary_operators"); - - internal static readonly PerLanguageOption> OtherBinaryParentheses = - CreateParenthesesOption( - nameof(OtherBinaryParentheses), - s_alwaysForClarityPreference, - "dotnet_style_parentheses_in_other_binary_operators"); - - internal static readonly PerLanguageOption> RelationalBinaryParentheses = - CreateParenthesesOption( - nameof(RelationalBinaryParentheses), - s_alwaysForClarityPreference, - "dotnet_style_parentheses_in_relational_binary_operators"); - - internal static readonly PerLanguageOption> OtherParentheses = - CreateParenthesesOption( - nameof(OtherParentheses), - s_neverIfUnnecessaryPreference, - "dotnet_style_parentheses_in_other_operators"); - - private static readonly BidirectionalMap s_parenthesesPreferenceMap = - new BidirectionalMap(new[] - { - KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), - KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), - }); - - private static readonly BidirectionalMap s_unusedParametersPreferenceMap = - new BidirectionalMap(new[] - { - KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), - KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), - }); - - internal static readonly PerLanguageOption> PreferSystemHashCode = new PerLanguageOption>( - nameof(CodeStyleOptions), - nameof(PreferSystemHashCode), - defaultValue: TrueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ - new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode") }); - - static CodeStyleOptions() - { - // Note that the static constructor executes after all the static field initializers for the options have executed, - // and each field initializer adds the created option to s_allOptionsBuilder. - AllOptions = s_allOptionsBuilder.ToImmutable(); - } - - private static Optional> ParseParenthesesPreference( - string optionString, Optional> defaultValue) - { - if (TryGetCodeStyleValueAndOptionalNotification(optionString, - out var value, out var notificationOpt)) - { - Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); - return new CodeStyleOption(s_parenthesesPreferenceMap.GetValueOrDefault(value), - notificationOpt ?? NotificationOption.Silent); - } - - return defaultValue; - } - - private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption option) - { - Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); - var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); - return option.Notification == null ? value : $"{value}:{option.Notification.ToEditorConfigString()}"; - } - - private static Optional> ParseUnusedParametersPreference(string optionString) - { - if (TryGetCodeStyleValueAndOptionalNotification(optionString, - out var value, out var notificationOpt)) - { - return new CodeStyleOption( - s_unusedParametersPreferenceMap.GetValueOrDefault(value), notificationOpt ?? NotificationOption.Suggestion); - } - - return s_preferNoneUnusedParametersPreference; - } - - private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption option, UnusedParametersPreference defaultPreference) - { - Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); - var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultPreference); - return option.Notification == null ? value : $"{value}:{option.Notification.ToEditorConfigString()}"; - } - } - - internal static class CodeStyleOptionGroups - { - public static readonly OptionGroup Usings = new OptionGroup(CompilerExtensionsResources.Organize_usings, priority: 1); - public static readonly OptionGroup ThisOrMe = new OptionGroup(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); - public static readonly OptionGroup PredefinedTypeNameUsage = new OptionGroup(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); - public static readonly OptionGroup Parentheses = new OptionGroup(CompilerExtensionsResources.Parentheses_preferences, priority: 4); - public static readonly OptionGroup Modifier = new OptionGroup(CompilerExtensionsResources.Modifier_preferences, priority: 5); - public static readonly OptionGroup ExpressionLevelPreferences = new OptionGroup(CompilerExtensionsResources.Expression_level_preferences, priority: 6); - public static readonly OptionGroup Field = new OptionGroup(CompilerExtensionsResources.Field_preferences, priority: 7); - public static readonly OptionGroup Parameter = new OptionGroup(CompilerExtensionsResources.Parameter_preferences, priority: 8); + /// + public static readonly PerLanguageOption> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = + CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.ToPublicOption(); } } diff --git a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptionsProvider.cs b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptionsProvider.cs index a8e3ce5ed5521..954125af1d737 100644 --- a/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptionsProvider.cs +++ b/src/Workspaces/Core/Portable/CodeStyle/CodeStyleOptionsProvider.cs @@ -17,6 +17,6 @@ public CodeStyleOptionsProvider() { } - public ImmutableArray Options { get; } = CodeStyleOptions.AllOptions; + public ImmutableArray Options { get; } = CodeStyleOptions2.AllOptions.As(); } } diff --git a/src/Workspaces/Core/Portable/CodeStyle/NotificationOption.cs b/src/Workspaces/Core/Portable/CodeStyle/NotificationOption.cs index 4716f4907b546..61dadba164ddc 100644 --- a/src/Workspaces/Core/Portable/CodeStyle/NotificationOption.cs +++ b/src/Workspaces/Core/Portable/CodeStyle/NotificationOption.cs @@ -5,32 +5,25 @@ using System; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; -#endif - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { - /// - /// Offers different notification styles for enforcing - /// a code style. Under the hood, it simply maps to - /// - /// - /// This also supports various properties for databinding. - /// - /// + /// public class NotificationOption { - public string Name { get; set; } + private readonly NotificationOption2 _notificationOptionImpl; + + /// + public string Name + { + get => _notificationOptionImpl.Name; + set => _notificationOptionImpl.Name = value; + } + /// public ReportDiagnostic Severity { - get; - set; + get => _notificationOptionImpl.Severity; + set => _notificationOptionImpl.Severity = value; } [Obsolete("Use " + nameof(Severity) + " instead.")] @@ -40,18 +33,26 @@ public DiagnosticSeverity Value set => Severity = value.ToReportDiagnostic(); } - public static readonly NotificationOption None = new NotificationOption(WorkspacesResources.None, ReportDiagnostic.Suppress); - public static readonly NotificationOption Silent = new NotificationOption(WorkspacesResources.Refactoring_Only, ReportDiagnostic.Hidden); - public static readonly NotificationOption Suggestion = new NotificationOption(WorkspacesResources.Suggestion, ReportDiagnostic.Info); - public static readonly NotificationOption Warning = new NotificationOption(WorkspacesResources.Warning, ReportDiagnostic.Warn); - public static readonly NotificationOption Error = new NotificationOption(WorkspacesResources.Error, ReportDiagnostic.Error); + /// + public static readonly NotificationOption None = new NotificationOption(NotificationOption2.None); + + /// + public static readonly NotificationOption Silent = new NotificationOption(NotificationOption2.Silent); + + /// + public static readonly NotificationOption Suggestion = new NotificationOption(NotificationOption2.Suggestion); + + /// + public static readonly NotificationOption Warning = new NotificationOption(NotificationOption2.Warning); + + /// + public static readonly NotificationOption Error = new NotificationOption(NotificationOption2.Error); - private NotificationOption(string name, ReportDiagnostic severity) + private NotificationOption(NotificationOption2 notificationOptionImpl) { - Name = name; - Severity = severity; + _notificationOptionImpl = notificationOptionImpl; } - public override string ToString() => Name; + public override string ToString() => _notificationOptionImpl.ToString(); } } diff --git a/src/Workspaces/Core/Portable/CodeStyle/NotificationOption2_operators.cs b/src/Workspaces/Core/Portable/CodeStyle/NotificationOption2_operators.cs new file mode 100644 index 0000000000000..48754d4020ab1 --- /dev/null +++ b/src/Workspaces/Core/Portable/CodeStyle/NotificationOption2_operators.cs @@ -0,0 +1,52 @@ +// 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. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CodeStyle +{ + internal sealed partial class NotificationOption2 + { + [return: NotNullIfNotNull("notificationOption")] + public static explicit operator NotificationOption2?(NotificationOption? notificationOption) + { + if (notificationOption is null) + { + return null; + } + + return notificationOption.Severity switch + { + ReportDiagnostic.Suppress => None, + ReportDiagnostic.Hidden => Silent, + ReportDiagnostic.Info => Suggestion, + ReportDiagnostic.Warn => Warning, + ReportDiagnostic.Error => Error, + _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), + }; + } + + [return: NotNullIfNotNull("notificationOption")] + public static explicit operator NotificationOption?(NotificationOption2? notificationOption) + { + if (notificationOption is null) + { + return null; + } + + return notificationOption.Severity switch + { + ReportDiagnostic.Suppress => NotificationOption.None, + ReportDiagnostic.Hidden => NotificationOption.Silent, + ReportDiagnostic.Info => NotificationOption.Suggestion, + ReportDiagnostic.Warn => NotificationOption.Warning, + ReportDiagnostic.Error => NotificationOption.Error, + _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), + }; + } + } +} diff --git a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs index 91faf01e666fe..5a029fcc52b84 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/Extensions.cs @@ -12,7 +12,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; @@ -201,30 +200,5 @@ public static ImmutableArray Filter(this ImmutableArray return diagnostics.RemoveAll(diagnostic => diagnosticIdsToFilter.Contains(diagnostic.Id)); } - - public static NotificationOption ToNotificationOption(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity) - { - switch (reportDiagnostic.WithDefaultSeverity(defaultSeverity)) - { - case ReportDiagnostic.Error: - return NotificationOption.Error; - - case ReportDiagnostic.Warn: - return NotificationOption.Warning; - - case ReportDiagnostic.Info: - return NotificationOption.Suggestion; - - case ReportDiagnostic.Hidden: - return NotificationOption.Silent; - - case ReportDiagnostic.Suppress: - return NotificationOption.None; - - case ReportDiagnostic.Default: - default: - throw ExceptionUtilities.UnexpectedValue(reportDiagnostic); - } - } } } diff --git a/src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs b/src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs index a17584fc4b796..b16b70e74eeed 100644 --- a/src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs +++ b/src/Workspaces/Core/Portable/Diagnostics/InternalDiagnosticsOptions.cs @@ -10,25 +10,25 @@ internal static class InternalDiagnosticsOptions { private const string LocalRegistryPath = @"Roslyn\Internal\Diagnostics\"; - public static readonly Option CompilationEndCodeFix = new Option(nameof(InternalDiagnosticsOptions), "Enable Compilation End Code Fix", defaultValue: true, + public static readonly Option2 CompilationEndCodeFix = new Option2(nameof(InternalDiagnosticsOptions), "Enable Compilation End Code Fix", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Enable Compilation End Code Fix")); - public static readonly Option UseCompilationEndCodeFixHeuristic = new Option(nameof(InternalDiagnosticsOptions), "Enable Compilation End Code Fix With Heuristic", defaultValue: true, + public static readonly Option2 UseCompilationEndCodeFixHeuristic = new Option2(nameof(InternalDiagnosticsOptions), "Enable Compilation End Code Fix With Heuristic", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Enable Compilation End Code Fix With Heuristic")); - public static readonly Option PreferLiveErrorsOnOpenedFiles = new Option(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true, + public static readonly Option2 PreferLiveErrorsOnOpenedFiles = new Option2(nameof(InternalDiagnosticsOptions), "Live errors will be preferred over errors from build on opened files from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Live errors will be preferred over errors from build on opened files from same analyzer")); - public static readonly Option PreferBuildErrorsOverLiveErrors = new Option(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true, + public static readonly Option2 PreferBuildErrorsOverLiveErrors = new Option2(nameof(InternalDiagnosticsOptions), "Errors from build will be preferred over live errors from same analyzer", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Errors from build will be preferred over live errors from same analyzer")); - public static readonly Option PutCustomTypeInBingSearch = new Option(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true, + public static readonly Option2 PutCustomTypeInBingSearch = new Option2(nameof(InternalDiagnosticsOptions), nameof(PutCustomTypeInBingSearch), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "PutCustomTypeInBingSearch")); - public static readonly Option CrashOnAnalyzerException = new Option(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false, + public static readonly Option2 CrashOnAnalyzerException = new Option2(nameof(InternalDiagnosticsOptions), nameof(CrashOnAnalyzerException), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "CrashOnAnalyzerException")); - public static readonly Option ProcessHiddenDiagnostics = new Option(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false, + public static readonly Option2 ProcessHiddenDiagnostics = new Option2(nameof(InternalDiagnosticsOptions), nameof(ProcessHiddenDiagnostics), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Process Hidden Diagnostics")); } } diff --git a/src/Workspaces/Core/Portable/Editing/GenerationOptionsProvider.cs b/src/Workspaces/Core/Portable/Editing/GenerationOptionsProvider.cs index 536cfcb19f44a..04015a6c2a32a 100644 --- a/src/Workspaces/Core/Portable/Editing/GenerationOptionsProvider.cs +++ b/src/Workspaces/Core/Portable/Editing/GenerationOptionsProvider.cs @@ -17,6 +17,6 @@ public GenerationOptionsProvider() { } - public ImmutableArray Options { get; } = GenerationOptions.AllOptions; + public ImmutableArray Options { get; } = GenerationOptions.AllOptions.As(); } } diff --git a/src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/RegularExpressionsOptions.cs b/src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/RegularExpressionsOptions.cs index b63d6354e0917..1e3898a3a35b6 100644 --- a/src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/RegularExpressionsOptions.cs +++ b/src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/RegularExpressionsOptions.cs @@ -13,29 +13,29 @@ namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal class RegularExpressionsOptions { - public static PerLanguageOption ColorizeRegexPatterns = - new PerLanguageOption( + public static PerLanguageOption2 ColorizeRegexPatterns = + new PerLanguageOption2( nameof(RegularExpressionsOptions), nameof(ColorizeRegexPatterns), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ColorizeRegexPatterns")); - public static PerLanguageOption ReportInvalidRegexPatterns = - new PerLanguageOption( + public static PerLanguageOption2 ReportInvalidRegexPatterns = + new PerLanguageOption2( nameof(RegularExpressionsOptions), nameof(ReportInvalidRegexPatterns), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ReportInvalidRegexPatterns")); - public static PerLanguageOption HighlightRelatedRegexComponentsUnderCursor = - new PerLanguageOption( + public static PerLanguageOption2 HighlightRelatedRegexComponentsUnderCursor = + new PerLanguageOption2( nameof(RegularExpressionsOptions), nameof(HighlightRelatedRegexComponentsUnderCursor), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.HighlightRelatedRegexComponentsUnderCursor")); - public static PerLanguageOption ProvideRegexCompletions = - new PerLanguageOption( + public static PerLanguageOption2 ProvideRegexCompletions = + new PerLanguageOption2( nameof(RegularExpressionsOptions), nameof(ProvideRegexCompletions), defaultValue: true, @@ -50,7 +50,7 @@ public RegularExpressionsOptionsProvider() { } - public ImmutableArray Options { get; } = ImmutableArray.Create( + public ImmutableArray Options { get; } = ImmutableArray.Create( RegularExpressionsOptions.ColorizeRegexPatterns, RegularExpressionsOptions.ReportInvalidRegexPatterns, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor); diff --git a/src/Workspaces/Core/Portable/Formatting/FormattingOptions.cs b/src/Workspaces/Core/Portable/Formatting/FormattingOptions.cs new file mode 100644 index 0000000000000..d39ee74058195 --- /dev/null +++ b/src/Workspaces/Core/Portable/Formatting/FormattingOptions.cs @@ -0,0 +1,50 @@ +// 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. + +#nullable enable + +using Microsoft.CodeAnalysis.Options; + +namespace Microsoft.CodeAnalysis.Formatting +{ + /// + public static partial class FormattingOptions + { + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption UseTabs { get; } = ((PerLanguageOption)FormattingOptions2.UseTabs)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption TabSize { get; } = ((PerLanguageOption)FormattingOptions2.TabSize)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption IndentationSize { get; } = ((PerLanguageOption)FormattingOptions2.IndentationSize)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption SmartIndent { get; } = ((PerLanguageOption)FormattingOptions2.SmartIndent)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + public static PerLanguageOption NewLine { get; } = ((PerLanguageOption)FormattingOptions2.NewLine)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + internal static Option InsertFinalNewLine { get; } = ((Option)FormattingOptions2.InsertFinalNewLine)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + internal static Option PreferredWrappingColumn { get; } = ((Option)FormattingOptions2.PreferredWrappingColumn)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + internal static Option AllowDisjointSpanMerging { get; } = ((Option)FormattingOptions2.AllowDisjointSpanMerging)!; + + /// + // Suppression due to https://github.com/dotnet/roslyn/issues/42614 + internal static readonly PerLanguageOption AutoFormattingOnReturn = ((PerLanguageOption)FormattingOptions2.AutoFormattingOnReturn)!; + } +} diff --git a/src/Workspaces/Core/Portable/Formatting/FormattingOptionsProvider.cs b/src/Workspaces/Core/Portable/Formatting/FormattingOptionsProvider.cs index 5405cc343aa7d..aab2f41d70f20 100644 --- a/src/Workspaces/Core/Portable/Formatting/FormattingOptionsProvider.cs +++ b/src/Workspaces/Core/Portable/Formatting/FormattingOptionsProvider.cs @@ -17,6 +17,6 @@ public FormattingOptionsProvider() { } - public ImmutableArray Options { get; } = FormattingOptions.AllOptions; + public ImmutableArray Options { get; } = FormattingOptions2.AllOptions.As(); } } diff --git a/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj b/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj index eb747f18a1c72..3f555ff91a3c7 100644 --- a/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj +++ b/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj @@ -127,9 +127,7 @@ - - - + diff --git a/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs b/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs index c8d6988deb608..29f306de71d9e 100644 --- a/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs @@ -37,6 +37,11 @@ public T GetOption(PerLanguageOption option) return _backingOptionSet.GetOption(option, _language); } + internal T GetOption(PerLanguageOption2 option) + { + return _backingOptionSet.GetOption(option, _language); + } + public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) { return new DocumentOptionSet(_backingOptionSet.WithChangedOption(optionAndLanguage, value), _language); @@ -50,6 +55,14 @@ public DocumentOptionSet WithChangedOption(PerLanguageOption option, T val return (DocumentOptionSet)WithChangedOption(option, _language, value); } + /// + /// Creates a new that contains the changed value. + /// + internal DocumentOptionSet WithChangedOption(PerLanguageOption2 option, T value) + { + return (DocumentOptionSet)WithChangedOption(option, _language, value); + } + private protected override AnalyzerConfigOptions CreateAnalyzerConfigOptions(IOptionService optionService, string? language) { Debug.Assert((language ?? _language) == _language, $"Use of a {nameof(DocumentOptionSet)} is not expected to differ from the language it was constructed with."); diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigDocumentOptionsProviderFactory.cs b/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigDocumentOptionsProviderFactory.cs index a3583e6b0aaf1..88126b9c146ef 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigDocumentOptionsProviderFactory.cs +++ b/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigDocumentOptionsProviderFactory.cs @@ -24,8 +24,8 @@ public static IDocumentOptionsProvider Create(Workspace workspace) private const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; - public static readonly Option UseLegacyEditorConfigSupport = - new Option(nameof(EditorConfigDocumentOptionsProviderFactory), nameof(UseLegacyEditorConfigSupport), defaultValue: false, + public static readonly Option2 UseLegacyEditorConfigSupport = + new Option2(nameof(EditorConfigDocumentOptionsProviderFactory), nameof(UseLegacyEditorConfigSupport), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "UseLegacySupport")); public static bool ShouldUseNativeEditorConfigSupport(Workspace workspace) diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigFileGenerator.cs b/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigFileGenerator.cs index b0028180a0d0b..c5f6bad0255ab 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigFileGenerator.cs +++ b/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigFileGenerator.cs @@ -4,20 +4,16 @@ #nullable enable -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.Options { - internal static class EditorConfigFileGenerator + internal static partial class EditorConfigFileGenerator { public static string Generate( ImmutableArray<(string feature, ImmutableArray options)> groupedOptions, @@ -90,119 +86,5 @@ string GetEditorConfigString(IOption option, IEditorConfigStorageLocation2 edito return editorConfigString; } } - - public static void AppendNamingStylePreferencesToEditorConfig(NamingStylePreferences namingStylePreferences, string language, StringBuilder editorconfig) - { - editorconfig.AppendLine($"#### {WorkspacesResources.Naming_styles} ####"); - - var serializedNameMap = AssignNamesToNamingStyleElements(namingStylePreferences); - var ruleNameMap = AssignNamesToNamingStyleRules(namingStylePreferences, serializedNameMap); - var referencedElements = new HashSet(); - - editorconfig.AppendLine(); - editorconfig.AppendLine($"# {WorkspacesResources.Naming_rules}"); - - foreach (var namingRule in namingStylePreferences.NamingRules) - { - referencedElements.Add(namingRule.SymbolSpecificationID); - referencedElements.Add(namingRule.NamingStyleID); - - editorconfig.AppendLine(); - editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.severity = {namingRule.EnforcementLevel.ToNotificationOption(defaultSeverity: DiagnosticSeverity.Hidden).ToEditorConfigString()}"); - editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.symbols = {serializedNameMap[namingRule.SymbolSpecificationID]}"); - editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.style = {serializedNameMap[namingRule.NamingStyleID]}"); - } - - editorconfig.AppendLine(); - editorconfig.AppendLine($"# {WorkspacesResources.Symbol_specifications}"); - - foreach (var symbolSpecification in namingStylePreferences.SymbolSpecifications) - { - if (!referencedElements.Contains(symbolSpecification.ID)) - { - continue; - } - - editorconfig.AppendLine(); - editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.applicable_kinds = {symbolSpecification.ApplicableSymbolKindList.ToEditorConfigString()}"); - editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.applicable_accessibilities = {symbolSpecification.ApplicableAccessibilityList.ToEditorConfigString(language)}"); - editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.required_modifiers = {symbolSpecification.RequiredModifierList.ToEditorConfigString(language)}"); - } - - editorconfig.AppendLine(); - editorconfig.AppendLine($"# {WorkspacesResources.Naming_styles}"); - - foreach (var namingStyle in namingStylePreferences.NamingStyles) - { - if (!referencedElements.Contains(namingStyle.ID)) - { - continue; - } - - editorconfig.AppendLine(); - editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.required_prefix = {namingStyle.Prefix}"); - editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.required_suffix = {namingStyle.Suffix}"); - editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.word_separator = {namingStyle.WordSeparator}"); - editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.capitalization = {namingStyle.CapitalizationScheme.ToEditorConfigString()}"); - } - } - - private static ImmutableDictionary AssignNamesToNamingStyleElements(NamingStylePreferences namingStylePreferences) - { - var symbolSpecificationNames = new HashSet(); - var builder = ImmutableDictionary.CreateBuilder(); - foreach (var symbolSpecification in namingStylePreferences.SymbolSpecifications) - { - var name = ToSnakeCaseName(symbolSpecification.Name); - if (!symbolSpecificationNames.Add(name)) - { - name = symbolSpecification.ID.ToString("n"); - } - - builder.Add(symbolSpecification.ID, name); - } - - var namingStyleNames = new HashSet(); - foreach (var namingStyle in namingStylePreferences.NamingStyles) - { - var name = ToSnakeCaseName(namingStyle.Name); - if (!namingStyleNames.Add(name)) - { - name = namingStyle.ID.ToString("n"); - } - - builder.Add(namingStyle.ID, name); - } - - return builder.ToImmutable(); - - static string ToSnakeCaseName(string name) - { - return new string(name - .Select(ch => - { - if (char.IsLetterOrDigit(ch)) - { - return char.ToLowerInvariant(ch); - } - else - { - return '_'; - } - }) - .ToArray()); - } - } - - private static ImmutableDictionary AssignNamesToNamingStyleRules(NamingStylePreferences namingStylePreferences, ImmutableDictionary serializedNameMap) - { - var builder = ImmutableDictionary.CreateBuilder(); - foreach (var rule in namingStylePreferences.NamingRules) - { - builder.Add(rule, $"{serializedNameMap[rule.SymbolSpecificationID]}_should_be_{serializedNameMap[rule.NamingStyleID]}"); - } - - return builder.ToImmutable(); - } } } diff --git a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs index 29888b21d131f..beb9a41489937 100644 --- a/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/GlobalOptionService.cs @@ -254,14 +254,16 @@ public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet(Option option) - { - return (T)GetOption(new OptionKey(option))!; - } + => OptionsHelpers.GetOption(option, GetOption); + + public T GetOption(Option2 option) + => OptionsHelpers.GetOption(option, GetOption); public T GetOption(PerLanguageOption option, string? language) - { - return (T)GetOption(new OptionKey(option, language))!; - } + => OptionsHelpers.GetOption(option, language, GetOption); + + public T GetOption(PerLanguageOption2 option, string? language) + => OptionsHelpers.GetOption(option, language, GetOption); public object? GetOption(OptionKey optionKey) { diff --git a/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs b/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs index 6fda9789ed910..df465757c92f6 100644 --- a/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/IGlobalOptionService.cs @@ -27,12 +27,24 @@ internal interface IGlobalOptionService [return: MaybeNull] T GetOption(Option option); + /// + /// Gets the current value of the specific option. + /// + [return: MaybeNull] + T GetOption(Option2 option); + /// /// Gets the current value of the specific option. /// [return: MaybeNull] T GetOption(PerLanguageOption option, string? languageName); + /// + /// Gets the current value of the specific option. + /// + [return: MaybeNull] + T GetOption(PerLanguageOption2 option, string? languageName); + /// /// Gets the current value of the specific option. /// diff --git a/src/Workspaces/Core/Portable/Options/IOption.cs b/src/Workspaces/Core/Portable/Options/IOption.cs index e34e0f10bacdb..e515933f6158b 100644 --- a/src/Workspaces/Core/Portable/Options/IOption.cs +++ b/src/Workspaces/Core/Portable/Options/IOption.cs @@ -7,11 +7,7 @@ using System; using System.Collections.Immutable; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { public interface IOption { diff --git a/src/Workspaces/Core/Portable/Options/IOptionService.cs b/src/Workspaces/Core/Portable/Options/IOptionService.cs index 17711346afe8a..4e8be2ccf92f9 100644 --- a/src/Workspaces/Core/Portable/Options/IOptionService.cs +++ b/src/Workspaces/Core/Portable/Options/IOptionService.cs @@ -29,12 +29,24 @@ internal interface IOptionService : IWorkspaceService [return: MaybeNull] T GetOption(Option option); + /// + /// Gets the current value of the specific option. + /// + [return: MaybeNull] + T GetOption(Option2 option); + /// /// Gets the current value of the specific option. /// [return: MaybeNull] T GetOption(PerLanguageOption option, string? languageName); + /// + /// Gets the current value of the specific option. + /// + [return: MaybeNull] + T GetOption(PerLanguageOption2 option, string? languageName); + /// /// Gets the current value of the specific option. /// diff --git a/src/Workspaces/Core/Portable/Options/Option2`1_operators.cs b/src/Workspaces/Core/Portable/Options/Option2`1_operators.cs new file mode 100644 index 0000000000000..be96825a31b80 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/Option2`1_operators.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Options +{ + internal partial class Option2 + { + [return: NotNullIfNotNull("option")] + public static explicit operator Option?(Option2? option) + { + if (option is null) + { + return null; + } + + return new Option(option.OptionDefinition, option.StorageLocations.As()); + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/OptionKey.cs b/src/Workspaces/Core/Portable/Options/OptionKey.cs index aedd8d724885b..b6bca7a28250d 100644 --- a/src/Workspaces/Core/Portable/Options/OptionKey.cs +++ b/src/Workspaces/Core/Portable/Options/OptionKey.cs @@ -7,20 +7,16 @@ using System; using Roslyn.Utilities; -#if CODE_STYLE -using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; -#endif - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { + /// [NonDefaultable] public readonly struct OptionKey : IEquatable { + /// public IOption Option { get; } + + /// public string? Language { get; } public OptionKey(IOption option, string? language = null) @@ -46,7 +42,19 @@ public override bool Equals(object? obj) public bool Equals(OptionKey other) { - return Option == other.Option && Language == other.Language; + return OptionEqual(Option, other.Option) && Language == other.Language; + + static bool OptionEqual(IOption thisOption, IOption otherOption) + { + if (!(thisOption is IOption2 thisOption2) || + !(otherOption is IOption2 otherOption2)) + { + // Third party definition of 'IOption'. + return thisOption.Equals(otherOption); + } + + return thisOption2.Equals(otherOption2); + } } public override int GetHashCode() diff --git a/src/Workspaces/Core/Portable/Options/OptionKey2_operators.cs b/src/Workspaces/Core/Portable/Options/OptionKey2_operators.cs new file mode 100644 index 0000000000000..e53b787a1b4b1 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/OptionKey2_operators.cs @@ -0,0 +1,14 @@ +// 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. + +#nullable enable + +namespace Microsoft.CodeAnalysis.Options +{ + internal readonly partial struct OptionKey2 + { + public static explicit operator OptionKey(OptionKey2 optionKey) + => new OptionKey(optionKey.Option, optionKey.Language); + } +} diff --git a/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs b/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs index a1628d2421897..095ec6eff2842 100644 --- a/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs +++ b/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs @@ -121,7 +121,9 @@ public event EventHandler OptionChanged public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet languages) => _globalOptionService.GetSerializableOptionsSnapshot(languages, this); public object? GetOption(OptionKey optionKey) => _globalOptionService.GetOption(optionKey); [return: MaybeNull] public T GetOption(Option option) => _globalOptionService.GetOption(option); + [return: MaybeNull] public T GetOption(Option2 option) => _globalOptionService.GetOption(option); [return: MaybeNull] public T GetOption(PerLanguageOption option, string? languageName) => _globalOptionService.GetOption(option, languageName); + [return: MaybeNull] public T GetOption(PerLanguageOption2 option, string? languageName) => _globalOptionService.GetOption(option, languageName); public IEnumerable GetRegisteredOptions() => _globalOptionService.GetRegisteredOptions(); public bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey) => _globalOptionService.TryMapEditorConfigKeyToOption(key, language, out storageLocation, out optionKey); public ImmutableHashSet GetRegisteredSerializableOptions(ImmutableHashSet languages) => _globalOptionService.GetRegisteredSerializableOptions(languages); diff --git a/src/Workspaces/Core/Portable/Options/OptionSet.cs b/src/Workspaces/Core/Portable/Options/OptionSet.cs index 7bcec63140b65..ddd1821de306f 100644 --- a/src/Workspaces/Core/Portable/Options/OptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/OptionSet.cs @@ -27,27 +27,47 @@ public abstract partial class OptionSet /// public abstract object? GetOption(OptionKey optionKey); + /// + /// Gets the value of the option, or the default value if not otherwise set. + /// + internal object? GetOption(OptionKey2 optionKey) + => OptionsHelpers.GetOption(optionKey, GetOption); + /// /// Gets the value of the option, or the default value if not otherwise set. /// public T GetOption(Option option) - { - return (T)GetOption(new OptionKey(option, language: null))!; - } + => OptionsHelpers.GetOption(option, GetOption); + + /// + /// Gets the value of the option, or the default value if not otherwise set. + /// + internal T GetOption(Option2 option) + => OptionsHelpers.GetOption(option, GetOption); /// /// Gets the value of the option, or the default value if not otherwise set. /// public T GetOption(PerLanguageOption option, string? language) - { - return (T)GetOption(new OptionKey(option, language))!; - } + => OptionsHelpers.GetOption(option, language, GetOption); + + /// + /// Gets the value of the option, or the default value if not otherwise set. + /// + internal T GetOption(PerLanguageOption2 option, string? language) + => OptionsHelpers.GetOption(option, language, GetOption); /// /// Creates a new that contains the changed value. /// public abstract OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value); + /// + /// Creates a new that contains the changed value. + /// + internal OptionSet WithChangedOption(OptionKey2 optionAndLanguage, object? value) + => WithChangedOption((OptionKey)optionAndLanguage, value); + /// /// Creates a new that contains the changed value. /// @@ -56,6 +76,14 @@ public OptionSet WithChangedOption(Option option, T value) return WithChangedOption(new OptionKey(option), value); } + /// + /// Creates a new that contains the changed value. + /// + internal OptionSet WithChangedOption(Option2 option, T value) + { + return WithChangedOption(new OptionKey(option), value); + } + /// /// Creates a new that contains the changed value. /// @@ -64,6 +92,14 @@ public OptionSet WithChangedOption(PerLanguageOption option, string? langu return WithChangedOption(new OptionKey(option, language), value); } + /// + /// Creates a new that contains the changed value. + /// + internal OptionSet WithChangedOption(PerLanguageOption2 option, string? language, T value) + { + return WithChangedOption(new OptionKey(option, language), value); + } + internal AnalyzerConfigOptions AsAnalyzerConfigOptions(IOptionService optionService, string? language) { return ImmutableInterlocked.GetOrAdd( diff --git a/src/Workspaces/Core/Portable/Options/OptionStorageLocation.cs b/src/Workspaces/Core/Portable/Options/OptionStorageLocation.cs index f57273dbc15d3..f8e51208441cb 100644 --- a/src/Workspaces/Core/Portable/Options/OptionStorageLocation.cs +++ b/src/Workspaces/Core/Portable/Options/OptionStorageLocation.cs @@ -4,11 +4,7 @@ #nullable enable -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { /// /// The base type of all types that specify where options are stored. diff --git a/src/Workspaces/Core/Portable/Options/Option`1.cs b/src/Workspaces/Core/Portable/Options/Option`1.cs index 05bcee9e118c5..5d52b71360835 100644 --- a/src/Workspaces/Core/Portable/Options/Option`1.cs +++ b/src/Workspaces/Core/Portable/Options/Option`1.cs @@ -7,49 +7,29 @@ using System; using System.Collections.Immutable; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { - /// - /// Marker interface for - /// - internal interface ILanguageSpecificOption : IOptionWithGroup + /// + public class Option : ILanguageSpecificOption { - } + private readonly OptionDefinition _optionDefinition; - /// - /// An global option. An instance of this class can be used to access an option value from an OptionSet. - /// - public class Option : ILanguageSpecificOption - { - /// - /// Feature this option is associated with. - /// - public string Feature { get; } - - /// - /// Optional group/sub-feature for this option. - /// - internal OptionGroup Group { get; } - - /// - /// The name of the option. - /// - public string Name { get; } - - /// - /// The default value of the option. - /// - public T DefaultValue { get; } - - /// - /// The type of the option value. - /// - public Type Type => typeof(T); + /// + public string Feature => _optionDefinition.Feature; + + /// + internal OptionGroup Group => _optionDefinition.Group; + + /// + public string Name => _optionDefinition.Name; + + /// + public T DefaultValue => (T)_optionDefinition.DefaultValue!; + + /// + public Type Type => _optionDefinition.Type; + /// public ImmutableArray StorageLocations { get; } [Obsolete("Use a constructor that specifies an explicit default value.")] @@ -70,33 +50,45 @@ public Option(string feature, string name, T defaultValue, params OptionStorageL } internal Option(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { - if (string.IsNullOrWhiteSpace(feature)) - { - throw new ArgumentNullException(nameof(feature)); - } + } - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException(nameof(name)); - } + internal Option(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray storageLocations) + : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false), storageLocations) + { + } - this.Feature = feature; - this.Group = group ?? throw new ArgumentNullException(nameof(group)); - this.Name = name; - this.DefaultValue = defaultValue; - this.StorageLocations = storageLocations.ToImmutableArray(); + internal Option(OptionDefinition optionDefinition, ImmutableArray storageLocations) + { + _optionDefinition = optionDefinition; + this.StorageLocations = storageLocations; } + OptionGroup IOptionWithGroup.Group => this.Group; + object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => false; - OptionGroup IOptionWithGroup.Group => this.Group; + OptionDefinition IOption2.OptionDefinition => _optionDefinition; + + bool IEquatable.Equals(IOption2? other) => Equals(other); - public override string ToString() + public override string ToString() => _optionDefinition.ToString(); + + public override int GetHashCode() => _optionDefinition.GetHashCode(); + + public override bool Equals(object? obj) => Equals(obj as IOption2); + + private bool Equals(IOption2? other) { - return string.Format("{0} - {1}", this.Feature, this.Name); + if (ReferenceEquals(this, other)) + { + return true; + } + + return _optionDefinition == other?.OptionDefinition; } public static implicit operator OptionKey(Option option) diff --git a/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs new file mode 100644 index 0000000000000..cdd3de65b1990 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/OptionsExtensions.cs @@ -0,0 +1,34 @@ +// 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. + +#nullable enable + +using Microsoft.CodeAnalysis.CodeStyle; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Options +{ + internal static class OptionsExtensions + { + public static Option> ToPublicOption(this Option2> option) + { + RoslynDebug.Assert(option != null); + + var codeStyleOption = new CodeStyleOption(option.DefaultValue); + var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, + defaultValue: codeStyleOption, type: typeof(CodeStyleOption), isPerLanguage: false); + return new Option>(optionDefinition, option.StorageLocations.As()); + } + + public static PerLanguageOption> ToPublicOption(this PerLanguageOption2> option) + { + RoslynDebug.Assert(option != null); + + var codeStyleOption = new CodeStyleOption(option.DefaultValue); + var optionDefinition = new OptionDefinition(option.Feature, option.Group, option.Name, + defaultValue: codeStyleOption, type: typeof(CodeStyleOption), isPerLanguage: true); + return new PerLanguageOption>(optionDefinition, option.StorageLocations.As()); + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/OptionsHelpers.cs b/src/Workspaces/Core/Portable/Options/OptionsHelpers.cs new file mode 100644 index 0000000000000..6a55d0aa1f2a2 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/OptionsHelpers.cs @@ -0,0 +1,50 @@ +// 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. + +#nullable enable + +using System; +using Microsoft.CodeAnalysis.CodeStyle; + +namespace Microsoft.CodeAnalysis.Options +{ + internal static class OptionsHelpers + { + public static T GetOption(Option option, Func getOption) + { + return GetOption(new OptionKey(option), getOption); + } + + public static T GetOption(Option2 option, Func getOption) + { + return GetOption(new OptionKey(option), getOption); + } + + public static T GetOption(PerLanguageOption option, string? language, Func getOption) + { + return GetOption(new OptionKey(option, language), getOption); + } + + public static T GetOption(PerLanguageOption2 option, string? language, Func getOption) + { + return GetOption(new OptionKey(option, language), getOption); + } + + public static T GetOption(OptionKey2 optionKey, Func getOption) + { + return GetOption(new OptionKey(optionKey.Option, optionKey.Language), getOption); + } + + public static T GetOption(OptionKey optionKey, Func getOption) + { + var value = getOption(optionKey); + if (value is ICodeStyleOption codeStyleOption) + { + return (T)codeStyleOption.AsCodeStyleOption(); + } + + return (T)value!; + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/PerLanguageOption.cs b/src/Workspaces/Core/Portable/Options/PerLanguageOption.cs index ad90d93599dca..86bae7e146861 100644 --- a/src/Workspaces/Core/Portable/Options/PerLanguageOption.cs +++ b/src/Workspaces/Core/Portable/Options/PerLanguageOption.cs @@ -7,50 +7,29 @@ using System; using System.Collections.Immutable; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { - /// - /// Marker interface for - /// - internal interface IPerLanguageOption : IOptionWithGroup + /// + public class PerLanguageOption : IPerLanguageOption { - } + private readonly OptionDefinition _optionDefinition; - /// - /// An option that can be specified once per language. - /// - /// - public class PerLanguageOption : IPerLanguageOption - { - /// - /// Feature this option is associated with. - /// - public string Feature { get; } - - /// - /// Optional group/sub-feature for this option. - /// - internal OptionGroup Group { get; } - - /// - /// The name of the option. - /// - public string Name { get; } - - /// - /// The type of the option value. - /// - public Type Type => typeof(T); - - /// - /// The default option value. - /// - public T DefaultValue { get; } + /// + public string Feature => _optionDefinition.Feature; + + /// + internal OptionGroup Group => _optionDefinition.Group; + + /// + public string Name => _optionDefinition.Name; + + /// + public Type Type => _optionDefinition.Type; + + /// + public T DefaultValue => (T)_optionDefinition.DefaultValue!; + /// public ImmutableArray StorageLocations { get; } public PerLanguageOption(string feature, string name, T defaultValue) @@ -64,33 +43,45 @@ public PerLanguageOption(string feature, string name, T defaultValue, params Opt } internal PerLanguageOption(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { - if (string.IsNullOrWhiteSpace(feature)) - { - throw new ArgumentNullException(nameof(feature)); - } + } - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException(nameof(name)); - } + internal PerLanguageOption(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray storageLocations) + : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true), storageLocations) + { + } - this.Feature = feature; - this.Group = group ?? throw new ArgumentNullException(nameof(group)); - this.Name = name; - this.DefaultValue = defaultValue; - this.StorageLocations = storageLocations.ToImmutableArray(); + internal PerLanguageOption(OptionDefinition optionDefinition, ImmutableArray storageLocations) + { + _optionDefinition = optionDefinition; + StorageLocations = storageLocations; } + OptionDefinition IOption2.OptionDefinition => _optionDefinition; + + OptionGroup IOptionWithGroup.Group => this.Group; + object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => true; - OptionGroup IOptionWithGroup.Group => this.Group; + bool IEquatable.Equals(IOption2? other) => Equals(other); - public override string ToString() + public override string ToString() => _optionDefinition.ToString(); + + public override int GetHashCode() => _optionDefinition.GetHashCode(); + + public override bool Equals(object? obj) => Equals(obj as IOption2); + + private bool Equals(IOption2? other) { - return string.Format("{0} - {1}", this.Feature, this.Name); + if (ReferenceEquals(this, other)) + { + return true; + } + + return _optionDefinition == other?.OptionDefinition; } } } diff --git a/src/Workspaces/Core/Portable/Options/PerLanguageOption2_operators.cs b/src/Workspaces/Core/Portable/Options/PerLanguageOption2_operators.cs new file mode 100644 index 0000000000000..b66452f130cf7 --- /dev/null +++ b/src/Workspaces/Core/Portable/Options/PerLanguageOption2_operators.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.CodeAnalysis.Options +{ + internal partial class PerLanguageOption2 + { + [return: NotNullIfNotNull("option")] + public static explicit operator PerLanguageOption?(PerLanguageOption2? option) + { + if (option is null) + { + return null; + } + + return new PerLanguageOption(option.OptionDefinition, option.StorageLocations.As()); + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs b/src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs index 5b1768e095d42..1d0ca69bd639c 100644 --- a/src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs @@ -327,7 +327,7 @@ public static SerializableOptionSet Deserialize(ObjectReader reader, IOptionServ continue; } - var parsedCodeStyleOption = CodeStyleOption.FromXElement(XElement.Parse((string)readValue)); + var parsedCodeStyleOption = CodeStyleOption2.FromXElement(XElement.Parse((string)readValue)); var value = parsedCodeStyleOption.Value; var type = optionKey.Option.Type.GenericTypeArguments[0]; var convertedValue = type.IsEnum ? Enum.ToObject(type, value) : Convert.ChangeType(value, type); diff --git a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt index bac44023f054b..1fec10e83b149 100644 --- a/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Workspaces/Core/Portable/PublicAPI.Unshipped.txt @@ -10,5 +10,9 @@ Microsoft.CodeAnalysis.Solution.RemoveDocuments(System.Collections.Immutable.Imm abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConditionalAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode whenNotNull) -> Microsoft.CodeAnalysis.SyntaxNode abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementBindingExpression(System.Collections.Generic.IEnumerable arguments) -> Microsoft.CodeAnalysis.SyntaxNode abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberBindingExpression(Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode +override Microsoft.CodeAnalysis.Options.Option.Equals(object obj) -> bool +override Microsoft.CodeAnalysis.Options.Option.GetHashCode() -> int +override Microsoft.CodeAnalysis.Options.PerLanguageOption.Equals(object obj) -> bool +override Microsoft.CodeAnalysis.Options.PerLanguageOption.GetHashCode() -> int static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/SolutionCrawler/SolutionCrawlerOptions.cs b/src/Workspaces/Core/Portable/SolutionCrawler/SolutionCrawlerOptions.cs index 30dc92fd6dd6f..0a59d988917d8 100644 --- a/src/Workspaces/Core/Portable/SolutionCrawler/SolutionCrawlerOptions.cs +++ b/src/Workspaces/Core/Portable/SolutionCrawler/SolutionCrawlerOptions.cs @@ -14,7 +14,7 @@ internal static class SolutionCrawlerOptions /// /// Option to turn configure background analysis scope. /// - public static readonly PerLanguageOption BackgroundAnalysisScopeOption = new PerLanguageOption( + public static readonly PerLanguageOption2 BackgroundAnalysisScopeOption = new PerLanguageOption2( nameof(SolutionCrawlerOptions), nameof(BackgroundAnalysisScopeOption), defaultValue: BackgroundAnalysisScope.Default, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.BackgroundAnalysisScopeOption")); diff --git a/src/Workspaces/Core/Portable/SymbolSearch/SymbolSearchOptions.cs b/src/Workspaces/Core/Portable/SymbolSearch/SymbolSearchOptions.cs index 2766dd1a4f544..5247f82ff9fe3 100644 --- a/src/Workspaces/Core/Portable/SymbolSearch/SymbolSearchOptions.cs +++ b/src/Workspaces/Core/Portable/SymbolSearch/SymbolSearchOptions.cs @@ -12,16 +12,16 @@ internal static class SymbolSearchOptions { private const string LocalRegistryPath = @"Roslyn\Features\SymbolSearch\"; - public static readonly Option Enabled = new Option( + public static readonly Option2 Enabled = new Option2( nameof(SymbolSearchOptions), nameof(Enabled), defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Enabled))); - public static PerLanguageOption SuggestForTypesInReferenceAssemblies = - new PerLanguageOption(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: true, + public static PerLanguageOption2 SuggestForTypesInReferenceAssemblies = + new PerLanguageOption2(nameof(SymbolSearchOptions), nameof(SuggestForTypesInReferenceAssemblies), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInReferenceAssemblies")); - public static PerLanguageOption SuggestForTypesInNuGetPackages = - new PerLanguageOption(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: true, + public static PerLanguageOption2 SuggestForTypesInNuGetPackages = + new PerLanguageOption2(nameof(SymbolSearchOptions), nameof(SuggestForTypesInNuGetPackages), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SuggestForTypesInNuGetPackages")); } } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Caching/CacheOptions.cs b/src/Workspaces/Core/Portable/Workspace/Host/Caching/CacheOptions.cs index ef2ca1ffdf876..19049b07b580c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Caching/CacheOptions.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Caching/CacheOptions.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Host { internal static class CacheOptions { - internal static readonly Option RecoverableTreeLengthThreshold = new Option(nameof(CacheOptions), "RecoverableTreeLengthThreshold", defaultValue: 4096, + internal static readonly Option2 RecoverableTreeLengthThreshold = new Option2(nameof(CacheOptions), "RecoverableTreeLengthThreshold", defaultValue: 4096, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\Cache\RecoverableTreeLengthThreshold")); } } diff --git a/src/Workspaces/Core/Portable/WorkspacesResources.resx b/src/Workspaces/Core/Portable/WorkspacesResources.resx index 4c0713e8de115..1b30649c14a1f 100644 --- a/src/Workspaces/Core/Portable/WorkspacesResources.resx +++ b/src/Workspaces/Core/Portable/WorkspacesResources.resx @@ -1305,15 +1305,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of DateTimeKind must be Utc - - Naming styles - - - Naming rules - - - Symbol specifications - Adding imports will bring an extension method into scope with the same name as '{0}' diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf index f6bb2a8cb83ce..545406a9f0afe 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.cs.xlf @@ -57,16 +57,6 @@ Odsazení a mezery - - Naming rules - Pravidla pojmenování - - - - Naming styles - Styly pojmenování - - New line preferences Předvolby nových řádků @@ -1282,11 +1272,6 @@ Pozitivní kontrolní výrazy zpětného vyhledávání s nulovou délkou se obv Přidávání projektů se nepodporuje. - - Symbol specifications - Specifikace symbolů - - Visual Basic files Soubory jazyka Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf index bf5c7ba313ec0..b351ea542e9d5 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf @@ -57,16 +57,6 @@ Einzüge und Abstände - - Naming rules - Benennungsregeln - - - - Naming styles - Benennungsstile - - New line preferences Einstellungen für neue Zeilen @@ -1282,11 +1272,6 @@ Positive Lookbehindassertionen mit Nullbreite werden normalerweise am Anfang reg Das Hinzufügen von Projekten wird nicht unterstützt. - - Symbol specifications - Symbolspezifikationen - - Visual Basic files Visual Basic-Dateien diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf index c4d3a274c0ee3..d0b102d861427 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf @@ -57,16 +57,6 @@ Sangría y espaciado - - Naming rules - Reglas de nomenclatura - - - - Naming styles - Estilos de nomenclatura - - New line preferences Nuevas preferencias de línea @@ -1282,11 +1272,6 @@ Las aserciones de búsqueda retrasada (lookbehind) positivas de ancho cero se us No se admite la adición de proyectos. - - Symbol specifications - Especificaciones de símbolos - - Visual Basic files Archivos de Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf index 5d2066eb88a8b..711a07c960d1f 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.xlf @@ -57,16 +57,6 @@ Indentation et espacement - - Naming rules - Règles de nommage - - - - Naming styles - Styles de nommage - - New line preferences Préférences de nouvelle ligne @@ -1282,11 +1272,6 @@ Les assertions arrière positives de largeur nulle sont généralement utilisée L'ajout de projets n'est pas pris en charge. - - Symbol specifications - Spécifications de symboles - - Visual Basic files Fichiers Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf index 552a7e9cd85a5..7084d34f4a263 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf @@ -57,16 +57,6 @@ Rientro e spaziatura - - Naming rules - Regole di denominazione - - - - Naming styles - Stili di denominazione - - New line preferences Preferenze per nuova riga @@ -1282,11 +1272,6 @@ Le asserzioni lookbehind positive di larghezza zero vengono usate in genere all' L'aggiunta di progetti non è supportata. - - Symbol specifications - Specifiche dei simboli - - Visual Basic files File Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf index cb3822698f0e9..c326bb5bc5719 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ja.xlf @@ -57,16 +57,6 @@ インデントと間隔 - - Naming rules - 名前付けルール - - - - Naming styles - 命名スタイル - - New line preferences 改行設定 @@ -1282,11 +1272,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of プロジェクトの追加はサポートされていません。 - - Symbol specifications - 記号の仕様 - - Visual Basic files Visual Basic ファイル diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf index 55f693ef747ff..a1e6cfb704c58 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf @@ -57,16 +57,6 @@ 들여쓰기 및 간격 - - Naming rules - 명명 규칙 - - - - Naming styles - 명명 스타일 - - New line preferences 새 줄 기본 설정 @@ -1282,11 +1272,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of 프로젝트 추가가 지원되지 않습니다. - - Symbol specifications - 기호 사양 - - Visual Basic files Visual Basic 파일 diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf index 6d2f943769605..a8d44be1fd321 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pl.xlf @@ -57,16 +57,6 @@ Wcięcia i odstępy - - Naming rules - Reguły nazewnictwa - - - - Naming styles - Style nazewnictwa - - New line preferences Preferencje nowego wiersza @@ -1282,11 +1272,6 @@ Pozytywne asercje wsteczne o zerowej szerokości są zwykle używane na początk Dodawanie projektów nie jest obsługiwane. - - Symbol specifications - Specyfikacje symboli - - Visual Basic files Pliki języka Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf index 07687112c1a34..f4f39d0e19e27 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf @@ -57,16 +57,6 @@ Recuo e espaçamento - - Naming rules - Regras de nomenclatura - - - - Naming styles - Estilos de nomenclatura - - New line preferences Preferências de nova linha @@ -1282,11 +1272,6 @@ As declarações de lookbehind positivas de largura zero normalmente são usadas Não há suporte para adicionar projetos. - - Symbol specifications - Especificações de símbolo - - Visual Basic files Arquivos do Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf index a4885083f7e65..21389bb4ee526 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf @@ -57,16 +57,6 @@ Отступы и интервалы - - Naming rules - Правила именования - - - - Naming styles - Стили именования - - New line preferences Предпочтения для новых строк @@ -1282,11 +1272,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of Добавление проектов не поддерживается. - - Symbol specifications - Спецификации символов - - Visual Basic files Файлы Visual Basic diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf index 2314840c38405..a7e722dd44306 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.tr.xlf @@ -57,16 +57,6 @@ Girinti ve aralığı - - Naming rules - Adlandırma kuralları - - - - Naming styles - Adlandırma stilleri - - New line preferences Yeni satır tercihleri @@ -1282,11 +1272,6 @@ Sıfır genişlikli pozitif geri yönlü onaylamalar genellikle normal ifadeleri Projelerin eklenmesi desteklenmiyor. - - Symbol specifications - Sembol belirtimleri - - Visual Basic files Visual Basic dosyaları diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf index 3773db4e16464..563406db21e38 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf @@ -57,16 +57,6 @@ 缩进和间距 - - Naming rules - 命名规则 - - - - Naming styles - 命名样式 - - New line preferences 新行首选项 @@ -1282,11 +1272,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of 不支持添加项目。 - - Symbol specifications - 符号规范 - - Visual Basic files visual basic 文件 diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf index a3c937cd6fa43..3699676809a2b 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hant.xlf @@ -57,16 +57,6 @@ 縮排和間距 - - Naming rules - 命名規則 - - - - Naming styles - 命名樣式 - - New line preferences 新行喜好設定 @@ -1282,11 +1272,6 @@ Zero-width positive lookbehind assertions are typically used at the beginning of 不支援新增專案。 - - Symbol specifications - 符號規格 - - Visual Basic files Visual Basic 檔案 diff --git a/src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs b/src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs index ba6743fc05171..bd5a54f943c3e 100644 --- a/src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs +++ b/src/Workspaces/CoreTest/CodeStyle/EditorConfigCodeStyleParserTests.cs @@ -58,8 +58,6 @@ public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, Re break; } - var codeStyleOption = new CodeStyleOption(value: isEnabled, notification: notificationOption); - CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, out var result); Assert.True(result.Value == isEnabled, $"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}"); @@ -80,13 +78,13 @@ public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, Re [InlineData("omit_if_default : error", (int)AccessibilityModifiersRequired.OmitIfDefault, ReportDiagnostic.Error)] public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity) { - var storageLocation = CodeStyleOptions.RequireAccessibilityModifiers.StorageLocations - .OfType>>() + var storageLocation = CodeStyleOptions2.RequireAccessibilityModifiers.StorageLocations + .OfType>>() .Single(); var allRawConventions = new Dictionary { { storageLocation.KeyName, args } }; - Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption), out var parsedCodeStyleOption)); - var codeStyleOption = (CodeStyleOption)parsedCodeStyleOption!; + Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption2), out var parsedCodeStyleOption)); + var codeStyleOption = (CodeStyleOption2)parsedCodeStyleOption!; Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value); Assert.Equal(severity, codeStyleOption.Notification.Severity); } diff --git a/src/Workspaces/CoreTest/Execution/SnapshotSerializationTests.cs b/src/Workspaces/CoreTest/Execution/SnapshotSerializationTests.cs index e69fcf534b304..a0b0d68d10289 100644 --- a/src/Workspaces/CoreTest/Execution/SnapshotSerializationTests.cs +++ b/src/Workspaces/CoreTest/Execution/SnapshotSerializationTests.cs @@ -319,31 +319,31 @@ public async Task OptionSet_Serialization_CustomValue() { var workspace = new AdhocWorkspace(); - var newQualifyFieldAccessValue = new CodeStyleOption(false, NotificationOption.Error); - var newQualifyMethodAccessValue = new CodeStyleOption(true, NotificationOption.Warning); - var newVarWhenTypeIsApparentValue = new CodeStyleOption(false, NotificationOption.Suggestion); - var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption(true, NotificationOption.Silent); + var newQualifyFieldAccessValue = new CodeStyleOption2(false, NotificationOption2.Error); + var newQualifyMethodAccessValue = new CodeStyleOption2(true, NotificationOption2.Warning); + var newVarWhenTypeIsApparentValue = new CodeStyleOption2(false, NotificationOption2.Suggestion); + var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption2(true, NotificationOption2.Silent); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options - .WithChangedOption(CodeStyleOptions.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue) - .WithChangedOption(CodeStyleOptions.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue) + .WithChangedOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue) + .WithChangedOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue) .WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, newVarWhenTypeIsApparentValue) - .WithChangedOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue))); + .WithChangedOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue))); await VerifyOptionSetsAsync(workspace, VerifyOptions).ConfigureAwait(false); void VerifyOptions(OptionSet options) { - var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions.QualifyFieldAccess, LanguageNames.CSharp); + var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp); Assert.Equal(newQualifyFieldAccessValue, actualQualifyFieldAccessValue); - var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions.QualifyMethodAccess, LanguageNames.VisualBasic); + var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic); Assert.Equal(newQualifyMethodAccessValue, actualQualifyMethodAccessValue); var actualVarWhenTypeIsApparentValue = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent); Assert.Equal(newVarWhenTypeIsApparentValue, actualVarWhenTypeIsApparentValue); - var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic); + var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic); Assert.Equal(newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue, actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue); } } diff --git a/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs b/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs index f738a9775154f..1dec0d4b576c5 100644 --- a/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.cs @@ -5,6 +5,7 @@ #nullable enable using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; @@ -178,13 +179,13 @@ public void TestChangedOptions() // Apply a non-serializable changed option to the option service // and verify that serializable options snapshot does not contain this changed option TestChangedOptionsCore( - new PerLanguageOption("Test Feature", "Test Name", defaultValue: true), + new PerLanguageOption2("Test Feature", "Test Name", defaultValue: true), optionProvider: new TestOptionService.TestOptionsProvider(), isSerializable: false); return; - static void TestChangedOptionsCore(PerLanguageOption option, IOptionProvider optionProvider, bool isSerializable) + static void TestChangedOptionsCore(PerLanguageOption2 option, IOptionProvider optionProvider, bool isSerializable) { var optionService = TestOptionService.GetService(optionProvider); var optionSet = optionService.GetOptions(); @@ -212,5 +213,128 @@ static void TestChangedOptionsCore(PerLanguageOption option, IOptionProvid } } } + + [Fact] + public void TestPerLanguageCodeStyleOptions() + { + PerLanguageOption2> perLanguageOption2 = new PerLanguageOption2>("test", "test", new CodeStyleOption2(false, NotificationOption2.Warning)); + PerLanguageOption> perLanguageOption = perLanguageOption2.ToPublicOption(); + CodeStyleOption2 newValueCodeStyleOption2 = new CodeStyleOption2(!perLanguageOption2.DefaultValue.Value, perLanguageOption2.DefaultValue.Notification); + CodeStyleOption newValueCodeStyleOption = (CodeStyleOption)newValueCodeStyleOption2!; + + // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. + + // 1. { PerLanguageOption, CodeStyleOption } + TestCodeStyleOptionsCommon(perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); + + // 2. { PerLanguageOption2, CodeStyleOption } + TestCodeStyleOptionsCommon(perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption); + + // 3. { PerLanguageOption, CodeStyleOption2 } + TestCodeStyleOptionsCommon(perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption2); + + // 4. { PerLanguageOption2, CodeStyleOption2 } + TestCodeStyleOptionsCommon(perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); + + var optionService = TestOptionService.GetService(); + var originalOptionSet = optionService.GetOptions(); + + // Test "PerLanguageOption" and "PerLanguageOption2" overloads for OptionSet and OptionService. + + // 1. Verify default value. + Assert.Equal(perLanguageOption.DefaultValue, originalOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); + Assert.Equal(perLanguageOption2.DefaultValue, originalOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); + + // 2. OptionSet validations. + var newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); + Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); + Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); + + newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); + Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); + Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); + + // 3. IOptionService validation + optionService.SetOptions(newOptionSet); + Assert.Equal(newValueCodeStyleOption, optionService.GetOption(perLanguageOption, LanguageNames.CSharp)); + Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(perLanguageOption2, LanguageNames.CSharp)); + } + + [Fact] + public void TestLanguageSpecificCodeStyleOptions() + { + Option2> option2 = new Option2>("test", "test", new CodeStyleOption2(false, NotificationOption2.Warning)); + Option> option = option2.ToPublicOption(); + CodeStyleOption2 newValueCodeStyleOption2 = new CodeStyleOption2(!option2.DefaultValue.Value, option2.DefaultValue.Notification); + CodeStyleOption newValueCodeStyleOption = (CodeStyleOption)newValueCodeStyleOption2!; + + // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. + + // 1. { Option, CodeStyleOption } + TestCodeStyleOptionsCommon(option, language: null, newValueCodeStyleOption); + + // 2. { Option2, CodeStyleOption } + TestCodeStyleOptionsCommon(option2, language: null, newValueCodeStyleOption); + + // 3. { Option, CodeStyleOption2 } + TestCodeStyleOptionsCommon(option, language: null, newValueCodeStyleOption2); + + // 4. { Option2, CodeStyleOption2 } + TestCodeStyleOptionsCommon(option2, language: null, newValueCodeStyleOption2); + + var optionService = TestOptionService.GetService(); + var originalOptionSet = optionService.GetOptions(); + + // Test "Option" and "Option2" overloads for OptionSet and OptionService. + + // 1. Verify default value. + Assert.Equal(option.DefaultValue, originalOptionSet.GetOption(option)); + Assert.Equal(option2.DefaultValue, originalOptionSet.GetOption(option2)); + + // 2. OptionSet validations. + var newOptionSet = originalOptionSet.WithChangedOption(option, newValueCodeStyleOption); + Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); + Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); + + newOptionSet = originalOptionSet.WithChangedOption(option2, newValueCodeStyleOption2); + Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); + Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); + + // 3. IOptionService validation + optionService.SetOptions(newOptionSet); + Assert.Equal(newValueCodeStyleOption, optionService.GetOption(option)); + Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(option2)); + } + + private static void TestCodeStyleOptionsCommon(IOption2 option, string? language, TCodeStyleOption newValue) + where TCodeStyleOption : ICodeStyleOption + { + var optionService = TestOptionService.GetService(); + var originalOptionSet = optionService.GetOptions(); + + // Test matrix using different OptionKey and OptionKey2 get/set operations. + var optionKey = new OptionKey(option, language); + var optionKey2 = new OptionKey2(option, language); + + // 1. WithChangedOption(OptionKey), GetOption(OptionKey) + var newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); + Assert.Equal(newValue, newOptionSet.GetOption(optionKey)); + + // 2. WithChangedOption(OptionKey), GetOption(OptionKey2) + newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); + Assert.Equal(newValue, newOptionSet.GetOption(optionKey2)); + + // 3. WithChangedOption(OptionKey2), GetOption(OptionKey) + newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); + Assert.Equal(newValue, newOptionSet.GetOption(optionKey)); + + // 4. WithChangedOption(OptionKey2), GetOption(OptionKey2) + newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); + Assert.Equal(newValue, newOptionSet.GetOption(optionKey2)); + + // 5. IOptionService.GetOption(OptionKey) + optionService.SetOptions(newOptionSet); + Assert.Equal(newValue, optionService.GetOption(optionKey)); + } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems index 469bccf056f8c..b4de4d01ce7cd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CSharpCompilerExtensions.projitems @@ -45,8 +45,8 @@ - - + + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs index c4ee14a184675..4d4df63aaa7cd 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs @@ -7,226 +7,217 @@ using System.Linq; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle -#else namespace Microsoft.CodeAnalysis.CSharp.CodeStyle -#endif { internal static partial class CSharpCodeStyleOptions { - private static readonly CodeStyleOption s_trueWithSuggestionEnforcement = new CodeStyleOption(value: true, notification: NotificationOption.Suggestion); + private static readonly CodeStyleOption2 s_trueWithSuggestionEnforcement = new CodeStyleOption2(value: true, notification: NotificationOption2.Suggestion); - private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); + private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); - internal static ImmutableArray AllOptions { get; } + internal static ImmutableArray AllOptions { get; } - private static Option CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + private static Option2 CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) => CodeStyleHelpers.CreateOption(group, nameof(CSharpCodeStyleOptions), name, defaultValue, s_allOptionsBuilder, storageLocations); - public static readonly Option> VarForBuiltInTypes = CreateOption( + public static readonly Option2> VarForBuiltInTypes = CreateOption( CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarForBuiltInTypes), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[] { + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_var_for_built_in_types"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.UseImplicitTypeForIntrinsicTypes")}); - public static readonly Option> VarWhenTypeIsApparent = CreateOption( + public static readonly Option2> VarWhenTypeIsApparent = CreateOption( CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarWhenTypeIsApparent), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[] { + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_var_when_type_is_apparent"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.UseImplicitTypeWhereApparent")}); - public static readonly Option> VarElsewhere = CreateOption( + public static readonly Option2> VarElsewhere = CreateOption( CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarElsewhere), - defaultValue: CodeStyleOption.Default, - storageLocations: new OptionStorageLocation[] { + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_var_elsewhere"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.UseImplicitTypeWherePossible")}); - public static readonly Option> PreferConditionalDelegateCall = CreateOption( + public static readonly Option2> PreferConditionalDelegateCall = CreateOption( CSharpCodeStyleOptionGroups.NullCheckingPreferences, nameof(PreferConditionalDelegateCall), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_conditional_delegate_call"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.PreferConditionalDelegateCall")}); - public static readonly Option> PreferSwitchExpression = CreateOption( + public static readonly Option2> PreferSwitchExpression = CreateOption( CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferSwitchExpression), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_prefer_switch_expression"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferSwitchExpression)}")}); - public static readonly Option> PreferPatternMatchingOverAsWithNullCheck = CreateOption( + public static readonly Option2> PreferPatternMatchingOverAsWithNullCheck = CreateOption( CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverAsWithNullCheck), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_pattern_matching_over_as_with_null_check"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverAsWithNullCheck)}")}); - public static readonly Option> PreferPatternMatchingOverIsWithCastCheck = CreateOption( + public static readonly Option2> PreferPatternMatchingOverIsWithCastCheck = CreateOption( CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverIsWithCastCheck), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_pattern_matching_over_is_with_cast_check"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverIsWithCastCheck)}")}); - public static readonly Option> PreferThrowExpression = CreateOption( + public static readonly Option2> PreferThrowExpression = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferThrowExpression), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ + storageLocations: new OptionStorageLocation2[]{ EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_throw_expression"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.PreferThrowExpression")}); - public static readonly Option> PreferInlinedVariableDeclaration = CreateOption( + public static readonly Option2> PreferInlinedVariableDeclaration = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInlinedVariableDeclaration), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[]{ + storageLocations: new OptionStorageLocation2[]{ EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_inlined_variable_declaration"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.PreferInlinedVariableDeclaration") }); - public static readonly Option> PreferDeconstructedVariableDeclaration = CreateOption( + public static readonly Option2> PreferDeconstructedVariableDeclaration = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferDeconstructedVariableDeclaration), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_deconstructed_variable_declaration"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferDeconstructedVariableDeclaration)}")}); - public static readonly Option> PreferIndexOperator = CreateOption( + public static readonly Option2> PreferIndexOperator = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIndexOperator), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_prefer_index_operator"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.PreferIndexOperator")}); - public static readonly Option> PreferRangeOperator = CreateOption( + public static readonly Option2> PreferRangeOperator = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferRangeOperator), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_prefer_range_operator"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.PreferRangeOperator")}); - public static readonly CodeStyleOption NeverWithSilentEnforcement = - new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.Silent); + public static readonly CodeStyleOption2 NeverWithSilentEnforcement = + new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.Silent); - public static readonly CodeStyleOption NeverWithSuggestionEnforcement = - new CodeStyleOption(ExpressionBodyPreference.Never, NotificationOption.Suggestion); + public static readonly CodeStyleOption2 NeverWithSuggestionEnforcement = + new CodeStyleOption2(ExpressionBodyPreference.Never, NotificationOption2.Suggestion); - public static readonly CodeStyleOption WhenPossibleWithSilentEnforcement = - new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.Silent); + public static readonly CodeStyleOption2 WhenPossibleWithSilentEnforcement = + new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent); - public static readonly CodeStyleOption WhenPossibleWithSuggestionEnforcement = - new CodeStyleOption(ExpressionBodyPreference.WhenPossible, NotificationOption.Suggestion); + public static readonly CodeStyleOption2 WhenPossibleWithSuggestionEnforcement = + new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, NotificationOption2.Suggestion); - public static readonly CodeStyleOption WhenOnSingleLineWithSilentEnforcement = - new CodeStyleOption(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption.Silent); + public static readonly CodeStyleOption2 WhenOnSingleLineWithSilentEnforcement = + new CodeStyleOption2(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent); - public static readonly CodeStyleOption UseBracesWithSilentEnforcement = - new CodeStyleOption(PreferBracesPreference.Always, NotificationOption.Silent); + public static readonly CodeStyleOption2 UseBracesWithSilentEnforcement = + new CodeStyleOption2(PreferBracesPreference.Always, NotificationOption2.Silent); - public static readonly Option> PreferExpressionBodiedConstructors = CreateOption( + public static readonly Option2> PreferExpressionBodiedConstructors = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedConstructors), defaultValue: NeverWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_constructors", s => ParseExpressionBodyPreference(s, NeverWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedConstructors)}")}); - public static readonly Option> PreferExpressionBodiedMethods = CreateOption( + public static readonly Option2> PreferExpressionBodiedMethods = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedMethods), defaultValue: NeverWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_methods", s => ParseExpressionBodyPreference(s, NeverWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedMethods)}")}); - public static readonly Option> PreferExpressionBodiedOperators = CreateOption( + public static readonly Option2> PreferExpressionBodiedOperators = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedOperators), defaultValue: NeverWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_operators", s => ParseExpressionBodyPreference(s, NeverWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedOperators)}")}); - public static readonly Option> PreferExpressionBodiedProperties = CreateOption( + public static readonly Option2> PreferExpressionBodiedProperties = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedProperties), defaultValue: WhenPossibleWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_properties", s => ParseExpressionBodyPreference(s, WhenPossibleWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedProperties)}")}); - public static readonly Option> PreferExpressionBodiedIndexers = CreateOption( + public static readonly Option2> PreferExpressionBodiedIndexers = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedIndexers), defaultValue: WhenPossibleWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_indexers", s => ParseExpressionBodyPreference(s, WhenPossibleWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedIndexers)}")}); - public static readonly Option> PreferExpressionBodiedAccessors = CreateOption( + public static readonly Option2> PreferExpressionBodiedAccessors = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedAccessors), defaultValue: WhenPossibleWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_accessors", s => ParseExpressionBodyPreference(s, WhenPossibleWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedAccessors)}")}); - public static readonly Option> PreferExpressionBodiedLambdas = CreateOption( + public static readonly Option2> PreferExpressionBodiedLambdas = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedLambdas), defaultValue: WhenPossibleWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_lambdas", s => ParseExpressionBodyPreference(s, WhenPossibleWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedLambdas)}")}); - public static readonly Option> PreferExpressionBodiedLocalFunctions = CreateOption( + public static readonly Option2> PreferExpressionBodiedLocalFunctions = CreateOption( CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, nameof(PreferExpressionBodiedLocalFunctions), defaultValue: NeverWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_style_expression_bodied_local_functions", s => ParseExpressionBodyPreference(s, NeverWithSilentEnforcement), GetExpressionBodyPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferExpressionBodiedLocalFunctions)}")}); - public static readonly Option> PreferBraces = CreateOption( + public static readonly Option2> PreferBraces = CreateOption( CSharpCodeStyleOptionGroups.CodeBlockPreferences, nameof(PreferBraces), defaultValue: UseBracesWithSilentEnforcement, - storageLocations: new OptionStorageLocation[] { - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[] { + new EditorConfigStorageLocation>( "csharp_prefer_braces", s => ParsePreferBracesPreference(s, UseBracesWithSilentEnforcement), GetPreferBracesPreferenceEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferBraces)}")}); - public static readonly Option> PreferSimpleDefaultExpression = CreateOption( + public static readonly Option2> PreferSimpleDefaultExpression = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimpleDefaultExpression), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_prefer_simple_default_expression"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferSimpleDefaultExpression)}")}); @@ -243,63 +234,63 @@ private static Option CreateOption(OptionGroup group, string name, T defau SyntaxKind.AsyncKeyword }; - public static readonly Option> PreferredModifierOrder = CreateOption( + public static readonly Option2> PreferredModifierOrder = CreateOption( CSharpCodeStyleOptionGroups.Modifier, nameof(PreferredModifierOrder), - defaultValue: new CodeStyleOption(string.Join(",", s_preferredModifierOrderDefault.Select(SyntaxFacts.GetText)), NotificationOption.Silent), - storageLocations: new OptionStorageLocation[] { + defaultValue: new CodeStyleOption2(string.Join(",", s_preferredModifierOrderDefault.Select(SyntaxFacts.GetText)), NotificationOption2.Silent), + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForStringCodeStyleOption("csharp_preferred_modifier_order"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferredModifierOrder)}")}); - public static readonly Option> PreferStaticLocalFunction = CreateOption( + public static readonly Option2> PreferStaticLocalFunction = CreateOption( CSharpCodeStyleOptionGroups.Modifier, nameof(PreferStaticLocalFunction), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_prefer_static_local_function"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferStaticLocalFunction)}")}); - public static readonly Option> PreferSimpleUsingStatement = CreateOption( + public static readonly Option2> PreferSimpleUsingStatement = CreateOption( CSharpCodeStyleOptionGroups.CodeBlockPreferences, nameof(PreferSimpleUsingStatement), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_prefer_simple_using_statement"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferSimpleUsingStatement)}")}); - public static readonly Option> PreferLocalOverAnonymousFunction = CreateOption( + public static readonly Option2> PreferLocalOverAnonymousFunction = CreateOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferLocalOverAnonymousFunction), defaultValue: s_trueWithSuggestionEnforcement, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_pattern_local_over_anonymous_function"), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferLocalOverAnonymousFunction)}")}); - public static readonly CodeStyleOption PreferOutsidePlacementWithSilentEnforcement = - new CodeStyleOption(AddImportPlacement.OutsideNamespace, NotificationOption.Silent); + public static readonly CodeStyleOption2 PreferOutsidePlacementWithSilentEnforcement = + new CodeStyleOption2(AddImportPlacement.OutsideNamespace, NotificationOption2.Silent); - public static readonly Option> PreferredUsingDirectivePlacement = CreateOption( + public static readonly Option2> PreferredUsingDirectivePlacement = CreateOption( CSharpCodeStyleOptionGroups.UsingDirectivePreferences, nameof(PreferredUsingDirectivePlacement), defaultValue: PreferOutsidePlacementWithSilentEnforcement, - storageLocations: new OptionStorageLocation[]{ - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[]{ + new EditorConfigStorageLocation>( "csharp_using_directive_placement", s => ParseUsingDirectivesPlacement(s, PreferOutsidePlacementWithSilentEnforcement), GetUsingDirectivesPlacementEditorConfigString), new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(PreferredUsingDirectivePlacement)}") }); - internal static readonly Option> UnusedValueExpressionStatement = + internal static readonly Option2> UnusedValueExpressionStatement = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, feature: nameof(CSharpCodeStyleOptions), name: nameof(UnusedValueExpressionStatement), editorConfigName: "csharp_style_unused_value_expression_statement_preference", - defaultValue: new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.Silent), + defaultValue: new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent), s_allOptionsBuilder); - internal static readonly Option> UnusedValueAssignment = + internal static readonly Option2> UnusedValueAssignment = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, feature: nameof(CSharpCodeStyleOptions), name: nameof(UnusedValueAssignment), editorConfigName: "csharp_style_unused_value_assignment_preference", - defaultValue: new CodeStyleOption(UnusedValuePreference.DiscardVariable, NotificationOption.Suggestion), + defaultValue: new CodeStyleOption2(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion), s_allOptionsBuilder); static CSharpCodeStyleOptions() @@ -309,7 +300,7 @@ static CSharpCodeStyleOptions() AllOptions = s_allOptionsBuilder.ToImmutable(); } - public static IEnumerable>> GetCodeStyleOptions() + public static IEnumerable>> GetCodeStyleOptions() { yield return VarForBuiltInTypes; yield return VarWhenTypeIsApparent; @@ -327,7 +318,7 @@ public static IEnumerable>> GetCodeStyleOptions() yield return PreferRangeOperator; } - public static IEnumerable>> GetExpressionBodyOptions() + public static IEnumerable>> GetExpressionBodyOptions() { yield return PreferExpressionBodiedConstructors; yield return PreferExpressionBodiedMethods; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions_Parsing.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions_Parsing.cs index 6e4be16a94110..f03ad7aff200a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions_Parsing.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions_Parsing.cs @@ -7,22 +7,12 @@ using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; -#endif - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle -#else namespace Microsoft.CodeAnalysis.CSharp.CodeStyle -#endif { internal static partial class CSharpCodeStyleOptions { - public static CodeStyleOption ParseExpressionBodyPreference( - string optionString, CodeStyleOption @default) + public static CodeStyleOption2 ParseExpressionBodyPreference( + string optionString, CodeStyleOption2 @default) { // optionString must be similar to true:error or when_on_single_line:suggestion. if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification(optionString, @@ -34,13 +24,13 @@ public static CodeStyleOption ParseExpressionBodyPrefe if (bool.TryParse(value, out var boolValue)) { return boolValue - ? new CodeStyleOption(ExpressionBodyPreference.WhenPossible, notificationOpt) - : new CodeStyleOption(ExpressionBodyPreference.Never, notificationOpt); + ? new CodeStyleOption2(ExpressionBodyPreference.WhenPossible, notificationOpt) + : new CodeStyleOption2(ExpressionBodyPreference.Never, notificationOpt); } if (value == "when_on_single_line") { - return new CodeStyleOption(ExpressionBodyPreference.WhenOnSingleLine, notificationOpt); + return new CodeStyleOption2(ExpressionBodyPreference.WhenOnSingleLine, notificationOpt); } } } @@ -48,7 +38,7 @@ public static CodeStyleOption ParseExpressionBodyPrefe return @default; } - private static string GetExpressionBodyPreferenceEditorConfigString(CodeStyleOption value) + private static string GetExpressionBodyPreferenceEditorConfigString(CodeStyleOption2 value) { var notificationString = value.Notification.ToEditorConfigString(); return value.Value switch @@ -60,8 +50,8 @@ private static string GetExpressionBodyPreferenceEditorConfigString(CodeStyleOpt }; } - public static CodeStyleOption ParseUsingDirectivesPlacement( - string optionString, CodeStyleOption @default) + public static CodeStyleOption2 ParseUsingDirectivesPlacement( + string optionString, CodeStyleOption2 @default) { // optionString must be similar to outside_namespace:error or inside_namespace:suggestion. if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( @@ -72,8 +62,8 @@ public static CodeStyleOption ParseUsingDirectivesPlacement( { return value switch { - "inside_namespace" => new CodeStyleOption(AddImportPlacement.InsideNamespace, notificationOpt), - "outside_namespace" => new CodeStyleOption(AddImportPlacement.OutsideNamespace, notificationOpt), + "inside_namespace" => new CodeStyleOption2(AddImportPlacement.InsideNamespace, notificationOpt), + "outside_namespace" => new CodeStyleOption2(AddImportPlacement.OutsideNamespace, notificationOpt), _ => throw new NotSupportedException(), }; } @@ -82,7 +72,7 @@ public static CodeStyleOption ParseUsingDirectivesPlacement( return @default; } - public static string GetUsingDirectivesPlacementEditorConfigString(CodeStyleOption value) + public static string GetUsingDirectivesPlacementEditorConfigString(CodeStyleOption2 value) { var notificationString = value.Notification.ToEditorConfigString(); return value.Value switch @@ -93,9 +83,9 @@ public static string GetUsingDirectivesPlacementEditorConfigString(CodeStyleOpti }; } - private static CodeStyleOption ParsePreferBracesPreference( + private static CodeStyleOption2 ParsePreferBracesPreference( string optionString, - CodeStyleOption defaultValue) + CodeStyleOption2 defaultValue) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, @@ -107,21 +97,21 @@ private static CodeStyleOption ParsePreferBracesPreferen if (bool.TryParse(value, out var boolValue)) { return boolValue - ? new CodeStyleOption(PreferBracesPreference.Always, notificationOption) - : new CodeStyleOption(PreferBracesPreference.None, notificationOption); + ? new CodeStyleOption2(PreferBracesPreference.Always, notificationOption) + : new CodeStyleOption2(PreferBracesPreference.None, notificationOption); } } if (value == "when_multiline") { - return new CodeStyleOption(PreferBracesPreference.WhenMultiline, notificationOption); + return new CodeStyleOption2(PreferBracesPreference.WhenMultiline, notificationOption); } } return defaultValue; } - private static string GetPreferBracesPreferenceEditorConfigString(CodeStyleOption value) + private static string GetPreferBracesPreferenceEditorConfigString(CodeStyleOption2 value) { var notificationString = value.Notification.ToEditorConfigString(); return value.Value switch diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs index 583ba9dd14624..972bfff8189e2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/PreferBracesPreference.cs @@ -3,18 +3,9 @@ // See the LICENSE file in the project root for more information. using System.Xml.Linq; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -#else using Microsoft.CodeAnalysis.CSharp.CodeStyle; -#endif -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { /// /// Defines the known values for . @@ -26,7 +17,7 @@ internal enum PreferBracesPreference /// /// /// The value 0 is important for serialization compatibility in - /// . Prior to the use of this enum, the serialized value + /// . Prior to the use of this enum, the serialized value /// was the value . /// None = 0, @@ -43,7 +34,7 @@ internal enum PreferBracesPreference /// /// /// The value 1 is important for serialization compatibility in - /// . Prior to the use of this enum, the serialized value + /// . Prior to the use of this enum, the serialized value /// was the value . /// Always = 1, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs index 57cdafb1d5abf..97f3ddb36372e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/TypeStyleHelper.cs @@ -12,14 +12,10 @@ #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else -using Microsoft.CodeAnalysis.Options; +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle.TypeStyle -#else namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle -#endif { internal static class TypeStyleHelper { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/UseVarPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/UseVarPreference.cs index 37f554f2a8392..876d1abe528f8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/UseVarPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/UseVarPreference.cs @@ -4,11 +4,7 @@ using System; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle.TypeStyle -#else namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle -#endif { [Flags] internal enum UseVarPreference diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs index 31bce5869f415..ea036a99465e2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs @@ -3,17 +3,12 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.CodeStyle; -#endif - namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class BlockSyntaxExtensions diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.Parsers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs similarity index 99% rename from src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.Parsers.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs index 658010f859bef..947a3aec1cc35 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.Parsers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.Parsers.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Formatting { - public static partial class CSharpFormattingOptions + internal static partial class CSharpFormattingOptions2 { internal static bool DetermineIfSpaceOptionIsSet(string value, SpacingWithinParenthesesOption parenthesesSpacingOption) => (from v in value.Split(',').Select(v => v.Trim()) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs similarity index 72% rename from src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs index 74c865acca872..16c8dfdb4e3b3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpFormattingOptions2.cs @@ -5,26 +5,24 @@ using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; +using Microsoft.CodeAnalysis.Options; #if CODE_STYLE using CSharpWorkspaceResources = Microsoft.CodeAnalysis.CSharp.CSharpCodeStyleResources; using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { - public static partial class CSharpFormattingOptions + internal static partial class CSharpFormattingOptions2 { - private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); + private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); // Maps to store mapping between special option kinds and the corresponding options. - private static readonly ImmutableDictionary, SpacingWithinParenthesesOption>.Builder s_spacingWithinParenthesisOptionsMapBuilder - = ImmutableDictionary.CreateBuilder, SpacingWithinParenthesesOption>(); - private static readonly ImmutableDictionary, NewLineOption>.Builder s_newLineOptionsMapBuilder = - ImmutableDictionary.CreateBuilder, NewLineOption>(); + private static readonly ImmutableDictionary, SpacingWithinParenthesesOption>.Builder s_spacingWithinParenthesisOptionsMapBuilder + = ImmutableDictionary.CreateBuilder, SpacingWithinParenthesesOption>(); + private static readonly ImmutableDictionary, NewLineOption>.Builder s_newLineOptionsMapBuilder = + ImmutableDictionary.CreateBuilder, NewLineOption>(); // Maps to store mapping between special option kinds and the corresponding editor config string representations. #region Editor Config maps @@ -72,23 +70,23 @@ private static readonly ImmutableDictionary, SpacingWithinParenthes }); #endregion - internal static ImmutableArray AllOptions { get; } - private static ImmutableDictionary, SpacingWithinParenthesesOption> SpacingWithinParenthesisOptionsMap { get; } - private static ImmutableDictionary, NewLineOption> NewLineOptionsMap { get; } + internal static ImmutableArray AllOptions { get; } + private static ImmutableDictionary, SpacingWithinParenthesesOption> SpacingWithinParenthesisOptionsMap { get; } + private static ImmutableDictionary, NewLineOption> NewLineOptionsMap { get; } - private static Option CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + private static Option2 CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { - var option = new Option(nameof(CSharpFormattingOptions), group, name, defaultValue, storageLocations); + var option = new Option2("CSharpFormattingOptions", group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } - private static Option CreateSpaceWithinParenthesesOption(SpacingWithinParenthesesOption parenthesesOption, string name) + private static Option2 CreateSpaceWithinParenthesesOption(SpacingWithinParenthesesOption parenthesesOption, string name) { var option = CreateOption( CSharpFormattingOptionGroups.Spacing, name, defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { new EditorConfigStorageLocation( "csharp_space_between_parentheses", s => DetermineIfSpaceOptionIsSet(s, parenthesesOption), @@ -101,12 +99,12 @@ private static Option CreateSpaceWithinParenthesesOption(SpacingWithinPare return option; } - private static Option CreateNewLineForBracesOption(NewLineOption newLineOption, string name) + private static Option2 CreateNewLineForBracesOption(NewLineOption newLineOption, string name) { var option = CreateOption( CSharpFormattingOptionGroups.NewLine, name, defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { new EditorConfigStorageLocation( "csharp_new_line_before_open_brace", value => DetermineIfNewLineOptionIsSet(value, newLineOption), @@ -119,297 +117,297 @@ private static Option CreateNewLineForBracesOption(NewLineOption newLineOp return option; } - public static Option SpacingAfterMethodDeclarationName { get; } = CreateOption( + public static Option2 SpacingAfterMethodDeclarationName { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpacingAfterMethodDeclarationName), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_declaration_name_and_open_parenthesis"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpacingAfterMethodDeclarationName")}); - public static Option SpaceWithinMethodDeclarationParenthesis { get; } = CreateOption( + public static Option2 SpaceWithinMethodDeclarationParenthesis { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceWithinMethodDeclarationParenthesis), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_declaration_parameter_list_parentheses"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceWithinMethodDeclarationParenthesis")}); - public static Option SpaceBetweenEmptyMethodDeclarationParentheses { get; } = CreateOption( + public static Option2 SpaceBetweenEmptyMethodDeclarationParentheses { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBetweenEmptyMethodDeclarationParentheses), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_declaration_empty_parameter_list_parentheses"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBetweenEmptyMethodDeclarationParentheses")}); - public static Option SpaceAfterMethodCallName { get; } = CreateOption( + public static Option2 SpaceAfterMethodCallName { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterMethodCallName), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_call_name_and_opening_parenthesis"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterMethodCallName")}); - public static Option SpaceWithinMethodCallParentheses { get; } = CreateOption( + public static Option2 SpaceWithinMethodCallParentheses { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceWithinMethodCallParentheses), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_call_parameter_list_parentheses"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceWithinMethodCallParentheses")}); - public static Option SpaceBetweenEmptyMethodCallParentheses { get; } = CreateOption( + public static Option2 SpaceBetweenEmptyMethodCallParentheses { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBetweenEmptyMethodCallParentheses), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_method_call_empty_parameter_list_parentheses"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBetweenEmptyMethodCallParentheses")}); - public static Option SpaceAfterControlFlowStatementKeyword { get; } = CreateOption( + public static Option2 SpaceAfterControlFlowStatementKeyword { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterControlFlowStatementKeyword), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_keywords_in_control_flow_statements"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterControlFlowStatementKeyword")}); - public static Option SpaceWithinExpressionParentheses { get; } = CreateSpaceWithinParenthesesOption( + public static Option2 SpaceWithinExpressionParentheses { get; } = CreateSpaceWithinParenthesesOption( SpacingWithinParenthesesOption.Expressions, nameof(SpaceWithinExpressionParentheses)); - public static Option SpaceWithinCastParentheses { get; } = CreateSpaceWithinParenthesesOption( + public static Option2 SpaceWithinCastParentheses { get; } = CreateSpaceWithinParenthesesOption( SpacingWithinParenthesesOption.TypeCasts, nameof(SpaceWithinCastParentheses)); - public static Option SpaceWithinOtherParentheses { get; } = CreateSpaceWithinParenthesesOption( + public static Option2 SpaceWithinOtherParentheses { get; } = CreateSpaceWithinParenthesesOption( SpacingWithinParenthesesOption.ControlFlowStatements, nameof(SpaceWithinOtherParentheses)); - public static Option SpaceAfterCast { get; } = CreateOption( + public static Option2 SpaceAfterCast { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterCast), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_cast"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterCast")}); - public static Option SpacesIgnoreAroundVariableDeclaration { get; } = CreateOption( + public static Option2 SpacesIgnoreAroundVariableDeclaration { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpacesIgnoreAroundVariableDeclaration), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { new EditorConfigStorageLocation( "csharp_space_around_declaration_statements", s => DetermineIfIgnoreSpacesAroundVariableDeclarationIsSet(s), v => v ? "ignore" : "false"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpacesIgnoreAroundVariableDeclaration")}); - public static Option SpaceBeforeOpenSquareBracket { get; } = CreateOption( + public static Option2 SpaceBeforeOpenSquareBracket { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBeforeOpenSquareBracket), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_before_open_square_brackets"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBeforeOpenSquareBracket")}); - public static Option SpaceBetweenEmptySquareBrackets { get; } = CreateOption( + public static Option2 SpaceBetweenEmptySquareBrackets { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBetweenEmptySquareBrackets), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_empty_square_brackets"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBetweenEmptySquareBrackets")}); - public static Option SpaceWithinSquareBrackets { get; } = CreateOption( + public static Option2 SpaceWithinSquareBrackets { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceWithinSquareBrackets), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_between_square_brackets"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceWithinSquareBrackets")}); - public static Option SpaceAfterColonInBaseTypeDeclaration { get; } = CreateOption( + public static Option2 SpaceAfterColonInBaseTypeDeclaration { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterColonInBaseTypeDeclaration), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_colon_in_inheritance_clause"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterColonInBaseTypeDeclaration")}); - public static Option SpaceAfterComma { get; } = CreateOption( + public static Option2 SpaceAfterComma { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterComma), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_comma"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterComma")}); - public static Option SpaceAfterDot { get; } = CreateOption( + public static Option2 SpaceAfterDot { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterDot), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_dot"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterDot")}); - public static Option SpaceAfterSemicolonsInForStatement { get; } = CreateOption( + public static Option2 SpaceAfterSemicolonsInForStatement { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceAfterSemicolonsInForStatement), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_after_semicolon_in_for_statement"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceAfterSemicolonsInForStatement")}); - public static Option SpaceBeforeColonInBaseTypeDeclaration { get; } = CreateOption( + public static Option2 SpaceBeforeColonInBaseTypeDeclaration { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBeforeColonInBaseTypeDeclaration), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_before_colon_in_inheritance_clause"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBeforeColonInBaseTypeDeclaration")}); - public static Option SpaceBeforeComma { get; } = CreateOption( + public static Option2 SpaceBeforeComma { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBeforeComma), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_before_comma"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBeforeComma")}); - public static Option SpaceBeforeDot { get; } = CreateOption( + public static Option2 SpaceBeforeDot { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBeforeDot), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_before_dot"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBeforeDot")}); - public static Option SpaceBeforeSemicolonsInForStatement { get; } = CreateOption( + public static Option2 SpaceBeforeSemicolonsInForStatement { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpaceBeforeSemicolonsInForStatement), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_space_before_semicolon_in_for_statement"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpaceBeforeSemicolonsInForStatement")}); - public static Option SpacingAroundBinaryOperator { get; } = CreateOption( + public static Option2 SpacingAroundBinaryOperator { get; } = CreateOption( CSharpFormattingOptionGroups.Spacing, nameof(SpacingAroundBinaryOperator), defaultValue: BinaryOperatorSpacingOptions.Single, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { new EditorConfigStorageLocation( "csharp_space_around_binary_operators", s => ParseEditorConfigSpacingAroundBinaryOperator(s), GetSpacingAroundBinaryOperatorEditorConfigString), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.SpacingAroundBinaryOperator")}); - public static Option IndentBraces { get; } = CreateOption( + public static Option2 IndentBraces { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(IndentBraces), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_indent_braces"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.OpenCloseBracesIndent")}); - public static Option IndentBlock { get; } = CreateOption( + public static Option2 IndentBlock { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(IndentBlock), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_indent_block_contents"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.IndentBlock")}); - public static Option IndentSwitchSection { get; } = CreateOption( + public static Option2 IndentSwitchSection { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(IndentSwitchSection), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_indent_switch_labels"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.IndentSwitchSection")}); - public static Option IndentSwitchCaseSection { get; } = CreateOption( + public static Option2 IndentSwitchCaseSection { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(IndentSwitchCaseSection), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_indent_case_contents"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.IndentSwitchCaseSection")}); - public static Option IndentSwitchCaseSectionWhenBlock { get; } = CreateOption( + public static Option2 IndentSwitchCaseSectionWhenBlock { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(IndentSwitchCaseSectionWhenBlock), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_indent_case_contents_when_block"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.IndentSwitchCaseSectionWhenBlock")}); - public static Option LabelPositioning { get; } = CreateOption( + public static Option2 LabelPositioning { get; } = CreateOption( CSharpFormattingOptionGroups.Indentation, nameof(LabelPositioning), defaultValue: LabelPositionOptions.OneLess, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { new EditorConfigStorageLocation( "csharp_indent_labels", s => ParseEditorConfigLabelPositioning(s), GetLabelPositionOptionEditorConfigString), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.LabelPositioning")}); - public static Option WrappingPreserveSingleLine { get; } = CreateOption( + public static Option2 WrappingPreserveSingleLine { get; } = CreateOption( CSharpFormattingOptionGroups.Wrapping, nameof(WrappingPreserveSingleLine), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_preserve_single_line_blocks"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.WrappingPreserveSingleLine")}); - public static Option WrappingKeepStatementsOnSingleLine { get; } = CreateOption( + public static Option2 WrappingKeepStatementsOnSingleLine { get; } = CreateOption( CSharpFormattingOptionGroups.Wrapping, nameof(WrappingKeepStatementsOnSingleLine), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_preserve_single_line_statements"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.WrappingKeepStatementsOnSingleLine")}); - public static Option NewLinesForBracesInTypes { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInTypes { get; } = CreateNewLineForBracesOption( NewLineOption.Types, nameof(NewLinesForBracesInTypes)); - public static Option NewLinesForBracesInMethods { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInMethods { get; } = CreateNewLineForBracesOption( NewLineOption.Methods, nameof(NewLinesForBracesInMethods)); - public static Option NewLinesForBracesInProperties { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInProperties { get; } = CreateNewLineForBracesOption( NewLineOption.Properties, nameof(NewLinesForBracesInProperties)); - public static Option NewLinesForBracesInAccessors { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInAccessors { get; } = CreateNewLineForBracesOption( NewLineOption.Accessors, nameof(NewLinesForBracesInAccessors)); - public static Option NewLinesForBracesInAnonymousMethods { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInAnonymousMethods { get; } = CreateNewLineForBracesOption( NewLineOption.AnonymousMethods, nameof(NewLinesForBracesInAnonymousMethods)); - public static Option NewLinesForBracesInControlBlocks { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInControlBlocks { get; } = CreateNewLineForBracesOption( NewLineOption.ControlBlocks, nameof(NewLinesForBracesInControlBlocks)); - public static Option NewLinesForBracesInAnonymousTypes { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInAnonymousTypes { get; } = CreateNewLineForBracesOption( NewLineOption.AnonymousTypes, nameof(NewLinesForBracesInAnonymousTypes)); - public static Option NewLinesForBracesInObjectCollectionArrayInitializers { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInObjectCollectionArrayInitializers { get; } = CreateNewLineForBracesOption( NewLineOption.ObjectCollectionsArrayInitializers, nameof(NewLinesForBracesInObjectCollectionArrayInitializers)); - public static Option NewLinesForBracesInLambdaExpressionBody { get; } = CreateNewLineForBracesOption( + public static Option2 NewLinesForBracesInLambdaExpressionBody { get; } = CreateNewLineForBracesOption( NewLineOption.Lambdas, nameof(NewLinesForBracesInLambdaExpressionBody)); - public static Option NewLineForElse { get; } = CreateOption( + public static Option2 NewLineForElse { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForElse), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_before_else"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForElse")}); - public static Option NewLineForCatch { get; } = CreateOption( + public static Option2 NewLineForCatch { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForCatch), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_before_catch"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForCatch")}); - public static Option NewLineForFinally { get; } = CreateOption( + public static Option2 NewLineForFinally { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForFinally), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_before_finally"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForFinally")}); - public static Option NewLineForMembersInObjectInit { get; } = CreateOption( + public static Option2 NewLineForMembersInObjectInit { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForMembersInObjectInit), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_before_members_in_object_initializers"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForMembersInObjectInit")}); - public static Option NewLineForMembersInAnonymousTypes { get; } = CreateOption( + public static Option2 NewLineForMembersInAnonymousTypes { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForMembersInAnonymousTypes), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_before_members_in_anonymous_types"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForMembersInAnonymousTypes")}); - public static Option NewLineForClausesInQuery { get; } = CreateOption( + public static Option2 NewLineForClausesInQuery { get; } = CreateOption( CSharpFormattingOptionGroups.NewLine, nameof(NewLineForClausesInQuery), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("csharp_new_line_between_query_expression_clauses"), new RoamingProfileStorageLocation("TextEditor.CSharp.Specific.NewLineForClausesInQuery")}); - static CSharpFormattingOptions() + static CSharpFormattingOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to the following builders. @@ -419,7 +417,11 @@ static CSharpFormattingOptions() } } +#if CODE_STYLE + internal enum LabelPositionOptions +#else public enum LabelPositionOptions +#endif { /// Placed in the Zeroth column of the text editor LeftMost = 0, @@ -431,7 +433,11 @@ public enum LabelPositionOptions NoIndent = 2 } +#if CODE_STYLE + internal enum BinaryOperatorSpacingOptions +#else public enum BinaryOperatorSpacingOptions +#endif { /// Single Spacing Single = 0, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.DocumentationCommentExteriorCommentRewriter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.DocumentationCommentExteriorCommentRewriter.cs index 9ad3512d890bd..9f9498dd15149 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.DocumentationCommentExteriorCommentRewriter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.DocumentationCommentExteriorCommentRewriter.cs @@ -46,8 +46,8 @@ public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) _forceIndentation, _indentation, _indentationDelta, - _options.GetOption(FormattingOptions.UseTabs), - _options.GetOption(FormattingOptions.TabSize)); + _options.GetOption(FormattingOptions2.UseTabs), + _options.GetOption(FormattingOptions2.TabSize)); if (triviaText == newTriviaText) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs index 5e02934b550c1..b63ff6fe7a238 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.cs @@ -65,7 +65,7 @@ protected override SyntaxTrivia CreateEndOfLine() { if (_newLine == default) { - var text = this.Context.Options.GetOption(FormattingOptions.NewLine); + var text = this.Context.Options.GetOption(FormattingOptions2.NewLine); _newLine = SyntaxFactory.EndOfLine(text); } @@ -200,9 +200,9 @@ private bool TryFormatMultiLineCommentTrivia(LineColumn lineColumn, SyntaxTrivia false /* forceIndentation */, indentation, indentationDelta, - this.Options.GetOption(FormattingOptions.UseTabs), - this.Options.GetOption(FormattingOptions.TabSize), - this.Options.GetOption(FormattingOptions.NewLine)); + this.Options.GetOption(FormattingOptions2.UseTabs), + this.Options.GetOption(FormattingOptions2.TabSize), + this.Options.GetOption(FormattingOptions2.NewLine)); var multilineCommentTrivia = SyntaxFactory.ParseLeadingTrivia(multiLineComment); Contract.ThrowIfFalse(multilineCommentTrivia.Count == 1); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs index 0599db1d544f1..32956bda6e24a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.cs @@ -134,7 +134,7 @@ private bool OnWhitespace(SyntaxTrivia trivia) return true; } - _indentation += text.ConvertTabToSpace(_options.GetOption(FormattingOptions.TabSize), _indentation, text.Length); + _indentation += text.ConvertTabToSpace(_options.GetOption(FormattingOptions2.TabSize), _indentation, text.Length); return false; } @@ -190,7 +190,7 @@ private bool OnComment(SyntaxTrivia trivia) // go deep down for single line documentation comment if (trivia.IsSingleLineDocComment() && - ShouldFormatSingleLineDocumentationComment(_indentation, _options.GetOption(FormattingOptions.TabSize), trivia)) + ShouldFormatSingleLineDocumentationComment(_indentation, _options.GetOption(FormattingOptions2.TabSize), trivia)) { return true; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.cs index d795de60a4011..93c60eff662db 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.cs @@ -28,7 +28,7 @@ public ComplexTrivia(AnalyzerConfigOptions options, TreeData treeInfo, SyntaxTok protected override void ExtractLineAndSpace(string text, out int lines, out int spaces) { - text.ProcessTextBetweenTokens(this.TreeInfo, this.Token1, this.Options.GetOption(FormattingOptions.TabSize), out lines, out spaces); + text.ProcessTextBetweenTokens(this.TreeInfo, this.Token1, this.Options.GetOption(FormattingOptions2.TabSize), out lines, out spaces); } protected override TriviaData CreateComplexTrivia(int line, int space) @@ -85,7 +85,7 @@ private bool ShouldFormat(FormattingContext context) Debug.Assert(this.SecondTokenIsFirstTokenOnLine); - if (this.Options.GetOption(FormattingOptions.UseTabs)) + if (this.Options.GetOption(FormattingOptions2.UseTabs)) { return true; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.cs index 52bbc95384119..eda133d6bf30e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.cs @@ -131,10 +131,10 @@ private TriviaData GetWhitespaceOnlyTriviaInfo(SyntaxToken token1, SyntaxToken t private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) { - var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(this.Options.GetOption(FormattingOptions.TabSize), token1) + token1.Span.Length; + var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(this.Options.GetOption(FormattingOptions2.TabSize), token1) + token1.Span.Length; var textSnippet = this.TreeInfo.GetTextBetween(token1, token2); - return textSnippet.ConvertTabToSpace(this.Options.GetOption(FormattingOptions.TabSize), initialColumn, textSnippet.Length); + return textSnippet.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, textSnippet.Length); } private (bool canUseTriviaAsItIs, int lineBreaks, int indentation) GetLineBreaksAndIndentation(Analyzer.AnalysisResult result) @@ -142,7 +142,7 @@ private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) Debug.Assert(result.Tab >= 0); Debug.Assert(result.LineBreaks >= 0); - var indentation = result.Tab * this.Options.GetOption(FormattingOptions.TabSize) + result.Space; + var indentation = result.Tab * this.Options.GetOption(FormattingOptions2.TabSize) + result.Space; if (result.HasTrailingSpace || result.HasUnknownWhitespace) { if (result.HasUnknownWhitespace && result.LineBreaks == 0 && indentation == 0) @@ -154,7 +154,7 @@ private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } - if (!this.Options.GetOption(FormattingOptions.UseTabs)) + if (!this.Options.GetOption(FormattingOptions2.UseTabs)) { if (result.Tab > 0) { @@ -164,7 +164,7 @@ private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } - Debug.Assert(this.Options.GetOption(FormattingOptions.UseTabs)); + Debug.Assert(this.Options.GetOption(FormattingOptions2.UseTabs)); // tab can only appear before space to be a valid tab for indentation if (result.HasTabAfterSpace) @@ -172,13 +172,13 @@ private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } - if (result.Space >= this.Options.GetOption(FormattingOptions.TabSize)) + if (result.Space >= this.Options.GetOption(FormattingOptions2.TabSize)) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } - Debug.Assert((indentation / this.Options.GetOption(FormattingOptions.TabSize)) == result.Tab); - Debug.Assert((indentation % this.Options.GetOption(FormattingOptions.TabSize)) == result.Space); + Debug.Assert((indentation / this.Options.GetOption(FormattingOptions2.TabSize)) == result.Tab); + Debug.Assert((indentation % this.Options.GetOption(FormattingOptions2.TabSize)) == result.Space); return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs index 8e27234f8a1df..6a237856efcfe 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentBlockFormattingRule.cs @@ -60,8 +60,8 @@ private void AddSwitchIndentationOperation(List list, Synt return; } - var indentSwitchCase = options.GetOption(CSharpFormattingOptions.IndentSwitchCaseSection); - var indentSwitchCaseWhenBlock = options.GetOption(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock); + var indentSwitchCase = options.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSection); + var indentSwitchCaseWhenBlock = options.GetOption(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock); if (!indentSwitchCase && !indentSwitchCaseWhenBlock) { // Never indent @@ -115,7 +115,7 @@ private void AddLabelIndentationOperation(List list, Synta // label statement if (node is LabeledStatementSyntax labeledStatement) { - var labelPositioningOption = options.GetOption(CSharpFormattingOptions.LabelPositioning); + var labelPositioningOption = options.GetOption(CSharpFormattingOptions2.LabelPositioning); if (labelPositioningOption == LabelPositionOptions.OneLess) { @@ -197,13 +197,13 @@ private void AddBlockIndentationOperation(List list, Synta AddAlignmentBlockOperationRelativeToFirstTokenOnBaseTokenLine(list, bracePair); } - if (node is BlockSyntax && !options.GetOption(CSharpFormattingOptions.IndentBlock)) + if (node is BlockSyntax && !options.GetOption(CSharpFormattingOptions2.IndentBlock)) { // do not add indent operation for block return; } - if (node is SwitchStatementSyntax && !options.GetOption(CSharpFormattingOptions.IndentSwitchSection)) + if (node is SwitchStatementSyntax && !options.GetOption(CSharpFormattingOptions2.IndentSwitchSection)) { // do not add indent operation for switch statement return; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentUserSettingsFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentUserSettingsFormattingRule.cs index 9262846efc764..155ffd3aaaf3d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentUserSettingsFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentUserSettingsFormattingRule.cs @@ -22,7 +22,7 @@ public override void AddIndentBlockOperations(List list, S return; } - if (options.GetOption(CSharpFormattingOptions.IndentBraces)) + if (options.GetOption(CSharpFormattingOptions2.IndentBraces)) { AddIndentBlockOperation(list, bracePair.Item1, bracePair.Item1, bracePair.Item1.Span); AddIndentBlockOperation(list, bracePair.Item2, bracePair.Item2, bracePair.Item2.Span); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/NewLineUserSettingFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/NewLineUserSettingFormattingRule.cs index 255b8530f92fa..b6a968cedb094 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/NewLineUserSettingFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/NewLineUserSettingFormattingRule.cs @@ -62,7 +62,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ && currentToken.IsKind(SyntaxKind.ElseKeyword) && previousToken.Parent.Parent == currentToken.Parent.Parent) { - if (!options.GetOption(CSharpFormattingOptions.NewLineForElse)) + if (!options.GetOption(CSharpFormattingOptions2.NewLineForElse)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -71,7 +71,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * catch in the try catch context if (currentToken.IsKind(SyntaxKind.CatchKeyword)) { - if (!options.GetOption(CSharpFormattingOptions.NewLineForCatch)) + if (!options.GetOption(CSharpFormattingOptions2.NewLineForCatch)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -80,7 +80,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * finally if (currentToken.IsKind(SyntaxKind.FinallyKeyword)) { - if (!options.GetOption(CSharpFormattingOptions.NewLineForFinally)) + if (!options.GetOption(CSharpFormattingOptions2.NewLineForFinally)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -89,7 +89,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * { in the type declaration context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && (currentToken.Parent is BaseTypeDeclarationSyntax || currentToken.Parent is NamespaceDeclarationSyntax)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInTypes)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInTypes)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -98,7 +98,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // new { - Anonymous object creation if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent != null && currentToken.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -107,7 +107,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // new { - Object Initialization if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent != null && currentToken.Parent.IsKind(SyntaxKind.ObjectInitializerExpression)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -119,8 +119,8 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentTokenParentParent != null && currentTokenParentParent is MemberDeclarationSyntax) { var option = currentTokenParentParent is BasePropertyDeclarationSyntax - ? CSharpFormattingOptions.NewLinesForBracesInProperties - : CSharpFormattingOptions.NewLinesForBracesInMethods; + ? CSharpFormattingOptions2.NewLinesForBracesInProperties + : CSharpFormattingOptions2.NewLinesForBracesInMethods; if (!options.GetOption(option)) { @@ -130,7 +130,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentTokenParentParent != null && currentTokenParentParent is AccessorDeclarationSyntax) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAccessors)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -139,7 +139,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * { - in the anonymous Method context if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentTokenParentParent != null && currentTokenParentParent.IsKind(SyntaxKind.AnonymousMethodExpression)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -148,7 +148,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * { - in the local function context if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentTokenParentParent != null && currentTokenParentParent.IsKind(SyntaxKind.LocalFunctionStatement)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInMethods)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInMethods)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -158,7 +158,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentTokenParentParent != null && (currentTokenParentParent.IsKind(SyntaxKind.SimpleLambdaExpression) || currentTokenParentParent.IsKind(SyntaxKind.ParenthesizedLambdaExpression))) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -167,7 +167,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // * { - in the control statement context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && IsControlBlock(currentToken.Parent)) { - if (!options.GetOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks)) + if (!options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks)) { operation = CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } @@ -185,7 +185,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // For Object Initialization Expression if (previousToken.Kind() == SyntaxKind.CommaToken && previousToken.Parent.Kind() == SyntaxKind.ObjectInitializerExpression) { - if (options.GetOption(CSharpFormattingOptions.NewLineForMembersInObjectInit)) + if (options.GetOption(CSharpFormattingOptions2.NewLineForMembersInObjectInit)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -199,7 +199,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // For Anonymous Object Creation Expression if (previousToken.Kind() == SyntaxKind.CommaToken && previousToken.Parent.Kind() == SyntaxKind.AnonymousObjectCreationExpression) { - if (options.GetOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes)) + if (options.GetOption(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -213,7 +213,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // } else in the if else context if (previousToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.IsKind(SyntaxKind.ElseKeyword)) { - if (options.GetOption(CSharpFormattingOptions.NewLineForElse) + if (options.GetOption(CSharpFormattingOptions2.NewLineForElse) || previousToken.Parent.Parent != currentToken.Parent.Parent) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); @@ -227,7 +227,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * catch in the try catch context if (currentToken.Kind() == SyntaxKind.CatchKeyword) { - if (options.GetOption(CSharpFormattingOptions.NewLineForCatch)) + if (options.GetOption(CSharpFormattingOptions2.NewLineForCatch)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -240,7 +240,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * Finally if (currentToken.Kind() == SyntaxKind.FinallyKeyword) { - if (options.GetOption(CSharpFormattingOptions.NewLineForFinally)) + if (options.GetOption(CSharpFormattingOptions2.NewLineForFinally)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -253,7 +253,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * { - in the type declaration context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && (currentToken.Parent is BaseTypeDeclarationSyntax || currentToken.Parent is NamespaceDeclarationSyntax)) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInTypes)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInTypes)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -266,7 +266,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // new { - Anonymous object creation if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentToken.Parent != null && currentToken.Parent.Kind() == SyntaxKind.AnonymousObjectCreationExpression) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -282,7 +282,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p (currentToken.Parent.Kind() == SyntaxKind.ObjectInitializerExpression || currentToken.Parent.Kind() == SyntaxKind.CollectionInitializerExpression)) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -309,8 +309,8 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null && currentTokenParentParent is MemberDeclarationSyntax) { var option = currentTokenParentParent is BasePropertyDeclarationSyntax - ? CSharpFormattingOptions.NewLinesForBracesInProperties - : CSharpFormattingOptions.NewLinesForBracesInMethods; + ? CSharpFormattingOptions2.NewLinesForBracesInProperties + : CSharpFormattingOptions2.NewLinesForBracesInMethods; if (options.GetOption(option)) { @@ -325,7 +325,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * { - in the property accessor context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null && currentTokenParentParent is AccessorDeclarationSyntax) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAccessors)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAccessors)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -338,7 +338,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * { - in the anonymous Method context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null && currentTokenParentParent.Kind() == SyntaxKind.AnonymousMethodExpression) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLinesIfOnSingleLine); } @@ -351,7 +351,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * { - in the local function context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null && currentTokenParentParent.Kind() == SyntaxKind.LocalFunctionStatement) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInMethods)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInMethods)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -365,7 +365,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p if (currentToken.Kind() == SyntaxKind.OpenBraceToken && currentTokenParentParent != null && (currentTokenParentParent.Kind() == SyntaxKind.SimpleLambdaExpression || currentTokenParentParent.Kind() == SyntaxKind.ParenthesizedLambdaExpression)) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLinesIfOnSingleLine); } @@ -378,7 +378,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // * { - in the control statement context if (currentToken.Kind() == SyntaxKind.OpenBraceToken && IsControlBlock(currentToken.Parent)) { - if (options.GetOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks)) + if (options.GetOption(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } @@ -393,7 +393,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p // ; * if (previousToken.Kind() == SyntaxKind.SemicolonToken && (previousToken.Parent is StatementSyntax && !previousToken.Parent.IsKind(SyntaxKind.ForStatement)) - && !options.GetOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine)) + && !options.GetOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/QueryExpressionFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/QueryExpressionFormattingRule.cs index 5f3938b19c18e..93dc16a775fc9 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/QueryExpressionFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/QueryExpressionFormattingRule.cs @@ -131,7 +131,7 @@ public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken p case SyntaxKind.SelectKeyword: if (currentToken.GetAncestor() != null) { - if (options.GetOption(CSharpFormattingOptions.NewLineForClausesInQuery)) + if (options.GetOption(CSharpFormattingOptions2.NewLineForClausesInQuery)) { return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs index 5fae048d46343..3d99c0b649b1f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs @@ -8,12 +8,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { @@ -36,13 +31,13 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // For Method Declaration if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.IdentifierToken) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpacingAfterMethodDeclarationName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } // For Generic Method Declaration if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.GreaterThanToken && previousParentKind == SyntaxKind.TypeParameterList) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpacingAfterMethodDeclarationName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } // Case: public static implicit operator string(Program p) { return null; } @@ -54,28 +49,28 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ if ((previousToken.IsKeyword() || previousToken.IsKind(SyntaxKind.QuestionToken, SyntaxKind.AsteriskToken, SyntaxKind.CloseBracketToken, SyntaxKind.CloseParenToken, SyntaxKind.GreaterThanToken)) && currentToken.IsOpenParenInParameterListOfAConversionOperatorDeclaration()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpacingAfterMethodDeclarationName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } // Case: public static Program operator !(Program p) { return null; } if (previousToken.Parent.IsKind(SyntaxKind.OperatorDeclaration) && currentToken.IsOpenParenInParameterListOfAOperationDeclaration()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpacingAfterMethodDeclarationName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpacingAfterMethodDeclarationName); } if (previousToken.IsOpenParenInParameterList() && currentToken.IsCloseParenInParameterList()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses); } if (previousToken.IsOpenParenInParameterList()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis); } if (currentToken.IsCloseParenInParameterList()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis); } // For Method Call @@ -84,38 +79,38 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // x is TypeName ( args ) if (currentToken.IsOpenParenInArgumentListOrPositionalPattern()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterMethodCallName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterMethodCallName); } if (previousToken.IsOpenParenInArgumentListOrPositionalPattern() && currentToken.IsCloseParenInArgumentListOrPositionalPattern()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses); } if (previousToken.IsOpenParenInArgumentListOrPositionalPattern()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodCallParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } if (currentToken.IsCloseParenInArgumentListOrPositionalPattern()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodCallParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } // For spacing around: typeof, default, and sizeof; treat like a Method Call if (currentKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterMethodCallName); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterMethodCallName); } if (previousKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(previousParentKind)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodCallParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } if (currentKind == SyntaxKind.CloseParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinMethodCallParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinMethodCallParentheses); } // For Spacing b/n control flow keyword and paren. Parent check not needed. @@ -125,21 +120,21 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ previousKind == SyntaxKind.UsingKeyword || previousKind == SyntaxKind.WhenKeyword || previousKind == SyntaxKind.LockKeyword || previousKind == SyntaxKind.FixedKeyword)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword); } // For spacing between parenthesis and expression if ((previousParentKind == SyntaxKind.ParenthesizedExpression && previousKind == SyntaxKind.OpenParenToken) || (currentParentKind == SyntaxKind.ParenthesizedExpression && currentKind == SyntaxKind.CloseParenToken)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinExpressionParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinExpressionParentheses); } // For spacing between the parenthesis and the cast expression if ((previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.OpenParenToken) || (currentParentKind == SyntaxKind.CastExpression && currentKind == SyntaxKind.CloseParenToken)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinCastParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinCastParentheses); } // Semicolons in an empty for statement. i.e. for(;;) @@ -148,35 +143,35 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ { if (currentKind == SyntaxKind.SemicolonToken && (previousKind != SyntaxKind.SemicolonToken - || options.GetOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement))) + || options.GetOption(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement))) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement); } - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement); } // For spacing between the parenthesis and the expression inside the control flow expression if (previousKind == SyntaxKind.OpenParenToken && IsControlFlowLikeKeywordStatementKind(previousParentKind)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinOtherParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinOtherParentheses); } if (currentKind == SyntaxKind.CloseParenToken && IsControlFlowLikeKeywordStatementKind(currentParentKind)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinOtherParentheses); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinOtherParentheses); } // For spacing after the cast if (previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.CloseParenToken) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterCast); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterCast); } // For spacing Before Square Braces if (currentKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(currentToken) && !previousToken.IsOpenBraceOrCommaOfObjectInitializer()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket); } // For spacing empty square braces, also treat [,] as empty @@ -184,18 +179,18 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ || currentKind == SyntaxKind.OmittedArraySizeExpressionToken) && HasFormattableBracketParent(previousToken)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets); } // For spacing square brackets within if (previousKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(previousToken)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinSquareBrackets); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinSquareBrackets); } if (currentKind == SyntaxKind.CloseBracketToken && previousKind != SyntaxKind.OmittedArraySizeExpressionToken && HasFormattableBracketParent(currentToken)) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceWithinSquareBrackets); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceWithinSquareBrackets); } // attribute case ] * @@ -212,13 +207,13 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ // For spacing delimiters - after colon if (previousToken.IsColonInTypeBaseList()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration); } // For spacing delimiters - before colon if (currentToken.IsColonInTypeBaseList()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration); } // For spacing delimiters - after comma @@ -228,7 +223,7 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ && currentKind != SyntaxKind.OmittedArraySizeExpressionToken && HasFormattableBracketParent(previousToken))) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterComma); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterComma); } // For spacing delimiters - before comma @@ -238,31 +233,31 @@ public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previ && previousKind != SyntaxKind.OmittedArraySizeExpressionToken && HasFormattableBracketParent(currentToken))) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeComma); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeComma); } // For Spacing delimiters - after Dot if (previousToken.IsDotInMemberAccessOrQualifiedName()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterDot); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterDot); } // For spacing delimiters - before Dot if (currentToken.IsDotInMemberAccessOrQualifiedName()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeDot); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeDot); } // For spacing delimiters - after semicolon if (previousToken.IsSemicolonInForStatement() && currentKind != SyntaxKind.CloseParenToken) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement); } // For spacing delimiters - before semicolon if (currentToken.IsSemicolonInForStatement()) { - return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); + return AdjustSpacesOperationZeroOrOne(options, CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement); } // For spacing around the binary operators @@ -271,7 +266,7 @@ previousToken.Parent is BinaryExpressionSyntax || currentToken.Parent is AssignmentExpressionSyntax || previousToken.Parent is AssignmentExpressionSyntax) { - switch (options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator)) + switch (options.GetOption(CSharpFormattingOptions2.SpacingAroundBinaryOperator)) { case BinaryOperatorSpacingOptions.Single: return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine); @@ -393,7 +388,7 @@ private void SuppressVariableDeclaration(List list, SyntaxNod node.IsKind(SyntaxKind.EventFieldDeclaration) || node.IsKind(SyntaxKind.LocalDeclarationStatement) || node.IsKind(SyntaxKind.EnumMemberDeclaration)) { - if (options.GetOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration)) + if (options.GetOption(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration)) { var firstToken = node.GetFirstToken(includeZeroWidth: true); var lastToken = node.GetLastToken(includeZeroWidth: true); @@ -403,7 +398,7 @@ private void SuppressVariableDeclaration(List list, SyntaxNod } } - private AdjustSpacesOperation AdjustSpacesOperationZeroOrOne(AnalyzerConfigOptions options, Option option, AdjustSpacesOption explicitOption = AdjustSpacesOption.ForceSpacesIfOnSingleLine) + private AdjustSpacesOperation AdjustSpacesOperationZeroOrOne(AnalyzerConfigOptions options, Option2 option, AdjustSpacesOption explicitOption = AdjustSpacesOption.ForceSpacesIfOnSingleLine) { if (options.GetOption(option)) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/TokenBasedFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/TokenBasedFormattingRule.cs index b27df23b52598..f0deeab33cf46 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/TokenBasedFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/TokenBasedFormattingRule.cs @@ -6,17 +6,11 @@ using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.CSharp.Utilities; using Roslyn.Utilities; -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Editing; -using Microsoft.CodeAnalysis.Internal.Options; -#else -using Microsoft.CodeAnalysis.Editing; -#endif - namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class TokenBasedFormattingRule : BaseFormattingRule diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/WrappingFormattingRule.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/WrappingFormattingRule.cs index 0eb14629ee627..893b30f537d88 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/WrappingFormattingRule.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/WrappingFormattingRule.cs @@ -24,12 +24,12 @@ public override void AddSuppressOperations(List list, SyntaxN AddSpecificNodesSuppressOperations(list, node); - if (!options.GetOption(CSharpFormattingOptions.WrappingPreserveSingleLine)) + if (!options.GetOption(CSharpFormattingOptions2.WrappingPreserveSingleLine)) { RemoveSuppressOperationForBlock(list, node); } - if (!options.GetOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine)) + if (!options.GetOption(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine)) { RemoveSuppressOperationForStatementMethodDeclaration(list, node); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.State.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.State.cs index 8d9fb6102414a..8dd2677143729 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.State.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpTypeStyleHelper.State.cs @@ -3,18 +3,16 @@ // See the LICENSE file in the project root for more information. using System.Threading; +using Microsoft.CodeAnalysis.CSharp.CodeStyle; +using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle.TypeStyle; #else -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.CSharp.CodeStyle; -using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseExplicitTypeHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseExplicitTypeHelper.cs index 23e7e98f8ebea..6deca3a726737 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseExplicitTypeHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseExplicitTypeHelper.cs @@ -4,16 +4,15 @@ using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle.TypeStyle; #else -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs index bf2d868ade443..d454ae70da75e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TypeStyle/CSharpUseImplicitTypeHelper.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -17,10 +18,8 @@ #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; -using Microsoft.CodeAnalysis.CSharp.Internal.CodeStyle.TypeStyle; #else -using Microsoft.CodeAnalysis.Options; -using Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle; +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.CSharp.Utilities diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/AccessibilityModifiersRequired.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/AccessibilityModifiersRequired.cs index 6a25c279338e5..b24c3d15bc4d2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/AccessibilityModifiersRequired.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/AccessibilityModifiersRequired.cs @@ -2,12 +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. - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { internal enum AccessibilityModifiersRequired { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs index 1fd89bd98c768..20cc484d4b239 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleHelpers.cs @@ -4,24 +4,19 @@ using System.Collections.Immutable; using System.Diagnostics; -using Roslyn.Utilities; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleHelpers { - public static bool TryParseStringEditorConfigCodeStyleOption(string arg, out CodeStyleOption option) + public static bool TryParseStringEditorConfigCodeStyleOption(string arg, out CodeStyleOption2 option) { if (TryGetCodeStyleValueAndOptionalNotification( arg, out var value, out var notificationOpt)) { - option = new CodeStyleOption(value, notificationOpt ?? NotificationOption.Silent); + option = new CodeStyleOption2(value, notificationOpt ?? NotificationOption2.Silent); return true; } @@ -29,7 +24,7 @@ public static bool TryParseStringEditorConfigCodeStyleOption(string arg, out Cod return false; } - public static bool TryParseBoolEditorConfigCodeStyleOption(string arg, out CodeStyleOption option) + public static bool TryParseBoolEditorConfigCodeStyleOption(string arg, out CodeStyleOption2 option) { if (TryGetCodeStyleValueAndOptionalNotification( arg, out var value, out var notificationOpt)) @@ -41,32 +36,32 @@ public static bool TryParseBoolEditorConfigCodeStyleOption(string arg, out CodeS // 'true' must always be provided with a notification option. if (isEnabled == false) { - notificationOpt ??= NotificationOption.Silent; - option = new CodeStyleOption(false, notificationOpt); + notificationOpt ??= NotificationOption2.Silent; + option = new CodeStyleOption2(false, notificationOpt); return true; } else if (notificationOpt != null) { - option = new CodeStyleOption(true, notificationOpt); + option = new CodeStyleOption2(true, notificationOpt); return true; } } } - option = CodeStyleOption.Default; + option = CodeStyleOption2.Default; return false; } /// /// Given an editor-config code-style-option, gives back the constituent parts of the /// option. For example, if the option is "true:error" then "true" will be returned - /// in and will be returned + /// in and will be returned /// in . Note that users are allowed to not provide /// a NotificationOption, so may be null. The caller /// of this method must decide what to do in that case. /// public static bool TryGetCodeStyleValueAndOptionalNotification( - string arg, out string value, out NotificationOption notificationOpt) + string arg, out string value, out NotificationOption2 notificationOpt) { var args = arg.Split(':'); Debug.Assert(args.Length > 0); @@ -99,43 +94,43 @@ public static bool TryGetCodeStyleValueAndOptionalNotification( return false; } - public static bool TryParseNotification(string value, out NotificationOption notification) + public static bool TryParseNotification(string value, out NotificationOption2 notification) { switch (value.Trim()) { case EditorConfigSeverityStrings.None: - notification = NotificationOption.None; + notification = NotificationOption2.None; return true; case EditorConfigSeverityStrings.Refactoring: case EditorConfigSeverityStrings.Silent: - notification = NotificationOption.Silent; + notification = NotificationOption2.Silent; return true; - case EditorConfigSeverityStrings.Suggestion: notification = NotificationOption.Suggestion; return true; - case EditorConfigSeverityStrings.Warning: notification = NotificationOption.Warning; return true; - case EditorConfigSeverityStrings.Error: notification = NotificationOption.Error; return true; + case EditorConfigSeverityStrings.Suggestion: notification = NotificationOption2.Suggestion; return true; + case EditorConfigSeverityStrings.Warning: notification = NotificationOption2.Warning; return true; + case EditorConfigSeverityStrings.Error: notification = NotificationOption2.Error; return true; } - notification = NotificationOption.Silent; + notification = NotificationOption2.Silent; return false; } - public static Option CreateOption( + public static Option2 CreateOption( OptionGroup group, string feature, string name, T defaultValue, - ImmutableArray.Builder optionsBuilder, - params OptionStorageLocation[] storageLocations) + ImmutableArray.Builder optionsBuilder, + params OptionStorageLocation2[] storageLocations) { - var option = new Option(feature, group, name, defaultValue, storageLocations); + var option = new Option2(feature, group, name, defaultValue, storageLocations); optionsBuilder.Add(option); return option; } - private static readonly CodeStyleOption s_preferNoneUnusedValuePreference = - new CodeStyleOption(default, NotificationOption.None); + private static readonly CodeStyleOption2 s_preferNoneUnusedValuePreference = + new CodeStyleOption2(default, NotificationOption2.None); private static readonly BidirectionalMap s_unusedExpressionAssignmentPreferenceMap = new BidirectionalMap(new[] @@ -144,41 +139,41 @@ public static Option CreateOption( KeyValuePairUtil.Create("unused_local_variable", UnusedValuePreference.UnusedLocalVariable), }); - public static Option> CreateUnusedExpressionAssignmentOption( + public static Option2> CreateUnusedExpressionAssignmentOption( OptionGroup group, string feature, string name, string editorConfigName, - CodeStyleOption defaultValue, - ImmutableArray.Builder optionsBuilder) + CodeStyleOption2 defaultValue, + ImmutableArray.Builder optionsBuilder) => CreateOption( group, feature, name, defaultValue, optionsBuilder, - storageLocations: new OptionStorageLocation[]{ - new EditorConfigStorageLocation>( + storageLocations: new OptionStorageLocation2[]{ + new EditorConfigStorageLocation>( editorConfigName, s => ParseUnusedExpressionAssignmentPreference(s, defaultValue), o => GetUnusedExpressionAssignmentPreferenceEditorConfigString(o, defaultValue.Value)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{name}Preference")}); - private static Optional> ParseUnusedExpressionAssignmentPreference( + private static Optional> ParseUnusedExpressionAssignmentPreference( string optionString, - CodeStyleOption defaultCodeStyleOption) + CodeStyleOption2 defaultCodeStyleOption) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, out var value, out var notificationOpt)) { - return new CodeStyleOption( + return new CodeStyleOption2( s_unusedExpressionAssignmentPreferenceMap.GetValueOrDefault(value), notificationOpt ?? defaultCodeStyleOption.Notification); } return s_preferNoneUnusedValuePreference; } - private static string GetUnusedExpressionAssignmentPreferenceEditorConfigString(CodeStyleOption option, UnusedValuePreference defaultPreference) + private static string GetUnusedExpressionAssignmentPreferenceEditorConfigString(CodeStyleOption2 option, UnusedValuePreference defaultPreference) { Debug.Assert(s_unusedExpressionAssignmentPreferenceMap.ContainsValue(option.Value)); var value = s_unusedExpressionAssignmentPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedExpressionAssignmentPreferenceMap.GetKeyOrDefault(defaultPreference); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs new file mode 100644 index 0000000000000..53f77b9f901b3 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`1.cs @@ -0,0 +1,200 @@ +// 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.Generic; +using System.Xml.Linq; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis.CodeStyle +{ + internal interface ICodeStyleOption + { + XElement ToXElement(); + object Value { get; } + NotificationOption2 Notification { get; } + ICodeStyleOption WithValue(object value); + ICodeStyleOption WithNotification(NotificationOption2 notification); + ICodeStyleOption AsCodeStyleOption(); + } + + /// + /// Represents a code style option and an associated notification option. Supports + /// being instantiated with T as a or an enum type. + /// + /// CodeStyleOption also has some basic support for migration a option + /// forward to an enum type option. Specifically, if a previously serialized + /// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false' + /// values will be migrated to have the 0-value of the enum, and 'true' values will be + /// migrated to have the 1-value of the enum. + /// + /// Similarly, enum-type code options will serialize out in a way that is compatible with + /// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1 + /// then those values will write back as false/true. + /// + internal partial class CodeStyleOption2 : ICodeStyleOption, IEquatable> + { + public static CodeStyleOption2 Default => new CodeStyleOption2(default, NotificationOption2.Silent); + + private const int SerializationVersion = 1; + + private NotificationOption2 _notification; + + public CodeStyleOption2(T value, NotificationOption2 notification) + { + Value = value; + _notification = notification ?? throw new ArgumentNullException(nameof(notification)); + } + + public T Value { get; set; } + + object ICodeStyleOption.Value => this.Value; + ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2((T)value, Notification); + ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2(Value, notification); + + ICodeStyleOption ICodeStyleOption.AsCodeStyleOption() +#if CODE_STYLE + => this; +#else + => this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption(this); +#endif + + private int EnumValueAsInt32 => (int)(object)Value; + + public NotificationOption2 Notification + { + get => _notification; + set => _notification = value ?? throw new ArgumentNullException(nameof(value)); + } + + public XElement ToXElement() => + new XElement("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. + new XAttribute(nameof(SerializationVersion), SerializationVersion), + new XAttribute("Type", GetTypeNameForSerialization()), + new XAttribute(nameof(Value), GetValueForSerialization()), + new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); + + private object GetValueForSerialization() + { + if (typeof(T) == typeof(string)) + { + return Value; + } + else if (typeof(T) == typeof(bool)) + { + return Value; + } + else if (IsZeroOrOneValueOfEnum()) + { + return EnumValueAsInt32 == 1; + } + else + { + return EnumValueAsInt32; + } + } + + private string GetTypeNameForSerialization() + { + if (typeof(T) == typeof(string)) + { + return nameof(String); + } + if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum()) + { + return nameof(Boolean); + } + else + { + return nameof(Int32); + } + } + + private bool IsZeroOrOneValueOfEnum() + { + var intVal = EnumValueAsInt32; + return intVal == 0 || intVal == 1; + } + + public static CodeStyleOption2 FromXElement(XElement element) + { + var typeAttribute = element.Attribute("Type"); + var valueAttribute = element.Attribute(nameof(Value)); + var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); + var version = (int)element.Attribute(nameof(SerializationVersion)); + + if (typeAttribute == null || valueAttribute == null || severityAttribute == null) + { + // data from storage is corrupt, or nothing has been stored yet. + return Default; + } + + if (version != SerializationVersion) + { + return Default; + } + + var parser = GetParser(typeAttribute.Value); + var value = parser(valueAttribute.Value); + var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value); + + return new CodeStyleOption2(value, severity switch + { + DiagnosticSeverity.Hidden => NotificationOption2.Silent, + DiagnosticSeverity.Info => NotificationOption2.Suggestion, + DiagnosticSeverity.Warning => NotificationOption2.Warning, + DiagnosticSeverity.Error => NotificationOption2.Error, + _ => throw new ArgumentException(nameof(element)), + }); + } + + private static Func GetParser(string type) + => type switch + { + nameof(Boolean) => + // Try to map a boolean value. Either map it to true/false if we're a + // CodeStyleOption or map it to the 0 or 1 value for an enum if we're + // a CodeStyleOption. + (Func)(v => Convert(bool.Parse(v))), + nameof(Int32) => v => Convert(int.Parse(v)), + nameof(String) => v => (T)(object)v, + _ => throw new ArgumentException(nameof(type)), + }; + + private static T Convert(bool b) + { + // If we had a bool and we wanted a bool, then just return this value. + if (typeof(T) == typeof(bool)) + { + return (T)(object)b; + } + + // Map booleans to the 1/0 value of the enum. + return b ? (T)(object)1 : (T)(object)0; + } + + private static T Convert(int i) + { + // We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default. + if (typeof(T) == typeof(bool)) + { + return (T)(object)(i == 1); + } + + // If had an int and we wanted an enum, then just return this value. + return (T)(object)(i); + } + + public bool Equals(CodeStyleOption2 other) + => EqualityComparer.Default.Equals(Value, other.Value) && + Notification == other.Notification; + + public override bool Equals(object obj) + => obj is CodeStyleOption2 option && + Equals(option); + + public override int GetHashCode() + => unchecked((Notification.GetHashCode() * (int)0xA5555529) + Value.GetHashCode()); + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs new file mode 100644 index 0000000000000..393220f93e030 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.cs @@ -0,0 +1,437 @@ +// 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. + +#nullable enable + +using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis.Options; +using Roslyn.Utilities; +using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; + +namespace Microsoft.CodeAnalysis.CodeStyle +{ + internal static class CodeStyleOptions2 + { + private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); + + internal static ImmutableArray AllOptions { get; } + + private static PerLanguageOption2 CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + { + var option = new PerLanguageOption2("CodeStyleOptions", group, name, defaultValue, storageLocations); + s_allOptionsBuilder.Add(option); + return option; + } + + private static Option2 CreateCommonOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + { + var option = new Option2("CodeStyleOptions", group, name, defaultValue, storageLocations); + s_allOptionsBuilder.Add(option); + return option; + } + + /// + /// When user preferences are not yet set for a style, we fall back to the default value. + /// One such default(s), is that the feature is turned on, so that codegen consumes it, + /// but with silent enforcement, so that the user is not prompted about their usage. + /// + internal static readonly CodeStyleOption2 TrueWithSilentEnforcement = new CodeStyleOption2(value: true, notification: NotificationOption2.Silent); + internal static readonly CodeStyleOption2 FalseWithSilentEnforcement = new CodeStyleOption2(value: false, notification: NotificationOption2.Silent); + internal static readonly CodeStyleOption2 TrueWithSuggestionEnforcement = new CodeStyleOption2(value: true, notification: NotificationOption2.Suggestion); + internal static readonly CodeStyleOption2 FalseWithSuggestionEnforcement = new CodeStyleOption2(value: false, notification: NotificationOption2.Suggestion); + + /// + /// This option says if we should simplify away the . or . in field access expressions. + /// + public static readonly PerLanguageOption2> QualifyFieldAccess = CreateOption( + CodeStyleOptionGroups.ThisOrMe, nameof(QualifyFieldAccess), + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_field"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyFieldAccess")}); + + /// + /// This option says if we should simplify away the . or . in property access expressions. + /// + public static readonly PerLanguageOption2> QualifyPropertyAccess = CreateOption( + CodeStyleOptionGroups.ThisOrMe, nameof(QualifyPropertyAccess), + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_property"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyPropertyAccess")}); + + /// + /// This option says if we should simplify away the . or . in method access expressions. + /// + public static readonly PerLanguageOption2> QualifyMethodAccess = CreateOption( + CodeStyleOptionGroups.ThisOrMe, nameof(QualifyMethodAccess), + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_method"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyMethodAccess")}); + + /// + /// This option says if we should simplify away the . or . in event access expressions. + /// + public static readonly PerLanguageOption2> QualifyEventAccess = CreateOption( + CodeStyleOptionGroups.ThisOrMe, nameof(QualifyEventAccess), + defaultValue: CodeStyleOption2.Default, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_qualification_for_event"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.QualifyEventAccess")}); + + /// + /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations + /// + public static readonly PerLanguageOption2> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( + CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), + defaultValue: TrueWithSilentEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_predefined_type_for_locals_parameters_members"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle")}); + + /// + /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression + /// + public static readonly PerLanguageOption2> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( + CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), + defaultValue: TrueWithSilentEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_predefined_type_for_member_access"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle")}); + + internal static readonly PerLanguageOption2> PreferObjectInitializer = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_object_initializer"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer")}); + + internal static readonly PerLanguageOption2> PreferCollectionInitializer = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_collection_initializer"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer")}); + + // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? + internal static readonly PerLanguageOption2 PreferObjectInitializer_FadeOutCode = new PerLanguageOption2( + "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), + defaultValue: false, + storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); + + internal static readonly PerLanguageOption2 PreferCollectionInitializer_FadeOutCode = new PerLanguageOption2( + "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), + defaultValue: false, + storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); + + internal static readonly PerLanguageOption2> PreferSimplifiedBooleanExpressions = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_simplified_boolean_expressions"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions")}); + + internal static readonly PerLanguageOption2 OperatorPlacementWhenWrapping = + CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, + nameof(OperatorPlacementWhenWrapping), + defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, + storageLocations: + new EditorConfigStorageLocation( + "dotnet_style_operator_placement_when_wrapping", + OperatorPlacementUtilities.Parse, + OperatorPlacementUtilities.GetEditorConfigString)); + + internal static readonly PerLanguageOption2> PreferCoalesceExpression = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_coalesce_expression"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression") }); + + internal static readonly PerLanguageOption2> PreferNullPropagation = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_null_propagation"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferNullPropagation") }); + + internal static readonly PerLanguageOption2> PreferExplicitTupleNames = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[] { + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_explicit_tuple_names"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames") }); + + internal static readonly PerLanguageOption2> PreferAutoProperties = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), + defaultValue: TrueWithSilentEnforcement, + storageLocations: new OptionStorageLocation2[] { + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_auto_properties"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferAutoProperties") }); + + internal static readonly PerLanguageOption2> PreferInferredTupleNames = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[] { + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_inferred_tuple_names"), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}") }); + + internal static readonly PerLanguageOption2> PreferInferredAnonymousTypeMemberNames = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[] { + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_inferred_anonymous_type_member_names"), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}") }); + + internal static readonly PerLanguageOption2> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_is_null_check_over_reference_equality_method"), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}") }); + + internal static readonly PerLanguageOption2> PreferConditionalExpressionOverAssignment = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), + defaultValue: TrueWithSilentEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_conditional_expression_over_assignment"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment")}); + + internal static readonly PerLanguageOption2> PreferConditionalExpressionOverReturn = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), + defaultValue: TrueWithSilentEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_conditional_expression_over_return"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn")}); + + internal static readonly PerLanguageOption2> PreferCompoundAssignment = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, + nameof(PreferCompoundAssignment), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_compound_assignment"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment") }); + + internal static readonly PerLanguageOption2> PreferSimplifiedInterpolation = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_prefer_simplified_interpolation"), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}") }); + + private static readonly CodeStyleOption2 s_preferNoneUnusedParametersPreference = + new CodeStyleOption2(default, NotificationOption2.None); + private static readonly CodeStyleOption2 s_preferAllMethodsUnusedParametersPreference = + new CodeStyleOption2(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); + + // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption and CodeQualityOptions + // and moving this option to CodeQualityOptions. + internal static readonly PerLanguageOption2> UnusedParameters = CreateOption( + CodeStyleOptionGroups.Parameter, + nameof(UnusedParameters), + defaultValue: s_preferAllMethodsUnusedParametersPreference, + storageLocations: new OptionStorageLocation2[]{ + new EditorConfigStorageLocation>( + "dotnet_code_quality_unused_parameters", + ParseUnusedParametersPreference, + o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference.Value)), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference") }); + + private static readonly CodeStyleOption2 s_requireAccessibilityModifiersDefault = + new CodeStyleOption2(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); + + internal static readonly PerLanguageOption2> RequireAccessibilityModifiers = + CreateOption( + CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), + defaultValue: s_requireAccessibilityModifiersDefault, + storageLocations: new OptionStorageLocation2[]{ + new EditorConfigStorageLocation>( + "dotnet_style_require_accessibility_modifiers", + s => ParseAccessibilityModifiersRequired(s), + GetAccessibilityModifiersRequiredEditorConfigString), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")}); + + internal static readonly PerLanguageOption2> PreferReadonly = CreateOption( + CodeStyleOptionGroups.Field, nameof(PreferReadonly), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + EditorConfigStorageLocation.ForBoolCodeStyleOption("dotnet_style_readonly_field"), + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferReadonly") }); + + internal static readonly Option2 FileHeaderTemplate = CreateCommonOption( + CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), + defaultValue: "", + EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); + + private static readonly BidirectionalMap s_accessibilityModifiersRequiredMap = + new BidirectionalMap(new[] + { + KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), + KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), + KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), + KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), + }); + + private static CodeStyleOption2 ParseAccessibilityModifiersRequired(string optionString) + { + if (TryGetCodeStyleValueAndOptionalNotification(optionString, + out var value, out var notificationOpt)) + { + if (value == "never") + { + // If they provide 'never', they don't need a notification level. + notificationOpt ??= NotificationOption2.Silent; + } + + if (notificationOpt is object) + { + Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); + return new CodeStyleOption2(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); + } + } + + return s_requireAccessibilityModifiersDefault; + } + + private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2 option) + { + // If they provide 'never', they don't need a notification level. + if (option.Notification == null) + { + Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); + return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never); + } + + Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); + return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}:{option.Notification.ToEditorConfigString()}"; + } + + private static readonly CodeStyleOption2 s_alwaysForClarityPreference = + new CodeStyleOption2(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); + + private static readonly CodeStyleOption2 s_neverIfUnnecessaryPreference = + new CodeStyleOption2(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); + + private static PerLanguageOption2> CreateParenthesesOption( + string fieldName, CodeStyleOption2 defaultValue, + string styleName) + { + return CreateOption( + CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, + storageLocations: new OptionStorageLocation2[]{ + new EditorConfigStorageLocation>( + styleName, + s => ParseParenthesesPreference(s, defaultValue), + v => GetParenthesesPreferenceEditorConfigString(v)), + new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")}); + } + + internal static readonly PerLanguageOption2> ArithmeticBinaryParentheses = + CreateParenthesesOption( + nameof(ArithmeticBinaryParentheses), + s_alwaysForClarityPreference, + "dotnet_style_parentheses_in_arithmetic_binary_operators"); + + internal static readonly PerLanguageOption2> OtherBinaryParentheses = + CreateParenthesesOption( + nameof(OtherBinaryParentheses), + s_alwaysForClarityPreference, + "dotnet_style_parentheses_in_other_binary_operators"); + + internal static readonly PerLanguageOption2> RelationalBinaryParentheses = + CreateParenthesesOption( + nameof(RelationalBinaryParentheses), + s_alwaysForClarityPreference, + "dotnet_style_parentheses_in_relational_binary_operators"); + + internal static readonly PerLanguageOption2> OtherParentheses = + CreateParenthesesOption( + nameof(OtherParentheses), + s_neverIfUnnecessaryPreference, + "dotnet_style_parentheses_in_other_operators"); + + private static readonly BidirectionalMap s_parenthesesPreferenceMap = + new BidirectionalMap(new[] + { + KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), + KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), + }); + + private static readonly BidirectionalMap s_unusedParametersPreferenceMap = + new BidirectionalMap(new[] + { + KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), + KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), + }); + + internal static readonly PerLanguageOption2> PreferSystemHashCode = CreateOption( + CodeStyleOptionGroups.ExpressionLevelPreferences, + nameof(PreferSystemHashCode), + defaultValue: TrueWithSuggestionEnforcement, + storageLocations: new OptionStorageLocation2[]{ + new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode") }); + + static CodeStyleOptions2() + { + // Note that the static constructor executes after all the static field initializers for the options have executed, + // and each field initializer adds the created option to s_allOptionsBuilder. + AllOptions = s_allOptionsBuilder.ToImmutable(); + } + + private static Optional> ParseParenthesesPreference( + string optionString, Optional> defaultValue) + { + if (TryGetCodeStyleValueAndOptionalNotification(optionString, + out var value, out var notificationOpt)) + { + Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); + return new CodeStyleOption2(s_parenthesesPreferenceMap.GetValueOrDefault(value), + notificationOpt ?? NotificationOption2.Silent); + } + + return defaultValue; + } + + private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2 option) + { + Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); + var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); + return option.Notification == null ? value : $"{value}:{option.Notification.ToEditorConfigString()}"; + } + + private static Optional> ParseUnusedParametersPreference(string optionString) + { + if (TryGetCodeStyleValueAndOptionalNotification(optionString, + out var value, out var notificationOpt)) + { + return new CodeStyleOption2( + s_unusedParametersPreferenceMap.GetValueOrDefault(value), notificationOpt ?? NotificationOption2.Suggestion); + } + + return s_preferNoneUnusedParametersPreference; + } + + private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2 option, UnusedParametersPreference defaultPreference) + { + Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); + var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultPreference); + return option.Notification == null ? value : $"{value}:{option.Notification.ToEditorConfigString()}"; + } + } + + internal static class CodeStyleOptionGroups + { + public static readonly OptionGroup Usings = new OptionGroup(CompilerExtensionsResources.Organize_usings, priority: 1); + public static readonly OptionGroup ThisOrMe = new OptionGroup(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); + public static readonly OptionGroup PredefinedTypeNameUsage = new OptionGroup(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); + public static readonly OptionGroup Parentheses = new OptionGroup(CompilerExtensionsResources.Parentheses_preferences, priority: 4); + public static readonly OptionGroup Modifier = new OptionGroup(CompilerExtensionsResources.Modifier_preferences, priority: 5); + public static readonly OptionGroup ExpressionLevelPreferences = new OptionGroup(CompilerExtensionsResources.Expression_level_preferences, priority: 6); + public static readonly OptionGroup Field = new OptionGroup(CompilerExtensionsResources.Field_preferences, priority: 7); + public static readonly OptionGroup Parameter = new OptionGroup(CompilerExtensionsResources.Parameter_preferences, priority: 8); + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ExpressionBodyPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ExpressionBodyPreference.cs index 6843bf94cb254..2a004f7a61ded 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ExpressionBodyPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ExpressionBodyPreference.cs @@ -2,11 +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. -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { /// /// Note: the order of this enum is important. We originally only supported two values, diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/NotificationOption2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/NotificationOption2.cs new file mode 100644 index 0000000000000..1a7508c09229e --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/NotificationOption2.cs @@ -0,0 +1,89 @@ +// 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. + +#nullable enable + +using System; + +#if CODE_STYLE +using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; +#endif + +namespace Microsoft.CodeAnalysis.CodeStyle +{ + /// + /// Offers different notification styles for enforcing + /// a code style. Under the hood, it simply maps to + /// + /// + /// This also supports various properties for databinding. + /// + /// + internal sealed partial class NotificationOption2 : IEquatable + { + /// + /// Name for the notification option. + /// + public string Name { get; set; } + + /// + /// Diagnostic severity associated with notification option. + /// + public ReportDiagnostic Severity + { + get; + set; + } + + /// + /// Notification option to disable or suppress an option with . + /// + public static readonly NotificationOption2 None = new NotificationOption2(WorkspacesResources.None, ReportDiagnostic.Suppress); + + /// + /// Notification option for a silent or hidden option with . + /// + public static readonly NotificationOption2 Silent = new NotificationOption2(WorkspacesResources.Refactoring_Only, ReportDiagnostic.Hidden); + + /// + /// Notification option for a suggestion or an info option with . + /// + public static readonly NotificationOption2 Suggestion = new NotificationOption2(WorkspacesResources.Suggestion, ReportDiagnostic.Info); + + /// + /// Notification option for a warning option with . + /// + public static readonly NotificationOption2 Warning = new NotificationOption2(WorkspacesResources.Warning, ReportDiagnostic.Warn); + + /// + /// Notification option for an error option with . + /// + public static readonly NotificationOption2 Error = new NotificationOption2(WorkspacesResources.Error, ReportDiagnostic.Error); + + private NotificationOption2(string name, ReportDiagnostic severity) + { + Name = name; + Severity = severity; + } + + public override string ToString() => Name; + + public override bool Equals(object? obj) + { + return ReferenceEquals(this, obj); + } + + public bool Equals(NotificationOption2? notificationOption2) + { + return ReferenceEquals(this, notificationOption2); + } + + public override int GetHashCode() + { + var hash = this.Name.GetHashCode(); + hash = unchecked((hash * (int)0xA5555529) + this.Severity.GetHashCode()); + return hash; + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/OperatorPlacementWhenWrappingPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/OperatorPlacementWhenWrappingPreference.cs index d1b9552de3139..956461f4f045e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/OperatorPlacementWhenWrappingPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/OperatorPlacementWhenWrappingPreference.cs @@ -2,12 +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. -#if CODE_STYLE -using Microsoft.CodeAnalysis.CodeStyle; -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { internal enum OperatorPlacementWhenWrappingPreference { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.cs index 6970e23020272..bf4329b68e49e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.cs @@ -2,11 +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. -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { internal enum ParenthesesPreference { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedParametersPreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedParametersPreference.cs index 27cd378da918d..cd7e60efe4c66 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedParametersPreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedParametersPreference.cs @@ -2,11 +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. -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { /// /// Preferences for flagging unused parameters. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedValuePreference.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedValuePreference.cs index 9d3e400466788..2cdfec4075136 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedValuePreference.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedValuePreference.cs @@ -2,11 +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. -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { /// /// Assignment preference for unused values from expression statements and assignments. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems index 9ea4066bf8e0a..620bf59187db3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensions.projitems @@ -172,8 +172,11 @@ + + + @@ -245,7 +248,8 @@ - + + @@ -295,6 +299,7 @@ + @@ -302,6 +307,22 @@ + + + + + + + + + + + + + + + + @@ -332,6 +353,7 @@ + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensionsResources.resx b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensionsResources.resx index 5e28c986c1d26..2178696150638 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensionsResources.resx +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CompilerExtensionsResources.resx @@ -258,4 +258,13 @@ Cast is redundant. + + Naming styles + + + Naming rules + + + Symbol specifications + \ No newline at end of file diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/GenerationOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/GenerationOptions.cs index e277ad647ab67..d30118f9255e2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/GenerationOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Editing/GenerationOptions.cs @@ -5,32 +5,27 @@ #nullable enable using System.Collections.Immutable; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -namespace Microsoft.CodeAnalysis.Internal.Editing -#else using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; + namespace Microsoft.CodeAnalysis.Editing -#endif { internal class GenerationOptions { - public static readonly PerLanguageOption PlaceSystemNamespaceFirst = new PerLanguageOption(nameof(GenerationOptions), + public static readonly PerLanguageOption2 PlaceSystemNamespaceFirst = new PerLanguageOption2(nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(PlaceSystemNamespaceFirst), defaultValue: true, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")}); - public static readonly PerLanguageOption SeparateImportDirectiveGroups = new PerLanguageOption( + public static readonly PerLanguageOption2 SeparateImportDirectiveGroups = new PerLanguageOption2( nameof(GenerationOptions), CodeStyleOptionGroups.Usings, nameof(SeparateImportDirectiveGroups), defaultValue: false, - storageLocations: new OptionStorageLocation[] { + storageLocations: new OptionStorageLocation2[] { EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")}); - public static readonly ImmutableArray AllOptions = ImmutableArray.Create( + public static readonly ImmutableArray AllOptions = ImmutableArray.Create( PlaceSystemNamespaceFirst, SeparateImportDirectiveGroups); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AnalyzerConfigOptionsExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AnalyzerConfigOptionsExtensions.cs index aefe2a5bf0d3b..93c085191627e 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AnalyzerConfigOptionsExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/AnalyzerConfigOptionsExtensions.cs @@ -4,11 +4,12 @@ using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Options; #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; +using TOption = Microsoft.CodeAnalysis.Options.IOption2; #else -using Microsoft.CodeAnalysis.Options; +using TOption = Microsoft.CodeAnalysis.Options.IOption; #endif namespace Microsoft.CodeAnalysis @@ -16,30 +17,28 @@ namespace Microsoft.CodeAnalysis internal static class AnalyzerConfigOptionsExtensions { #if CODE_STYLE - public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption option, string language) + public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2 option, string language) { // Language is not used for .editorconfig lookups _ = language; return GetOption(analyzerConfigOptions, option); } +#else + public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, Options.Option option) + => GetOptionWithAssertOnFailure(analyzerConfigOptions, option); + + public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, Options.PerLanguageOption option) + => GetOptionWithAssertOnFailure(analyzerConfigOptions, option); #endif - public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, Option option) - { - if (!TryGetEditorConfigOptionOrDefault(analyzerConfigOptions, option, out T value)) - { - // There are couple of reasons this assert might fire: - // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. - // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. - Debug.Fail("Failed to find a .editorconfig key for the option."); - value = option.DefaultValue; - } + public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, Option2 option) + => GetOptionWithAssertOnFailure(analyzerConfigOptions, option); - return value; - } + public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption2 option) + => GetOptionWithAssertOnFailure(analyzerConfigOptions, option); - public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, PerLanguageOption option) + private static T GetOptionWithAssertOnFailure(AnalyzerConfigOptions analyzerConfigOptions, TOption option) { if (!TryGetEditorConfigOptionOrDefault(analyzerConfigOptions, option, out T value)) { @@ -47,19 +46,19 @@ public static T GetOption(this AnalyzerConfigOptions analyzerConfigOptions, P // 1. Attempting to access an option which does not have an IEditorConfigStorageLocation. // 2. Attempting to access an option which is not exposed from any option provider, i.e. IOptionProvider.Options. Debug.Fail("Failed to find a .editorconfig key for the option."); - value = option.DefaultValue; + value = (T)option.DefaultValue; } return value; } - public static bool TryGetEditorConfigOptionOrDefault(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, out T value) + public static bool TryGetEditorConfigOptionOrDefault(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: true, out value); - public static bool TryGetEditorConfigOption(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, out T value) + public static bool TryGetEditorConfigOption(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, out T value) => TryGetEditorConfigOption(analyzerConfigOptions, option, useDefaultIfMissing: false, out value); - private static bool TryGetEditorConfigOption(this AnalyzerConfigOptions analyzerConfigOptions, IOption option, bool useDefaultIfMissing, out T value) + private static bool TryGetEditorConfigOption(this AnalyzerConfigOptions analyzerConfigOptions, TOption option, bool useDefaultIfMissing, out T value) { var hasEditorConfigStorage = false; foreach (var storageLocation in option.StorageLocations) diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/NotificationOptionExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/NotificationOptionExtensions.cs index fae1a025fab05..0d26e682103fa 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/NotificationOptionExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/NotificationOptionExtensions.cs @@ -4,15 +4,11 @@ using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.CodeStyle -#endif { internal static class NotificationOptionExtensions { - public static string ToEditorConfigString(this NotificationOption notificationOption) + public static string ToEditorConfigString(this NotificationOption2 notificationOption) => notificationOption.Severity.ToEditorConfigString(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs index e5c2f7d0d53b8..bf44e66f0a7ba 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ReportDiagnosticExtensions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics @@ -79,5 +80,30 @@ public static string ToEditorConfigString(this ReportDiagnostic reportDiagnostic _ => throw ExceptionUtilities.UnexpectedValue(reportDiagnostic) }; } + + public static NotificationOption2 ToNotificationOption(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity) + { + switch (reportDiagnostic.WithDefaultSeverity(defaultSeverity)) + { + case ReportDiagnostic.Error: + return NotificationOption2.Error; + + case ReportDiagnostic.Warn: + return NotificationOption2.Warning; + + case ReportDiagnostic.Info: + return NotificationOption2.Suggestion; + + case ReportDiagnostic.Hidden: + return NotificationOption2.Silent; + + case ReportDiagnostic.Suppress: + return NotificationOption2.None; + + case ReportDiagnostic.Default: + default: + throw ExceptionUtilities.UnexpectedValue(reportDiagnostic); + } + } } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Fading/FadingOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Fading/FadingOptions.cs index 42dbbecfb6e6a..7b7d5602ff0d8 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Fading/FadingOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Fading/FadingOptions.cs @@ -4,21 +4,17 @@ #nullable enable -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif namespace Microsoft.CodeAnalysis.Fading { internal static class FadingOptions { - public static readonly PerLanguageOption FadeOutUnusedImports = new PerLanguageOption( + public static readonly PerLanguageOption2 FadeOutUnusedImports = new PerLanguageOption2( nameof(FadingOptions), nameof(FadeOutUnusedImports), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(FadeOutUnusedImports)}")); - public static readonly PerLanguageOption FadeOutUnreachableCode = new PerLanguageOption( + public static readonly PerLanguageOption2 FadeOutUnreachableCode = new PerLanguageOption2( nameof(FadingOptions), nameof(FadeOutUnreachableCode), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(FadeOutUnreachableCode)}")); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs index eac38fa943617..2c419ac1d16c7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs @@ -110,8 +110,8 @@ public void Initialize( var initialOperation = indentationOperations[0]; var baseIndentationFinder = new BottomUpBaseIndentationFinder( formattingRules, - this.Options.GetOption(FormattingOptions.TabSize), - this.Options.GetOption(FormattingOptions.IndentationSize), + this.Options.GetOption(FormattingOptions2.TabSize), + this.Options.GetOption(FormattingOptions2.IndentationSize), _tokenStream); var initialIndentation = baseIndentationFinder.GetIndentationOfCurrentPosition( rootNode, @@ -204,7 +204,7 @@ public void AddIndentBlockOperation(IndentBlockOperation operation) var inseparableRegionStartingPosition = operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken).FullSpan.Start : operation.BaseToken.FullSpan.Start; var relativeIndentationGetter = new Lazy(() => { - var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions.IndentationSize); + var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); // baseIndentation is calculated for the adjusted token if option is RelativeToFirstTokenOnBaseTokenLine var baseIndentation = _tokenStream.GetCurrentColumn(operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? @@ -237,7 +237,7 @@ public void AddIndentBlockOperation(IndentBlockOperation operation) if (indentationData == null) { // no previous indentation - var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions.IndentationSize); + var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, indentation)); _indentationMap.Add(intervalTreeSpan); return; @@ -246,7 +246,7 @@ public void AddIndentBlockOperation(IndentBlockOperation operation) // get indentation based on its previous indentation var indentationGetter = new Lazy(() => { - var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions.IndentationSize); + var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); return indentationData.Indentation + indentationDelta; }, isThreadSafe: true); diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.FormattedWhitespace.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.FormattedWhitespace.cs index 449bc600382cd..d8cb95b37a7ac 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.FormattedWhitespace.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.FormattedWhitespace.cs @@ -23,7 +23,7 @@ public FormattedWhitespace(AnalyzerConfigOptions options, int lineBreaks, int in this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, indentation); - _newString = CreateString(this.Options.GetOption(FormattingOptions.NewLine)); + _newString = CreateString(this.Options.GetOption(FormattingOptions2.NewLine)); } private string CreateString(string newLine) @@ -36,7 +36,7 @@ private string CreateString(string newLine) builder.Append(newLine); } - builder.AppendIndentationString(this.Spaces, this.Options.GetOption(FormattingOptions.UseTabs), this.Options.GetOption(FormattingOptions.TabSize)); + builder.AppendIndentationString(this.Spaces, this.Options.GetOption(FormattingOptions2.UseTabs), this.Options.GetOption(FormattingOptions2.TabSize)); return StringBuilderPool.ReturnAndFree(builder); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs index 5e4b728a8e9c6..6d85d64944697 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs @@ -67,11 +67,11 @@ protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bo useTriviaAsItIs && lineBreaks > 0 && lineBreaks <= LineBreakCacheSize && - indentation % this.Options.GetOption(FormattingOptions.IndentationSize) == 0; + indentation % this.Options.GetOption(FormattingOptions2.IndentationSize) == 0; if (canUseCache) { - var indentationLevel = indentation / this.Options.GetOption(FormattingOptions.IndentationSize); + var indentationLevel = indentation / this.Options.GetOption(FormattingOptions2.IndentationSize); if (indentationLevel < IndentationLevelCacheSize) { var lineIndex = lineBreaks - 1; @@ -94,7 +94,7 @@ private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel) // set up caches if (_whitespaces[lineIndex, indentationLevel] == null) { - var indentation = indentationLevel * this.Options.GetOption(FormattingOptions.IndentationSize); + var indentation = indentationLevel * this.Options.GetOption(FormattingOptions2.IndentationSize); var triviaInfo = new Whitespace(this.Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language); Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.cs index 3a7aebac6bbf9..bba37a97787a6 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.cs @@ -330,7 +330,7 @@ public void GetTokenLength(SyntaxToken token, out int length, out bool onMultipl { // get indentation from last line of the text onMultipleLines = true; - length = text.GetTextColumn(_options.GetOption(FormattingOptions.TabSize), initialColumn: 0); + length = text.GetTextColumn(_options.GetOption(FormattingOptions2.TabSize), initialColumn: 0); return; } @@ -340,8 +340,8 @@ public void GetTokenLength(SyntaxToken token, out int length, out bool onMultipl if (text.ContainsTab()) { // do expansive calculation - var initialColumn = _treeData.GetOriginalColumn(_options.GetOption(FormattingOptions.TabSize), token); - length = text.ConvertTabToSpace(_options.GetOption(FormattingOptions.TabSize), initialColumn, text.Length); + var initialColumn = _treeData.GetOriginalColumn(_options.GetOption(FormattingOptions2.TabSize), token); + length = text.ConvertTabToSpace(_options.GetOption(FormattingOptions2.TabSize), initialColumn, text.Length); return; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.IndentStyle.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.IndentStyle.cs new file mode 100644 index 0000000000000..fee8a8256aaab --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.IndentStyle.cs @@ -0,0 +1,22 @@ +// 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. + +#nullable enable + +namespace Microsoft.CodeAnalysis.Formatting +{ +#if CODE_STYLE + internal static class FormattingOptions +#else + public static partial class FormattingOptions +#endif + { + public enum IndentStyle + { + None = 0, + Block = 1, + Smart = 2 + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs similarity index 69% rename from src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs index 707ce6ef8ce3b..d1ad86b630d0a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/FormattingOptions2.cs @@ -7,37 +7,35 @@ using System; using System.Collections.Immutable; using Roslyn.Utilities; +using Microsoft.CodeAnalysis.Options; #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; -#else -using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.Formatting { - public static class FormattingOptions + internal static class FormattingOptions2 { - private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); + private static readonly ImmutableArray.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder(); - internal static ImmutableArray AllOptions { get; } + internal static ImmutableArray AllOptions { get; } - private static PerLanguageOption CreatePerLanguageOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + private static PerLanguageOption2 CreatePerLanguageOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { - var option = new PerLanguageOption(nameof(FormattingOptions), group, name, defaultValue, storageLocations); + var option = new PerLanguageOption2(nameof(FormattingOptions), group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } - private static Option CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) + private static Option2 CreateOption(OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) { - var option = new Option(nameof(FormattingOptions), group, name, defaultValue, storageLocations); + var option = new Option2(nameof(FormattingOptions), group, name, defaultValue, storageLocations); s_allOptionsBuilder.Add(option); return option; } - public static PerLanguageOption UseTabs { get; } = CreatePerLanguageOption( + public static PerLanguageOption2 UseTabs { get; } = CreatePerLanguageOption( FormattingOptionGroups.IndentationAndSpacing, nameof(UseTabs), defaultValue: false, storageLocations: new EditorConfigStorageLocation( @@ -46,23 +44,23 @@ private static Option CreateOption(OptionGroup group, string name, T defau isSet => isSet ? "tab" : "space")); // This is also serialized by the Visual Studio-specific LanguageSettingsPersister - public static PerLanguageOption TabSize { get; } = CreatePerLanguageOption( + public static PerLanguageOption2 TabSize { get; } = CreatePerLanguageOption( FormattingOptionGroups.IndentationAndSpacing, nameof(TabSize), defaultValue: 4, storageLocations: EditorConfigStorageLocation.ForInt32Option("tab_width")); // This is also serialized by the Visual Studio-specific LanguageSettingsPersister - public static PerLanguageOption IndentationSize { get; } = CreatePerLanguageOption( + public static PerLanguageOption2 IndentationSize { get; } = CreatePerLanguageOption( FormattingOptionGroups.IndentationAndSpacing, nameof(IndentationSize), defaultValue: 4, storageLocations: EditorConfigStorageLocation.ForInt32Option("indent_size")); // This is also serialized by the Visual Studio-specific LanguageSettingsPersister - public static PerLanguageOption SmartIndent { get; } = CreatePerLanguageOption( + public static PerLanguageOption2 SmartIndent { get; } = CreatePerLanguageOption( FormattingOptionGroups.IndentationAndSpacing, nameof(SmartIndent), - defaultValue: IndentStyle.Smart); + defaultValue: FormattingOptions.IndentStyle.Smart); - public static PerLanguageOption NewLine { get; } = CreatePerLanguageOption( + public static PerLanguageOption2 NewLine { get; } = CreatePerLanguageOption( FormattingOptionGroups.NewLine, nameof(NewLine), defaultValue: Environment.NewLine, storageLocations: new EditorConfigStorageLocation( @@ -70,7 +68,7 @@ private static Option CreateOption(OptionGroup group, string name, T defau ParseEditorConfigEndOfLine, GetEndOfLineEditorConfigString)); - internal static Option InsertFinalNewLine { get; } = CreateOption( + internal static Option2 InsertFinalNewLine { get; } = CreateOption( FormattingOptionGroups.NewLine, nameof(InsertFinalNewLine), defaultValue: false, storageLocations: EditorConfigStorageLocation.ForBoolOption("insert_final_newline")); @@ -83,7 +81,7 @@ private static Option CreateOption(OptionGroup group, string name, T defau /// default indentation of at least 16 (for namespace, class, member, plus the final construct /// indentation). /// - internal static Option PreferredWrappingColumn { get; } = new Option( + internal static Option2 PreferredWrappingColumn { get; } = new Option2( nameof(FormattingOptions), FormattingOptionGroups.NewLine, nameof(PreferredWrappingColumn), @@ -103,24 +101,17 @@ private static Optional ParseEditorConfigEndOfLine(string endOfLineValue private static string GetEndOfLineEditorConfigString(string option) => s_parenthesesPreferenceMap.TryGetKey(option, out var editorConfigString) ? editorConfigString : "unset"; - internal static Option AllowDisjointSpanMerging { get; } = CreateOption(OptionGroup.Default, nameof(AllowDisjointSpanMerging), defaultValue: false); + internal static Option2 AllowDisjointSpanMerging { get; } = CreateOption(OptionGroup.Default, nameof(AllowDisjointSpanMerging), defaultValue: false); - internal static readonly PerLanguageOption AutoFormattingOnReturn = CreatePerLanguageOption(OptionGroup.Default, nameof(AutoFormattingOnReturn), defaultValue: true, + internal static readonly PerLanguageOption2 AutoFormattingOnReturn = CreatePerLanguageOption(OptionGroup.Default, nameof(AutoFormattingOnReturn), defaultValue: true, storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Return")); - static FormattingOptions() + static FormattingOptions2() { // Note that the static constructor executes after all the static field initializers for the options have executed, // and each field initializer adds the created option to s_allOptionsBuilder. AllOptions = s_allOptionsBuilder.ToImmutable(); } - - public enum IndentStyle - { - None = 0, - Block = 1, - Smart = 2 - } } internal static class FormattingOptionGroups diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/AbstractTriviaFormatter.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/AbstractTriviaFormatter.cs index 4610065ae6267..5b8e4fa83cddc 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/AbstractTriviaFormatter.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/TriviaEngine/AbstractTriviaFormatter.cs @@ -576,8 +576,8 @@ private int GetIndentation() return this.Spaces; } - var position = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions.TabSize), initialColumn, index); - var tokenPosition = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions.TabSize), initialColumn, lastText.Length); + var position = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, index); + var tokenPosition = lastText.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, lastText.Length); return this.Spaces - (tokenPosition - position); } @@ -749,8 +749,8 @@ private void AddWhitespaceTrivia( return; } - var useTabs = this.Options.GetOption(FormattingOptions.UseTabs); - var tabSize = this.Options.GetOption(FormattingOptions.TabSize); + var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs); + var tabSize = this.Options.GetOption(FormattingOptions2.TabSize); // space indicates indentation if (delta.Lines > 0 || lineColumn.Column == 0) @@ -767,7 +767,7 @@ private string GetWhitespaceString(LineColumn lineColumn, LineColumnDelta delta) { var sb = StringBuilderPool.Allocate(); - var newLine = this.Options.GetOption(FormattingOptions.NewLine); + var newLine = this.Options.GetOption(FormattingOptions2.NewLine); for (var i = 0; i < delta.Lines; i++) { sb.Append(newLine); @@ -778,8 +778,8 @@ private string GetWhitespaceString(LineColumn lineColumn, LineColumnDelta delta) return StringBuilderPool.ReturnAndFree(sb); } - var useTabs = this.Options.GetOption(FormattingOptions.UseTabs); - var tabSize = this.Options.GetOption(FormattingOptions.TabSize); + var useTabs = this.Options.GetOption(FormattingOptions2.UseTabs); + var tabSize = this.Options.GetOption(FormattingOptions2.TabSize); // space indicates indentation if (delta.Lines > 0 || lineColumn.Column == 0) @@ -864,7 +864,7 @@ private LineColumnDelta GetLineColumnOfWhitespace( var text = trivia2.ToFullString(); return new LineColumnDelta( lines: 0, - spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions.TabSize), lineColumn.With(whitespaceBetween).Column, text.Length), + spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), lineColumn.With(whitespaceBetween).Column, text.Length), whitespaceOnly: true, forceUpdate: false); } @@ -900,13 +900,13 @@ protected LineColumnDelta GetLineColumnDelta(int initialColumn, string text) { return new LineColumnDelta( lines: text.GetNumberOfLineBreaks(), - spaces: lineText.GetColumnFromLineOffset(lineText.Length, this.Options.GetOption(FormattingOptions.TabSize)), + spaces: lineText.GetColumnFromLineOffset(lineText.Length, this.Options.GetOption(FormattingOptions2.TabSize)), whitespaceOnly: IsNullOrWhitespace(lineText)); } return new LineColumnDelta( lines: 0, - spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions.TabSize), initialColumn, text.Length), + spaces: text.ConvertTabToSpace(this.Options.GetOption(FormattingOptions2.TabSize), initialColumn, text.Length), whitespaceOnly: IsNullOrWhitespace(lineText)); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionIdOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionIdOptions.cs index 2179e564f8c60..1d382f5b0098c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionIdOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionIdOptions.cs @@ -4,31 +4,26 @@ using System; using System.Collections.Concurrent; - -#if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; -#else using Microsoft.CodeAnalysis.Options; -#endif namespace Microsoft.CodeAnalysis.Internal.Log { internal static class FunctionIdOptions { - private static readonly ConcurrentDictionary> s_options = - new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary> s_options = + new ConcurrentDictionary>(); - private static readonly Func> s_optionCreator = CreateOption; + private static readonly Func> s_optionCreator = CreateOption; - private static Option CreateOption(FunctionId id) + private static Option2 CreateOption(FunctionId id) { var name = Enum.GetName(typeof(FunctionId), id); - return new Option(nameof(FunctionIdOptions), name, defaultValue: false, + return new Option2(nameof(FunctionIdOptions), name, defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name)); } - public static Option GetOption(FunctionId id) + public static Option2 GetOption(FunctionId id) { return s_options.GetOrAdd(id, s_optionCreator); } diff --git a/src/Workspaces/Core/Portable/Simplification/NamingStyleOptions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs similarity index 66% rename from src/Workspaces/Core/Portable/Simplification/NamingStyleOptions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs index 2ed64f9ea6606..98d1859c6a07f 100644 --- a/src/Workspaces/Core/Portable/Simplification/NamingStyleOptions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleOptions.cs @@ -3,19 +3,11 @@ // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; - -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else using Microsoft.CodeAnalysis.Options; + namespace Microsoft.CodeAnalysis.Simplification -#endif { -#if CODE_STYLE - public static class NamingStyleOptions -#else internal static class NamingStyleOptions -#endif { // Use 'SimplificationOptions' for back compat as the below option 'NamingPreferences' was defined with feature name 'SimplificationOptions'. private const string FeatureName = "SimplificationOptions"; @@ -24,14 +16,14 @@ internal static class NamingStyleOptions /// This option describes the naming rules that should be applied to specified categories of symbols, /// and the level to which those rules should be enforced. /// - internal static PerLanguageOption NamingPreferences { get; } = new PerLanguageOption(FeatureName, nameof(NamingPreferences), defaultValue: NamingStylePreferences.Default, - storageLocations: new OptionStorageLocation[] { + internal static PerLanguageOption2 NamingPreferences { get; } = new PerLanguageOption2(FeatureName, nameof(NamingPreferences), defaultValue: NamingStylePreferences.Default, + storageLocations: new OptionStorageLocation2[] { new NamingStylePreferenceEditorConfigStorageLocation(), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NamingPreferences5"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NamingPreferences") }); - public static OptionKey GetNamingPreferencesOptionKey(string language) - => new OptionKey(NamingPreferences, language); + public static OptionKey2 GetNamingPreferencesOptionKey(string language) + => new OptionKey2(NamingPreferences, language); } } diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation.cs similarity index 73% rename from src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation.cs index a3d9c5855a294..3c3e30bcbc04b 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation.cs @@ -7,11 +7,7 @@ using System; using Microsoft.CodeAnalysis.CodeStyle; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { internal static class EditorConfigStorageLocation { @@ -24,11 +20,11 @@ public static EditorConfigStorageLocation ForInt32Option(string keyName) public static EditorConfigStorageLocation ForStringOption(string keyName, string emptyStringRepresentation) => new EditorConfigStorageLocation(keyName, s_parseString, (string value) => string.IsNullOrEmpty(value) ? emptyStringRepresentation : s_getStringEditorConfigStringForValue(value)); - public static EditorConfigStorageLocation> ForBoolCodeStyleOption(string keyName) - => new EditorConfigStorageLocation>(keyName, s_parseBoolCodeStyleOption, s_getBoolCodeStyleOptionEditorConfigStringForValue); + public static EditorConfigStorageLocation> ForBoolCodeStyleOption(string keyName) + => new EditorConfigStorageLocation>(keyName, s_parseBoolCodeStyleOption, s_getBoolCodeStyleOptionEditorConfigStringForValue); - public static EditorConfigStorageLocation> ForStringCodeStyleOption(string keyName) - => new EditorConfigStorageLocation>(keyName, s_parseStringCodeStyleOption, s_getStringCodeStyleOptionEditorConfigStringForValue); + public static EditorConfigStorageLocation> ForStringCodeStyleOption(string keyName) + => new EditorConfigStorageLocation>(keyName, s_parseStringCodeStyleOption, s_getStringCodeStyleOptionEditorConfigStringForValue); private static readonly Func> s_parseBool = ParseBool; private static Optional ParseBool(string str) @@ -58,18 +54,18 @@ private static Optional ParseString(string str) private static readonly Func s_getStringEditorConfigStringForValue = GetStringEditorConfigStringForValue; private static string GetStringEditorConfigStringForValue(string value) => value.ToString().Replace("\r", "\\r").Replace("\n", "\\n"); - private static readonly Func>> s_parseBoolCodeStyleOption = ParseBoolCodeStyleOption; - private static Optional> ParseBoolCodeStyleOption(string str) - => CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(str, out var result) ? result : new Optional>(); - private static readonly Func, string> s_getBoolCodeStyleOptionEditorConfigStringForValue = GetBoolCodeStyleOptionEditorConfigStringForValue; - private static string GetBoolCodeStyleOptionEditorConfigStringForValue(CodeStyleOption value) + private static readonly Func>> s_parseBoolCodeStyleOption = ParseBoolCodeStyleOption; + private static Optional> ParseBoolCodeStyleOption(string str) + => CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(str, out var result) ? result : new Optional>(); + private static readonly Func, string> s_getBoolCodeStyleOptionEditorConfigStringForValue = GetBoolCodeStyleOptionEditorConfigStringForValue; + private static string GetBoolCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2 value) => $"{(value.Value ? "true" : "false")}:{value.Notification.ToEditorConfigString()}"; - private static readonly Func>> s_parseStringCodeStyleOption = ParseStringCodeStyleOption; - private static Optional> ParseStringCodeStyleOption(string str) - => CodeStyleHelpers.TryParseStringEditorConfigCodeStyleOption(str, out var result) ? result : new Optional>(); - private static readonly Func, string> s_getStringCodeStyleOptionEditorConfigStringForValue = GetStringCodeStyleOptionEditorConfigStringForValue; - private static string GetStringCodeStyleOptionEditorConfigStringForValue(CodeStyleOption value) + private static readonly Func>> s_parseStringCodeStyleOption = ParseStringCodeStyleOption; + private static Optional> ParseStringCodeStyleOption(string str) + => CodeStyleHelpers.TryParseStringEditorConfigCodeStyleOption(str, out var result) ? result : new Optional>(); + private static readonly Func, string> s_getStringCodeStyleOptionEditorConfigStringForValue = GetStringCodeStyleOptionEditorConfigStringForValue; + private static string GetStringCodeStyleOptionEditorConfigStringForValue(CodeStyleOption2 value) => $"{value.Value.ToLowerInvariant()}:{value.Notification.ToEditorConfigString()}"; } } diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs similarity index 94% rename from src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs index bbe3a173becae..ad623a811736f 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs @@ -6,11 +6,7 @@ using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { internal static class EditorConfigStorageLocationExtensions { diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation`1.cs similarity index 97% rename from src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation`1.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation`1.cs index 8d14132fe9f48..d58de2c4ea5db 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/EditorConfigStorageLocation`1.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation`1.cs @@ -15,16 +15,12 @@ using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { /// /// Specifies that an option should be read from an .editorconfig file. /// - internal sealed class EditorConfigStorageLocation : OptionStorageLocation, IEditorConfigStorageLocation2 + internal sealed class EditorConfigStorageLocation : OptionStorageLocation2, IEditorConfigStorageLocation2 { public string KeyName { get; } diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation.cs similarity index 78% rename from src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation.cs index 6d324c57865eb..baa9b45669561 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation.cs @@ -7,15 +7,9 @@ using System; using System.Collections.Generic; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -{ - public interface IEditorConfigStorageLocation -#else namespace Microsoft.CodeAnalysis.Options { internal interface IEditorConfigStorageLocation -#endif { bool TryGetOption(IReadOnlyDictionary rawOptions, Type type, out object? value); } diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation2.cs similarity index 88% rename from src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation2.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation2.cs index 71b068601abdc..35dafdbe4db78 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/IEditorConfigStorageLocation2.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation2.cs @@ -6,17 +6,13 @@ #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; +#else +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -{ - public interface IEditorConfigStorageLocation2 : IEditorConfigStorageLocation -#else namespace Microsoft.CodeAnalysis.Options { internal interface IEditorConfigStorageLocation2 : IEditorConfigStorageLocation -#endif { string KeyName { get; } diff --git a/src/Workspaces/Core/Portable/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs similarity index 93% rename from src/Workspaces/Core/Portable/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs index 102f9cfebeac3..1a763eaabb583 100644 --- a/src/Workspaces/Core/Portable/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs @@ -8,15 +8,12 @@ using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; +using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { - internal sealed class NamingStylePreferenceEditorConfigStorageLocation : OptionStorageLocation, IEditorConfigStorageLocation + internal sealed class NamingStylePreferenceEditorConfigStorageLocation : OptionStorageLocation2, IEditorConfigStorageLocation { public bool TryGetOption(IReadOnlyDictionary rawOptions, Type type, out object result) { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs new file mode 100644 index 0000000000000..9626c653e3f6f --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOption2.cs @@ -0,0 +1,29 @@ +// 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. + +#nullable enable + +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Options +{ + internal interface IOption2 : IEquatable +#if !CODE_STYLE + , IOption +#endif + { + OptionDefinition OptionDefinition { get; } + +#if CODE_STYLE + string Feature { get; } + string Name { get; } + Type Type { get; } + object? DefaultValue { get; } + bool IsPerLanguage { get; } + + ImmutableArray StorageLocations { get; } +#endif + } +} diff --git a/src/Workspaces/Core/Portable/Options/IOptionWithGroup.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionWithGroup.cs similarity index 69% rename from src/Workspaces/Core/Portable/Options/IOptionWithGroup.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionWithGroup.cs index 8c77cfe46cf7c..04deca9e88548 100644 --- a/src/Workspaces/Core/Portable/Options/IOptionWithGroup.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionWithGroup.cs @@ -4,16 +4,12 @@ #nullable enable -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { /// - /// Group/sub-feature associated with an . + /// Group/sub-feature associated with an . /// - internal interface IOptionWithGroup : IOption + internal interface IOptionWithGroup : IOption2 { /// /// Group/sub-feature for this option. diff --git a/src/Workspaces/Core/Portable/Options/LocalUserProfileStorageLocation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/LocalUserProfileStorageLocation.cs similarity index 86% rename from src/Workspaces/Core/Portable/Options/LocalUserProfileStorageLocation.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/LocalUserProfileStorageLocation.cs index eda7956b742ab..b9535ddc60956 100644 --- a/src/Workspaces/Core/Portable/Options/LocalUserProfileStorageLocation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/LocalUserProfileStorageLocation.cs @@ -4,16 +4,14 @@ #nullable enable -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else +using Microsoft.CodeAnalysis.Options; + namespace Microsoft.CodeAnalysis.Options -#endif { /// /// Specifies that the option should be stored into the user's local registry hive. /// - internal sealed class LocalUserProfileStorageLocation : OptionStorageLocation + internal sealed class LocalUserProfileStorageLocation : OptionStorageLocation2 { public string KeyName { get; } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2`1.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2`1.cs new file mode 100644 index 0000000000000..97fc808bf35d5 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2`1.cs @@ -0,0 +1,123 @@ +// 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. + +#nullable enable + +using System; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Options +{ + /// + /// Marker interface for language specific options. + /// + internal interface ILanguageSpecificOption : IOptionWithGroup + { + } + + /// + /// Marker interface for language specific options. + /// + internal interface ILanguageSpecificOption : ILanguageSpecificOption + { + } + + /// + /// An global option. An instance of this class can be used to access an option value from an OptionSet. + /// + internal partial class Option2 : ILanguageSpecificOption + { + public OptionDefinition OptionDefinition { get; } + + /// + public string Feature => OptionDefinition.Feature; + + /// + internal OptionGroup Group => OptionDefinition.Group; + + /// + public string Name => OptionDefinition.Name; + + /// + public T DefaultValue => (T)OptionDefinition.DefaultValue!; + + /// + public Type Type => OptionDefinition.Type; + + /// + /// Storage locations for the option. + /// + public ImmutableArray StorageLocations { get; } + + public Option2(string feature, string name, T defaultValue) + : this(feature, name, defaultValue, storageLocations: Array.Empty()) + { + } + + public Option2(string feature, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) + { + } + + internal Option2(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) + { + } + + internal Option2(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray storageLocations) + { + if (string.IsNullOrWhiteSpace(feature)) + { + throw new ArgumentNullException(nameof(feature)); + } + + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException(nameof(name)); + } + + OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false); + this.StorageLocations = storageLocations; + } + +#if CODE_STYLE + object? IOption2.DefaultValue => this.DefaultValue; + + bool IOption2.IsPerLanguage => false; +#else + object? IOption.DefaultValue => this.DefaultValue; + + bool IOption.IsPerLanguage => false; + + ImmutableArray IOption.StorageLocations + => this.StorageLocations.As(); +#endif + + OptionGroup IOptionWithGroup.Group => this.Group; + + OptionDefinition IOption2.OptionDefinition => OptionDefinition; + + public override string ToString() => OptionDefinition.ToString(); + + public override int GetHashCode() => OptionDefinition.GetHashCode(); + + public override bool Equals(object? obj) => Equals(obj as IOption2); + + public bool Equals(IOption2? other) + { + if (ReferenceEquals(this, other)) + { + return true; + } + + return OptionDefinition == other?.OptionDefinition; + } + + public static implicit operator OptionKey2(Option2 option) + { + return new OptionKey2(option); + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs new file mode 100644 index 0000000000000..930491de0366d --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.cs @@ -0,0 +1,119 @@ +// 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. + +#nullable enable + +using System; +using System.Diagnostics; +using Microsoft.CodeAnalysis.CodeStyle; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Options +{ + [NonDefaultable] + internal readonly struct OptionDefinition : IEquatable + { + /// + /// Feature this option is associated with. + /// + public string Feature { get; } + + /// + /// Optional group/sub-feature for this option. + /// + internal OptionGroup Group { get; } + + /// + /// The name of the option. + /// + public string Name { get; } + + /// + /// The default value of the option. + /// + public object? DefaultValue { get; } + + /// + /// The type of the option value. + /// + public Type Type { get; } + + /// + /// Flag indicating if this is a per-language option or a language specific option. + /// + public bool IsPerLanguage { get; } + + public OptionDefinition(string feature, OptionGroup group, string name, object? defaultValue, Type type, bool isPerLanguage) + { + if (string.IsNullOrWhiteSpace(feature)) + { + throw new ArgumentNullException(nameof(feature)); + } + + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException(nameof(name)); + } + + this.Feature = feature; + this.Group = group ?? throw new ArgumentNullException(nameof(group)); + this.Name = name; + this.DefaultValue = defaultValue; + this.Type = type ?? throw new ArgumentNullException(nameof(type)); + this.IsPerLanguage = isPerLanguage; + } + + public override bool Equals(object? obj) + { + return obj is OptionDefinition key && + Equals(key); + } + + public bool Equals(OptionDefinition other) + { + var equals = this.Name == other.Name && + this.Feature == other.Feature && + this.Group == other.Group && + this.IsPerLanguage == other.IsPerLanguage; + + if (equals && !(this.DefaultValue is ICodeStyleOption)) + { + equals = Equals(this.DefaultValue, other.DefaultValue) && this.Type == other.Type; + } + + return equals; + } + + public override int GetHashCode() + { + var hash = this.Feature.GetHashCode(); + hash = unchecked((hash * (int)0xA5555529) + this.Group.GetHashCode()); + hash = unchecked((hash * (int)0xA5555529) + this.Name.GetHashCode()); + hash = unchecked((hash * (int)0xA5555529) + this.IsPerLanguage.GetHashCode()); + + if (!(this.DefaultValue is ICodeStyleOption)) + { + hash = unchecked((hash * (int)0xA5555529) + this.DefaultValue?.GetHashCode() ?? 0); + hash = unchecked((hash * (int)0xA5555529) + this.Type.GetHashCode()); + } + + return hash; + } + + public override string ToString() + { + return string.Format("{0} - {1}", this.Feature, this.Name); + } + + public static bool operator ==(OptionDefinition left, OptionDefinition right) + { + return left.Equals(right); + } + + public static bool operator !=(OptionDefinition left, OptionDefinition right) + { + return !left.Equals(right); + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/OptionGroup.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs similarity index 87% rename from src/Workspaces/Core/Portable/Options/OptionGroup.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs index 4b65e0a176a22..bdeba731c3195 100644 --- a/src/Workspaces/Core/Portable/Options/OptionGroup.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs @@ -6,14 +6,10 @@ using System; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { /// - /// Group/sub-feature associated with an . + /// Group/sub-feature associated with an option. /// internal sealed class OptionGroup { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionKey2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionKey2.cs new file mode 100644 index 0000000000000..dc6b377990fcb --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionKey2.cs @@ -0,0 +1,84 @@ +// 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. + +#nullable enable + +using System; +using Roslyn.Utilities; + +#if CODE_STYLE +using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources; +#endif + +namespace Microsoft.CodeAnalysis.Options +{ + [NonDefaultable] + internal readonly partial struct OptionKey2 : IEquatable + { + public IOption2 Option { get; } + public string? Language { get; } + + public OptionKey2(IOption2 option, string? language = null) + { + if (language != null && !option.IsPerLanguage) + { + throw new ArgumentException(WorkspacesResources.A_language_name_cannot_be_specified_for_this_option); + } + else if (language == null && option.IsPerLanguage) + { + throw new ArgumentNullException(WorkspacesResources.A_language_name_must_be_specified_for_this_option); + } + + this.Option = option ?? throw new ArgumentNullException(nameof(option)); + this.Language = language; + } + + public override bool Equals(object? obj) + { + return obj is OptionKey2 key && + Equals(key); + } + + public bool Equals(OptionKey2 other) + { + return Option.Equals(other.Option) && Language == other.Language; + } + + public override int GetHashCode() + { + var hash = Option?.GetHashCode() ?? 0; + + if (Language != null) + { + hash = unchecked((hash * (int)0xA5555529) + Language.GetHashCode()); + } + + return hash; + } + + public override string ToString() + { + if (Option is null) + { + return ""; + } + + var languageDisplay = Option.IsPerLanguage + ? $"({Language}) " + : string.Empty; + + return languageDisplay + Option.ToString(); + } + + public static bool operator ==(OptionKey2 left, OptionKey2 right) + { + return left.Equals(right); + } + + public static bool operator !=(OptionKey2 left, OptionKey2 right) + { + return !left.Equals(right); + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionStorageLocation2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionStorageLocation2.cs new file mode 100644 index 0000000000000..f36a851c8eb06 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionStorageLocation2.cs @@ -0,0 +1,18 @@ +// 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. + +#nullable enable + +namespace Microsoft.CodeAnalysis.Options +{ + /// + /// The base type of all types that specify where options are stored. + /// + internal abstract class OptionStorageLocation2 +#if !CODE_STYLE + : OptionStorageLocation +#endif + { + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs new file mode 100644 index 0000000000000..4ba604877c417 --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.cs @@ -0,0 +1,117 @@ +// 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. + +#nullable enable + +using System; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.Options +{ + /// + /// Marker interface for + /// + internal interface IPerLanguageOption : IOptionWithGroup + { + } + + /// + /// Marker interface for + /// + internal interface IPerLanguageOption : IPerLanguageOption + { + } + + /// + /// An option that can be specified once per language. + /// + /// + internal partial class PerLanguageOption2 : IPerLanguageOption + { + public OptionDefinition OptionDefinition { get; } + + /// + public string Feature => OptionDefinition.Feature; + + /// + internal OptionGroup Group => OptionDefinition.Group; + + /// + public string Name => OptionDefinition.Name; + + /// + public Type Type => OptionDefinition.Type; + + /// + public T DefaultValue => (T)OptionDefinition.DefaultValue!; + + /// + /// Storage locations for the option. + /// + public ImmutableArray StorageLocations { get; } + + public PerLanguageOption2(string feature, string name, T defaultValue) + : this(feature, name, defaultValue, storageLocations: Array.Empty()) + { + } + + public PerLanguageOption2(string feature, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) + { + } + + internal PerLanguageOption2(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) + : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) + { + } + + internal PerLanguageOption2(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray storageLocations) + { + if (string.IsNullOrWhiteSpace(feature)) + { + throw new ArgumentNullException(nameof(feature)); + } + + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException(nameof(name)); + } + + OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true); + this.StorageLocations = storageLocations; + } + + OptionGroup IOptionWithGroup.Group => this.Group; + + OptionDefinition IOption2.OptionDefinition => OptionDefinition; + +#if CODE_STYLE + object? IOption2.DefaultValue => this.DefaultValue; + + bool IOption2.IsPerLanguage => true; +#else + object? IOption.DefaultValue => this.DefaultValue; + + bool IOption.IsPerLanguage => true; + + ImmutableArray IOption.StorageLocations + => this.StorageLocations.As(); +#endif + public override string ToString() => OptionDefinition.ToString(); + + public override int GetHashCode() => OptionDefinition.GetHashCode(); + + public override bool Equals(object? obj) => Equals(obj as IOption2); + + public bool Equals(IOption2? other) + { + if (ReferenceEquals(this, other)) + { + return true; + } + + return OptionDefinition == other?.OptionDefinition; + } + } +} diff --git a/src/Workspaces/Core/Portable/Options/RoamingProfileStorageLocation.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/RoamingProfileStorageLocation.cs similarity index 95% rename from src/Workspaces/Core/Portable/Options/RoamingProfileStorageLocation.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/RoamingProfileStorageLocation.cs index c42364844c459..c6cc8c8d0a0a6 100644 --- a/src/Workspaces/Core/Portable/Options/RoamingProfileStorageLocation.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/RoamingProfileStorageLocation.cs @@ -6,16 +6,12 @@ using System; -#if CODE_STYLE -namespace Microsoft.CodeAnalysis.Internal.Options -#else namespace Microsoft.CodeAnalysis.Options -#endif { /// /// Specifies that the option should be stored into a roamed profile across machines. /// - internal sealed class RoamingProfileStorageLocation : OptionStorageLocation + internal sealed class RoamingProfileStorageLocation : OptionStorageLocation2 { private readonly Func _keyNameFromLanguageName; diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditorConfigFileGenerator_NamingStyles.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditorConfigFileGenerator_NamingStyles.cs new file mode 100644 index 0000000000000..6c89fd20b944e --- /dev/null +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EditorConfigFileGenerator_NamingStyles.cs @@ -0,0 +1,134 @@ +// 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. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis.CodeStyle; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; + +namespace Microsoft.CodeAnalysis.Options +{ + internal static partial class EditorConfigFileGenerator + { + public static void AppendNamingStylePreferencesToEditorConfig(NamingStylePreferences namingStylePreferences, string language, StringBuilder editorconfig) + { + editorconfig.AppendLine($"#### {CompilerExtensionsResources.Naming_styles} ####"); + + var serializedNameMap = AssignNamesToNamingStyleElements(namingStylePreferences); + var ruleNameMap = AssignNamesToNamingStyleRules(namingStylePreferences, serializedNameMap); + var referencedElements = new HashSet(); + + editorconfig.AppendLine(); + editorconfig.AppendLine($"# {CompilerExtensionsResources.Naming_rules}"); + + foreach (var namingRule in namingStylePreferences.NamingRules) + { + referencedElements.Add(namingRule.SymbolSpecificationID); + referencedElements.Add(namingRule.NamingStyleID); + + editorconfig.AppendLine(); + editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.severity = {namingRule.EnforcementLevel.ToNotificationOption(defaultSeverity: DiagnosticSeverity.Hidden).ToEditorConfigString()}"); + editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.symbols = {serializedNameMap[namingRule.SymbolSpecificationID]}"); + editorconfig.AppendLine($"dotnet_naming_rule.{ruleNameMap[namingRule]}.style = {serializedNameMap[namingRule.NamingStyleID]}"); + } + + editorconfig.AppendLine(); + editorconfig.AppendLine($"# {CompilerExtensionsResources.Symbol_specifications}"); + + foreach (var symbolSpecification in namingStylePreferences.SymbolSpecifications) + { + if (!referencedElements.Contains(symbolSpecification.ID)) + { + continue; + } + + editorconfig.AppendLine(); + editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.applicable_kinds = {symbolSpecification.ApplicableSymbolKindList.ToEditorConfigString()}"); + editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.applicable_accessibilities = {symbolSpecification.ApplicableAccessibilityList.ToEditorConfigString(language)}"); + editorconfig.AppendLine($"dotnet_naming_symbols.{serializedNameMap[symbolSpecification.ID]}.required_modifiers = {symbolSpecification.RequiredModifierList.ToEditorConfigString(language)}"); + } + + editorconfig.AppendLine(); + editorconfig.AppendLine($"# {CompilerExtensionsResources.Naming_styles}"); + + foreach (var namingStyle in namingStylePreferences.NamingStyles) + { + if (!referencedElements.Contains(namingStyle.ID)) + { + continue; + } + + editorconfig.AppendLine(); + editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.required_prefix = {namingStyle.Prefix}"); + editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.required_suffix = {namingStyle.Suffix}"); + editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.word_separator = {namingStyle.WordSeparator}"); + editorconfig.AppendLine($"dotnet_naming_style.{serializedNameMap[namingStyle.ID]}.capitalization = {namingStyle.CapitalizationScheme.ToEditorConfigString()}"); + } + } + + private static ImmutableDictionary AssignNamesToNamingStyleElements(NamingStylePreferences namingStylePreferences) + { + var symbolSpecificationNames = new HashSet(); + var builder = ImmutableDictionary.CreateBuilder(); + foreach (var symbolSpecification in namingStylePreferences.SymbolSpecifications) + { + var name = ToSnakeCaseName(symbolSpecification.Name); + if (!symbolSpecificationNames.Add(name)) + { + name = symbolSpecification.ID.ToString("n"); + } + + builder.Add(symbolSpecification.ID, name); + } + + var namingStyleNames = new HashSet(); + foreach (var namingStyle in namingStylePreferences.NamingStyles) + { + var name = ToSnakeCaseName(namingStyle.Name); + if (!namingStyleNames.Add(name)) + { + name = namingStyle.ID.ToString("n"); + } + + builder.Add(namingStyle.ID, name); + } + + return builder.ToImmutable(); + + static string ToSnakeCaseName(string name) + { + return new string(name + .Select(ch => + { + if (char.IsLetterOrDigit(ch)) + { + return char.ToLowerInvariant(ch); + } + else + { + return '_'; + } + }) + .ToArray()); + } + } + + private static ImmutableDictionary AssignNamesToNamingStyleRules(NamingStylePreferences namingStylePreferences, ImmutableDictionary serializedNameMap) + { + var builder = ImmutableDictionary.CreateBuilder(); + foreach (var rule in namingStylePreferences.NamingRules) + { + builder.Add(rule, $"{serializedNameMap[rule.SymbolSpecificationID]}_should_be_{serializedNameMap[rule.NamingStyleID]}"); + } + + return builder.ToImmutable(); + } + } +} diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.cs.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.cs.xlf index c460544cd8ff5..9c8b97c3178e3 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.cs.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.cs.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf index d44f06e1c5676..bf4c4cd0d51f7 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.de.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf index 4cffebae20a8d..dcc93d274c198 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.es.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf index 12d7c9d15641e..b339ca6709cd2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.fr.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf index a8363314b5134..109c873ede69c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.it.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf index d4aae48276b27..dfbb70cb063d4 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ja.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf index cd14cd4955af0..79c2aa64abfa5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ko.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf index d10144853df0f..943790f0e8baa 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pl.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf index 2fafa2bdcb392..a65d73ab6f174 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.pt-BR.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf index 942f17c0c54be..f53a4d59ed436 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.ru.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf index f1e531a9990b1..213caad190de2 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.tr.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf index 7d3aef607d139..ffd385e4af953 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hans.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf index 7534dae9cb314..806f518f5cc8a 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/xlf/CompilerExtensionsResources.zh-Hant.xlf @@ -87,6 +87,16 @@ Modifier preferences + + Naming rules + Naming rules + + + + Naming styles + Naming styles + + Non-Field Members Non-Field Members @@ -162,6 +172,11 @@ Struct {locked} unless the capitalization should be handled differently + + Symbol specifications + Symbol specifications + + The first word, '{0}', must begin with a lower case character The first word, '{0}', must begin with a lower case character diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/CodeStyle/VisualBasicCodeStyleOptions.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/CodeStyle/VisualBasicCodeStyleOptions.vb index 553dd04d1b466..add5c7294b714 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/CodeStyle/VisualBasicCodeStyleOptions.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/CodeStyle/VisualBasicCodeStyleOptions.vb @@ -4,30 +4,21 @@ Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeStyle - -#If CODE_STYLE Then -imports Microsoft.CodeAnalysis.Internal.Options -#Else Imports Microsoft.CodeAnalysis.Options -#End If -#If CODE_STYLE Then -Namespace Microsoft.CodeAnalysis.VisualBasic.Internal.CodeStyle -#Else Namespace Microsoft.CodeAnalysis.VisualBasic.CodeStyle -#End If Friend NotInheritable Class VisualBasicCodeStyleOptions - Private Shared ReadOnly s_allOptionsBuilder As ImmutableArray(Of IOption).Builder = ImmutableArray.CreateBuilder(Of IOption) + Private Shared ReadOnly s_allOptionsBuilder As ImmutableArray(Of IOption2).Builder = ImmutableArray.CreateBuilder(Of IOption2) Shared Sub New() AllOptions = s_allOptionsBuilder.ToImmutable() End Sub - Private Shared Function CreateOption(Of T)(group As OptionGroup, name As String, defaultValue As T, ParamArray storageLocations As OptionStorageLocation()) As [Option](Of T) + Private Shared Function CreateOption(Of T)(group As OptionGroup, name As String, defaultValue As T, ParamArray storageLocations As OptionStorageLocation2()) As [Option2](Of T) Return CodeStyleHelpers.CreateOption(group, NameOf(VisualBasicCodeStyleOptions), name, defaultValue, s_allOptionsBuilder, storageLocations) End Function - Public Shared ReadOnly Property AllOptions As ImmutableArray(Of IOption) + Public Shared ReadOnly Property AllOptions As ImmutableArray(Of IOption2) Public Shared ReadOnly PreferredModifierOrderDefault As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create( @@ -39,28 +30,28 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeStyle SyntaxKind.WithEventsKeyword, SyntaxKind.WideningKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.CustomKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.IteratorKeyword) - Public Shared ReadOnly PreferredModifierOrder As [Option](Of CodeStyleOption(Of String)) = CreateOption( + Public Shared ReadOnly PreferredModifierOrder As [Option2](Of CodeStyleOption2(Of String)) = CreateOption( VisualBasicCodeStyleOptionGroups.Modifier, NameOf(PreferredModifierOrder), - defaultValue:=New CodeStyleOption(Of String)(String.Join(",", PreferredModifierOrderDefault.Select(AddressOf SyntaxFacts.GetText)), NotificationOption.Silent), + defaultValue:=New CodeStyleOption2(Of String)(String.Join(",", PreferredModifierOrderDefault.Select(AddressOf SyntaxFacts.GetText)), NotificationOption2.Silent), EditorConfigStorageLocation.ForStringCodeStyleOption("visual_basic_preferred_modifier_order"), New RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{NameOf(PreferredModifierOrder)}")) - Public Shared ReadOnly UnusedValueExpressionStatement As [Option](Of CodeStyleOption(Of UnusedValuePreference)) = + Public Shared ReadOnly UnusedValueExpressionStatement As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueExpressionStatement), editorConfigName:="visual_basic_style_unused_value_expression_statement_preference", - defaultValue:=New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Silent), + defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent), optionsBuilder:=s_allOptionsBuilder) - Public Shared ReadOnly UnusedValueAssignment As [Option](Of CodeStyleOption(Of UnusedValuePreference)) = + Public Shared ReadOnly UnusedValueAssignment As [Option2](Of CodeStyleOption2(Of UnusedValuePreference)) = CodeStyleHelpers.CreateUnusedExpressionAssignmentOption( group:=VisualBasicCodeStyleOptionGroups.ExpressionLevelPreferences, feature:=NameOf(VisualBasicCodeStyleOptions), name:=NameOf(UnusedValueAssignment), editorConfigName:="visual_basic_style_unused_value_assignment_preference", - defaultValue:=New CodeStyleOption(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Suggestion), + defaultValue:=New CodeStyleOption2(Of UnusedValuePreference)(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Suggestion), optionsBuilder:=s_allOptionsBuilder) End Class diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/DocumentBasedFixAllProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/DocumentBasedFixAllProvider.cs index 97a6fe4b27027..a40a87f3c8616 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/DocumentBasedFixAllProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/DocumentBasedFixAllProvider.cs @@ -4,18 +4,16 @@ #nullable enable -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; #pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction -namespace Microsoft.CodeAnalysis.CodeStyle +namespace Microsoft.CodeAnalysis.CodeFixes { /// /// Provides a base class to write a that fixes documents independently. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/FixAllContextHelper.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/FixAllContextHelper.cs index cee686e82e254..76b681dc151d5 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/FixAllContextHelper.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/FixAllContextHelper.cs @@ -2,18 +2,16 @@ // 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.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; -namespace Microsoft.CodeAnalysis.CodeStyle +namespace Microsoft.CodeAnalysis.CodeFixes { internal static class FixAllContextHelper { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.FixAllProvider.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.FixAllProvider.cs index 73cec6244d6eb..bcd14ed91640c 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.FixAllProvider.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/SyntaxEditorBasedCodeFixProvider.FixAllProvider.cs @@ -2,15 +2,10 @@ // 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.Linq; -using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.GeneratedCodeRecognition; -using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeFixes { diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/SimplificationHelpers.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/SimplificationHelpers.cs index ee7d1eff3260a..6c33c315e2dfb 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/SimplificationHelpers.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/SimplificationHelpers.cs @@ -3,15 +3,14 @@ // See the LICENSE file in the project root for more information. using System.Linq; +using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE -using Microsoft.CodeAnalysis.Internal.Options; using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else -using Microsoft.CodeAnalysis.CodeStyle; -using Microsoft.CodeAnalysis.Options; +using OptionSet = Microsoft.CodeAnalysis.Options.OptionSet; #endif namespace Microsoft.CodeAnalysis.Simplification @@ -118,10 +117,10 @@ internal static bool ShouldSimplifyThisOrMeMemberAccessExpression( if (symbol.IsStatic) return true; - if ((symbol.IsKind(SymbolKind.Field) && optionSet.GetOption(CodeStyleOptions.QualifyFieldAccess, semanticModel.Language).Value || - (symbol.IsKind(SymbolKind.Property) && optionSet.GetOption(CodeStyleOptions.QualifyPropertyAccess, semanticModel.Language).Value) || - (symbol.IsKind(SymbolKind.Method) && optionSet.GetOption(CodeStyleOptions.QualifyMethodAccess, semanticModel.Language).Value) || - (symbol.IsKind(SymbolKind.Event) && optionSet.GetOption(CodeStyleOptions.QualifyEventAccess, semanticModel.Language).Value))) + if ((symbol.IsKind(SymbolKind.Field) && optionSet.GetOption(CodeStyleOptions2.QualifyFieldAccess, semanticModel.Language).Value || + (symbol.IsKind(SymbolKind.Property) && optionSet.GetOption(CodeStyleOptions2.QualifyPropertyAccess, semanticModel.Language).Value) || + (symbol.IsKind(SymbolKind.Method) && optionSet.GetOption(CodeStyleOptions2.QualifyMethodAccess, semanticModel.Language).Value) || + (symbol.IsKind(SymbolKind.Event) && optionSet.GetOption(CodeStyleOptions2.QualifyEventAccess, semanticModel.Language).Value))) { return false; } @@ -131,12 +130,12 @@ internal static bool ShouldSimplifyThisOrMeMemberAccessExpression( internal static bool PreferPredefinedTypeKeywordInDeclarations(OptionSet optionSet, string language) { - return optionSet.GetOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language).Value; + return optionSet.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language).Value; } internal static bool PreferPredefinedTypeKeywordInMemberAccess(OptionSet optionSet, string language) { - return optionSet.GetOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, language).Value; + return optionSet.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, language).Value; } } } diff --git a/src/Workspaces/VisualBasic/Portable/CodeStyle/VisualBasicCodeStyleOptionsProvider.vb b/src/Workspaces/VisualBasic/Portable/CodeStyle/VisualBasicCodeStyleOptionsProvider.vb index 5ea51c4d2440d..42e3cd3d78b02 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeStyle/VisualBasicCodeStyleOptionsProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeStyle/VisualBasicCodeStyleOptionsProvider.vb @@ -18,7 +18,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeStyle Public ReadOnly Property Options As ImmutableArray(Of IOption) Implements IOptionProvider.Options Get - Return VisualBasicCodeStyleOptions.AllOptions + Return VisualBasicCodeStyleOptions.AllOptions.As(Of IOption) End Get End Property End Class diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb b/src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb index d57bb14a86516..a91d09efc6068 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/DefaultOperationProvider.vb @@ -4,16 +4,11 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics +Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities -#If CODE_STYLE Then -Imports Microsoft.CodeAnalysis.Internal.Editing -#Else -Imports Microsoft.CodeAnalysis.Editing -#End If - Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting ' the default provider that will be called by the engine at the end of provider's chain. ' there is no way for a user to be remove this provider. diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb index 7410930dfbcdf..e05e14c748143 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.CodeShapeAnalyzer.vb @@ -123,7 +123,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Return True End If - Dim currentSpaces = text.ConvertTabToSpace(_options.GetOption(FormattingOptions.TabSize), Me._currentColumn, text.Length) + Dim currentSpaces = text.ConvertTabToSpace(_options.GetOption(FormattingOptions2.TabSize), Me._currentColumn, text.Length) If currentIndex + 1 < Me._list.Count AndAlso Me._list(currentIndex + 1).RawKind = SyntaxKind.LineContinuationTrivia Then If currentSpaces <> 1 Then @@ -225,7 +225,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting End If If trivia.Kind = SyntaxKind.DocumentationCommentTrivia AndAlso - ShouldFormatDocumentationComment(_indentation, _options.GetOption(FormattingOptions.TabSize), trivia) Then + ShouldFormatDocumentationComment(_indentation, _options.GetOption(FormattingOptions2.TabSize), trivia) Then Return True End If diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb index 9e4ca4d2cffba..61b6d907dfe31 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.ComplexTrivia.vb @@ -24,7 +24,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting End Sub Protected Overrides Sub ExtractLineAndSpace(text As String, ByRef lines As Integer, ByRef spaces As Integer) - text.ProcessTextBetweenTokens(Me.TreeInfo, Me.Token1, Me.Options.GetOption(FormattingOptions.TabSize), lines, spaces) + text.ProcessTextBetweenTokens(Me.TreeInfo, Me.Token1, Me.Options.GetOption(FormattingOptions2.TabSize), lines, spaces) End Sub Protected Overrides Function CreateComplexTrivia(line As Integer, space As Integer) As TriviaData @@ -77,7 +77,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Debug.Assert(Me.SecondTokenIsFirstTokenOnLine OrElse beginningOfNewLine) - If Me.Options.GetOption(FormattingOptions.UseTabs) Then + If Me.Options.GetOption(FormattingOptions2.UseTabs) Then Return True End If diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb index b07008655019e..9a2fc2a4a559a 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb @@ -29,7 +29,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting builder.Append(" "c) builder.Append(SyntaxFacts.GetText(SyntaxKind.LineContinuationTrivia)) - builder.AppendIndentationString(Me.Spaces, Me.Options.GetOption(FormattingOptions.UseTabs), Me.Options.GetOption(FormattingOptions.TabSize)) + builder.AppendIndentationString(Me.Spaces, Me.Options.GetOption(FormattingOptions2.UseTabs), Me.Options.GetOption(FormattingOptions2.TabSize)) Return StringBuilderPool.ReturnAndFree(builder) End Function diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb index 73c1cbc8ee724..23d1a9939e41f 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.vb @@ -174,22 +174,22 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting End Function Private Function CalculateSpaces(token1 As SyntaxToken, token2 As SyntaxToken) As Integer - Dim initialColumn = If(token1.Kind = 0, 0, Me.TreeInfo.GetOriginalColumn(Me.Options.GetOption(FormattingOptions.TabSize), token1) + token1.Width) + Dim initialColumn = If(token1.Kind = 0, 0, Me.TreeInfo.GetOriginalColumn(Me.Options.GetOption(FormattingOptions2.TabSize), token1) + token1.Width) Dim textSnippet = Me.TreeInfo.GetTextBetween(token1, token2) - Return textSnippet.ConvertTabToSpace(Me.Options.GetOption(FormattingOptions.TabSize), initialColumn, textSnippet.Length) + Return textSnippet.ConvertTabToSpace(Me.Options.GetOption(FormattingOptions2.TabSize), initialColumn, textSnippet.Length) End Function Private Function GetLineBreaksAndIndentation(result As Analyzer.AnalysisResult) As ValueTuple(Of Boolean, Integer, Integer) Debug.Assert(result.Tab >= 0) Debug.Assert(result.LineBreaks >= 0) - Dim indentation = result.Tab * Me.Options.GetOption(FormattingOptions.TabSize) + result.Space + Dim indentation = result.Tab * Me.Options.GetOption(FormattingOptions2.TabSize) + result.Space If result.HasTrailingSpace OrElse result.HasUnknownWhitespace Then Return ValueTuple.Create(False, result.LineBreaks, indentation) End If - If Not Me.Options.GetOption(FormattingOptions.UseTabs) Then + If Not Me.Options.GetOption(FormattingOptions2.UseTabs) Then If result.Tab > 0 Then Return ValueTuple.Create(False, result.LineBreaks, indentation) End If @@ -197,19 +197,19 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Return ValueTuple.Create(True, result.LineBreaks, indentation) End If - Debug.Assert(Me.Options.GetOption(FormattingOptions.UseTabs)) + Debug.Assert(Me.Options.GetOption(FormattingOptions2.UseTabs)) ' tab can only appear before space to be a valid tab for indentation If result.HasTabAfterSpace Then Return ValueTuple.Create(False, result.LineBreaks, indentation) End If - If result.Space >= Me.Options.GetOption(FormattingOptions.TabSize) Then + If result.Space >= Me.Options.GetOption(FormattingOptions2.TabSize) Then Return ValueTuple.Create(False, result.LineBreaks, indentation) End If - Debug.Assert((indentation \ Me.Options.GetOption(FormattingOptions.TabSize)) = result.Tab) - Debug.Assert((indentation Mod Me.Options.GetOption(FormattingOptions.TabSize)) = result.Space) + Debug.Assert((indentation \ Me.Options.GetOption(FormattingOptions2.TabSize)) = result.Tab) + Debug.Assert((indentation Mod Me.Options.GetOption(FormattingOptions2.TabSize)) = result.Space) Return ValueTuple.Create(True, result.LineBreaks, indentation) End Function diff --git a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb index da7ce83e2c11f..dbc78e7c8175f 100644 --- a/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb +++ b/src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb @@ -54,7 +54,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Protected Overrides Function CreateEndOfLine() As SyntaxTrivia If _newLine = Nothing Then - Dim text = Me.Context.Options.GetOption(FormattingOptions.NewLine) + Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine) _newLine = SyntaxFactory.EndOfLine(text) End If @@ -285,9 +285,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting forceIndentation:=True, indentation:=indentation, indentationDelta:=0, - useTab:=Me.Options.GetOption(FormattingOptions.UseTabs), - tabSize:=Me.Options.GetOption(FormattingOptions.TabSize), - newLine:=Me.Options.GetOption(FormattingOptions.NewLine)) + useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs), + tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize), + newLine:=Me.Options.GetOption(FormattingOptions2.NewLine)) If text = singlelineDocComments Then Return trivia diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb index 22e78720f3f39..5b6399f3fc306 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/ExpressionSimplifier.vb @@ -134,7 +134,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification.Simplifiers memberAccess.GetTrailingTrivia())) replacementNode = replacementNode.WithAdditionalAnnotations( - New SyntaxAnnotation(NameOf(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))) + New SyntaxAnnotation(NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess))) issueSpan = memberAccess.Span Return True diff --git a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb index 3dad3df164373..dadf58d53561e 100644 --- a/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb +++ b/src/Workspaces/VisualBasic/Portable/Simplification/Simplifiers/NameSimplifier.vb @@ -171,9 +171,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification.Simplifiers Dim codeStyleOptionName As String = Nothing If inDeclarationContext Then - codeStyleOptionName = NameOf(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration) + codeStyleOptionName = NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration) ElseIf inMemberAccessContext Then - codeStyleOptionName = NameOf(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess) + codeStyleOptionName = NameOf(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess) End If replacementNode = SyntaxFactory.PredefinedType(token)