diff --git a/src/Analyzers/Analyzers.Template.xml b/src/Analyzers/Analyzers.Template.xml index e58bb2c91a..3fdbcd1c5e 100644 --- a/src/Analyzers/Analyzers.Template.xml +++ b/src/Analyzers/Analyzers.Template.xml @@ -22,6 +22,8 @@ + + false false diff --git a/src/Analyzers/Analyzers.xml b/src/Analyzers/Analyzers.xml index 38cfdbbf6b..c057e3d718 100644 --- a/src/Analyzers/Analyzers.xml +++ b/src/Analyzers/Analyzers.xml @@ -263,6 +263,7 @@ foreach (var item in items) // [|Id|] Use implicitly typed array (when type is obvious). a + use_implicit_type_when_obvious Change true @@ -275,6 +276,7 @@ foreach (var item in items) // [|Id|] Use implicitly typed array. i + invert Invert @@ -334,6 +336,7 @@ foreach (var item in items) // [|Id|] Convert expression-body to block body when expression is multi-line. a + use_block_body_when_expression_is_multiline Change @@ -358,6 +361,7 @@ foreach (var item in items) // [|Id|] Convert expression-body to block body when declaration is multi-line. b + use_block_body_when_declaration_is_multiline Change @@ -432,6 +436,7 @@ foreach (var item in items) // [|Id|] Remove accessibility modifiers. i + invert Invert true @@ -818,6 +823,7 @@ if (f) a Remove empty line between closing brace and switch section. + remove_empty_line_between_closing_brace_and_switch_section Enable @@ -1012,6 +1018,7 @@ catch (Exception ex) Do not rename private static read-only field to camel case with underscore. a + suppress_private_static_readonly_field Disable @@ -1128,6 +1135,7 @@ if (!f) Remove argument list from object creation expression. i + invert Invert @@ -1155,6 +1163,7 @@ if (!f) a Remove parentheses from condition of conditional expression (when condition is a single token). Remove parentheses from condition of conditional expression. + do_not_parenthesize_single_token Change @@ -1847,6 +1856,7 @@ object x = items.Peek();]]> Use string.Empty instead of "". i + invert Invert @@ -2036,6 +2046,7 @@ public string Foo // [|Id|] Remove call to 'ConfigureAwait'. i + invert Invert true @@ -2139,6 +2150,7 @@ namespace Foo Convert bitwise operation to 'HasFlag' call. i + invert Invert @@ -2344,6 +2356,7 @@ else Simplify conditional expression (when it includes negation of condition). a + enable_negation_of_condition Enable @@ -4249,6 +4262,7 @@ int i = (x != null) ? x.Value.GetHashCode() : 0; // [|Id|]]]> Convert method group to anonymous function. i + invert Invert @@ -4428,10 +4442,14 @@ x = "";]]> Info true true - Use following EditorConfig option to suppress diagnostic from [Unity script methods](https://docs.unity3d.com/ScriptReference/MonoBehaviour.html): -```editorconfig -roslynator.RCS1213.suppress_unity_script_methods = true -``` + + + Suppress Unity script methods. + suppress_unity_script_methods + Disable + Suppress diagnostic from [Unity script methods](https://docs.unity3d.com/ScriptReference/MonoBehaviour.html). + + RCS1214 @@ -5475,6 +5493,7 @@ public class C Do not use element access when expression is invocation. a + suppress_when_expression_is_invocation Disable @@ -5551,6 +5570,7 @@ void M() a Use 'is null' pattern instead of '!=' operator. + enable_inequality_operator Enable @@ -5562,6 +5582,7 @@ void M() i Use comparison instead of 'is null' pattern. + invert Invert diff --git a/src/Analyzers/CSharp/Analysis/AddAccessibilityModifiersOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddAccessibilityModifiersOrViceVersaAnalyzer.cs index f58b58e2ab..3c6868d2d4 100644 --- a/src/Analyzers/CSharp/Analysis/AddAccessibilityModifiersOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddAccessibilityModifiersOrViceVersaAnalyzer.cs @@ -169,7 +169,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclaration if (explicitAccessibility == Accessibility.NotApplicable) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveAccessibilityModifiers)) + if (AnalyzerOptions.RemoveAccessibilityModifiers.IsEnabled(context)) return; Accessibility accessibility = GetAccessibility(context, declaration, modifiers); @@ -188,7 +188,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclaration location, Properties[accessibility]); } - else if (!context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveAccessibilityModifiers) + else if (AnalyzerOptions.RemoveAccessibilityModifiers.IsEnabled(context) && !declaration.IsKind(SyntaxKind.OperatorDeclaration, SyntaxKind.ConversionOperatorDeclaration)) { Accessibility accessibility = SyntaxAccessibility.GetDefaultAccessibility(declaration); diff --git a/src/Analyzers/CSharp/Analysis/AddArgumentListToObjectCreationOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddArgumentListToObjectCreationOrViceVersaAnalyzer.cs index 8d3c421a47..25f99c91be 100644 --- a/src/Analyzers/CSharp/Analysis/AddArgumentListToObjectCreationOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddArgumentListToObjectCreationOrViceVersaAnalyzer.cs @@ -38,7 +38,7 @@ private static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext co if (argumentList == null) { - if (context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveArgumentListFromObjectCreation)) + if (!AnalyzerOptions.RemoveArgumentListFromObjectCreation.IsEnabled(context)) { var span = new TextSpan(objectCreationExpression.Type.Span.End, 0); @@ -49,7 +49,7 @@ private static void AnalyzeObjectCreationExpression(SyntaxNodeAnalysisContext co } } else if (!argumentList.Arguments.Any() - && !context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveArgumentListFromObjectCreation)) + && AnalyzerOptions.RemoveArgumentListFromObjectCreation.IsEnabled(context)) { SyntaxToken openParen = argumentList.OpenParenToken; SyntaxToken closeParen = argumentList.CloseParenToken; diff --git a/src/Analyzers/CSharp/Analysis/AddCallToConfigureAwaitOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddCallToConfigureAwaitOrViceVersaAnalyzer.cs index ffcc2ab9ec..3193a0dd42 100644 --- a/src/Analyzers/CSharp/Analysis/AddCallToConfigureAwaitOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddCallToConfigureAwaitOrViceVersaAnalyzer.cs @@ -22,20 +22,19 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(AnalyzerOptions.RemoveCallToConfigureAwait)) - { - if (startContext.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1") == null) - return; - - startContext.RegisterSyntaxNodeAction(f => AddCallToConfigureAwait(f), SyntaxKind.AwaitExpression); - } - else + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => RemoveCallToConfigureAwait(f), SyntaxKind.AwaitExpression); - } - }); + if (AnalyzerOptions.RemoveCallToConfigureAwait.IsEnabled(c)) + { + RemoveCallToConfigureAwait(c); + } + else if (c.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1") != null) + { + AddCallToConfigureAwait(c); + } + }, + SyntaxKind.AwaitExpression); } private static void AddCallToConfigureAwait(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/AnonymousMethodAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AnonymousMethodAnalyzer.cs index 696fb482dd..85c2cd72fe 100644 --- a/src/Analyzers/CSharp/Analysis/AnonymousMethodAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AnonymousMethodAnalyzer.cs @@ -27,13 +27,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UseLambdaExpressionInsteadOfAnonymousMethod)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethod(f), SyntaxKind.AnonymousMethodExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseLambdaExpressionInsteadOfAnonymousMethod.IsEffective(c)) + AnalyzeAnonymousMethod(c); + }, + SyntaxKind.AnonymousMethodExpression); } private static void AnalyzeAnonymousMethod(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/AvoidMultilineExpressionBodyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidMultilineExpressionBodyAnalyzer.cs index b8f29612cb..65c2587b5e 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidMultilineExpressionBodyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidMultilineExpressionBodyAnalyzer.cs @@ -20,16 +20,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa) - && !startContext.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine)) + context.RegisterSyntaxNodeAction( + c => { - return; - } - - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); - }); + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(c, checkParent: true) == false) + AnalyzeArrowExpressionClause(c); + }, + SyntaxKind.ArrowExpressionClause); } private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs index eb91e479d8..3000cf9344 100644 --- a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs @@ -30,23 +30,33 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UnnecessaryOperator)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeLessThanExpression(f), SyntaxKind.LessThanExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeGreaterThanExpression(f), SyntaxKind.GreaterThanExpression); - } + if (DiagnosticDescriptors.UnnecessaryOperator.IsEffective(c)) + AnalyzeLessThanExpression(c); + }, + SyntaxKind.LessThanExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLessThanOrEqualExpression(f), SyntaxKind.LessThanOrEqualExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeGreaterThanOrEqualExpression(f), SyntaxKind.GreaterThanOrEqualExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLogicalOrExpression(f), SyntaxKind.LogicalOrExpression); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UnnecessaryOperator.IsEffective(c)) + AnalyzeGreaterThanExpression(c); + }, + SyntaxKind.GreaterThanExpression); - if (!startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); - } - }); + if (DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse.IsEffective(c)) + AnalyzeSimpleMemberAccessExpression(c); + }, + SyntaxKind.SimpleMemberAccessExpression); + + context.RegisterSyntaxNodeAction(c => AnalyzeLessThanOrEqualExpression(c), SyntaxKind.LessThanOrEqualExpression); + context.RegisterSyntaxNodeAction(c => AnalyzeGreaterThanOrEqualExpression(c), SyntaxKind.GreaterThanOrEqualExpression); + context.RegisterSyntaxNodeAction(c => AnalyzeLogicalOrExpression(c), SyntaxKind.LogicalOrExpression); } // x == double.NaN >>> double.IsNaN(x) @@ -102,12 +112,12 @@ private static void AnalyzeGreaterThanOrEqualExpression(SyntaxNodeAnalysisContex if (!info.Success) return; - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse) + if (DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse.IsEffective(context) && IsAlwaysEqualToTrueOrFalse(greaterThanOrEqualExpression, info.Left, info.Right, context.SemanticModel, context.CancellationToken)) { ReportExpressionAlwaysEqualToTrueOrFalse(context, "true"); } - else if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnnecessaryOperator) + else if (DiagnosticDescriptors.UnnecessaryOperator.IsEffective(context) && IsUnnecessaryRelationalOperator(info.Right, info.Left, context.SemanticModel, context.CancellationToken)) { ReportUnnecessaryRelationalOperator(context, info.OperatorToken); @@ -141,12 +151,12 @@ private static void AnalyzeLessThanOrEqualExpression(SyntaxNodeAnalysisContext c if (!info.Success) return; - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse) + if (DiagnosticDescriptors.ExpressionIsAlwaysEqualToTrueOrFalse.IsEffective(context) && IsAlwaysEqualToTrueOrFalse(lessThanOrEqualExpression, info.Right, info.Left, context.SemanticModel, context.CancellationToken)) { ReportExpressionAlwaysEqualToTrueOrFalse(context, "true"); } - else if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnnecessaryOperator) + else if (DiagnosticDescriptors.UnnecessaryOperator.IsEffective(context) && IsUnnecessaryRelationalOperator(info.Left, info.Right, context.SemanticModel, context.CancellationToken)) { ReportUnnecessaryRelationalOperator(context, info.OperatorToken); diff --git a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs index 3d59fba978..278a3b0bcf 100644 --- a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs @@ -29,19 +29,45 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.AreAnalyzersSuppressed(DiagnosticDescriptors.RemoveRedundantBooleanLiteral, DiagnosticDescriptors.SimplifyBooleanComparison)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsExpression(f), SyntaxKind.EqualsExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeNotEqualsExpression(f), SyntaxKind.NotEqualsExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLogicalAndExpression(f), SyntaxKind.LogicalAndExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLogicalOrExpression(f), SyntaxKind.LogicalOrExpression); - } + if (DiagnosticHelpers.IsAnyEffective(c, DiagnosticDescriptors.RemoveRedundantBooleanLiteral, DiagnosticDescriptors.SimplifyBooleanComparison)) + AnalyzeEqualsExpression(c); + }, + SyntaxKind.EqualsExpression); - if (!startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantBooleanLiteral)) - startContext.RegisterSyntaxNodeAction(f => AnalyzeForStatement(f), SyntaxKind.ForStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticHelpers.IsAnyEffective(c, DiagnosticDescriptors.RemoveRedundantBooleanLiteral, DiagnosticDescriptors.SimplifyBooleanComparison)) + AnalyzeNotEqualsExpression(c); + }, + SyntaxKind.NotEqualsExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticHelpers.IsAnyEffective(c, DiagnosticDescriptors.RemoveRedundantBooleanLiteral, DiagnosticDescriptors.SimplifyBooleanComparison)) + AnalyzeLogicalAndExpression(c); + }, + SyntaxKind.LogicalAndExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticHelpers.IsAnyEffective(c, DiagnosticDescriptors.RemoveRedundantBooleanLiteral, DiagnosticDescriptors.SimplifyBooleanComparison)) + AnalyzeLogicalOrExpression(c); + }, + SyntaxKind.LogicalOrExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantBooleanLiteral.IsEffective(c)) + AnalyzeForStatement(c); + }, + SyntaxKind.ForStatement); } private static void AnalyzeForStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/ConvertAnonymousFunctionToMethodGroupOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertAnonymousFunctionToMethodGroupOrViceVersaAnalyzer.cs index c0e37504b9..609d017d9c 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertAnonymousFunctionToMethodGroupOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertAnonymousFunctionToMethodGroupOrViceVersaAnalyzer.cs @@ -1,7 +1,6 @@ // Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Diagnostics; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis; @@ -31,35 +30,33 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(startContext => { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa)) - return; - - if (startContext.IsAnalyzerSuppressed(AnalyzerOptions.ConvertMethodGroupToAnonymousFunction)) - { - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); - } - else - { - startContext.RegisterSyntaxNodeAction(f => AnalyzeArgument(f), SyntaxKind.Argument); - startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsValueClause(f), SyntaxKind.EqualsValueClause); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignment(f), SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression, SyntaxKind.SubtractAssignmentExpression, SyntaxKind.CoalesceAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeReturnStatement(f), SyntaxKind.ReturnStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeYieldReturnStatement(f), SyntaxKind.YieldReturnStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSwitchExpressionArm(f), SyntaxKind.SwitchExpressionArm); - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrayInitializer(f), SyntaxKind.ArrayInitializerExpression, SyntaxKind.CollectionInitializerExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); + + startContext.RegisterSyntaxNodeAction(f => AnalyzeArgument(f), SyntaxKind.Argument); + startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsValueClause(f), SyntaxKind.EqualsValueClause); + startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignment(f), SyntaxKind.SimpleAssignmentExpression, SyntaxKind.AddAssignmentExpression, SyntaxKind.SubtractAssignmentExpression, SyntaxKind.CoalesceAssignmentExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeReturnStatement(f), SyntaxKind.ReturnStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeYieldReturnStatement(f), SyntaxKind.YieldReturnStatement); + startContext.RegisterSyntaxNodeAction(f => AnalyzeArrowExpressionClause(f), SyntaxKind.ArrowExpressionClause); + startContext.RegisterSyntaxNodeAction(f => AnalyzeSwitchExpressionArm(f), SyntaxKind.SwitchExpressionArm); + startContext.RegisterSyntaxNodeAction(f => AnalyzeArrayInitializer(f), SyntaxKind.ArrayInitializerExpression, SyntaxKind.CollectionInitializerExpression); #if DEBUG - startContext.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); + startContext.RegisterSyntaxNodeAction(f => AnalyzeIdentifierName(f), SyntaxKind.IdentifierName); + startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); #endif - } }); } private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + if (context.Node.SpanContainsDirectives()) return; @@ -146,6 +143,12 @@ private static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext cont private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + if (context.Node.SpanContainsDirectives()) return; @@ -242,6 +245,12 @@ private static void AnalyzeParenthesizedLambdaExpression(SyntaxNodeAnalysisConte private static void AnalyzeAnonymousMethodExpression(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + if (context.Node.SpanContainsDirectives()) return; @@ -570,6 +579,12 @@ private static void FadeOut( private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var argument = (ArgumentSyntax)context.Node; ExpressionSyntax expression = argument.Expression.WalkDownParentheses(); @@ -587,6 +602,12 @@ private static void AnalyzeArgument(SyntaxNodeAnalysisContext context) private static void AnalyzeEqualsValueClause(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var argument = (EqualsValueClauseSyntax)context.Node; ExpressionSyntax expression = argument.Value.WalkDownParentheses(); @@ -604,6 +625,12 @@ private static void AnalyzeEqualsValueClause(SyntaxNodeAnalysisContext context) private static void AnalyzeAssignment(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var argument = (AssignmentExpressionSyntax)context.Node; ExpressionSyntax expression = argument.Right.WalkDownParentheses(); @@ -621,6 +648,12 @@ private static void AnalyzeAssignment(SyntaxNodeAnalysisContext context) private static void AnalyzeReturnStatement(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var returnStatement = (ReturnStatementSyntax)context.Node; ExpressionSyntax expression = returnStatement.Expression?.WalkDownParentheses(); @@ -638,6 +671,12 @@ private static void AnalyzeReturnStatement(SyntaxNodeAnalysisContext context) private static void AnalyzeYieldReturnStatement(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var yieldReturnStatement = (YieldStatementSyntax)context.Node; ExpressionSyntax expression = yieldReturnStatement.Expression?.WalkDownParentheses(); @@ -655,6 +694,12 @@ private static void AnalyzeYieldReturnStatement(SyntaxNodeAnalysisContext contex private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var arrowExpressionClause = (ArrowExpressionClauseSyntax)context.Node; ExpressionSyntax expression = arrowExpressionClause.Expression?.WalkDownParentheses(); @@ -673,6 +718,12 @@ private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext conte //TODO: test private static void AnalyzeSwitchExpressionArm(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var switchExpressionArm = (SwitchExpressionArmSyntax)context.Node; ExpressionSyntax expression = switchExpressionArm.Expression?.WalkDownParentheses(); @@ -690,6 +741,12 @@ private static void AnalyzeSwitchExpressionArm(SyntaxNodeAnalysisContext context private static void AnalyzeArrayInitializer(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var initializer = (InitializerExpressionSyntax)context.Node; foreach (ExpressionSyntax expression in initializer.Expressions) @@ -708,6 +765,12 @@ private static void AnalyzeArrayInitializer(SyntaxNodeAnalysisContext context) #if DEBUG private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var identifierName = (IdentifierNameSyntax)context.Node; ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(identifierName, context.SemanticModel, context.CancellationToken); @@ -715,6 +778,12 @@ private static void AnalyzeIdentifierName(SyntaxNodeAnalysisContext context) private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa.IsEffective(context)) + return; + + if (!AnalyzerOptions.ConvertMethodGroupToAnonymousFunction.IsEnabled(context)) + return; + var simpleMemberAccess = (MemberAccessExpressionSyntax)context.Node; ConvertMethodGroupToAnonymousFunctionAnalysis.IsFixable(simpleMemberAccess, context.SemanticModel, context.CancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/ConvertBlockBodyToExpressionBodyOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertBlockBodyToExpressionBodyOrViceVersaAnalyzer.cs index c4e923fdc6..83fdd98d4f 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertBlockBodyToExpressionBodyOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertBlockBodyToExpressionBodyOrViceVersaAnalyzer.cs @@ -29,9 +29,6 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(startContext => { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa)) - return; - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) return; @@ -53,6 +50,9 @@ public override void Initialize(AnalysisContext context) private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var methodDeclaration = (MethodDeclarationSyntax)context.Node; BlockSyntax body = methodDeclaration.Body; @@ -66,7 +66,7 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && methodDeclaration.SyntaxTree.IsMultiLineSpan(methodDeclaration.HeaderSpan())) { return; @@ -80,14 +80,14 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && methodDeclaration.SyntaxTree.IsMultiLineSpan(methodDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -98,20 +98,23 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && propertyDeclaration.SyntaxTree.IsMultiLineSpan(propertyDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -121,20 +124,23 @@ private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var indexerDeclaration = (IndexerDeclarationSyntax)context.Node; ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && indexerDeclaration.SyntaxTree.IsMultiLineSpan(indexerDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -144,6 +150,9 @@ private static void AnalyzeIndexerDeclaration(SyntaxNodeAnalysisContext context) private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var operatorDeclaration = (OperatorDeclarationSyntax)context.Node; BlockSyntax body = operatorDeclaration.Body; @@ -157,7 +166,7 @@ private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { return; @@ -171,14 +180,14 @@ private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -189,6 +198,9 @@ private static void AnalyzeOperatorDeclaration(SyntaxNodeAnalysisContext context private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var operatorDeclaration = (ConversionOperatorDeclarationSyntax)context.Node; BlockSyntax body = operatorDeclaration.Body; @@ -202,7 +214,7 @@ private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisConte if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { return; @@ -216,14 +228,14 @@ private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisConte if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && operatorDeclaration.SyntaxTree.IsMultiLineSpan(operatorDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -234,6 +246,9 @@ private static void AnalyzeConversionOperatorDeclaration(SyntaxNodeAnalysisConte private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node; BlockSyntax body = constructorDeclaration.Body; @@ -247,7 +262,7 @@ private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext cont if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) { return; @@ -261,14 +276,14 @@ private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext cont if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && constructorDeclaration.SyntaxTree.IsMultiLineSpan(constructorDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -279,6 +294,9 @@ private static void AnalyzeConstructorDeclaration(SyntaxNodeAnalysisContext cont private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var destructorDeclaration = (DestructorDeclarationSyntax)context.Node; BlockSyntax body = destructorDeclaration.Body; @@ -292,7 +310,7 @@ private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext conte if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) { return; @@ -306,14 +324,14 @@ private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext conte if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && destructorDeclaration.SyntaxTree.IsMultiLineSpan(destructorDeclaration.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -324,6 +342,9 @@ private static void AnalyzeDestructorDeclaration(SyntaxNodeAnalysisContext conte private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var localFunction = (LocalFunctionStatementSyntax)context.Node; BlockSyntax body = localFunction.Body; @@ -337,7 +358,7 @@ private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext cont if (!analysis.Success) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) { return; @@ -351,14 +372,14 @@ private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext cont if (expressionBody?.ContainsDirectives == false) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context) && localFunction.SyntaxTree.IsMultiLineSpan(localFunction.HeaderSpan())) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, expressionBody); return; } - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -369,6 +390,9 @@ private static void AnalyzeLocalFunctionStatement(SyntaxNodeAnalysisContext cont private static void AnalyzeAccessorDeclaration(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa.IsEffective(context)) + return; + var accessor = (AccessorDeclarationSyntax)context.Node; BlockSyntax body = accessor.Body; @@ -382,7 +406,7 @@ private static void AnalyzeAccessorDeclaration(SyntaxNodeAnalysisContext context ArrowExpressionClauseSyntax expressionBody = accessor.ExpressionBody; if (expressionBody?.ContainsDirectives == false - && !context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + && AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expressionBody.Expression?.IsMultiLine() == true) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ReportOnly.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, expressionBody); @@ -410,7 +434,7 @@ private static void AnalyzeAccessorDeclarationBlock( if (expression == null) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && expression.IsMultiLine()) { return; @@ -429,7 +453,7 @@ private static void AnalyzeAccessorDeclarationBlock( if (!SyntaxTriviaAnalysis.IsExteriorTriviaEmptyOrWhitespace(body.OpenBraceToken)) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine)) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine.IsEnabled(context)) { switch (accessorList.Parent.Kind()) { @@ -476,7 +500,7 @@ private static void AnalyzeAccessorDeclarationBlock( private static void AnalyzeBlock(SyntaxNodeAnalysisContext context, BlockSyntax block, BlockExpressionAnalysis analysis) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine) + if (AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine.IsEnabled(context) && analysis.Expression.IsMultiLine()) { return; diff --git a/src/Analyzers/CSharp/Analysis/ConvertHasFlagCallToBitwiseOperationOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertHasFlagCallToBitwiseOperationOrViceVersaAnalyzer.cs index a3237335f4..fabd454d60 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertHasFlagCallToBitwiseOperationOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertHasFlagCallToBitwiseOperationOrViceVersaAnalyzer.cs @@ -23,17 +23,21 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.IsAnalyzerSuppressed(AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeBitwiseAndExpression(f), SyntaxKind.BitwiseAndExpression); - } - else + if (AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall.IsEnabled(c)) + AnalyzeBitwiseAndExpression(c); + }, + SyntaxKind.BitwiseAndExpression); + + context.RegisterSyntaxNodeAction( + c => { - context.RegisterSyntaxNodeAction(f => AnalyzeInvocationExpression(f), SyntaxKind.InvocationExpression); - } - }); + if (!AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall.IsEnabled(c)) + AnalyzeInvocationExpression(c); + }, + SyntaxKind.InvocationExpression); } private static void AnalyzeBitwiseAndExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs index ef9768430a..bb53e23478 100644 --- a/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ConvertInterpolatedStringToConcatenationAnalyzer.cs @@ -26,13 +26,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertInterpolatedStringToConcatenation)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeInterpolatedStringExpression(f), SyntaxKind.InterpolatedStringExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.ConvertInterpolatedStringToConcatenation.IsEffective(c)) + AnalyzeInterpolatedStringExpression(c); + }, + SyntaxKind.InterpolatedStringExpression); } private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs b/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs index 3de992575f..910aefa18a 100644 --- a/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/EnumSymbolAnalyzer.cs @@ -49,7 +49,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) ImmutableArray members = default; if (hasFlagsAttribute - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.DeclareEnumMemberWithZeroValue)) + && DiagnosticDescriptors.DeclareEnumMemberWithZeroValue.IsEffective(context)) { members = typeSymbol.GetMembers(); @@ -64,7 +64,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) EnumSymbolInfo enumInfo = default; if (hasFlagsAttribute - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.CompositeEnumValueContainsUndefinedFlag)) + && DiagnosticDescriptors.CompositeEnumValueContainsUndefinedFlag.IsEffective(context)) { enumInfo = EnumSymbolInfo.Create(typeSymbol); @@ -85,7 +85,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) } if (hasFlagsAttribute - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.DeclareEnumValueAsCombinationOfNames)) + && DiagnosticDescriptors.DeclareEnumValueAsCombinationOfNames.IsEffective(context)) { if (members.IsDefault) members = typeSymbol.GetMembers(); @@ -130,7 +130,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) } if (hasFlagsAttribute - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseBitShiftOperator)) + && DiagnosticDescriptors.UseBitShiftOperator.IsEffective(context)) { if (members.IsDefault) members = typeSymbol.GetMembers(); @@ -165,7 +165,7 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) } } - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.DuplicateEnumValue)) + if (DiagnosticDescriptors.DuplicateEnumValue.IsEffective(context)) { if (enumInfo.IsDefault) enumInfo = EnumSymbolInfo.Create(typeSymbol); diff --git a/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs index e6c5eedf70..a263da17b5 100644 --- a/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs @@ -36,18 +36,19 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.AreAnalyzersSuppressed( - DiagnosticDescriptors.UseCoalesceExpressionInsteadOfIf, - DiagnosticDescriptors.ConvertIfToReturnStatement, - DiagnosticDescriptors.ConvertIfToAssignment)) + context.RegisterSyntaxNodeAction( + c => { - return; - } - - startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - }); + if (DiagnosticHelpers.IsAnyEffective( + c, + DiagnosticDescriptors.UseCoalesceExpressionInsteadOfIf, + DiagnosticDescriptors.ConvertIfToReturnStatement, + DiagnosticDescriptors.ConvertIfToAssignment)) + { + AnalyzeIfStatement(c); + } + }, + SyntaxKind.IfStatement); } private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) @@ -75,7 +76,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression: case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression: { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCoalesceExpressionInsteadOfIf)) + if (DiagnosticDescriptors.UseCoalesceExpressionInsteadOfIf.IsEffective(context)) DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.UseCoalesceExpressionInsteadOfIf, ifStatement); break; @@ -84,7 +85,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IfAnalysisKind.IfElseToYieldReturnWithExpression: case IfAnalysisKind.IfReturnToReturnWithExpression: { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertIfToReturnStatement)) + if (DiagnosticDescriptors.ConvertIfToReturnStatement.IsEffective(context)) DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ConvertIfToReturnStatement, ifStatement); break; @@ -92,7 +93,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IfAnalysisKind.IfElseToAssignmentWithExpression: case IfAnalysisKind.IfElseToAssignmentWithCondition: { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertIfToAssignment)) + if (DiagnosticDescriptors.ConvertIfToAssignment.IsEffective(context)) DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ConvertIfToAssignment, ifStatement); break; diff --git a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs index bf33048350..29dc5e08de 100644 --- a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs @@ -31,13 +31,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.InlineLocalVariable)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeLocalDeclarationStatement(f), SyntaxKind.LocalDeclarationStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.InlineLocalVariable.IsEffective(c)) + AnalyzeLocalDeclarationStatement(c); + }, + SyntaxKind.LocalDeclarationStatement); } private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs index 8a42de2709..f7061272e6 100644 --- a/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs @@ -74,10 +74,10 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex { case "Any": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCountOrLengthPropertyInsteadOfAnyMethod)) + if (DiagnosticDescriptors.UseCountOrLengthPropertyInsteadOfAnyMethod.IsEffective(context)) UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.Analyze(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) { OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); OptimizeLinqMethodCallAnalysis.AnalyzeAny(context, invocationInfo); @@ -87,17 +87,17 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "Cast": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndCast(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantCast)) + if (DiagnosticDescriptors.RemoveRedundantCast.IsEffective(context)) RemoveRedundantCastAnalyzer.Analyze(context, invocationInfo); break; } case "Count": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context) && !OptimizeLinqMethodCallAnalysis.AnalyzeSelectManyAndCount(context, invocationInfo)) { OptimizeLinqMethodCallAnalysis.AnalyzeCount(context, invocationInfo); @@ -108,7 +108,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "First": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) { if (CanUseElementAccess(context, invocationInfo) && UseElementAccessAnalysis.IsFixableFirst(invocationInfo, context.SemanticModel, context.CancellationToken)) @@ -125,24 +125,24 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "Max": case "Min": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndMinOrMax(context, invocationInfo); break; } case "Reverse": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndReverse(context, invocationInfo); break; } case "ToString": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantToStringCall)) + if (DiagnosticDescriptors.RemoveRedundantToStringCall.IsEffective(context)) RemoveRedundantToStringCallAnalysis.Analyze(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseNameOfOperator) + if (DiagnosticDescriptors.UseNameOfOperator.IsEffective(context) && ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp6) { UseNameOfOperatorAnalyzer.Analyze(context, invocationInfo); @@ -152,7 +152,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "ToList": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndToList(context, invocationInfo); break; @@ -162,14 +162,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "ToUpper": case "ToUpperInvariant": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseStringComparison)) + if (DiagnosticDescriptors.UseStringComparison.IsEffective(context)) UseStringComparisonAnalysis.Analyze(context, invocationInfo); break; } case "FirstOrDefault": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) { OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); @@ -183,14 +183,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "Single": case "SingleOrDefault": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); break; } case "OfType": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context) && !invocation.SpanContainsDirectives()) { OptimizeLinqMethodCallAnalysis.AnalyzeOfType(context, invocationInfo); @@ -200,7 +200,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "ToCharArray": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantStringToCharArrayCall)) + if (DiagnosticDescriptors.RemoveRedundantStringToCharArrayCall.IsEffective(context)) RemoveRedundantStringToCharArrayCallAnalysis.Analyze(context, invocationInfo); break; @@ -216,10 +216,10 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "All": case "Any": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.SimplifyLogicalNegation)) + if (DiagnosticDescriptors.SimplifyLogicalNegation.IsEffective(context)) SimplifyLogicalNegationAnalyzer.Analyze(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context) && !invocation.SpanContainsDirectives()) { OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndAny(context, invocationInfo); @@ -229,14 +229,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "ContainsKey": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeMethodCall)) + if (DiagnosticDescriptors.OptimizeMethodCall.IsEffective(context)) OptimizeMethodCallAnalysis.OptimizeDictionaryContainsKey(context, invocationInfo); break; } case "ElementAt": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context) && CanUseElementAccess(context, invocationInfo) && UseElementAccessAnalysis.IsFixableElementAt(invocationInfo, context.SemanticModel, context.CancellationToken)) { @@ -247,14 +247,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "FirstOrDefault": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); break; } case "GetValueOrDefault": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCoalesceExpression) + if (DiagnosticDescriptors.UseCoalesceExpression.IsEffective(context) && invocationInfo.Name.IsKind(SyntaxKind.IdentifierName) && !invocation.IsParentKind(SyntaxKind.InvocationExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) && context.SemanticModel @@ -270,24 +270,24 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "Where": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.CombineEnumerableWhereMethodChain)) + if (DiagnosticDescriptors.CombineEnumerableWhereMethodChain.IsEffective(context)) CombineEnumerableWhereMethodChainAnalysis.Analyze(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndWhere(context, invocationInfo); break; } case "Select": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); break; } case "OrderBy": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.CallThenByInsteadOfOrderBy)) + if (DiagnosticDescriptors.CallThenByInsteadOfOrderBy.IsEffective(context)) CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); break; @@ -305,7 +305,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "Matches": case "Split": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod) + if (DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) && !invocation.SpanContainsDirectives()) { UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); @@ -315,14 +315,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "Select": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeLinqMethodCall)) + if (DiagnosticDescriptors.OptimizeLinqMethodCall.IsEffective(context)) CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); break; } case "OrderBy": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.CallThenByInsteadOfOrderBy)) + if (DiagnosticDescriptors.CallThenByInsteadOfOrderBy.IsEffective(context)) CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); break; @@ -341,7 +341,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "Split": case "Replace": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod) + if (DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) && !invocation.SpanContainsDirectives()) { UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); @@ -351,14 +351,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "OrderBy": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.CallThenByInsteadOfOrderBy)) + if (DiagnosticDescriptors.CallThenByInsteadOfOrderBy.IsEffective(context)) CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); break; } case "Compare": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeMethodCall)) + if (DiagnosticDescriptors.OptimizeMethodCall.IsEffective(context)) OptimizeMethodCallAnalysis.OptimizeStringCompare(context, invocationInfo); break; @@ -373,7 +373,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex { case "Replace": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod) + if (DiagnosticDescriptors.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) && !invocation.SpanContainsDirectives()) { UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); @@ -394,7 +394,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "LastOrDefault": case "SingleOrDefault": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.AvoidNullReferenceException)) + if (DiagnosticDescriptors.AvoidNullReferenceException.IsEffective(context)) AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); break; @@ -404,17 +404,17 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "AppendFormat": case "Insert": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeStringBuilderAppendCall)) + if (DiagnosticDescriptors.OptimizeStringBuilderAppendCall.IsEffective(context)) OptimizeStringBuilderAppendCallAnalysis.Analyze(context, invocationInfo); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.AvoidBoxingOfValueType)) + if (DiagnosticDescriptors.AvoidBoxingOfValueType.IsEffective(context)) AvoidBoxingOfValueTypeAnalysis.Analyze(context, invocationInfo); break; } case "Assert": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeMethodCall) + if (DiagnosticDescriptors.OptimizeMethodCall.IsEffective(context) && (argumentCount >= 1 && argumentCount <= 3)) { OptimizeMethodCallAnalysis.OptimizeDebugAssert(context, invocationInfo); @@ -424,7 +424,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } case "Join": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.OptimizeMethodCall) + if (DiagnosticDescriptors.OptimizeMethodCall.IsEffective(context) && argumentCount >= 2) { OptimizeMethodCallAnalysis.OptimizeStringJoin(context, invocationInfo); @@ -436,7 +436,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex { if (methodName.Length > "OrDefault".Length && methodName.EndsWith("OrDefault", StringComparison.Ordinal) - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.AvoidNullReferenceException)) + && DiagnosticDescriptors.AvoidNullReferenceException.IsEffective(context)) { AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); } @@ -445,7 +445,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } } - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseMethodChaining) + if (DiagnosticDescriptors.UseMethodChaining.IsEffective(context) && UseMethodChainingAnalysis.IsFixable(invocationInfo, context.SemanticModel, context.CancellationToken)) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.UseMethodChaining, invocationInfo.InvocationExpression); @@ -456,7 +456,7 @@ public static bool CanUseElementAccess(SyntaxNodeAnalysisContext context, in Sim { return !invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression) && (!invocationInfo.Expression.IsKind(SyntaxKind.InvocationExpression) - || context.IsAnalyzerSuppressed(AnalyzerOptions.DoNotUseElementAccessWhenExpressionIsInvocation)); + || !AnalyzerOptions.DoNotUseElementAccessWhenExpressionIsInvocation.IsEnabled(context)); } } } diff --git a/src/Analyzers/CSharp/Analysis/LambdaExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/LambdaExpressionAnalyzer.cs index 6839fdeb40..81f4823eee 100644 --- a/src/Analyzers/CSharp/Analysis/LambdaExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/LambdaExpressionAnalyzer.cs @@ -25,18 +25,15 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertLambdaExpressionBodyToExpressionBody)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - }); + context.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); + context.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); } private static void AnalyzeLambdaExpression(SyntaxNodeAnalysisContext context) { + if (!DiagnosticDescriptors.ConvertLambdaExpressionBodyToExpressionBody.IsEffective(context)) + return; + var lambda = (LambdaExpressionSyntax)context.Node; if (lambda.ContainsDiagnostics) diff --git a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs index 08c36314f5..a5c3d5d225 100644 --- a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs @@ -39,9 +39,9 @@ private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) if (typeDeclaration.Modifiers.Contains(SyntaxKind.PartialKeyword)) return; - bool skipField = context.IsAnalyzerSuppressed(DiagnosticDescriptors.MakeFieldReadOnly); + bool skipField = !DiagnosticDescriptors.MakeFieldReadOnly.IsEffective(context); - bool skipProperty = context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseReadOnlyAutoProperty) + bool skipProperty = !DiagnosticDescriptors.UseReadOnlyAutoProperty.IsEffective(context) || ((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp6; MakeMemberReadOnlyWalker walker = MakeMemberReadOnlyWalker.GetInstance(); diff --git a/src/Analyzers/CSharp/Analysis/MergeElseWithNestedIfAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MergeElseWithNestedIfAnalyzer.cs index ef3b041520..a8b8bca5ba 100644 --- a/src/Analyzers/CSharp/Analysis/MergeElseWithNestedIfAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MergeElseWithNestedIfAnalyzer.cs @@ -26,13 +26,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.MergeElseWithNestedIf)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeElseClause(f), SyntaxKind.ElseClause); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.MergeElseWithNestedIf.IsEffective(c)) + AnalyzeElseClause(c); + }, + SyntaxKind.ElseClause); } private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/MergeIfWithNestedIfAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MergeIfWithNestedIfAnalyzer.cs index 68b355b598..e935fc63dd 100644 --- a/src/Analyzers/CSharp/Analysis/MergeIfWithNestedIfAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MergeIfWithNestedIfAnalyzer.cs @@ -30,13 +30,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.MergeIfWithNestedIf)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.MergeIfWithNestedIf.IsEffective(c)) + AnalyzeIfStatement(c); + }, + SyntaxKind.IfStatement); } private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs b/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs index 0ea1052f2c..beb924f63b 100644 --- a/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/NonAsynchronousMethodNameShouldNotEndWithAsyncAnalyzer.cs @@ -30,14 +30,22 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(startContext => { - if (startContext.AreAnalyzersSuppressed(DiagnosticDescriptors.AsynchronousMethodNameShouldEndWithAsync, DiagnosticDescriptors.NonAsynchronousMethodNameShouldNotEndWithAsync)) - return; - INamedTypeSymbol asyncAction = startContext.Compilation.GetTypeByMetadataName("Windows.Foundation.IAsyncAction"); bool shouldCheckWindowsRuntimeTypes = asyncAction != null; - startContext.RegisterSyntaxNodeAction(nodeContext => AnalyzeMethodDeclaration(nodeContext, shouldCheckWindowsRuntimeTypes), SyntaxKind.MethodDeclaration); + startContext.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticHelpers.IsAnyEffective( + c, + DiagnosticDescriptors.AsynchronousMethodNameShouldEndWithAsync, + DiagnosticDescriptors.NonAsynchronousMethodNameShouldNotEndWithAsync)) + { + AnalyzeMethodDeclaration(c, shouldCheckWindowsRuntimeTypes); + } + }, + SyntaxKind.MethodDeclaration); }); } diff --git a/src/Analyzers/CSharp/Analysis/ParenthesizeConditionOfConditionalExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/ParenthesizeConditionOfConditionalExpressionAnalyzer.cs index 4ada594e56..8743c1791b 100644 --- a/src/Analyzers/CSharp/Analysis/ParenthesizeConditionOfConditionalExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/ParenthesizeConditionOfConditionalExpressionAnalyzer.cs @@ -39,7 +39,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte if (kind == SyntaxKind.ParenthesizedExpression) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)) + if (AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken.IsEnabled(context)) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)condition; @@ -53,7 +53,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte } } else if (!CSharpFacts.IsSingleTokenExpression(kind) - || context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)) + || !AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.ParenthesizeConditionOfConditionalExpression, condition); } diff --git a/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs index 35d9066b05..5bd464084c 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveBracesAnalyzer.cs @@ -27,21 +27,77 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveBraces)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeCommonForEachStatement(f), SyntaxKind.ForEachStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeCommonForEachStatement(f), SyntaxKind.ForEachVariableStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeForStatement(f), SyntaxKind.ForStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeUsingStatement(f), SyntaxKind.UsingStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeWhileStatement(f), SyntaxKind.WhileStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeDoStatement(f), SyntaxKind.DoStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLockStatement(f), SyntaxKind.LockStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeFixedStatement(f), SyntaxKind.FixedStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeIfStatement(c); + }, + SyntaxKind.IfStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeCommonForEachStatement(c); + }, + SyntaxKind.ForEachStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeCommonForEachStatement(c); + }, + SyntaxKind.ForEachVariableStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeForStatement(c); + }, + SyntaxKind.ForStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeUsingStatement(c); + }, + SyntaxKind.UsingStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeWhileStatement(c); + }, + SyntaxKind.WhileStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeDoStatement(c); + }, + SyntaxKind.DoStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeLockStatement(c); + }, + SyntaxKind.LockStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBraces.IsEffective(c)) + AnalyzeFixedStatement(c); + }, + SyntaxKind.FixedStatement); } private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs index 2b3acc2a61..b58afc7708 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveBracesFromIfElseAnalyzer.cs @@ -26,13 +26,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveBracesFromIfElse)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveBracesFromIfElse.IsEffective(c)) + AnalyzeIfStatement(c); + }, + SyntaxKind.IfStatement); } private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveEmptyRegionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveEmptyRegionAnalyzer.cs index a31f909560..80bd1b597a 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveEmptyRegionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveEmptyRegionAnalyzer.cs @@ -27,13 +27,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveEmptyRegion)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeRegionDirective(f), SyntaxKind.RegionDirectiveTrivia); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveEmptyRegion.IsEffective(c)) + AnalyzeRegionDirective(c); + }, + SyntaxKind.RegionDirectiveTrivia); } private static void AnalyzeRegionDirective(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs index b5c7b6f04b..e644c8bf44 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs @@ -30,14 +30,21 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantAssignmentFadeOut)) - return; + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAssignment.IsEffective(c)) + AnalyzeLocalDeclarationStatement(c); + }, + SyntaxKind.LocalDeclarationStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLocalDeclarationStatement(f), SyntaxKind.LocalDeclarationStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleAssignment(f), SyntaxKind.SimpleAssignmentExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAssignment.IsEffective(c)) + AnalyzeSimpleAssignment(c); + }, + SyntaxKind.SimpleAssignmentExpression); } private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs index 801c23507f..cbc793d9fb 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAsyncAwaitAnalyzer.cs @@ -27,17 +27,45 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantAsyncAwait)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeMethodDeclaration(f), SyntaxKind.MethodDeclaration); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLocalFunctionStatement(f), SyntaxKind.LocalFunctionStatement); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAnonymousMethodExpression(f), SyntaxKind.AnonymousMethodExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.SimpleLambdaExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeLambdaExpression(f), SyntaxKind.ParenthesizedLambdaExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAsyncAwait.IsEffective(c)) + AnalyzeMethodDeclaration(c); + }, + SyntaxKind.MethodDeclaration); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAsyncAwait.IsEffective(c)) + AnalyzeLocalFunctionStatement(c); + }, + SyntaxKind.LocalFunctionStatement); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAsyncAwait.IsEffective(c)) + AnalyzeAnonymousMethodExpression(c); + }, + SyntaxKind.AnonymousMethodExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAsyncAwait.IsEffective(c)) + AnalyzeLambdaExpression(c); + }, + SyntaxKind.SimpleLambdaExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantAsyncAwait.IsEffective(c)) + AnalyzeLambdaExpression(c); + }, + SyntaxKind.ParenthesizedLambdaExpression); } private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantBooleanLiteralAnalysis.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantBooleanLiteralAnalysis.cs index 290d0be4b0..8cd240c15a 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantBooleanLiteralAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantBooleanLiteralAnalysis.cs @@ -16,7 +16,7 @@ public static void ReportDiagnostic( ExpressionSyntax left, ExpressionSyntax right) { - if (context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantBooleanLiteral)) + if (!DiagnosticDescriptors.RemoveRedundantBooleanLiteral.IsEffective(context)) return; if (binaryExpression.SpanContainsDirectives()) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs index d00f3d18b2..b59020a953 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantDelegateCreationAnalyzer.cs @@ -28,14 +28,21 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantDelegateCreation)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignmentExpression(f), SyntaxKind.AddAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAssignmentExpression(f), SyntaxKind.SubtractAssignmentExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantDelegateCreation.IsEffective(c)) + AnalyzeAssignmentExpression(c); + }, + SyntaxKind.AddAssignmentExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantDelegateCreation.IsEffective(c)) + AnalyzeAssignmentExpression(c); + }, + SyntaxKind.SubtractAssignmentExpression); } private static void AnalyzeAssignmentExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantEmptyLineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantEmptyLineAnalyzer.cs index c6428d9f1c..71d88db456 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantEmptyLineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantEmptyLineAnalyzer.cs @@ -122,7 +122,7 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) AnalyzeEnd(context, sections.Last(), switchStatement.CloseBraceToken); if (sections.Count > 1 - && !context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection)) + && AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection.IsEnabled(context)) { SwitchSectionSyntax prevSection = sections[0]; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs index f442ee83fe..68d4b3ca03 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs @@ -27,13 +27,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantParentheses)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeParenthesizedExpression(f), SyntaxKind.ParenthesizedExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveRedundantParentheses.IsEffective(c)) + AnalyzeParenthesizedExpression(c); + }, + SyntaxKind.ParenthesizedExpression); } private static void AnalyzeParenthesizedExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs index 4210955d72..4cdc475a4a 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBracesAnalyzer.cs @@ -26,13 +26,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveUnnecessaryBraces)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzerSwitchSection(f), SyntaxKind.SwitchSection); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.RemoveUnnecessaryBraces.IsEffective(c)) + AnalyzerSwitchSection(c); + }, + SyntaxKind.SwitchSection); } public static void AnalyzerSwitchSection(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/RenamePrivateFieldAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RenamePrivateFieldAnalyzer.cs index 08d88d18f1..fc6a36c92d 100644 --- a/src/Analyzers/CSharp/Analysis/RenamePrivateFieldAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RenamePrivateFieldAnalyzer.cs @@ -33,7 +33,7 @@ private static void AnalyzeFieldSymbol(SymbolAnalysisContext context) { if (!fieldSymbol.IsStatic || !fieldSymbol.IsReadOnly - || context.IsAnalyzerSuppressed(AnalyzerOptions.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore)) + || !AnalyzerOptions.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic( context, diff --git a/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs b/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs index b08a309bab..ae62325857 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs @@ -17,7 +17,7 @@ public static void ReportDiagnostic( ExpressionSyntax right, bool fadeOut) { - if (context.IsAnalyzerSuppressed(DiagnosticDescriptors.SimplifyBooleanComparison)) + if (!DiagnosticDescriptors.SimplifyBooleanComparison.IsEffective(context)) return; if (binaryExpression.SpanContainsDirectives()) diff --git a/src/Analyzers/CSharp/Analysis/SimplifyConditionalExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyConditionalExpressionAnalyzer.cs index 3e7441fb22..3417acf25f 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyConditionalExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyConditionalExpressionAnalyzer.cs @@ -60,7 +60,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte ReportDiagnostic(); } /// a ? false : b >>> !a && b - else if (!context.IsAnalyzerSuppressed(AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition) + else if (AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition.IsEnabled(context) && context.SemanticModel.GetTypeInfo(info.WhenFalse, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Boolean) { ReportDiagnostic(); @@ -69,7 +69,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte else if (falseKind == SyntaxKind.TrueLiteralExpression) { // a ? b : true >>> !a || b - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition) + if (AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition.IsEnabled(context) && context.SemanticModel.GetTypeInfo(info.WhenTrue, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Boolean) { ReportDiagnostic(); diff --git a/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs index 24fe2750ae..efdd3a2409 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyNestedUsingStatementAnalyzer.cs @@ -27,13 +27,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.SimplifyNestedUsingStatement)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeUsingStatement(f), SyntaxKind.UsingStatement); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.SimplifyNestedUsingStatement.IsEffective(c)) + AnalyzeUsingStatement(c); + }, + SyntaxKind.UsingStatement); } private static void AnalyzeUsingStatement(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs index d74b007031..3719dd7c1c 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyNullCheckAnalyzer.cs @@ -57,7 +57,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte if (CSharpFactory.AreEquivalent(nullCheck.Expression, whenNotNull)) { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCoalesceExpressionInsteadOfConditionalExpression) + if (DiagnosticDescriptors.UseCoalesceExpressionInsteadOfConditionalExpression.IsEffective(context) && semanticModel .GetTypeSymbol(nullCheck.Expression, cancellationToken)? .IsReferenceTypeOrNullableType() == true) @@ -103,7 +103,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte { if (memberAccessExpression == whenNotNull) { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCoalesceExpressionInsteadOfConditionalExpression)) + if (DiagnosticDescriptors.UseCoalesceExpressionInsteadOfConditionalExpression.IsEffective(context)) { DiagnosticHelpers.ReportDiagnostic( context, @@ -119,7 +119,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte } } } - else if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseConditionalAccessInsteadOfConditionalExpression) + else if (DiagnosticDescriptors.UseConditionalAccessInsteadOfConditionalExpression.IsEffective(context) && ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp6 && whenNotNull.IsKind(SyntaxKind.CastExpression) && whenNull.IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression)) @@ -161,7 +161,7 @@ private static void Analyze( SemanticModel semanticModel, CancellationToken cancellationToken) { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseConditionalAccessInsteadOfConditionalExpression) + if (DiagnosticDescriptors.UseConditionalAccessInsteadOfConditionalExpression.IsEffective(context) && ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp6) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(whenNotNull, cancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs index 01ae82d78a..db3e641ed3 100644 --- a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs @@ -34,13 +34,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.AreAnalyzersSuppressed(_supportedDiagnosticsWithoutFadeOut)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeSingleLineDocumentationCommentTrivia(f), SyntaxKind.SingleLineDocumentationCommentTrivia); - } - }); + if (IsAnyEffective(c, _supportedDiagnosticsWithoutFadeOut)) + AnalyzeSingleLineDocumentationCommentTrivia(c); + }, + SyntaxKind.SingleLineDocumentationCommentTrivia); } private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalysisContext context) @@ -96,7 +96,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys containsSummaryElement = true; - if (useCorrectDocumentationTagEnabled ??= !context.IsAnalyzerSuppressed(DiagnosticDescriptors.FixDocumentationCommentTag)) + if (useCorrectDocumentationTagEnabled ??= DiagnosticDescriptors.FixDocumentationCommentTag.IsEffective(context)) FixDocumentationCommentTagAnalysis.Analyze(context, info); break; @@ -109,7 +109,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys if (info.IsContentEmptyOrWhitespace) ReportUnusedElement(context, info.Element, i, content); - if (useCorrectDocumentationTagEnabled ??= !context.IsAnalyzerSuppressed(DiagnosticDescriptors.FixDocumentationCommentTag)) + if (useCorrectDocumentationTagEnabled ??= DiagnosticDescriptors.FixDocumentationCommentTag.IsEffective(context)) FixDocumentationCommentTagAnalysis.Analyze(context, info); break; @@ -120,7 +120,7 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys case XmlTag.Permission: case XmlTag.TypeParam: { - if (useCorrectDocumentationTagEnabled ??= !context.IsAnalyzerSuppressed(DiagnosticDescriptors.FixDocumentationCommentTag)) + if (useCorrectDocumentationTagEnabled ??= DiagnosticDescriptors.FixDocumentationCommentTag.IsEffective(context)) FixDocumentationCommentTagAnalysis.Analyze(context, info); break; @@ -167,10 +167,10 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys SyntaxNode parent = documentationComment.ParentTrivia.Token.Parent; - bool unusedElement = !context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnusedElementInDocumentationComment); - bool orderParams = !context.IsAnalyzerSuppressed(DiagnosticDescriptors.OrderElementsInDocumentationComment); - bool addParam = !context.IsAnalyzerSuppressed(DiagnosticDescriptors.AddParamElementToDocumentationComment); - bool addTypeParam = !context.IsAnalyzerSuppressed(DiagnosticDescriptors.AddTypeParamElementToDocumentationComment); + bool unusedElement = DiagnosticDescriptors.UnusedElementInDocumentationComment.IsEffective(context); + bool orderParams = DiagnosticDescriptors.OrderElementsInDocumentationComment.IsEffective(context); + bool addParam = DiagnosticDescriptors.AddParamElementToDocumentationComment.IsEffective(context); + bool addTypeParam = DiagnosticDescriptors.AddTypeParamElementToDocumentationComment.IsEffective(context); if (addParam || orderParams @@ -337,7 +337,7 @@ private static void ReportUnusedElement( int index, SyntaxList xmlNodes) { - if (context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnusedElementInDocumentationComment)) + if (!DiagnosticDescriptors.UnusedElementInDocumentationComment.IsEffective(context)) return; ReportDiagnostic(context, DiagnosticDescriptors.UnusedElementInDocumentationComment, xmlNode); diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs index ed3e9da6e3..6c246b6471 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryInterpolatedStringAnalyzer.cs @@ -27,13 +27,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UnnecessaryInterpolatedString)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeInterpolatedStringExpression(f), SyntaxKind.InterpolatedStringExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UnnecessaryInterpolatedString.IsEffective(c)) + AnalyzeInterpolatedStringExpression(c); + }, + SyntaxKind.InterpolatedStringExpression); } private static void AnalyzeInterpolatedStringExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs index 25f663c76b..58a5345782 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs @@ -146,10 +146,7 @@ private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) break; if (declaration.ReturnsVoid() - && EditorConfigOptions.IsTrue( - context, - declaration.SyntaxTree, - EditorConfigIdentifiers.SuppressUnityScriptMethods)) + && AnalyzerOptions.SuppressUnityScriptMethods.IsEnabled(context)) { if (canContainUnityScriptMethods == null) { diff --git a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs index 5d0ac09594..ac44b50035 100644 --- a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs @@ -31,13 +31,13 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UseAutoProperty)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzePropertyDeclaration(f), SyntaxKind.PropertyDeclaration); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseAutoProperty.IsEffective(c)) + AnalyzePropertyDeclaration(c); + }, + SyntaxKind.PropertyDeclaration); } private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/UseCoalesceExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseCoalesceExpressionAnalyzer.cs index cf6659e3a6..4141798d21 100644 --- a/src/Analyzers/CSharp/Analysis/UseCoalesceExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseCoalesceExpressionAnalyzer.cs @@ -74,7 +74,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) int index = statements.IndexOf(ifStatement); if (index > 0 - && !context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCoalesceExpression)) + && DiagnosticDescriptors.UseCoalesceExpression.IsEffective(context)) { StatementSyntax previousStatement = statements[index - 1]; @@ -87,7 +87,7 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) } } - if (context.IsAnalyzerSuppressed(DiagnosticDescriptors.InlineLazyInitialization)) + if (!DiagnosticDescriptors.InlineLazyInitialization.IsEffective(context)) return; if (index == statements.Count - 1) diff --git a/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs index abebbd70e0..cb2c3b62d8 100644 --- a/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs @@ -26,15 +26,26 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseCompoundAssignment.IsEffective(c)) + AnalyzeSimpleAssignment(c); + }, + SyntaxKind.SimpleAssignmentExpression); + context.RegisterCompilationStartAction(startContext => { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UseCompoundAssignment)) - return; - - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleAssignment(f), SyntaxKind.SimpleAssignmentExpression); - if (((CSharpCompilation)startContext.Compilation).LanguageVersion >= LanguageVersion.CSharp8) - startContext.RegisterSyntaxNodeAction(f => AnalyzeCoalesceExpression(f), SyntaxKind.CoalesceExpression); + { + startContext.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseCompoundAssignment.IsEffective(c)) + AnalyzeCoalesceExpression(c); + }, + SyntaxKind.CoalesceExpression); + } }); } diff --git a/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaAnalyzer.cs index 4ad6b18ec4..00cb0a0559 100644 --- a/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaAnalyzer.cs @@ -21,18 +21,29 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleMemberAccessExpression(f), SyntaxKind.SimpleMemberAccessExpression); - } - else + if (!AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral.IsEnabled(c)) + AnalyzeSimpleMemberAccessExpression(c); + }, + SyntaxKind.SimpleMemberAccessExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral.IsEnabled(c)) + AnalyzeStringLiteralExpression(c); + }, + SyntaxKind.StringLiteralExpression); + + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeStringLiteralExpression(f), SyntaxKind.StringLiteralExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeInterpolatedStringExpression(f), SyntaxKind.InterpolatedStringExpression); - } - }); + if (AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral.IsEnabled(c)) + AnalyzeInterpolatedStringExpression(c); + }, + SyntaxKind.InterpolatedStringExpression); } private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/UseExplicitlyTypedArrayOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExplicitlyTypedArrayOrViceVersaAnalyzer.cs index 66445ce705..1039f1eb9b 100644 --- a/src/Analyzers/CSharp/Analysis/UseExplicitlyTypedArrayOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExplicitlyTypedArrayOrViceVersaAnalyzer.cs @@ -21,17 +21,27 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - bool useImplicit = !startContext.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArray); - bool useImplicitWhenObvious = !startContext.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious); - - if (useImplicitWhenObvious || !useImplicit) - startContext.RegisterSyntaxNodeAction(f => AnalyzeImplicitArrayCreationExpression(f), SyntaxKind.ImplicitArrayCreationExpression); + context.RegisterSyntaxNodeAction( + c => + { + if (AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious.IsEnabled(c) + || !AnalyzerOptions.UseImplicitlyTypedArray.IsEnabled(c)) + { + AnalyzeImplicitArrayCreationExpression(c); + } + }, + SyntaxKind.ImplicitArrayCreationExpression); - if (useImplicitWhenObvious || useImplicit) - startContext.RegisterSyntaxNodeAction(f => AnalyzeArrayCreationExpression(f), SyntaxKind.ArrayCreationExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious.IsEnabled(c) + || AnalyzerOptions.UseImplicitlyTypedArray.IsEnabled(c)) + { + AnalyzeArrayCreationExpression(c); + } + }, + SyntaxKind.ArrayCreationExpression); } private static void AnalyzeImplicitArrayCreationExpression(SyntaxNodeAnalysisContext context) @@ -50,7 +60,7 @@ private static void AnalyzeImplicitArrayCreationExpression(SyntaxNodeAnalysisCon if (expression.CloseBracketToken.ContainsDirectives) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)) + if (AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious.IsEnabled(context)) { InitializerExpressionSyntax initializer = expression.Initializer; @@ -100,7 +110,7 @@ private static void AnalyzeArrayCreationExpression(SyntaxNodeAnalysisContext con if (!expressions.Any()) return; - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)) + if (AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious.IsEnabled(context)) { foreach (ExpressionSyntax expression in expressions) { diff --git a/src/Analyzers/CSharp/Analysis/UseIsNullPatternInsteadOfComparisonOrViceVersaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseIsNullPatternInsteadOfComparisonOrViceVersaAnalyzer.cs index 96554ddb63..cc971fd408 100644 --- a/src/Analyzers/CSharp/Analysis/UseIsNullPatternInsteadOfComparisonOrViceVersaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseIsNullPatternInsteadOfComparisonOrViceVersaAnalyzer.cs @@ -22,20 +22,32 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (!startContext.IsAnalyzerSuppressed(AnalyzerOptions.UseComparisonInsteadOfIsNullPattern)) + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeIsPatternExpression(f), SyntaxKind.IsPatternExpression); - } - else + if (AnalyzerOptions.UseComparisonInsteadOfIsNullPattern.IsEnabled(c)) + AnalyzeIsPatternExpression(c); + }, + SyntaxKind.IsPatternExpression); + + context.RegisterSyntaxNodeAction( + c => { - startContext.RegisterSyntaxNodeAction(f => AnalyzeEqualsExpression(f), SyntaxKind.EqualsExpression); + if (!AnalyzerOptions.UseComparisonInsteadOfIsNullPattern.IsEnabled(c)) + AnalyzeEqualsExpression(c); + }, + SyntaxKind.EqualsExpression); - if (!startContext.IsAnalyzerSuppressed(AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator)) - startContext.RegisterSyntaxNodeAction(f => AnalyzeNotEqualsExpression(f), SyntaxKind.NotEqualsExpression); - } - }); + context.RegisterSyntaxNodeAction( + c => + { + if (!AnalyzerOptions.UseComparisonInsteadOfIsNullPattern.IsEnabled(c) + && AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator.IsEnabled(c)) + { + AnalyzeNotEqualsExpression(c); + } + }, + SyntaxKind.NotEqualsExpression); } private static void AnalyzeEqualsExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs index ce9486dd65..884be59c79 100644 --- a/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseNameOfOperatorAnalyzer.cs @@ -32,13 +32,16 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(startContext => { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UseNameOfOperator)) - return; - if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6) return; - startContext.RegisterSyntaxNodeAction(f => AnalyzeArgument(f), SyntaxKind.Argument); + startContext.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseNameOfOperator.IsEffective(c)) + AnalyzeArgument(c); + }, + SyntaxKind.Argument); }); } diff --git a/src/Analyzers/CSharp/Analysis/UseUnaryOperatorInsteadOfAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseUnaryOperatorInsteadOfAssignmentAnalyzer.cs index 96308331ad..51ef5e7279 100644 --- a/src/Analyzers/CSharp/Analysis/UseUnaryOperatorInsteadOfAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseUnaryOperatorInsteadOfAssignmentAnalyzer.cs @@ -27,15 +27,29 @@ public override void Initialize(AnalysisContext context) { base.Initialize(context); - context.RegisterCompilationStartAction(startContext => - { - if (startContext.IsAnalyzerSuppressed(DiagnosticDescriptors.UseUnaryOperatorInsteadOfAssignment)) - return; + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseUnaryOperatorInsteadOfAssignment.IsEffective(c)) + AnalyzeSimpleAssignmentExpression(c); + }, + SyntaxKind.SimpleAssignmentExpression); + + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseUnaryOperatorInsteadOfAssignment.IsEffective(c)) + AnalyzeAddAssignmentExpression(c); + }, + SyntaxKind.AddAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSimpleAssignmentExpression(f), SyntaxKind.SimpleAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeAddAssignmentExpression(f), SyntaxKind.AddAssignmentExpression); - startContext.RegisterSyntaxNodeAction(f => AnalyzeSubtractAssignmentExpression(f), SyntaxKind.SubtractAssignmentExpression); - }); + context.RegisterSyntaxNodeAction( + c => + { + if (DiagnosticDescriptors.UseUnaryOperatorInsteadOfAssignment.IsEffective(c)) + AnalyzeSubtractAssignmentExpression(c); + }, + SyntaxKind.SubtractAssignmentExpression); } private static void AnalyzeSimpleAssignmentExpression(SyntaxNodeAnalysisContext context) diff --git a/src/Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs b/src/Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs new file mode 100644 index 0000000000..f6e280e84a --- /dev/null +++ b/src/Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs @@ -0,0 +1,217 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +// + +using System; +using Microsoft.CodeAnalysis; + +namespace Roslynator.CSharp +{ + public static partial class AnalyzerOptionDiagnosticDescriptors + { + /// RCS1014a + public static readonly DiagnosticDescriptor UseImplicitlyTypedArrayWhenTypeIsObvious = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.UseImplicitlyTypedArrayWhenTypeIsObvious, + title: "Use implicitly typed array (when type is obvious).", + messageFormat: "Use implicitly typed array (when type is obvious).", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.UseImplicitlyTypedArrayWhenTypeIsObvious, + customTags: WellKnownDiagnosticTags.Unnecessary); + + /// RCS1014i + public static readonly DiagnosticDescriptor UseImplicitlyTypedArray = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.UseImplicitlyTypedArray, + title: "Use implicitly typed array.", + messageFormat: "Use implicitly typed array.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.UseImplicitlyTypedArray, + customTags: Array.Empty()); + + /// RCS1016a + public static readonly DiagnosticDescriptor ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, + title: "Convert expression-body to block body when expression is multi-line.", + messageFormat: "Convert expression-body to block body when expression is multi-line.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Hidden, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, + customTags: Array.Empty()); + + /// RCS1016b + public static readonly DiagnosticDescriptor ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, + title: "Convert expression-body to block body when declaration is multi-line.", + messageFormat: "Convert expression-body to block body when declaration is multi-line.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Hidden, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, + customTags: Array.Empty()); + + /// RCS1018i + public static readonly DiagnosticDescriptor RemoveAccessibilityModifiers = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveAccessibilityModifiers, + title: "Remove accessibility modifiers.", + messageFormat: "Remove accessibility modifiers.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveAccessibilityModifiers, + customTags: WellKnownDiagnosticTags.Unnecessary); + + /// RCS1036a + public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenClosingBraceAndSwitchSection = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, + title: "Remove empty line between closing brace and switch section.", + messageFormat: "Remove empty line between closing brace and switch section.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, + customTags: Array.Empty()); + + /// RCS1045a + public static readonly DiagnosticDescriptor DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, + title: "Do not rename private static read-only field to camel case with underscore.", + messageFormat: "Do not rename private static read-only field to camel case with underscore.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, + customTags: Array.Empty()); + + /// RCS1050i + public static readonly DiagnosticDescriptor RemoveArgumentListFromObjectCreation = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveArgumentListFromObjectCreation, + title: "Remove argument list from object creation expression.", + messageFormat: "Remove argument list from object creation expression.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveArgumentListFromObjectCreation, + customTags: Array.Empty()); + + /// RCS1051a + public static readonly DiagnosticDescriptor RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, + title: "Remove parentheses from condition of conditional expression (when condition is a single token).", + messageFormat: "Remove parentheses from condition of conditional expression (when condition is a single token).", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, + customTags: Array.Empty()); + + /// RCS1078i + public static readonly DiagnosticDescriptor UseStringEmptyInsteadOfEmptyStringLiteral = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral, + title: "Use string.Empty instead of \"\".", + messageFormat: "Use string.Empty instead of \"\".", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral, + customTags: Array.Empty()); + + /// RCS1090i + public static readonly DiagnosticDescriptor RemoveCallToConfigureAwait = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveCallToConfigureAwait, + title: "Remove call to 'ConfigureAwait'.", + messageFormat: "Remove call to 'ConfigureAwait'.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveCallToConfigureAwait, + customTags: WellKnownDiagnosticTags.Unnecessary); + + /// RCS1096i + public static readonly DiagnosticDescriptor ConvertBitwiseOperationToHasFlagCall = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.ConvertBitwiseOperationToHasFlagCall, + title: "Convert bitwise operation to 'HasFlag' call.", + messageFormat: "Convert bitwise operation to 'HasFlag' call.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.ConvertBitwiseOperationToHasFlagCall, + customTags: Array.Empty()); + + /// RCS1104a + public static readonly DiagnosticDescriptor SimplifyConditionalExpressionWhenItIncludesNegationOfCondition = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, + title: "Simplify conditional expression (when it includes negation of condition).", + messageFormat: "Simplify conditional expression (when it includes negation of condition).", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, + customTags: Array.Empty()); + + /// RCS1207i + public static readonly DiagnosticDescriptor ConvertMethodGroupToAnonymousFunction = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.ConvertMethodGroupToAnonymousFunction, + title: "Convert method group to anonymous function.", + messageFormat: "Convert method group to anonymous function.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Hidden, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.ConvertMethodGroupToAnonymousFunction, + customTags: Array.Empty()); + + /// RCS1246a + public static readonly DiagnosticDescriptor DoNotUseElementAccessWhenExpressionIsInvocation = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.DoNotUseElementAccessWhenExpressionIsInvocation, + title: "Do not use element access when expression is invocation.", + messageFormat: "Do not use element access when expression is invocation.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.DoNotUseElementAccessWhenExpressionIsInvocation, + customTags: Array.Empty()); + + /// RCS1248a + public static readonly DiagnosticDescriptor UseIsNullPatternInsteadOfInequalityOperator = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.UseIsNullPatternInsteadOfInequalityOperator, + title: "Use 'is null' pattern instead of '!=' operator.", + messageFormat: "Use 'is null' pattern instead of '!=' operator.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.UseIsNullPatternInsteadOfInequalityOperator, + customTags: Array.Empty()); + + /// RCS1248i + public static readonly DiagnosticDescriptor UseComparisonInsteadOfIsNullPattern = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.UseComparisonInsteadOfIsNullPattern, + title: "Use comparison instead of 'is null' pattern.", + messageFormat: "Use comparison instead of 'is null' pattern.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.UseComparisonInsteadOfIsNullPattern, + customTags: Array.Empty()); + + } +} \ No newline at end of file diff --git a/src/Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs b/src/Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs similarity index 96% rename from src/Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs rename to src/Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs index c042256069..3636fc33be 100644 --- a/src/Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs +++ b/src/Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs @@ -6,7 +6,7 @@ namespace Roslynator.CSharp { - public static partial class AnalyzerOptionIdentifiers + public static partial class AnalyzerOptionDiagnosticIdentifiers { public const string UseImplicitlyTypedArrayWhenTypeIsObvious = "RCS1014a"; public const string UseImplicitlyTypedArray = "RCS1014i"; diff --git a/src/Analyzers/CSharp/AnalyzerOptions.Generated.cs b/src/Analyzers/CSharp/AnalyzerOptions.Generated.cs index 89466c7595..794f5f31c4 100644 --- a/src/Analyzers/CSharp/AnalyzerOptions.Generated.cs +++ b/src/Analyzers/CSharp/AnalyzerOptions.Generated.cs @@ -2,311 +2,27 @@ // -using System; -using Microsoft.CodeAnalysis; - namespace Roslynator.CSharp { public static partial class AnalyzerOptions { - /// RCS1014a - public static readonly DiagnosticDescriptor UseImplicitlyTypedArrayWhenTypeIsObvious = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.UseImplicitlyTypedArrayWhenTypeIsObvious, - title: "Use implicitly typed array (when type is obvious).", - messageFormat: "Use implicitly typed array (when type is obvious).", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.UseImplicitlyTypedArrayWhenTypeIsObvious, - customTags: WellKnownDiagnosticTags.Unnecessary); - - /// RCS1014i - public static readonly DiagnosticDescriptor UseImplicitlyTypedArray = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.UseImplicitlyTypedArray, - title: "Use implicitly typed array.", - messageFormat: "Use implicitly typed array.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.UseImplicitlyTypedArray, - customTags: Array.Empty()); - - /// RCS1016a - public static readonly DiagnosticDescriptor ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, - title: "Convert expression-body to block body when expression is multi-line.", - messageFormat: "Convert expression-body to block body when expression is multi-line.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Hidden, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, - customTags: Array.Empty()); - - /// RCS1016b - public static readonly DiagnosticDescriptor ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, - title: "Convert expression-body to block body when declaration is multi-line.", - messageFormat: "Convert expression-body to block body when declaration is multi-line.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Hidden, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, - customTags: Array.Empty()); - - /// RCS1018i - public static readonly DiagnosticDescriptor RemoveAccessibilityModifiers = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveAccessibilityModifiers, - title: "Remove accessibility modifiers.", - messageFormat: "Remove accessibility modifiers.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveAccessibilityModifiers, - customTags: WellKnownDiagnosticTags.Unnecessary); - - /// RCS1036a - public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenClosingBraceAndSwitchSection = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, - title: "Remove empty line between closing brace and switch section.", - messageFormat: "Remove empty line between closing brace and switch section.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, - customTags: Array.Empty()); - - /// RCS1045a - public static readonly DiagnosticDescriptor DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, - title: "Do not rename private static read-only field to camel case with underscore.", - messageFormat: "Do not rename private static read-only field to camel case with underscore.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, - customTags: Array.Empty()); - - /// RCS1050i - public static readonly DiagnosticDescriptor RemoveArgumentListFromObjectCreation = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveArgumentListFromObjectCreation, - title: "Remove argument list from object creation expression.", - messageFormat: "Remove argument list from object creation expression.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveArgumentListFromObjectCreation, - customTags: Array.Empty()); - - /// RCS1051a - public static readonly DiagnosticDescriptor RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, - title: "Remove parentheses from condition of conditional expression (when condition is a single token).", - messageFormat: "Remove parentheses from condition of conditional expression (when condition is a single token).", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, - customTags: Array.Empty()); - - /// RCS1078i - public static readonly DiagnosticDescriptor UseStringEmptyInsteadOfEmptyStringLiteral = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral, - title: "Use string.Empty instead of \"\".", - messageFormat: "Use string.Empty instead of \"\".", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral, - customTags: Array.Empty()); - - /// RCS1090i - public static readonly DiagnosticDescriptor RemoveCallToConfigureAwait = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveCallToConfigureAwait, - title: "Remove call to 'ConfigureAwait'.", - messageFormat: "Remove call to 'ConfigureAwait'.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveCallToConfigureAwait, - customTags: WellKnownDiagnosticTags.Unnecessary); - - /// RCS1096i - public static readonly DiagnosticDescriptor ConvertBitwiseOperationToHasFlagCall = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.ConvertBitwiseOperationToHasFlagCall, - title: "Convert bitwise operation to 'HasFlag' call.", - messageFormat: "Convert bitwise operation to 'HasFlag' call.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.ConvertBitwiseOperationToHasFlagCall, - customTags: Array.Empty()); - - /// RCS1104a - public static readonly DiagnosticDescriptor SimplifyConditionalExpressionWhenItIncludesNegationOfCondition = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, - title: "Simplify conditional expression (when it includes negation of condition).", - messageFormat: "Simplify conditional expression (when it includes negation of condition).", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, - customTags: Array.Empty()); - - /// RCS1207i - public static readonly DiagnosticDescriptor ConvertMethodGroupToAnonymousFunction = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.ConvertMethodGroupToAnonymousFunction, - title: "Convert method group to anonymous function.", - messageFormat: "Convert method group to anonymous function.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Hidden, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.ConvertMethodGroupToAnonymousFunction, - customTags: Array.Empty()); - - /// RCS1246a - public static readonly DiagnosticDescriptor DoNotUseElementAccessWhenExpressionIsInvocation = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.DoNotUseElementAccessWhenExpressionIsInvocation, - title: "Do not use element access when expression is invocation.", - messageFormat: "Do not use element access when expression is invocation.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.DoNotUseElementAccessWhenExpressionIsInvocation, - customTags: Array.Empty()); - - /// RCS1248a - public static readonly DiagnosticDescriptor UseIsNullPatternInsteadOfInequalityOperator = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.UseIsNullPatternInsteadOfInequalityOperator, - title: "Use 'is null' pattern instead of '!=' operator.", - messageFormat: "Use 'is null' pattern instead of '!=' operator.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.UseIsNullPatternInsteadOfInequalityOperator, - customTags: Array.Empty()); - - /// RCS1248i - public static readonly DiagnosticDescriptor UseComparisonInsteadOfIsNullPattern = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.UseComparisonInsteadOfIsNullPattern, - title: "Use comparison instead of 'is null' pattern.", - messageFormat: "Use comparison instead of 'is null' pattern.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.UseComparisonInsteadOfIsNullPattern, - customTags: Array.Empty()); - - public static bool IsEnabled(CompilationOptions compilationOptions, DiagnosticDescriptor analyzerOption) - { - switch (analyzerOption.Id) - { - case AnalyzerOptionIdentifiers.UseImplicitlyTypedArrayWhenTypeIsObvious: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseExplicitlyTypedArrayOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious); - } - - case AnalyzerOptionIdentifiers.UseImplicitlyTypedArray: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseExplicitlyTypedArrayOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.UseImplicitlyTypedArray); - } - - case AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine); - } - - case AnalyzerOptionIdentifiers.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine); - } - - case AnalyzerOptionIdentifiers.RemoveAccessibilityModifiers: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddAccessibilityModifiersOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveAccessibilityModifiers); - } - - case AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenClosingBraceAndSwitchSection: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveRedundantEmptyLine) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection); - } - - case AnalyzerOptionIdentifiers.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.RenamePrivateFieldToCamelCaseWithUnderscore) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore); - } - - case AnalyzerOptionIdentifiers.RemoveArgumentListFromObjectCreation: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddArgumentListToObjectCreationOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveArgumentListFromObjectCreation); - } - - case AnalyzerOptionIdentifiers.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.ParenthesizeConditionOfConditionalExpression) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken); - } - - case AnalyzerOptionIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral); - } - - case AnalyzerOptionIdentifiers.RemoveCallToConfigureAwait: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddCallToConfigureAwaitOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveCallToConfigureAwait); - } - - case AnalyzerOptionIdentifiers.ConvertBitwiseOperationToHasFlagCall: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertHasFlagCallToBitwiseOperationOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall); - } - - case AnalyzerOptionIdentifiers.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.SimplifyConditionalExpression) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition); - } - - case AnalyzerOptionIdentifiers.ConvertMethodGroupToAnonymousFunction: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.ConvertMethodGroupToAnonymousFunction); - } - - case AnalyzerOptionIdentifiers.DoNotUseElementAccessWhenExpressionIsInvocation: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseElementAccess) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.DoNotUseElementAccessWhenExpressionIsInvocation); - } - - case AnalyzerOptionIdentifiers.UseIsNullPatternInsteadOfInequalityOperator: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseIsNullPatternInsteadOfComparisonOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator); - } - - case AnalyzerOptionIdentifiers.UseComparisonInsteadOfIsNullPattern: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.UseIsNullPatternInsteadOfComparisonOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.UseComparisonInsteadOfIsNullPattern); - } - - default: - { - throw new ArgumentException("", nameof(analyzerOption)); - } - } - } + internal static readonly AnalyzerOptionDescriptor SuppressUnityScriptMethods = new AnalyzerOptionDescriptor(null, DiagnosticDescriptors.RemoveUnusedMemberDeclaration, "roslynator.RCS1213.suppress_unity_script_methods"); + internal static readonly AnalyzerOptionDescriptor UseImplicitlyTypedArrayWhenTypeIsObvious = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious, DiagnosticDescriptors.UseExplicitlyTypedArrayOrViceVersa, "roslynator.RCS1014.use_implicit_type_when_obvious"); + internal static readonly AnalyzerOptionDescriptor ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa, "roslynator.RCS1016.use_block_body_when_expression_is_multiline"); + internal static readonly AnalyzerOptionDescriptor RemoveEmptyLineBetweenClosingBraceAndSwitchSection = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, DiagnosticDescriptors.RemoveRedundantEmptyLine, "roslynator.RCS1036.remove_empty_line_between_closing_brace_and_switch_section"); + internal static readonly AnalyzerOptionDescriptor DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, DiagnosticDescriptors.RenamePrivateFieldToCamelCaseWithUnderscore, "roslynator.RCS1045.suppress_private_static_readonly_field"); + internal static readonly AnalyzerOptionDescriptor RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, DiagnosticDescriptors.ParenthesizeConditionOfConditionalExpression, "roslynator.RCS1051.do_not_parenthesize_single_token"); + internal static readonly AnalyzerOptionDescriptor SimplifyConditionalExpressionWhenItIncludesNegationOfCondition = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, DiagnosticDescriptors.SimplifyConditionalExpression, "roslynator.RCS1104.enable_negation_of_condition"); + internal static readonly AnalyzerOptionDescriptor DoNotUseElementAccessWhenExpressionIsInvocation = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.DoNotUseElementAccessWhenExpressionIsInvocation, DiagnosticDescriptors.UseElementAccess, "roslynator.RCS1246.suppress_when_expression_is_invocation"); + internal static readonly AnalyzerOptionDescriptor UseIsNullPatternInsteadOfInequalityOperator = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.UseIsNullPatternInsteadOfInequalityOperator, DiagnosticDescriptors.UseIsNullPatternInsteadOfComparisonOrViceVersa, "roslynator.RCS1248.enable_inequality_operator"); + internal static readonly AnalyzerOptionDescriptor ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, DiagnosticDescriptors.ConvertBlockBodyToExpressionBodyOrViceVersa, "roslynator.RCS1016.use_block_body_when_declaration_is_multiline"); + internal static readonly AnalyzerOptionDescriptor UseImplicitlyTypedArray = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArray, DiagnosticDescriptors.UseExplicitlyTypedArrayOrViceVersa, "roslynator.RCS1014.invert"); + internal static readonly AnalyzerOptionDescriptor RemoveAccessibilityModifiers = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveAccessibilityModifiers, DiagnosticDescriptors.AddAccessibilityModifiersOrViceVersa, "roslynator.RCS1018.invert"); + internal static readonly AnalyzerOptionDescriptor RemoveArgumentListFromObjectCreation = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveArgumentListFromObjectCreation, DiagnosticDescriptors.AddArgumentListToObjectCreationOrViceVersa, "roslynator.RCS1050.invert"); + internal static readonly AnalyzerOptionDescriptor UseStringEmptyInsteadOfEmptyStringLiteral = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.UseStringEmptyInsteadOfEmptyStringLiteral, DiagnosticDescriptors.UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersa, "roslynator.RCS1078.invert"); + internal static readonly AnalyzerOptionDescriptor RemoveCallToConfigureAwait = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveCallToConfigureAwait, DiagnosticDescriptors.AddCallToConfigureAwaitOrViceVersa, "roslynator.RCS1090.invert"); + internal static readonly AnalyzerOptionDescriptor ConvertBitwiseOperationToHasFlagCall = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.ConvertBitwiseOperationToHasFlagCall, DiagnosticDescriptors.ConvertHasFlagCallToBitwiseOperationOrViceVersa, "roslynator.RCS1096.invert"); + internal static readonly AnalyzerOptionDescriptor ConvertMethodGroupToAnonymousFunction = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.ConvertMethodGroupToAnonymousFunction, DiagnosticDescriptors.ConvertAnonymousFunctionToMethodGroupOrViceVersa, "roslynator.RCS1207.invert"); + internal static readonly AnalyzerOptionDescriptor UseComparisonInsteadOfIsNullPattern = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.UseComparisonInsteadOfIsNullPattern, DiagnosticDescriptors.UseIsNullPatternInsteadOfComparisonOrViceVersa, "roslynator.RCS1248.invert"); } } \ No newline at end of file diff --git a/src/Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs b/src/Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs index 3745c8d989..eda0e9284b 100644 --- a/src/Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs +++ b/src/Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs @@ -15,7 +15,7 @@ public override ImmutableArray SupportedDiagnostics { get { - return ImmutableArray.Create(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious, AnalyzerOptions.UseImplicitlyTypedArray, AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, AnalyzerOptions.RemoveAccessibilityModifiers, AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, AnalyzerOptions.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, AnalyzerOptions.RemoveArgumentListFromObjectCreation, AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral, AnalyzerOptions.RemoveCallToConfigureAwait, AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall, AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, AnalyzerOptions.ConvertMethodGroupToAnonymousFunction, AnalyzerOptions.DoNotUseElementAccessWhenExpressionIsInvocation, AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator, AnalyzerOptions.UseComparisonInsteadOfIsNullPattern); + return ImmutableArray.Create(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious, AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArray, AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine, AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine, AnalyzerOptionDiagnosticDescriptors.RemoveAccessibilityModifiers, AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenClosingBraceAndSwitchSection, AnalyzerOptionDiagnosticDescriptors.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore, AnalyzerOptionDiagnosticDescriptors.RemoveArgumentListFromObjectCreation, AnalyzerOptionDiagnosticDescriptors.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken, AnalyzerOptionDiagnosticDescriptors.UseStringEmptyInsteadOfEmptyStringLiteral, AnalyzerOptionDiagnosticDescriptors.RemoveCallToConfigureAwait, AnalyzerOptionDiagnosticDescriptors.ConvertBitwiseOperationToHasFlagCall, AnalyzerOptionDiagnosticDescriptors.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition, AnalyzerOptionDiagnosticDescriptors.ConvertMethodGroupToAnonymousFunction, AnalyzerOptionDiagnosticDescriptors.DoNotUseElementAccessWhenExpressionIsInvocation, AnalyzerOptionDiagnosticDescriptors.UseIsNullPatternInsteadOfInequalityOperator, AnalyzerOptionDiagnosticDescriptors.UseComparisonInsteadOfIsNullPattern); } } diff --git a/src/Analyzers/CSharp/EditorConfigIdentifiers.cs b/src/Analyzers/CSharp/EditorConfigIdentifiers.cs deleted file mode 100644 index d72d629409..0000000000 --- a/src/Analyzers/CSharp/EditorConfigIdentifiers.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Roslynator.CSharp -{ - internal static class EditorConfigIdentifiers - { - public static readonly string SuppressUnityScriptMethods - = $"roslynator.{DiagnosticIdentifiers.RemoveUnusedMemberDeclaration}.suppress_unity_script_methods"; - } -} diff --git a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs index d53787a55b..921400b6fa 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs @@ -56,7 +56,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex { case "First": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseElementAccess)) + if (DiagnosticDescriptors.UseElementAccess.IsEffective(context)) UseElementAccessInsteadOfCallingFirst(); break; @@ -71,14 +71,14 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex { case "ElementAt": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseElementAccess)) + if (DiagnosticDescriptors.UseElementAccess.IsEffective(context)) UseElementAccessInsteadOfCallingElementAt(); break; } case "IsKind": { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnnecessaryNullCheck)) + if (DiagnosticDescriptors.UnnecessaryNullCheck.IsEffective(context)) AnalyzeUnnecessaryNullCheck(); break; @@ -89,7 +89,7 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex } } - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UseReturnValue) + if (DiagnosticDescriptors.UseReturnValue.IsEffective(context) && invocationExpression.IsParentKind(SyntaxKind.ExpressionStatement)) { UseReturnValue(); diff --git a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs index a2e94c3c77..86943d3cb9 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs @@ -86,7 +86,7 @@ private static void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext context, INa if (attribute == null) return; - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnknownLanguageName)) + if (DiagnosticDescriptors.UnknownLanguageName.IsEffective(context)) AnalyzeLanguageName(context, attribute); } @@ -97,10 +97,10 @@ private static void AnalyzeCodeFixProvider(SymbolAnalysisContext context, INamed if (attribute == null) return; - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnknownLanguageName)) + if (DiagnosticDescriptors.UnknownLanguageName.IsEffective(context)) AnalyzeLanguageName(context, attribute); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.SpecifyExportCodeFixProviderAttributeName) + if (DiagnosticDescriptors.SpecifyExportCodeFixProviderAttributeName.IsEffective(context) && !ContainsNamedArgument(attribute, "Name")) { ReportDiagnostic(context, attribute, DiagnosticDescriptors.SpecifyExportCodeFixProviderAttributeName); @@ -114,10 +114,10 @@ private static void AnalyzeCodeRefactoringProvider(SymbolAnalysisContext context if (attribute == null) return; - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.UnknownLanguageName)) + if (DiagnosticDescriptors.UnknownLanguageName.IsEffective(context)) AnalyzeLanguageName(context, attribute); - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.SpecifyExportCodeRefactoringProviderAttributeName) + if (DiagnosticDescriptors.SpecifyExportCodeRefactoringProviderAttributeName.IsEffective(context) && !ContainsNamedArgument(attribute, "Name")) { ReportDiagnostic(context, attribute, DiagnosticDescriptors.SpecifyExportCodeRefactoringProviderAttributeName); diff --git a/src/Common/DiagnosticHelpers.cs b/src/Common/DiagnosticHelpers.cs index 2b5be98c58..f75911a90f 100644 --- a/src/Common/DiagnosticHelpers.cs +++ b/src/Common/DiagnosticHelpers.cs @@ -7,8 +7,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; -#pragma warning disable RCS0047 - namespace Roslynator { internal static class DiagnosticHelpers @@ -132,10 +130,8 @@ public static void ReportDiagnosticIfNotSuppressed( SyntaxNode node, params object[] messageArgs) { - if (context.IsAnalyzerSuppressed(descriptor)) - return; - - ReportDiagnostic(context, descriptor, node, messageArgs); + if (descriptor.IsEffective(context)) + ReportDiagnostic(context, descriptor, node, messageArgs); } public static void ReportDiagnosticIfNotSuppressed( @@ -144,10 +140,8 @@ public static void ReportDiagnosticIfNotSuppressed( Location location, params object[] messageArgs) { - if (context.IsAnalyzerSuppressed(descriptor)) - return; - - ReportDiagnostic(context, descriptor, location, messageArgs); + if (descriptor.IsEffective(context)) + ReportDiagnostic(context, descriptor, location, messageArgs); } public static void ReportDiagnostic( @@ -390,5 +384,44 @@ private static void VerifyDiagnostic(Diagnostic diagnostic) { Debug.Assert(Regex.IsMatch(diagnostic.Id, @"\ARCS[0-9]{4}(FadeOut)?\z"), $"Invalid diagnostic id '{diagnostic.Id}'."); } + + internal static bool IsAnyEffective(SyntaxNodeAnalysisContext context, ImmutableArray descriptors) + { + return IsAnyEffective(context.Compilation, descriptors); + } + + internal static bool IsAnyEffective(SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2) + { + return IsAnyEffective(context.Compilation, descriptor1, descriptor2); + } + + internal static bool IsAnyEffective(SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2, DiagnosticDescriptor descriptor3) + { + return IsAnyEffective(context.Compilation, descriptor1, descriptor2, descriptor3); + } + + internal static bool IsAnyEffective(Compilation compilation, ImmutableArray descriptors) + { + foreach (DiagnosticDescriptor descriptor in descriptors) + { + if (descriptor.IsEffective(compilation)) + return true; + } + + return false; + } + + internal static bool IsAnyEffective(Compilation compilation, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2) + { + return descriptor1.IsEffective(compilation) + || descriptor2.IsEffective(compilation); + } + + internal static bool IsAnyEffective(Compilation compilation, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2, DiagnosticDescriptor descriptor3) + { + return descriptor1.IsEffective(compilation) + || descriptor2.IsEffective(compilation) + || descriptor3.IsEffective(compilation); + } } } diff --git a/src/Common/EditorConfigOptions.cs b/src/Common/EditorConfigOptions.cs deleted file mode 100644 index 3d792cae4c..0000000000 --- a/src/Common/EditorConfigOptions.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Roslynator -{ - internal static class EditorConfigOptions - { - public static bool IsTrue( - SyntaxNodeAnalysisContext context, - SyntaxTree syntaxTree, - string key) - { - return TryGetValue(context, syntaxTree, key, out bool value) - && value; - } - - public static bool TryGetValue( - SyntaxNodeAnalysisContext context, - SyntaxTree syntaxTree, - string key, - out bool value) - { - if (context - .Options - .AnalyzerConfigOptionsProvider - .GetOptions(syntaxTree) - .TryGetValue(key, out string valueText) - && bool.TryParse(valueText, out value)) - { - return true; - } - - value = false; - return false; - } - } -} diff --git a/src/Common/Extensions/CommonExtensions.cs b/src/Common/Extensions/CommonExtensions.cs new file mode 100644 index 0000000000..88e8b79803 --- /dev/null +++ b/src/Common/Extensions/CommonExtensions.cs @@ -0,0 +1,130 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Globalization; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Roslynator +{ + internal static class CommonExtensions + { + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxNodeAnalysisContext context) + { + return IsEnabled( + analyzerOption, + context.Node.SyntaxTree, + context.Compilation.Options, + context.Options); + } + + public static bool? IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxNodeAnalysisContext context, + bool checkParent) + { + return IsEnabled( + analyzerOption, + context.Node.SyntaxTree, + context.Compilation.Options, + context.Options, + checkParent); + } + + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + SymbolAnalysisContext context) + { + return IsEnabled( + analyzerOption, + context.Symbol.Locations[0].SourceTree, + context.Compilation.Options, + context.Options); + } + + public static bool? IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxTree syntaxTree, + CompilationOptions compilationOptions, + AnalyzerOptions analyzerOptions, + bool checkParent) + { + if (checkParent && !analyzerOption.Parent.IsEffective(syntaxTree, compilationOptions)) + return null; + + return IsEnabled(analyzerOption, syntaxTree, compilationOptions, analyzerOptions); + } + + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxTree syntaxTree, + CompilationOptions compilationOptions, + AnalyzerOptions analyzerOptions) + { + if (analyzerOptions + .AnalyzerConfigOptionsProvider + .GetOptions(syntaxTree) + .TryGetValue(analyzerOption.OptionKey, out string value) + && bool.TryParse(value, out bool enabled) + && enabled) + { + return true; + } + + if (analyzerOption.Descriptor != null + && compilationOptions + .SpecificDiagnosticOptions + .TryGetValue(analyzerOption.Descriptor.Id, out ReportDiagnostic reportDiagnostic)) + { + switch (reportDiagnostic) + { + case ReportDiagnostic.Default: + case ReportDiagnostic.Suppress: + return false; + case ReportDiagnostic.Error: + case ReportDiagnostic.Warn: + case ReportDiagnostic.Info: + case ReportDiagnostic.Hidden: + return true; + default: + throw new InvalidOperationException(); + } + } + + return false; + } + + public static bool TryGetInt32Value( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxTree syntaxTree, + AnalyzerOptions analyzerOptions, + out int result) + { + if (analyzerOptions + .AnalyzerConfigOptionsProvider + .GetOptions(syntaxTree) + .TryGetValue(analyzerOption.OptionKey, out string textValue) + && int.TryParse(textValue, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.CurrentCulture, out int value)) + { + result = value; + return true; + } + + result = default; + return false; + } + + public static int GetInt32Value( + this AnalyzerOptionDescriptor analyzerOption, + SyntaxTree syntaxTree, + AnalyzerOptions analyzerOptions, + int defaultValue) + { + return (TryGetInt32Value(analyzerOption, syntaxTree, analyzerOptions, out int result)) + ? result + : defaultValue; + } + } +} diff --git a/src/Core/AnalyzerOptionDescriptor.cs b/src/Core/AnalyzerOptionDescriptor.cs new file mode 100644 index 0000000000..fc7b66a8a3 --- /dev/null +++ b/src/Core/AnalyzerOptionDescriptor.cs @@ -0,0 +1,25 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.CodeAnalysis; + +namespace Roslynator +{ + internal readonly struct AnalyzerOptionDescriptor + { + public AnalyzerOptionDescriptor( + DiagnosticDescriptor descriptor, + DiagnosticDescriptor parent, + string optionKey) + { + Descriptor = descriptor; + Parent = parent; + OptionKey = optionKey; + } + + public DiagnosticDescriptor Descriptor { get; } + + public DiagnosticDescriptor Parent { get; } + + public string OptionKey { get; } + } +} diff --git a/src/Core/Extensions/CompilationExtensions.cs b/src/Core/Extensions/CompilationExtensions.cs deleted file mode 100644 index 9dbd920177..0000000000 --- a/src/Core/Extensions/CompilationExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; - -namespace Roslynator -{ - internal static class CompilationExtensions - { - internal static bool IsAnalyzerSuppressed(this Compilation compilation, DiagnosticDescriptor descriptor) - { - return IsAnalyzerSuppressed(compilation.Options, descriptor); - } - - internal static bool IsAnalyzerSuppressed(this CompilationOptions compilationOptions, DiagnosticDescriptor descriptor) - { - ReportDiagnostic reportDiagnostic = compilationOptions - .SpecificDiagnosticOptions - .GetValueOrDefault(descriptor.Id); - - switch (reportDiagnostic) - { - case ReportDiagnostic.Default: - return !descriptor.IsEnabledByDefault; - case ReportDiagnostic.Suppress: - return true; - default: - return false; - } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.")] - internal static bool AreAnalyzersSuppressed(this Compilation compilation, ImmutableArray descriptors) - { - foreach (DiagnosticDescriptor descriptor in descriptors) - { - if (!compilation.IsAnalyzerSuppressed(descriptor)) - return false; - } - - return true; - } - - internal static bool AreAnalyzersSuppressed(this Compilation compilation, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2) - { - return IsAnalyzerSuppressed(compilation, descriptor1) - && IsAnalyzerSuppressed(compilation, descriptor2); - } - - internal static bool AreAnalyzersSuppressed(this Compilation compilation, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2, DiagnosticDescriptor descriptor3) - { - return IsAnalyzerSuppressed(compilation, descriptor1) - && IsAnalyzerSuppressed(compilation, descriptor2) - && IsAnalyzerSuppressed(compilation, descriptor3); - } - } -} diff --git a/src/Core/Extensions/DiagnosticsExtensions.cs b/src/Core/Extensions/DiagnosticsExtensions.cs index ece15ab90e..e4528e8af0 100644 --- a/src/Core/Extensions/DiagnosticsExtensions.cs +++ b/src/Core/Extensions/DiagnosticsExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -526,36 +527,66 @@ internal static bool IsAnalyzerExceptionDescriptor(this DiagnosticDescriptor des return false; } - internal static bool IsAnalyzerSuppressed(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor) + internal static bool IsEffective(this DiagnosticDescriptor descriptor, SymbolAnalysisContext context) { - return context.Compilation.IsAnalyzerSuppressed(descriptor); + return IsEffective( + descriptor, + context.Symbol.Locations[0].SourceTree, + context.Compilation.Options, + context.CancellationToken); } - internal static bool IsAnalyzerSuppressed(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor) + internal static bool IsEffective(this DiagnosticDescriptor descriptor, SyntaxNodeAnalysisContext context) { - return context.Compilation.IsAnalyzerSuppressed(descriptor); + return IsEffective( + descriptor, + context.Node.SyntaxTree, + context.Compilation.Options, + context.CancellationToken); } -#pragma warning disable RS1012 - internal static bool IsAnalyzerSuppressed(this CompilationStartAnalysisContext context, DiagnosticDescriptor descriptor) + public static bool IsEffective( + this DiagnosticDescriptor descriptor, + SyntaxTree syntaxTree, + CompilationOptions compilationOptions, + CancellationToken cancellationToken = default) { - return context.Compilation.IsAnalyzerSuppressed(descriptor); - } + var reportDiagnostic = Microsoft.CodeAnalysis.ReportDiagnostic.Default; + + if (compilationOptions + .SyntaxTreeOptionsProvider? + .TryGetDiagnosticValue( + syntaxTree, + descriptor.Id, + cancellationToken, + out reportDiagnostic) != true) + { + reportDiagnostic = compilationOptions + .SpecificDiagnosticOptions + .GetValueOrDefault(descriptor.Id); + } - internal static bool AreAnalyzersSuppressed(this CompilationStartAnalysisContext context, ImmutableArray descriptors) - { - return context.Compilation.AreAnalyzersSuppressed(descriptors); + return reportDiagnostic switch + { + Microsoft.CodeAnalysis.ReportDiagnostic.Default => descriptor.IsEnabledByDefault, + Microsoft.CodeAnalysis.ReportDiagnostic.Suppress => false, + _ => true, + }; } - internal static bool AreAnalyzersSuppressed(this CompilationStartAnalysisContext context, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2) + internal static bool IsEffective(this DiagnosticDescriptor descriptor, Compilation compilation) { - return context.Compilation.AreAnalyzersSuppressed(descriptor1, descriptor2); + return IsEffective(descriptor, compilation.Options); } - internal static bool AreAnalyzersSuppressed(this CompilationStartAnalysisContext context, DiagnosticDescriptor descriptor1, DiagnosticDescriptor descriptor2, DiagnosticDescriptor descriptor3) + internal static bool IsEffective(this DiagnosticDescriptor descriptor, CompilationOptions compilationOptions) { - return context.Compilation.AreAnalyzersSuppressed(descriptor1, descriptor2, descriptor3); + return (compilationOptions.SpecificDiagnosticOptions.GetValueOrDefault(descriptor.Id)) switch + { + Microsoft.CodeAnalysis.ReportDiagnostic.Default => descriptor.IsEnabledByDefault, + Microsoft.CodeAnalysis.ReportDiagnostic.Suppress => false, + _ => true, + }; } -#pragma warning restore RS1012 } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs index 4977d19026..1f290994a7 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/CodeFixHelpers.cs @@ -562,7 +562,7 @@ public static Task FixBinaryExpressionAsync( string indentation; if (indentationAnalysis.Indentation == binaryExpression.GetLeadingTrivia().LastOrDefault() - && document.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)) + && AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(document, binaryExpression)) { indentation = indentationAnalysis.Indentation.ToString(); } @@ -606,7 +606,7 @@ public static Task FixBinaryExpressionAsync( else if (leftTrailing.IsEmptyOrWhitespace() && tokenTrailing.IsEmptyOrWhitespace()) { - if (document.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)) + if (AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(document, binaryExpression)) { if (!SetIndentation(right)) break; diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs index 34fc0209b2..36aa93de56 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/LineIsTooLongCodeFixProvider.cs @@ -35,7 +35,10 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) Document document = context.Document; Diagnostic diagnostic = context.Diagnostics[0]; - var maxLength = int.Parse(diagnostic.Properties[LineIsTooLongAnalyzer.PropertyKey]); + + SyntaxTree syntaxTree = await document.GetSyntaxTreeAsync(context.CancellationToken).ConfigureAwait(false); + + int maxLength = AnalyzerOptions.MaxLineLength.GetInt32Value(syntaxTree, document.Project.AnalyzerOptions, AnalyzerSettings.Current.MaxLineLength); SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); @@ -180,7 +183,7 @@ private static Task AddNewLineBeforeOrAfterArrowAsync( return AddNewLineBeforeOrAfterAsync( document, arrowExpressionClause.ArrowToken, - document.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt), + AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt.IsEnabled(document, arrowExpressionClause), cancellationToken); } @@ -192,7 +195,7 @@ private static Task AddNewLineBeforeOrAfterEqualsSignAsync( return AddNewLineBeforeOrAfterAsync( document, operatorToken, - document.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt), + AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt.IsEnabled(document, operatorToken), cancellationToken); } @@ -203,7 +206,7 @@ private static Task AddNewLineBeforeOrAfterConditionalOperatorAsync( { string indentation = SyntaxTriviaAnalysis.GetIncreasedIndentation(conditionalExpression, cancellationToken); - if (document.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)) + if (AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt.IsEnabled(document, conditionalExpression)) { return document.WithTextChangesAsync( new TextChange[] diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs index 3189df4f3b..2fc41affc2 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs @@ -139,8 +139,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) if (previousToken.SpanStart < Span.Start) return null; - bool addNewLineAfter = Document.IsAnalyzerOptionEnabled( - AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt); + bool addNewLineAfter = AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt.IsEnabled(Document, node); int wrapPosition = (addNewLineAfter) ? arrowToken.Span.End : previousToken.Span.End; int start = (addNewLineAfter) ? expressionBody.Expression.SpanStart : arrowToken.SpanStart; @@ -161,8 +160,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) if (previousToken.SpanStart < Span.Start) return null; - bool addNewLineAfter = Document.IsAnalyzerOptionEnabled( - AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt); + bool addNewLineAfter = AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt.IsEnabled(Document, node); int wrapPosition = (addNewLineAfter) ? equalsToken.Span.End : previousToken.Span.End; int start = (addNewLineAfter) ? equalsValueClause.Value.SpanStart : equalsToken.SpanStart; @@ -302,8 +300,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) SyntaxToken questionToken = conditionalExpression.QuestionToken; SyntaxToken colonToken = conditionalExpression.ColonToken; - bool addNewLineAfter = Document.IsAnalyzerOptionEnabled( - AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt); + bool addNewLineAfter = AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(Document, node); int wrapPosition = (addNewLineAfter) ? questionToken.Span.End @@ -359,8 +356,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) SyntaxToken operatorToken = binaryExpression.OperatorToken; - bool addNewLineAfter = Document.IsAnalyzerOptionEnabled( - AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt); + bool addNewLineAfter = AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(Document, node); int wrapPosition = (addNewLineAfter) ? operatorToken.Span.End @@ -426,8 +422,7 @@ private SyntaxNode GetFixableNode(SyntaxNode node) if (left.SpanStart < Span.Start) return null; - bool addNewLineAfter = Document.IsAnalyzerOptionEnabled( - AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt); + bool addNewLineAfter = AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt.IsEnabled(Document, node); int wrapPosition = (addNewLineAfter) ? operatorToken.Span.End : left.Span.End; int start = (addNewLineAfter) ? assignment.Right.SpanStart : operatorToken.SpanStart; diff --git a/src/Formatting.Analyzers.CodeFixes/CodeFixesExtensions.cs b/src/Formatting.Analyzers.CodeFixes/CodeFixesExtensions.cs deleted file mode 100644 index 46bf4611f6..0000000000 --- a/src/Formatting.Analyzers.CodeFixes/CodeFixesExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis; - -namespace Roslynator.Formatting -{ - internal static class CodeFixesExtensions - { - public static bool IsAnalyzerOptionEnabled(this Document document, DiagnosticDescriptor analyzerOption) - { - return document.Project.CompilationOptions.IsAnalyzerOptionEnabled(analyzerOption); - } - } -} diff --git a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs index e672b4b2df..706b8c3433 100644 --- a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs @@ -41,7 +41,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) if (accessors.Any(f => f.BodyOrExpressionBody() != null)) { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBeforeAccessorOfFullProperty)) + if (DiagnosticDescriptors.AddNewLineBeforeAccessorOfFullProperty.IsEffective(context)) { SyntaxToken token = accessorList.OpenBraceToken; @@ -65,7 +65,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) } } - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveNewLinesFromAccessorWithSingleLineExpression) + if (DiagnosticDescriptors.RemoveNewLinesFromAccessorWithSingleLineExpression.IsEffective(context) && !accessorList.IsSingleLine(includeExteriorTrivia: false)) { foreach (AccessorDeclarationSyntax accessor in accessors) @@ -75,7 +75,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) } } } - else if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.RemoveNewLinesFromAccessorListOfAutoProperty)) + else if (DiagnosticDescriptors.RemoveNewLinesFromAccessorListOfAutoProperty.IsEffective(context)) { SyntaxNode parent = accessorList.Parent; diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs index 849f7b37a6..1010caa573 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs @@ -61,11 +61,11 @@ private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context) if (SyntaxTriviaAnalysis.IsTokenFollowedWithNewLineAndNotPrecededWithNewLine(left, binaryExpression.OperatorToken, right)) { - if (context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)) + if (!AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(context)) ReportDiagnostic(DiagnosticDescriptors.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa, ImmutableDictionary.Empty); } else if (SyntaxTriviaAnalysis.IsTokenPrecededWithNewLineAndNotFollowedWithNewLine(left, binaryExpression.OperatorToken, right) - && !context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)) + && AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(context)) { ReportDiagnostic(DiagnosticDescriptors.ReportOnly.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, DiagnosticProperties.AnalyzerOption_Invert); } diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs index 27609bb15e..49ab8d360f 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaAnalyzer.cs @@ -40,7 +40,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte if (SyntaxTriviaAnalysis.IsTokenFollowedWithNewLineAndNotPrecededWithNewLine(condition, conditionalExpression.QuestionToken, whenTrue)) { - if (context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)) + if (!AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context)) { ReportDiagnostic(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa, conditionalExpression.QuestionToken, ImmutableDictionary.Empty); return; @@ -48,7 +48,7 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte } else if (SyntaxTriviaAnalysis.IsTokenPrecededWithNewLineAndNotFollowedWithNewLine(condition, conditionalExpression.QuestionToken, whenTrue)) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)) + if (AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context)) { ReportDiagnostic(DiagnosticDescriptors.ReportOnly.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, conditionalExpression.QuestionToken, DiagnosticProperties.AnalyzerOption_Invert); return; @@ -61,12 +61,12 @@ private static void AnalyzeConditionalExpression(SyntaxNodeAnalysisContext conte { if (SyntaxTriviaAnalysis.IsTokenFollowedWithNewLineAndNotPrecededWithNewLine(whenTrue, conditionalExpression.ColonToken, whenFalse)) { - if (context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)) + if (!AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context)) ReportDiagnostic(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa, conditionalExpression.ColonToken, ImmutableDictionary.Empty); } else if (SyntaxTriviaAnalysis.IsTokenPrecededWithNewLineAndNotFollowedWithNewLine(whenTrue, conditionalExpression.ColonToken, whenFalse)) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)) + if (AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt.IsEnabled(context)) ReportDiagnostic(DiagnosticDescriptors.ReportOnly.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, conditionalExpression.ColonToken, DiagnosticProperties.AnalyzerOption_Invert); } } diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaAnalyzer.cs index 56b129921a..86813d5f31 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaAnalyzer.cs @@ -81,7 +81,7 @@ private static void AnalyzeAssignmentExpression(SyntaxNodeAnalysisContext contex private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxToken token, ExpressionSyntax expression) { - FormattingSuggestion suggestion = FormattingAnalysis.AnalyzeNewLineBeforeOrAfter(context, token, expression, AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt); + FormattingSuggestion suggestion = FormattingAnalysis.AnalyzeNewLineBeforeOrAfter(context, token, expression, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt); if (suggestion == FormattingSuggestion.AddNewLineBefore) { diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaAnalyzer.cs index 0d6e45a208..cf856ca068 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaAnalyzer.cs @@ -29,7 +29,7 @@ private static void AnalyzeArrowExpressionClause(SyntaxNodeAnalysisContext conte SyntaxToken arrowToken = arrowExpressionClause.ArrowToken; - FormattingSuggestion suggestion = FormattingAnalysis.AnalyzeNewLineBeforeOrAfter(context, arrowToken, arrowExpressionClause.Expression, AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt); + FormattingSuggestion suggestion = FormattingAnalysis.AnalyzeNewLineBeforeOrAfter(context, arrowToken, arrowExpressionClause.Expression, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt); if (suggestion == FormattingSuggestion.AddNewLineBefore) { diff --git a/src/Formatting.Analyzers/CSharp/AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersaAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersaAnalyzer.cs index 878110cc8b..bbc99f70ea 100644 --- a/src/Formatting.Analyzers/CSharp/AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersaAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersaAnalyzer.cs @@ -40,7 +40,7 @@ private static void AnalyzeDoStatement(SyntaxNodeAnalysisContext context) || trailingTrivia.SingleOrDefault(shouldThrow: false).IsWhitespaceTrivia()) { if (!doStatement.WhileKeyword.LeadingTrivia.Any() - && context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)) + && !AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword.IsEnabled(context)) { context.ReportDiagnostic( DiagnosticDescriptors.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa, @@ -50,7 +50,7 @@ private static void AnalyzeDoStatement(SyntaxNodeAnalysisContext context) else if (SyntaxTriviaAnalysis.IsOptionalWhitespaceThenEndOfLineTrivia(trailingTrivia)) { if (doStatement.WhileKeyword.LeadingTrivia.IsEmptyOrWhitespace() - && !context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)) + && AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword.IsEnabled(context)) { context.ReportDiagnostic( DiagnosticDescriptors.ReportOnly.RemoveNewLineBetweenClosingBraceAndWhileKeyword, diff --git a/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenAccessorsAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenAccessorsAnalyzer.cs index 3908bf865e..f8e8ac5175 100644 --- a/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenAccessorsAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenAccessorsAnalyzer.cs @@ -64,11 +64,11 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) if (accessorList.SyntaxTree.IsSingleLineSpan(accessor1.Span, context.CancellationToken) && accessorList.SyntaxTree.IsSingleLineSpan(accessor2.Span, context.CancellationToken)) { - if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa)) + if (DiagnosticDescriptors.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa.IsEffective(context)) { if (isEmptyLine) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors)) + if (AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic( context, @@ -77,7 +77,7 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) properties: DiagnosticProperties.AnalyzerOption_Invert); } } - else if (context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors)) + else if (!AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic( context, diff --git a/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenUsingDirectiveAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenUsingDirectiveAnalyzer.cs index 1febd1333c..604e77ba40 100644 --- a/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenUsingDirectiveAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddOrRemoveEmptyLineBetweenUsingDirectiveAnalyzer.cs @@ -99,11 +99,11 @@ private static void AnalyzeUsings(SyntaxNodeAnalysisContext context, SyntaxList< Location.Create(context.Node.SyntaxTree, leadingTrivia[0].Span.WithLength(0))); } } - else if (!context.IsAnalyzerSuppressed(DiagnosticDescriptors.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa)) + else if (DiagnosticDescriptors.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa.IsEffective(context)) { if (isEmptyLine) { - if (!context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)) + if (AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic( context, @@ -112,7 +112,7 @@ private static void AnalyzeUsings(SyntaxNodeAnalysisContext context, SyntaxList< properties: DiagnosticProperties.AnalyzerOption_Invert); } } - else if (context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)) + else if (!AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace.IsEnabled(context)) { DiagnosticHelpers.ReportDiagnostic( context, diff --git a/src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs b/src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs new file mode 100644 index 0000000000..feee5a2e45 --- /dev/null +++ b/src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticDescriptors.Generated.cs @@ -0,0 +1,97 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +// + +using System; +using Microsoft.CodeAnalysis; + +namespace Roslynator.Formatting.CSharp +{ + public static partial class AnalyzerOptionDiagnosticDescriptors + { + /// RCS0011i + public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenSingleLineAccessors = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenSingleLineAccessors, + title: "Remove empty line between single-line accessors.", + messageFormat: "Remove empty line between single-line accessors.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenSingleLineAccessors, + customTags: Array.Empty()); + + /// RCS0015i + public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, + title: "Remove empty line between using directives with different root namespace.", + messageFormat: "Remove empty line between using directives with different root namespace.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, + customTags: Array.Empty()); + + /// RCS0027i + public static readonly DiagnosticDescriptor AddNewLineAfterBinaryOperatorInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, + title: "Add newline after binary operator instead of before it.", + messageFormat: "Add newline after binary operator instead of before it.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, + customTags: Array.Empty()); + + /// RCS0028i + public static readonly DiagnosticDescriptor AddNewLineAfterConditionalOperatorInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, + title: "Add newline after conditional operator instead of before it.", + messageFormat: "Add newline after conditional operator instead of before it.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, + customTags: Array.Empty()); + + /// RCS0032i + public static readonly DiagnosticDescriptor AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, + title: "Add newline after expression-body arrow instead of before it.", + messageFormat: "Add newline after expression-body arrow instead of before it.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, + customTags: Array.Empty()); + + /// RCS0051i + public static readonly DiagnosticDescriptor RemoveNewLineBetweenClosingBraceAndWhileKeyword = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.RemoveNewLineBetweenClosingBraceAndWhileKeyword, + title: "Remove newline between closing brace and 'while' keyword.", + messageFormat: "Remove newline between closing brace and 'while' keyword.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.RemoveNewLineBetweenClosingBraceAndWhileKeyword, + customTags: Array.Empty()); + + /// RCS0052i + public static readonly DiagnosticDescriptor AddNewLineAfterEqualsSignInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( + id: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterEqualsSignInsteadOfBeforeIt, + title: "Add newline after equals sign instead of before it.", + messageFormat: "Add newline after equals sign instead of before it.", + category: DiagnosticCategories.AnalyzerOption, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: false, + description: null, + helpLinkUri: AnalyzerOptionDiagnosticIdentifiers.AddNewLineAfterEqualsSignInsteadOfBeforeIt, + customTags: Array.Empty()); + + } +} \ No newline at end of file diff --git a/src/Formatting.Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs b/src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs similarity index 92% rename from src/Formatting.Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs rename to src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs index eb933e2be6..f4ebcc60ad 100644 --- a/src/Formatting.Analyzers/CSharp/AnalyzerOptionIdentifiers.Generated.cs +++ b/src/Formatting.Analyzers/CSharp/AnalyzerOptionDiagnosticIdentifiers.Generated.cs @@ -6,7 +6,7 @@ namespace Roslynator.Formatting.CSharp { - public static partial class AnalyzerOptionIdentifiers + public static partial class AnalyzerOptionDiagnosticIdentifiers { public const string RemoveEmptyLineBetweenSingleLineAccessors = "RCS0011i"; public const string RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace = "RCS0015i"; diff --git a/src/Formatting.Analyzers/CSharp/AnalyzerOptions.Generated.cs b/src/Formatting.Analyzers/CSharp/AnalyzerOptions.Generated.cs index c808e9077b..826aa038a4 100644 --- a/src/Formatting.Analyzers/CSharp/AnalyzerOptions.Generated.cs +++ b/src/Formatting.Analyzers/CSharp/AnalyzerOptions.Generated.cs @@ -2,141 +2,17 @@ // -using System; -using Microsoft.CodeAnalysis; - namespace Roslynator.Formatting.CSharp { public static partial class AnalyzerOptions { - /// RCS0011i - public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenSingleLineAccessors = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenSingleLineAccessors, - title: "Remove empty line between single-line accessors.", - messageFormat: "Remove empty line between single-line accessors.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenSingleLineAccessors, - customTags: Array.Empty()); - - /// RCS0015i - public static readonly DiagnosticDescriptor RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, - title: "Remove empty line between using directives with different root namespace.", - messageFormat: "Remove empty line between using directives with different root namespace.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, - customTags: Array.Empty()); - - /// RCS0027i - public static readonly DiagnosticDescriptor AddNewLineAfterBinaryOperatorInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, - title: "Add newline after binary operator instead of before it.", - messageFormat: "Add newline after binary operator instead of before it.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, - customTags: Array.Empty()); - - /// RCS0028i - public static readonly DiagnosticDescriptor AddNewLineAfterConditionalOperatorInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, - title: "Add newline after conditional operator instead of before it.", - messageFormat: "Add newline after conditional operator instead of before it.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, - customTags: Array.Empty()); - - /// RCS0032i - public static readonly DiagnosticDescriptor AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, - title: "Add newline after expression-body arrow instead of before it.", - messageFormat: "Add newline after expression-body arrow instead of before it.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, - customTags: Array.Empty()); - - /// RCS0051i - public static readonly DiagnosticDescriptor RemoveNewLineBetweenClosingBraceAndWhileKeyword = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.RemoveNewLineBetweenClosingBraceAndWhileKeyword, - title: "Remove newline between closing brace and 'while' keyword.", - messageFormat: "Remove newline between closing brace and 'while' keyword.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.RemoveNewLineBetweenClosingBraceAndWhileKeyword, - customTags: Array.Empty()); - - /// RCS0052i - public static readonly DiagnosticDescriptor AddNewLineAfterEqualsSignInsteadOfBeforeIt = DiagnosticDescriptorFactory.Default.Create( - id: AnalyzerOptionIdentifiers.AddNewLineAfterEqualsSignInsteadOfBeforeIt, - title: "Add newline after equals sign instead of before it.", - messageFormat: "Add newline after equals sign instead of before it.", - category: DiagnosticCategories.AnalyzerOption, - defaultSeverity: DiagnosticSeverity.Info, - isEnabledByDefault: false, - description: null, - helpLinkUri: AnalyzerOptionIdentifiers.AddNewLineAfterEqualsSignInsteadOfBeforeIt, - customTags: Array.Empty()); - - public static bool IsEnabled(CompilationOptions compilationOptions, DiagnosticDescriptor analyzerOption) - { - switch (analyzerOption.Id) - { - case AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenSingleLineAccessors: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors); - } - - case AnalyzerOptionIdentifiers.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace); - } - - case AnalyzerOptionIdentifiers.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt); - } - - case AnalyzerOptionIdentifiers.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt); - } - - case AnalyzerOptionIdentifiers.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt); - } - - case AnalyzerOptionIdentifiers.RemoveNewLineBetweenClosingBraceAndWhileKeyword: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword); - } - - case AnalyzerOptionIdentifiers.AddNewLineAfterEqualsSignInsteadOfBeforeIt: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa) && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt); - } - - default: - { - throw new ArgumentException("", nameof(analyzerOption)); - } - } - } + internal static readonly AnalyzerOptionDescriptor MaxLineLength = new AnalyzerOptionDescriptor(null, DiagnosticDescriptors.LineIsTooLong, "roslynator.max_line_length"); + internal static readonly AnalyzerOptionDescriptor RemoveEmptyLineBetweenSingleLineAccessors = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenSingleLineAccessors, DiagnosticDescriptors.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa, "roslynator.RCS0011.invert"); + internal static readonly AnalyzerOptionDescriptor RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, DiagnosticDescriptors.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa, "roslynator.RCS0015.invert"); + internal static readonly AnalyzerOptionDescriptor AddNewLineAfterBinaryOperatorInsteadOfBeforeIt = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, DiagnosticDescriptors.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa, "roslynator.RCS0027.invert"); + internal static readonly AnalyzerOptionDescriptor AddNewLineAfterConditionalOperatorInsteadOfBeforeIt = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, DiagnosticDescriptors.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa, "roslynator.RCS0028.invert"); + internal static readonly AnalyzerOptionDescriptor AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, "roslynator.RCS0032.invert"); + internal static readonly AnalyzerOptionDescriptor RemoveNewLineBetweenClosingBraceAndWhileKeyword = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword, DiagnosticDescriptors.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa, "roslynator.RCS0051.invert"); + internal static readonly AnalyzerOptionDescriptor AddNewLineAfterEqualsSignInsteadOfBeforeIt = new AnalyzerOptionDescriptor(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt, DiagnosticDescriptors.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa, "roslynator.RCS0052.invert"); } } \ No newline at end of file diff --git a/src/Formatting.Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs b/src/Formatting.Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs index 46972f6680..23f9e2e302 100644 --- a/src/Formatting.Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs +++ b/src/Formatting.Analyzers/CSharp/AnalyzerOptionsAnalyzer.Generated.cs @@ -15,7 +15,7 @@ public override ImmutableArray SupportedDiagnostics { get { - return ImmutableArray.Create(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors, AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword, AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt); + return ImmutableArray.Create(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenSingleLineAccessors, AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt, AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt); } } diff --git a/src/Formatting.Analyzers/CSharp/EmptyLineBetweenDeclarationsAnalyzer.cs b/src/Formatting.Analyzers/CSharp/EmptyLineBetweenDeclarationsAnalyzer.cs index a876c05cb1..aba35bf98d 100644 --- a/src/Formatting.Analyzers/CSharp/EmptyLineBetweenDeclarationsAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/EmptyLineBetweenDeclarationsAnalyzer.cs @@ -251,7 +251,7 @@ private static void ReportDiagnostic( DiagnosticDescriptor descriptor, SyntaxTrivia trivia) { - if (!context.IsAnalyzerSuppressed(descriptor)) + if (descriptor.IsEffective(context)) DiagnosticHelpers.ReportDiagnostic(context, descriptor, Location.Create(context.Node.SyntaxTree, trivia.Span.WithLength(0))); } } diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs index 86b6df70bd..1f2822c683 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs @@ -154,7 +154,7 @@ int GetIndentationLength() if (leadingTrivia.Any() && leadingTrivia.Last() == indentationAnalysis.Indentation - && context.IsAnalyzerOptionEnabled(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)) + && AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt.IsEnabled(context, checkParent: true) == true) { return indentationAnalysis.IndentationLength; } diff --git a/src/Formatting.Analyzers/CSharp/FormattingAnalysis.cs b/src/Formatting.Analyzers/CSharp/FormattingAnalysis.cs index 834e573e20..9ddfd60638 100644 --- a/src/Formatting.Analyzers/CSharp/FormattingAnalysis.cs +++ b/src/Formatting.Analyzers/CSharp/FormattingAnalysis.cs @@ -22,7 +22,7 @@ public static FormattingSuggestion AnalyzeNewLineBeforeOrAfter( if (!token.LeadingTrivia.Any() && SyntaxTriviaAnalysis.IsOptionalWhitespaceThenEndOfLineTrivia(token.TrailingTrivia) && SyntaxTriviaAnalysis.IsEmptyOrSingleWhitespaceTrivia(expression.GetLeadingTrivia()) - && context.IsAnalyzerSuppressed(afterDescriptor)) + && !afterDescriptor.IsEffective(context)) { return FormattingSuggestion.AddNewLineBefore; } @@ -32,7 +32,7 @@ public static FormattingSuggestion AnalyzeNewLineBeforeOrAfter( if (SyntaxTriviaAnalysis.IsEmptyOrSingleWhitespaceTrivia(token.LeadingTrivia) && SyntaxTriviaAnalysis.IsEmptyOrSingleWhitespaceTrivia(token.TrailingTrivia) && !expression.GetLeadingTrivia().Any() - && !context.IsAnalyzerSuppressed(afterDescriptor)) + && afterDescriptor.IsEffective(context)) { return FormattingSuggestion.AddNewLineAfter; } diff --git a/src/Formatting.Analyzers/CSharp/LineIsTooLongAnalyzer.cs b/src/Formatting.Analyzers/CSharp/LineIsTooLongAnalyzer.cs index 3ebd2d7d68..1a05a6b259 100644 --- a/src/Formatting.Analyzers/CSharp/LineIsTooLongAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/LineIsTooLongAnalyzer.cs @@ -1,8 +1,6 @@ // Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Collections.Generic; using System.Collections.Immutable; -using System.Globalization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; @@ -15,10 +13,6 @@ namespace Roslynator.Formatting [DiagnosticAnalyzer(LanguageNames.CSharp)] public class LineIsTooLongAnalyzer : BaseDiagnosticAnalyzer { - private static volatile ImmutableDictionary _properties; - - public static string PropertyKey { get; } = "MaxLineLength"; - public override ImmutableArray SupportedDiagnostics { get { return ImmutableArray.Create(DiagnosticDescriptors.LineIsTooLong); } @@ -38,13 +32,7 @@ private static void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) if (!tree.TryGetText(out SourceText sourceText)) return; - int maxLength = AnalyzerSettings.Current.MaxLineLength; - - if (context.Options.AnalyzerConfigOptionsProvider.GetOptions(tree).TryGetValue("roslynator.max_line_length", out string maxLengthText) - && int.TryParse(maxLengthText, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.CurrentCulture, out int maxLength2)) - { - maxLength = maxLength2; - } + int maxLength = CSharp.AnalyzerOptions.MaxLineLength.GetInt32Value(context.Tree, context.Options, AnalyzerSettings.Current.MaxLineLength); if (maxLength <= 0) return; @@ -150,25 +138,10 @@ private static void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) } } - ImmutableDictionary properties = _properties; - - if (properties == null - || int.Parse(properties[PropertyKey]) != maxLength) - { - properties = ImmutableDictionary.CreateRange( - new[] - { - new KeyValuePair(PropertyKey, maxLength.ToString()) - }); - - _properties = properties; - } - DiagnosticHelpers.ReportDiagnostic( context, DiagnosticDescriptors.LineIsTooLong, Location.Create(tree, line.Span), - properties, line.Span.Length); } } diff --git a/src/Formatting.Analyzers/Formatting.Analyzers.Template.xml b/src/Formatting.Analyzers/Formatting.Analyzers.Template.xml index 435292ffa4..d0e0f6e54d 100644 --- a/src/Formatting.Analyzers/Formatting.Analyzers.Template.xml +++ b/src/Formatting.Analyzers/Formatting.Analyzers.Template.xml @@ -21,6 +21,8 @@ + + diff --git a/src/Formatting.Analyzers/Formatting.Analyzers.xml b/src/Formatting.Analyzers/Formatting.Analyzers.xml index 60bd1a7ddc..025e6ec820 100644 --- a/src/Formatting.Analyzers/Formatting.Analyzers.xml +++ b/src/Formatting.Analyzers/Formatting.Analyzers.xml @@ -334,6 +334,7 @@ This rule does not enforce an empty line between two single-line declaration. Remove empty line between single-line accessors. i + invert Invert @@ -442,6 +443,7 @@ namespace N Remove empty line between using directives with different root namespace. Remove empty line between using directives. i + invert Invert @@ -680,6 +682,7 @@ namespace N Add newline after binary operator instead of before it. i + invert Invert @@ -720,6 +723,7 @@ namespace N Add newline after conditional operator instead of before it. i + invert Invert @@ -808,6 +812,7 @@ namespace N Add newline after expression-body arrow instead of before it. i + invert Invert @@ -1200,6 +1205,7 @@ while (x);]]> Remove newline between closing brace and 'while' keyword. i + invert Invert @@ -1236,6 +1242,7 @@ while (x);]]> Add newline after equals sign instead of before it. i + invert Invert @@ -1403,11 +1410,14 @@ void M( false This analyzer reports any line that is longer than maximal length. -Default maximal length is 125. Use EditorConfig to change maximal length \(See [Configuration](#configuration)\). - -```]]> +Default maximal length is 125. + + + Max line length. + roslynator.max_line_length + <MAX_LINE_LENGTH> + None + + \ No newline at end of file diff --git a/src/Formatting.Analyzers/FormattingExtensions.cs b/src/Formatting.Analyzers/FormattingExtensions.cs deleted file mode 100644 index b73ae12f36..0000000000 --- a/src/Formatting.Analyzers/FormattingExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Roslynator.Formatting -{ - internal static class FormattingExtensions - { - public static bool IsAnalyzerOptionEnabled(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor analyzerOption) - { - return IsAnalyzerOptionEnabled(context.Compilation.Options, analyzerOption); - } - - public static bool IsAnalyzerOptionEnabled(this CompilationOptions compilationOptions, DiagnosticDescriptor analyzerOption) - { - return CSharp.AnalyzerOptions.IsEnabled(compilationOptions, analyzerOption); - } - } -} diff --git a/src/Tests/Analyzers.Tests/RCS1014UseExplicitlyTypedArrayOrViceVersaTests.cs b/src/Tests/Analyzers.Tests/RCS1014UseExplicitlyTypedArrayOrViceVersaTests.cs index b4bdf72265..0b453e4bff 100644 --- a/src/Tests/Analyzers.Tests/RCS1014UseExplicitlyTypedArrayOrViceVersaTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1014UseExplicitlyTypedArrayOrViceVersaTests.cs @@ -57,7 +57,7 @@ void M() string M2() => null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] @@ -145,7 +145,7 @@ void M() var x = new[] { """" }; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1014UseImplicitlyTypedArrayTests.cs b/src/Tests/Analyzers.Tests/RCS1014UseImplicitlyTypedArrayTests.cs index b149c138e1..c468fdbcd5 100644 --- a/src/Tests/Analyzers.Tests/RCS1014UseImplicitlyTypedArrayTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1014UseImplicitlyTypedArrayTests.cs @@ -14,7 +14,7 @@ public class RCS1014UseImplicitlyTypedArrayTests : AbstractCSharpDiagnosticVerif public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArray); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArray); } } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] @@ -84,7 +84,7 @@ void M() var x = new[] { """" }; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] @@ -130,7 +130,7 @@ class A class B : A { } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] @@ -172,7 +172,7 @@ void M() string M2() => null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseImplicitlyTypedArrayWhenTypeIsObvious)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseImplicitlyTypedArrayWhenTypeIsObvious)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseExplicitlyTypedArrayOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1016ConvertBlockBodyToExpressionBodyTests.cs b/src/Tests/Analyzers.Tests/RCS1016ConvertBlockBodyToExpressionBodyTests.cs index eb760597ec..8d64c89d1c 100644 --- a/src/Tests/Analyzers.Tests/RCS1016ConvertBlockBodyToExpressionBodyTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1016ConvertBlockBodyToExpressionBodyTests.cs @@ -774,7 +774,7 @@ string M() b""; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertBlockBodyToExpressionBodyOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1016ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLineTests.cs b/src/Tests/Analyzers.Tests/RCS1016ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLineTests.cs index e12c9f2e72..6895d70d21 100644 --- a/src/Tests/Analyzers.Tests/RCS1016ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLineTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1016ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLineTests.cs @@ -17,14 +17,14 @@ public class RCS1016ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLineTes public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine); } } private CSharpTestOptions Options_ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine - => _options_ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine ??= Options.EnableDiagnostic(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine); + => _options_ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine ??= Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenExpressionIsMultiLine); private CSharpTestOptions Options_ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine - => _options_ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine ??= Options.EnableDiagnostic(AnalyzerOptions.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine); + => _options_ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine ??= Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertExpressionBodyToBlockBodyWhenDeclarationIsMultiLine); [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertBlockBodyToExpressionBodyOrViceVersa)] public async Task Test_Method_MultilineExpression() diff --git a/src/Tests/Analyzers.Tests/RCS1018RemoveAccessibilityModifiersTests.cs b/src/Tests/Analyzers.Tests/RCS1018RemoveAccessibilityModifiersTests.cs index 77bed10515..c2bd32a741 100644 --- a/src/Tests/Analyzers.Tests/RCS1018RemoveAccessibilityModifiersTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1018RemoveAccessibilityModifiersTests.cs @@ -14,7 +14,7 @@ public class RCS1018RemoveAccessibilityModifiersTests : AbstractCSharpDiagnostic public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.RemoveAccessibilityModifiers); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveAccessibilityModifiers); } } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddAccessibilityModifiersOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1036RemoveRedundantEmptyLineTests.cs b/src/Tests/Analyzers.Tests/RCS1036RemoveRedundantEmptyLineTests.cs index 26ac52f9c1..af07cc196f 100644 --- a/src/Tests/Analyzers.Tests/RCS1036RemoveRedundantEmptyLineTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1036RemoveRedundantEmptyLineTests.cs @@ -268,7 +268,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenClosingBraceAndSwitchSection)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.RemoveRedundantEmptyLine)] diff --git a/src/Tests/Analyzers.Tests/RCS1045RenamePrivateFieldToCamelCaseWithUnderscoreTests.cs b/src/Tests/Analyzers.Tests/RCS1045RenamePrivateFieldToCamelCaseWithUnderscoreTests.cs index 9e57451d45..21a1ba53e3 100644 --- a/src/Tests/Analyzers.Tests/RCS1045RenamePrivateFieldToCamelCaseWithUnderscoreTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1045RenamePrivateFieldToCamelCaseWithUnderscoreTests.cs @@ -104,7 +104,7 @@ class C { private static readonly string f; } -", options: Options.EnableDiagnostic(AnalyzerOptions.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.DoNotRenamePrivateStaticReadOnlyFieldToCamelCaseWithUnderscore)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.RenamePrivateFieldToCamelCaseWithUnderscore)] diff --git a/src/Tests/Analyzers.Tests/RCS1050AddArgumentListToObjectCreationOrViceVersaTests.cs b/src/Tests/Analyzers.Tests/RCS1050AddArgumentListToObjectCreationOrViceVersaTests.cs index eb3b8da69c..59165d79e1 100644 --- a/src/Tests/Analyzers.Tests/RCS1050AddArgumentListToObjectCreationOrViceVersaTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1050AddArgumentListToObjectCreationOrViceVersaTests.cs @@ -49,7 +49,7 @@ public class C { List items = new List { ""a"", ""b"", ""c"" }; } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveArgumentListFromObjectCreation)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveArgumentListFromObjectCreation)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddArgumentListToObjectCreationOrViceVersa)] @@ -88,7 +88,7 @@ public class C { List items = new List(); } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveArgumentListFromObjectCreation)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveArgumentListFromObjectCreation)); } } } \ No newline at end of file diff --git a/src/Tests/Analyzers.Tests/RCS1051ParenthesizeConditionOfConditionalExpressionTests.cs b/src/Tests/Analyzers.Tests/RCS1051ParenthesizeConditionOfConditionalExpressionTests.cs index 02fa923d43..bbe878f582 100644 --- a/src/Tests/Analyzers.Tests/RCS1051ParenthesizeConditionOfConditionalExpressionTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1051ParenthesizeConditionOfConditionalExpressionTests.cs @@ -81,7 +81,7 @@ void M() string s = b ? ""true"" : ""false""; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ParenthesizeConditionOfConditionalExpression)] @@ -96,7 +96,7 @@ void M() string s = b ? ""true"" : ""false""; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveParenthesesFromConditionOfConditionalExpressionWhenExpressionIsSingleToken)); } } } diff --git a/src/Tests/Analyzers.Tests/RCS1078UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaTests.cs b/src/Tests/Analyzers.Tests/RCS1078UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaTests.cs index 74617e4506..0cc4eaed0e 100644 --- a/src/Tests/Analyzers.Tests/RCS1078UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1078UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersaTests.cs @@ -75,7 +75,7 @@ void M() s = string.Empty; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseStringEmptyInsteadOfEmptyStringLiteral)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersa)] @@ -91,7 +91,7 @@ void M() s = ""a""; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseStringEmptyInsteadOfEmptyStringLiteral)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseEmptyStringLiteralInsteadOfStringEmptyOrViceVersa)] @@ -116,7 +116,7 @@ void M(string p = """") } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseStringEmptyInsteadOfEmptyStringLiteral)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseStringEmptyInsteadOfEmptyStringLiteral)); } } } diff --git a/src/Tests/Analyzers.Tests/RCS1090RemoveCallToConfigureAwaitTests.cs b/src/Tests/Analyzers.Tests/RCS1090RemoveCallToConfigureAwaitTests.cs index 38f3741374..3d14c2a531 100644 --- a/src/Tests/Analyzers.Tests/RCS1090RemoveCallToConfigureAwaitTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1090RemoveCallToConfigureAwaitTests.cs @@ -14,7 +14,7 @@ public class RCS1090RemoveCallToConfigureAwaitTests : AbstractCSharpDiagnosticVe public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.RemoveCallToConfigureAwait); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveCallToConfigureAwait); } } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddCallToConfigureAwaitOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1096ConvertBitwiseOperationToHasFlagCallTests.cs b/src/Tests/Analyzers.Tests/RCS1096ConvertBitwiseOperationToHasFlagCallTests.cs index 29e721a8ac..7adb5ee72a 100644 --- a/src/Tests/Analyzers.Tests/RCS1096ConvertBitwiseOperationToHasFlagCallTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1096ConvertBitwiseOperationToHasFlagCallTests.cs @@ -14,7 +14,7 @@ public class RCS1096ConvertBitwiseOperationToHasFlagCallTests : AbstractCSharpDi public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertBitwiseOperationToHasFlagCall); } } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertHasFlagCallToBitwiseOperationOrViceVersa)] diff --git a/src/Tests/Analyzers.Tests/RCS1096ConvertHasFlagCallToBitwiseOperationTests.cs b/src/Tests/Analyzers.Tests/RCS1096ConvertHasFlagCallToBitwiseOperationTests.cs index 3a1eba11fb..2b949f2c1d 100644 --- a/src/Tests/Analyzers.Tests/RCS1096ConvertHasFlagCallToBitwiseOperationTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1096ConvertHasFlagCallToBitwiseOperationTests.cs @@ -428,7 +428,7 @@ void M() if (options.HasFlag(StringSplitOptions.RemoveEmptyEntries)) { } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.ConvertBitwiseOperationToHasFlagCall)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertBitwiseOperationToHasFlagCall)); } } } diff --git a/src/Tests/Analyzers.Tests/RCS1104SimplifyConditionalExpressionTests.cs b/src/Tests/Analyzers.Tests/RCS1104SimplifyConditionalExpressionTests.cs index 6b85267ab3..9e21ac9610 100644 --- a/src/Tests/Analyzers.Tests/RCS1104SimplifyConditionalExpressionTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1104SimplifyConditionalExpressionTests.cs @@ -104,7 +104,7 @@ void M() bool z = !x && y; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.SimplifyConditionalExpression)] @@ -130,7 +130,7 @@ void M() bool z = !x || y; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.SimplifyConditionalExpressionWhenItIncludesNegationOfCondition)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.SimplifyConditionalExpression)] diff --git a/src/Tests/Analyzers.Tests/RCS1207ConvertMethodGroupToAnonymousFunctionTests.cs b/src/Tests/Analyzers.Tests/RCS1207ConvertMethodGroupToAnonymousFunctionTests.cs index b5a3c1b3fc..efe8a50915 100644 --- a/src/Tests/Analyzers.Tests/RCS1207ConvertMethodGroupToAnonymousFunctionTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1207ConvertMethodGroupToAnonymousFunctionTests.cs @@ -14,7 +14,7 @@ public class RCS1207ConvertMethodGroupToAnonymousFunctionTests : AbstractCSharpD public override CSharpTestOptions Options { - get { return base.Options.EnableDiagnostic(AnalyzerOptions.ConvertMethodGroupToAnonymousFunction); } + get { return base.Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertMethodGroupToAnonymousFunction); } } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertAnonymousFunctionToMethodGroupOrViceVersa)] @@ -596,7 +596,7 @@ void M2(Func p) M2(M); } } -", options: Options.DisableDiagnostic(AnalyzerOptions.ConvertMethodGroupToAnonymousFunction)); +", options: Options.DisableDiagnostic(AnalyzerOptionDiagnosticDescriptors.ConvertMethodGroupToAnonymousFunction)); } } } diff --git a/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs b/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs index 578047a75e..c52ccfc103 100644 --- a/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs @@ -199,7 +199,7 @@ void M() x = ((string)x).ToString().ElementAt(1); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.DoNotUseElementAccessWhenExpressionIsInvocation)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.DoNotUseElementAccessWhenExpressionIsInvocation)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)] diff --git a/src/Tests/Analyzers.Tests/RCS1248UseIsNullPatternInsteadOfComparisonOrViceVersaTests.cs b/src/Tests/Analyzers.Tests/RCS1248UseIsNullPatternInsteadOfComparisonOrViceVersaTests.cs index 51333baf9b..6c53dd101d 100644 --- a/src/Tests/Analyzers.Tests/RCS1248UseIsNullPatternInsteadOfComparisonOrViceVersaTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1248UseIsNullPatternInsteadOfComparisonOrViceVersaTests.cs @@ -103,7 +103,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseIsNullPatternInsteadOfInequalityOperator)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseIsNullPatternInsteadOfComparisonOrViceVersa)] @@ -133,7 +133,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseIsNullPatternInsteadOfInequalityOperator)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseIsNullPatternInsteadOfInequalityOperator)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseIsNullPatternInsteadOfComparisonOrViceVersa)] @@ -163,7 +163,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseComparisonInsteadOfIsNullPattern)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseComparisonInsteadOfIsNullPattern)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseIsNullPatternInsteadOfComparisonOrViceVersa)] @@ -193,7 +193,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.UseComparisonInsteadOfIsNullPattern)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.UseComparisonInsteadOfIsNullPattern)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0011AddEmptyLineBetweenSingleLineAccessorsOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0011AddEmptyLineBetweenSingleLineAccessorsOrViceVersaTests.cs index 64cec8406d..c20b7431a7 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0011AddEmptyLineBetweenSingleLineAccessorsOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0011AddEmptyLineBetweenSingleLineAccessorsOrViceVersaTests.cs @@ -67,7 +67,7 @@ string P set { _p = value; } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenSingleLineAccessors)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa)] @@ -97,7 +97,7 @@ string P set { _p = value; } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenSingleLineAccessors)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa)] @@ -126,7 +126,7 @@ event EventHandler E remove { } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenSingleLineAccessors)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenSingleLineAccessors)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenSingleLineAccessorsOrViceVersa)] diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0015AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0015AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersaTests.cs index 91118b90f6..90e049ca2c 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0015AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0015AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersaTests.cs @@ -57,7 +57,7 @@ class C class C { } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa)] @@ -79,7 +79,7 @@ class C class C { } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa)] @@ -146,7 +146,7 @@ await VerifyNoDiagnosticAsync(@" class C { } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddEmptyLineBetweenUsingDirectivesWithDifferentRootNamespaceOrViceVersa)] @@ -160,7 +160,7 @@ await VerifyNoDiagnosticAsync(@" class C { } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveEmptyLineBetweenUsingDirectivesWithDifferentRootNamespace)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0027AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0027AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaTests.cs index b2c1efe56e..8ce4ef86a7 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0027AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0027AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersaTests.cs @@ -85,7 +85,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa)] @@ -149,7 +149,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa)] @@ -169,7 +169,7 @@ void M() } } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0028AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0028AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaTests.cs index fb49f4cd1e..6362860972 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0028AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0028AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersaTests.cs @@ -129,7 +129,7 @@ void M() z; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa)] @@ -159,7 +159,7 @@ void M() z; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa)] @@ -189,7 +189,7 @@ void M() z; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeConditionalOperatorInsteadOfAfterItOrViceVersa)] @@ -225,7 +225,7 @@ void M() z; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterConditionalOperatorInsteadOfBeforeIt)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0032AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0032AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaTests.cs index b87f9e92ab..8328c99b42 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0032AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0032AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersaTests.cs @@ -45,7 +45,7 @@ class C string M() => null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa)] @@ -69,7 +69,7 @@ class C string M() // x => null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0051AddNewLineBetweenClosingBraceAndWhileKeywordTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0051AddNewLineBetweenClosingBraceAndWhileKeywordTests.cs index bbbb5fdd30..48f77aa837 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0051AddNewLineBetweenClosingBraceAndWhileKeywordTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0051AddNewLineBetweenClosingBraceAndWhileKeywordTests.cs @@ -108,7 +108,7 @@ void M() } while (x); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa)] @@ -142,7 +142,7 @@ void M() } while (x); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa)] @@ -199,7 +199,7 @@ void M() } while (x); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBetweenClosingBraceAndWhileKeywordOrViceVersa)] @@ -217,7 +217,7 @@ void M() while (x); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.RemoveNewLineBetweenClosingBraceAndWhileKeyword)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0052AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0052AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaTests.cs index eb3f546cdf..5b055fb48e 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0052AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0052AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersaTests.cs @@ -57,7 +57,7 @@ void M() null; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -113,7 +113,7 @@ void M() null; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -149,7 +149,7 @@ class C string P { get; } = null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -185,7 +185,7 @@ class C string F = null; } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -229,7 +229,7 @@ void M(string p = { } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -293,7 +293,7 @@ void M() """" }); } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -337,7 +337,7 @@ class C class C { } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AddNewLineBeforeEqualsSignInsteadOfAfterItOrViceVersa)] @@ -367,7 +367,7 @@ string s // x = null; } } -", options: Options.EnableDiagnostic(AnalyzerOptions.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterEqualsSignInsteadOfBeforeIt)); } } } diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0055FixFormattingOfBinaryExpressionChainTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0055FixFormattingOfBinaryExpressionChainTests.cs index 7aae8e5b9f..b21216767b 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0055FixFormattingOfBinaryExpressionChainTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0055FixFormattingOfBinaryExpressionChainTests.cs @@ -125,7 +125,7 @@ string M(string x) """"); } } -", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa, AnalyzerOptions.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeBinaryOperatorInsteadOfAfterItOrViceVersa, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterBinaryOperatorInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.FixFormattingOfBinaryExpressionChain)] diff --git a/src/Tests/Formatting.Analyzers.Tests/RCS0056LineIsTooLongTests.cs b/src/Tests/Formatting.Analyzers.Tests/RCS0056LineIsTooLongTests.cs index e01b01601c..674157df1b 100644 --- a/src/Tests/Formatting.Analyzers.Tests/RCS0056LineIsTooLongTests.cs +++ b/src/Tests/Formatting.Analyzers.Tests/RCS0056LineIsTooLongTests.cs @@ -45,7 +45,7 @@ class C string M(object pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp) => null; } -", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.LineIsTooLong)] @@ -70,7 +70,7 @@ void M( { } } -", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.LineIsTooLong)] @@ -964,7 +964,7 @@ class C { [| string Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo() => null;|] } -", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptions.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); +", options: Options.EnableDiagnostic(DiagnosticDescriptors.AddNewLineBeforeExpressionBodyArrowInsteadOfAfterItOrViceVersa, AnalyzerOptionDiagnosticDescriptors.AddNewLineAfterExpressionBodyArrowInsteadOfBeforeIt)); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.LineIsTooLong)] diff --git a/src/Tools/CodeGeneration/CSharp/AnalyzerOptionDescriptorsGenerator.cs b/src/Tools/CodeGeneration/CSharp/AnalyzerOptionDescriptorsGenerator.cs new file mode 100644 index 0000000000..e8a0617bbf --- /dev/null +++ b/src/Tools/CodeGeneration/CSharp/AnalyzerOptionDescriptorsGenerator.cs @@ -0,0 +1,63 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Roslynator.CSharp; +using Roslynator.Metadata; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Roslynator.CSharp.CSharpFactory; + +namespace Roslynator.CodeGeneration.CSharp +{ + public static class AnalyzerOptionDescriptorsGenerator + { + public static CompilationUnitSyntax Generate( + IEnumerable analyzers, + bool obsolete, + IComparer comparer, + string @namespace, + string className) + { + return CompilationUnit( + UsingDirectives(), + NamespaceDeclaration( + @namespace, + ClassDeclaration( + Modifiers.Public_Static_Partial(), + className, + analyzers + .SelectMany(f => f.Options) + .Where(f => f.IsObsolete == obsolete) + .OrderBy(f => f.Id, comparer) + .Select(f => CreateMember(f, analyzers.Single(a => a.Id == f.ParentId))) + .ToSyntaxList()))); + } + + private static FieldDeclarationSyntax CreateMember(AnalyzerOptionMetadata analyzer, AnalyzerMetadata parent) + { + string optionKey = analyzer.OptionKey; + + if (!optionKey.StartsWith("roslynator.", System.StringComparison.Ordinal)) + optionKey = $"roslynator.{analyzer.ParentId}.{optionKey}"; + + FieldDeclarationSyntax fieldDeclaration = FieldDeclaration( + Modifiers.Internal_Static_ReadOnly(), + IdentifierName(nameof(AnalyzerOptionDescriptor)), + analyzer.Identifier, + ObjectCreationExpression( + IdentifierName(nameof(AnalyzerOptionDescriptor)), + ArgumentList( + (analyzer.Id != null) + ? Argument(SimpleMemberAccessExpression(IdentifierName("AnalyzerOptionDiagnosticDescriptors"), IdentifierName(analyzer.Identifier))) + : Argument(NullLiteralExpression()), + Argument(SimpleMemberAccessExpression(IdentifierName("DiagnosticDescriptors"), IdentifierName(parent.Identifier))), + Argument(StringLiteralExpression(optionKey))))); + + if (analyzer.IsObsolete) + fieldDeclaration = fieldDeclaration.AddObsoleteAttributeIf(analyzer.IsObsolete, error: true); + + return fieldDeclaration; + } + } +} diff --git a/src/Tools/CodeGeneration/CSharp/AnalyzerOptionsAnalyzerGenerator.cs b/src/Tools/CodeGeneration/CSharp/AnalyzerOptionsAnalyzerGenerator.cs index f2d709e98b..93c4fdb5fd 100644 --- a/src/Tools/CodeGeneration/CSharp/AnalyzerOptionsAnalyzerGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/AnalyzerOptionsAnalyzerGenerator.cs @@ -54,7 +54,7 @@ private static IEnumerable CreateMembers(IEnumerable Argument(SimpleMemberAccessExpression(IdentifierName("AnalyzerOptions"), IdentifierName(identifier)).WithTrailingTrivia(NewLine()))).ToSeparatedSyntaxList())) + ArgumentList(identifiers.Select(identifier => Argument(SimpleMemberAccessExpression(IdentifierName("AnalyzerOptionDiagnosticDescriptors"), IdentifierName(identifier)).WithTrailingTrivia(NewLine()))).ToSeparatedSyntaxList())) : ParseExpression("ImmutableArray.Empty")))))); yield return MethodDeclaration( diff --git a/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerator.cs b/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerator.cs index 33e1c1afb7..596cedd4b5 100644 --- a/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerator.cs @@ -1,6 +1,5 @@ // Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; @@ -14,9 +13,9 @@ namespace Roslynator.CodeGeneration.CSharp { - public static class DiagnosticDescriptorsGenerator + public class DiagnosticDescriptorsGenerator { - public static CompilationUnitSyntax Generate( + public CompilationUnitSyntax Generate( IEnumerable analyzers, bool obsolete, IComparer comparer, @@ -33,15 +32,6 @@ public static CompilationUnitSyntax Generate( className, identifiersClassName); - analyzers = analyzers.Where(f => f.Parent != null); - - if (analyzers.Any()) - { - MemberDeclarationSyntax methodDeclaration = CreateIsEnabledMethod(analyzers); - - classDeclaration = classDeclaration.AddMembers(methodDeclaration); - } - CompilationUnitSyntax compilationUnit = CompilationUnit( UsingDirectives("System", "Microsoft.CodeAnalysis"), NamespaceDeclaration( @@ -53,10 +43,13 @@ public static CompilationUnitSyntax Generate( return (CompilationUnitSyntax)Rewriter.Instance.Visit(compilationUnit); } - private static IEnumerable CreateMembers(IEnumerable analyzers, string identifiersClassName, bool useParentProperties = false) + private IEnumerable CreateMembers(IEnumerable analyzers, string identifiersClassName, bool useParentProperties = false) { foreach (AnalyzerMetadata analyzer in analyzers) { + if (analyzer.Id == null) + continue; + string identifier = analyzer.Identifier; string title = analyzer.Title; string messageFormat = analyzer.MessageFormat; @@ -89,7 +82,7 @@ private static IEnumerable CreateMembers(IEnumerable analyzers, string className, string identifiersClassName, @@ -105,14 +98,16 @@ private static ClassDeclarationSyntax CreateClassDeclaration( useParentProperties))); } - private static MemberDeclarationSyntax CreateMember( + private MemberDeclarationSyntax CreateMember( AnalyzerMetadata analyzer, string identifiersClassName, bool useParentProperties = false) { AnalyzerMetadata parent = (useParentProperties) ? analyzer.Parent : null; - MemberAccessExpressionSyntax idExpression = SimpleMemberAccessExpression(IdentifierName(identifiersClassName), IdentifierName(parent?.Identifier ?? analyzer.Identifier)); + ExpressionSyntax idExpression = SimpleMemberAccessExpression(IdentifierName(identifiersClassName), IdentifierName(parent?.Identifier ?? analyzer.Identifier)); + + idExpression = ModifyIdExpression(idExpression); FieldDeclarationSyntax fieldDeclaration = FieldDeclaration( (analyzer.IsObsolete) ? Modifiers.Internal_Static_ReadOnly() : Modifiers.Public_Static_ReadOnly(), @@ -167,6 +162,11 @@ private static MemberDeclarationSyntax CreateMember( return fieldDeclaration; } + protected virtual ExpressionSyntax ModifyIdExpression(ExpressionSyntax expression) + { + return expression; + } + private class Rewriter : CSharpSyntaxRewriter { private int _classDeclarationDepth; @@ -206,40 +206,5 @@ public override SyntaxNode VisitAttribute(AttributeSyntax node) return node; } } - - private static MemberDeclarationSyntax CreateIsEnabledMethod(IEnumerable analyzers) - { - var methodDeclaration = @" -public static bool IsEnabled(CompilationOptions compilationOptions, DiagnosticDescriptor analyzerOption) -{ - switch (analyzerOption.Id) - { -$SwitchSection$ default: - { - throw new ArgumentException("""", nameof(analyzerOption)); - } - } -} - - -"; - const string switchSection = @" case AnalyzerOptionIdentifiers.$AnalyzerOptionIdentifier$: - { - return !compilationOptions.IsAnalyzerSuppressed(DiagnosticDescriptors.$DiagnosticDescriptorIdentifier$) - && !compilationOptions.IsAnalyzerSuppressed(AnalyzerOptions.$AnalyzerOptionIdentifier$); - } -"; - - string switchSections = string.Concat(analyzers.Select(f => - { - return switchSection - .Replace("$AnalyzerOptionIdentifier$", f.Identifier) - .Replace("$DiagnosticDescriptorIdentifier$", f.Parent.Identifier); - })); - - methodDeclaration = methodDeclaration.Replace("$SwitchSection$", switchSections); - - return ParseMemberDeclaration(methodDeclaration); - } } } diff --git a/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerators.cs b/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerators.cs new file mode 100644 index 0000000000..92ac873375 --- /dev/null +++ b/src/Tools/CodeGeneration/CSharp/DiagnosticDescriptorsGenerators.cs @@ -0,0 +1,9 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Roslynator.CodeGeneration.CSharp +{ + public static class DiagnosticDescriptorsGenerators + { + public static DiagnosticDescriptorsGenerator Default { get; } = new DiagnosticDescriptorsGenerator(); + } +} diff --git a/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs b/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs index 2da8015d07..7585eb8fed 100644 --- a/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs +++ b/src/Tools/CodeGeneration/CSharp/DiagnosticIdentifiersGenerator.cs @@ -38,7 +38,8 @@ private static IEnumerable CreateMembers(AnalyzerMetadat string id = analyzer.Id; string identifier = analyzer.Identifier; - yield return CreateMember(id, identifier, analyzer.IsObsolete); + if (id != null) + yield return CreateMember(id, identifier, analyzer.IsObsolete); } private static FieldDeclarationSyntax CreateMember(string id, string identifier, bool isObsolete) diff --git a/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs b/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs index e0d3757bd7..df68c7e417 100644 --- a/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs +++ b/src/Tools/CodeGeneration/Markdown/MarkdownGenerator.cs @@ -1,5 +1,6 @@ // Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; @@ -197,7 +198,6 @@ public static string CreateAnalyzerMarkdown(AnalyzerMetadata analyzer, IEnumerab (!string.IsNullOrEmpty(analyzer.MinLanguageVersion)) ? TableRow("Minimal Language Version", analyzer.MinLanguageVersion) : null), CreateSummary(), GetAnalyzerSamples(analyzer), - CreateConfiguration(analyzer.Configuration), CreateOptions(analyzer), CreateRemarks(analyzer.Remarks), CreateAppliesTo(appliesTo), @@ -372,18 +372,9 @@ private static IEnumerable CreateSummary(string summary) } } - private static IEnumerable CreateConfiguration(string configuration) - { - if (!string.IsNullOrEmpty(configuration)) - { - yield return Heading2("Configuration"); - yield return Raw(configuration); - } - } - private static IEnumerable CreateOptions(AnalyzerMetadata analyzer) { - using (IEnumerator en = analyzer.OptionAnalyzers.GetEnumerator()) + using (IEnumerator en = analyzer.Options.GetEnumerator()) { if (en.MoveNext()) { @@ -391,9 +382,25 @@ private static IEnumerable CreateOptions(AnalyzerMetadata analyzer) do { - string id = en.Current.Id; + yield return Heading3(en.Current.Title.TrimEnd('.')); + + if (!string.IsNullOrEmpty(en.Current.Summary)) + { + yield return new MText(en.Current.Summary); + yield return new MText(NewLine); + } + + string helpValue = en.Current.OptionKey; + + if (!helpValue.StartsWith("roslynator.", StringComparison.Ordinal)) + helpValue = $"roslynator.{en.Current.ParentId}.{helpValue}"; + + helpValue += " = "; + helpValue += en.Current.OptionValue ?? "true"; - yield return BulletItem(Link(id, $"{id}.md"), " - ", en.Current.Title); + yield return FencedCodeBlock( + helpValue, + "editorconfig"); } while (en.MoveNext()); } diff --git a/src/Tools/CodeGenerator/Program.cs b/src/Tools/CodeGenerator/Program.cs index 906077701e..4614203303 100644 --- a/src/Tools/CodeGenerator/Program.cs +++ b/src/Tools/CodeGenerator/Program.cs @@ -134,12 +134,12 @@ void WriteDiagnostics( { WriteCompilationUnit( Path.Combine(dirPath, $"{descriptorsClassName}.Generated.cs"), - DiagnosticDescriptorsGenerator.Generate(analyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: descriptorsClassName, identifiersClassName: identifiersClassName), + DiagnosticDescriptorsGenerators.Default.Generate(analyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: descriptorsClassName, identifiersClassName: identifiersClassName), normalizeWhitespace: false); WriteCompilationUnit( Path.Combine(dirPath, $"{descriptorsClassName}.Deprecated.Generated.cs"), - DiagnosticDescriptorsGenerator.Generate(analyzers, obsolete: true, comparer: comparer, @namespace: @namespace, className: descriptorsClassName, identifiersClassName: identifiersClassName), + DiagnosticDescriptorsGenerators.Default.Generate(analyzers, obsolete: true, comparer: comparer, @namespace: @namespace, className: descriptorsClassName, identifiersClassName: identifiersClassName), normalizeWhitespace: false); WriteCompilationUnit( @@ -155,19 +155,25 @@ void WriteDiagnostics( if (optionAnalyzers.Any()) { WriteCompilationUnit( - Path.Combine(dirPath, "AnalyzerOptions.Generated.cs"), - DiagnosticDescriptorsGenerator.Generate(optionAnalyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: "AnalyzerOptions", identifiersClassName: "AnalyzerOptionIdentifiers"), + Path.Combine(dirPath, "AnalyzerOptionDiagnosticDescriptors.Generated.cs"), + DiagnosticDescriptorsGenerators.Default.Generate(optionAnalyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: "AnalyzerOptionDiagnosticDescriptors", identifiersClassName: "AnalyzerOptionDiagnosticIdentifiers"), normalizeWhitespace: false, fileMustExist: false); WriteCompilationUnit( - Path.Combine(dirPath, "AnalyzerOptionIdentifiers.Generated.cs"), - DiagnosticIdentifiersGenerator.Generate(optionAnalyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: "AnalyzerOptionIdentifiers"), + Path.Combine(dirPath, "AnalyzerOptionDiagnosticIdentifiers.Generated.cs"), + DiagnosticIdentifiersGenerator.Generate(optionAnalyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: "AnalyzerOptionDiagnosticIdentifiers"), + fileMustExist: false); + + WriteCompilationUnit( + Path.Combine(dirPath, "AnalyzerOptions.Generated.cs"), + AnalyzerOptionDescriptorsGenerator.Generate(analyzers, obsolete: false, comparer: comparer, @namespace: @namespace, className: "AnalyzerOptions"), fileMustExist: false); } IEnumerable analyzerOptionIdentifiers = analyzers .SelectMany(f => f.OptionAnalyzers) + .Where(f => f.Id != null) .Select(f => f.Identifier); WriteCompilationUnit( diff --git a/src/Tools/Metadata/AnalyzerMetadata.cs b/src/Tools/Metadata/AnalyzerMetadata.cs index a42efcbce8..fae036a5d8 100644 --- a/src/Tools/Metadata/AnalyzerMetadata.cs +++ b/src/Tools/Metadata/AnalyzerMetadata.cs @@ -26,7 +26,6 @@ public AnalyzerMetadata( string minLanguageVersion, string summary, string remarks, - string configuration, IEnumerable samples, IEnumerable links, IEnumerable options, @@ -46,7 +45,6 @@ public AnalyzerMetadata( MinLanguageVersion = minLanguageVersion; Summary = summary; Remarks = remarks; - Configuration = configuration; Samples = new ReadOnlyCollection(samples?.ToArray() ?? Array.Empty()); Links = new ReadOnlyCollection(links?.ToArray() ?? Array.Empty()); Options = new ReadOnlyCollection(options?.ToArray() ?? Array.Empty()); @@ -83,8 +81,6 @@ public AnalyzerMetadata( public string Remarks { get; } - public string Configuration { get; } - public IReadOnlyList Samples { get; } public IReadOnlyList Links { get; } diff --git a/src/Tools/Metadata/AnalyzerOptionMetadata.cs b/src/Tools/Metadata/AnalyzerOptionMetadata.cs index f8e21c9f30..c93bf3ebf0 100644 --- a/src/Tools/Metadata/AnalyzerOptionMetadata.cs +++ b/src/Tools/Metadata/AnalyzerOptionMetadata.cs @@ -12,6 +12,9 @@ public class AnalyzerOptionMetadata public AnalyzerOptionMetadata( string identifier, string id, + string parentId, + string optionKey, + string optionValue, AnalyzerOptionKind kind, string title, bool isEnabledByDefault, @@ -23,6 +26,9 @@ public AnalyzerOptionMetadata( { Identifier = identifier; Id = id; + ParentId = parentId; + OptionKey = optionKey; + OptionValue = optionValue; Kind = kind; Title = title; IsEnabledByDefault = isEnabledByDefault; @@ -36,7 +42,7 @@ public AnalyzerOptionMetadata( public AnalyzerMetadata CreateAnalyzerMetadata(AnalyzerMetadata parent) { return new AnalyzerMetadata( - id: parent.Id + Id, + id: (Id != null) ? parent.Id + Id : null, identifier: Identifier, title: Title, messageFormat: Title, @@ -49,7 +55,6 @@ public AnalyzerMetadata CreateAnalyzerMetadata(AnalyzerMetadata parent) minLanguageVersion: MinLanguageVersion ?? parent.MinLanguageVersion, summary: Summary, remarks: null, - configuration: null, samples: Samples, links: null, options: null, @@ -61,6 +66,12 @@ public AnalyzerMetadata CreateAnalyzerMetadata(AnalyzerMetadata parent) public string Id { get; } + public string ParentId { get; } + + public string OptionKey { get; } + + public string OptionValue { get; } + public AnalyzerOptionKind Kind { get; } public string Title { get; } diff --git a/src/Tools/Metadata/MetadataFile.cs b/src/Tools/Metadata/MetadataFile.cs index 52ab60e956..4f6e712877 100644 --- a/src/Tools/Metadata/MetadataFile.cs +++ b/src/Tools/Metadata/MetadataFile.cs @@ -46,7 +46,6 @@ public static IEnumerable ReadAnalyzers(string filePath) string minLanguageVersion = element.Element("MinLanguageVersion")?.Value; string summary = element.Element("Summary")?.Value.NormalizeNewLine(); string remarks = element.Element("Remarks")?.Value.NormalizeNewLine(); - string configuration = element.Element("Configuration")?.Value.NormalizeNewLine(); IEnumerable samples = LoadSamples(element)?.Select(f => f.WithBefore(f.Before.Replace("[|Id|]", id))); IEnumerable links = LoadLinks(element); IEnumerable options = LoadOptions(element, id); @@ -65,7 +64,6 @@ public static IEnumerable ReadAnalyzers(string filePath) minLanguageVersion: minLanguageVersion, summary: summary, remarks: remarks, - configuration: configuration, samples: samples, links: links, options: options, @@ -148,7 +146,9 @@ private static AnalyzerOptionMetadata LoadOption(XElement element, string parent string title = element.Element("Title").Value; string identifier = element.Attribute("Identifier").Value; - string id = element.Element("Id").Value; + string id = element.Element("Id")?.Value; + string optionKey = element.Element("OptionKey").Value; + string optionValue = element.Element("OptionValue")?.Value; var kind = (AnalyzerOptionKind)Enum.Parse(typeof(AnalyzerOptionKind), element.Element("Kind").Value); bool isEnabledByDefault = element.ElementValueAsBooleanOrDefault("IsEnabledByDefault"); bool supportsFadeOut = element.ElementValueAsBooleanOrDefault("SupportsFadeOut"); @@ -160,6 +160,9 @@ private static AnalyzerOptionMetadata LoadOption(XElement element, string parent return new AnalyzerOptionMetadata( identifier: identifier, id: id, + parentId: parentId, + optionKey: optionKey, + optionValue: optionValue, kind: kind, title: title, isEnabledByDefault: isEnabledByDefault, diff --git a/src/Tools/MetadataGenerator/Program.cs b/src/Tools/MetadataGenerator/Program.cs index cfc86dfa02..c0fe638dc2 100644 --- a/src/Tools/MetadataGenerator/Program.cs +++ b/src/Tools/MetadataGenerator/Program.cs @@ -154,7 +154,9 @@ void WriteAnalyzerMarkdowns(IEnumerable analyzers, IEnumerable WriteAnalyzerMarkdown(analyzer, appliesTo); } - foreach (AnalyzerMetadata analyzer in analyzers.SelectMany(a => a.OptionAnalyzers)) + foreach (AnalyzerMetadata analyzer in analyzers + .SelectMany(a => a.OptionAnalyzers) + .Where(a => a.Id != null)) { WriteAnalyzerMarkdown(analyzer, appliesTo); } @@ -167,7 +169,8 @@ void WriteAnalyzerMarkdown(AnalyzerMetadata analyzer, IEnumerable<(string title, MarkdownGenerator.CreateAnalyzerMarkdown(analyzer, appliesTo), fileMustExists: false); - foreach (AnalyzerMetadata optionAnalyzer in analyzer.OptionAnalyzers) + foreach (AnalyzerMetadata optionAnalyzer in analyzer.OptionAnalyzers + .Where(f => f.Id != null)) { WriteAllText( $@"..\docs\analyzers\{optionAnalyzer.Id}.md", @@ -226,6 +229,7 @@ void UpdateChangeLog() ImmutableDictionary dic = allAnalyzers .Concat(allAnalyzers.SelectMany(f => f.OptionAnalyzers)) + .Where(f => f.Id != null) .ToImmutableDictionary(f => f.Id, f => f); s = issueRegex.Replace(s, "([issue](https://github.com/JosefPihrt/Roslynator/issues/${issue}))"); diff --git a/src/Workspaces.Common/CommonWorkspaceExtensions.cs b/src/Workspaces.Common/CommonWorkspaceExtensions.cs new file mode 100644 index 0000000000..180207d915 --- /dev/null +++ b/src/Workspaces.Common/CommonWorkspaceExtensions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.CodeAnalysis; + +namespace Roslynator +{ + internal static class CommonWorkspaceExtensions + { + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + Document document, + SyntaxNode node) + { + return IsEnabled(analyzerOption, document, node.SyntaxTree); + } + + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + Document document, + SyntaxToken token) + { + return IsEnabled(analyzerOption, document, token.SyntaxTree); + } + + public static bool IsEnabled( + this AnalyzerOptionDescriptor analyzerOption, + Document document, + SyntaxTree syntaxTree) + { + return analyzerOption.Parent.IsEffective(syntaxTree, document.Project.CompilationOptions) + && analyzerOption.IsEnabled( + syntaxTree, + document.Project.CompilationOptions, + document.Project.AnalyzerOptions); + } + } +}