From f15e24447ccf2f1dbc0f2d1652f79fd43530d23c Mon Sep 17 00:00:00 2001 From: Josef Pihrt Date: Sat, 23 Nov 2024 17:07:29 +0100 Subject: [PATCH] Add formatting rules (#1576) --- .editorconfig | 55 +- .gitignore | 4 +- ChangeLog.md | 4 + ...onToDocumentationCommentCodeFixProvider.cs | 42 +- .../AssignmentExpressionCodeFixProvider.cs | 78 +- .../AvoidBoxingOfValueTypeCodeFixProvider.cs | 22 +- .../AwaitExpressionCodeFixProvider.cs | 22 +- .../BaseArgumentListCodeFixProvider.cs | 18 +- .../BinaryExpressionCodeFixProvider.cs | 338 +++---- .../CSharp/CodeFixes/BlockCodeFixProvider.cs | 36 +- .../ClassDeclarationCodeFixProvider.cs | 102 +- .../ConditionalExpressionCodeFixProvider.cs | 110 +-- .../ConstructorDeclarationCodeFixProvider.cs | 50 +- .../DefaultExpressionCodeFixProvider.cs | 18 +- .../DestructorDeclarationCodeFixProvider.cs | 18 +- ...seResourceAsynchronouslyCodeFixProvider.cs | 48 +- .../CodeFixes/DocumentCodeFixProvider.cs | 26 +- .../DocumentationCommentCodeFixProvider.cs | 16 +- .../CodeFixes/ElseClauseCodeFixProvider.cs | 36 +- .../EnumDeclarationCodeFixProvider.cs | 94 +- .../EnumMemberDeclarationCodeFixProvider.cs | 88 +- .../CodeFixes/ExpressionCodeFixProvider.cs | 138 +-- .../CodeFixes/ForStatementCodeFixProvider.cs | 28 +- .../CodeFixes/IfStatementCodeFixProvider.cs | 148 +-- ...entNonGenericCounterpartCodeFixProvider.cs | 96 +- .../CodeFixes/InitializerCodeFixProvider.cs | 32 +- .../InterpolatedStringCodeFixProvider.cs | 50 +- .../InvocationExpressionCodeFixProvider.cs | 134 +-- ...ocalDeclarationStatementCodeFixProvider.cs | 84 +- .../MemberDeclarationCodeFixProvider.cs | 202 ++-- .../NamespaceDeclarationCodeFixProvider.cs | 38 +- ...ObjectCreationExpressionCodeFixProvider.cs | 16 +- .../OptimizeLinqMethodCallCodeFixProvider.cs | 342 +++---- .../OptimizeMethodCallCodeFixProvider.cs | 124 +-- ...eStringBuilderAppendCallCodeFixProvider.cs | 86 +- ...tsInDocumentationCommentCodeFixProvider.cs | 22 +- .../CodeFixes/ParameterCodeFixProvider.cs | 40 +- ...meterNameDiffersFromBaseCodeFixProvider.cs | 72 +- .../PropertyDeclarationCodeFixProvider.cs | 16 +- .../RemoveEmptySyntaxCodeFixProvider.cs | 114 +-- ...emoveRedundantAssignmentCodeFixProvider.cs | 40 +- ...eRedundantBooleanLiteralCodeFixProvider.cs | 56 +- .../RemoveRedundantCastCodeFixProvider.cs | 36 +- .../RemoveUnnecessaryElseCodeFixProvider.cs | 18 +- ...pletedTaskInsteadOfNullCodeFixProvider2.cs | 64 +- .../SimplifyCodeBranchingCodeFixProvider.cs | 92 +- .../SimplifyLogicalNegationCodeFixProvider.cs | 58 +- ...cumentationCommentTriviaCodeFixProvider.cs | 104 +- .../CodeFixes/StatementCodeFixProvider.cs | 110 +-- .../CodeFixes/SwitchSectionCodeFixProvider.cs | 64 +- .../CSharp/CodeFixes/TokenCodeFixProvider.cs | 108 +-- .../CodeFixes/TypeParameterCodeFixProvider.cs | 16 +- .../UnnecessaryAssignmentCodeFixProvider.cs | 32 +- .../UnnecessaryEnumFlagCodeFixProvider.cs | 40 +- .../CodeFixes/UseAsyncAwaitCodeFixProvider.cs | 84 +- .../UseAutoPropertyCodeFixProvider.cs | 64 +- .../UseCoalesceExpressionCodeFixProvider.cs | 84 +- .../UseConditionalAccessCodeFixProvider.cs | 54 +- ...ringLiteralOrStringEmptyCodeFixProvider.cs | 40 +- ...ypeInsteadOfVarInForEachCodeFixProvider.cs | 38 +- .../UseStringComparisonCodeFixProvider.cs | 128 +-- ...VarInsteadOfExplicitTypeCodeFixProvider.cs | 26 +- .../UseVarOrExplicitTypeCodeFixProvider.cs | 124 +-- .../VariableDeclaratorCodeFixProvider.cs | 16 +- .../WhileStatementCodeFixProvider.cs | 60 +- .../CodeFixes/XmlNodeCodeFixProvider.cs | 46 +- .../JoinStringExpressionsRefactoring.cs | 16 +- ...eSemicolonAtEndOfDeclarationRefactoring.cs | 60 +- .../WhitespaceTriviaCodeFixProvider.cs | 32 +- ...ParagraphToDocumentationCommentAnalyzer.cs | 226 ++--- .../AvoidBoxingOfValueTypeAnalysis.cs | 56 +- .../AvoidNullReferenceExceptionAnalyzer.cs | 24 +- .../CSharp/Analysis/BinaryOperatorAnalyzer.cs | 56 +- .../CSharp/Analysis/BooleanLiteralAnalyzer.cs | 116 +-- .../CallCastInsteadOfSelectAnalysis.cs | 16 +- .../Analysis/DefaultExpressionAnalyzer.cs | 152 +-- .../Analysis/FileContainsNoCodeAnalyzer.cs | 26 +- .../FixDocumentationCommentTagAnalysis.cs | 32 +- .../CSharp/Analysis/IfStatementAnalyzer.cs | 30 +- .../Analysis/InlineLocalVariableAnalyzer.cs | 176 ++-- .../Analysis/InvocationExpressionAnalyzer.cs | 664 ++++++------- .../Analysis/JoinStringExpressionsAnalyzer.cs | 212 ++--- .../Analysis/MakeClassStaticAnalyzer.cs | 88 +- .../MakeMemberReadOnlyAnalyzer.cs | 86 +- .../MarkLocalVariableAsConstAnalyzer.cs | 48 +- .../Analysis/MergeSwitchSectionsAnalyzer.cs | 26 +- .../Analysis/NamedTypeSymbolAnalyzer.cs | 60 +- ...ImplicitOrExplicitArrayCreationAnalysis.cs | 124 +-- .../ImplicitOrExplicitCreationAnalysis.cs | 506 +++++----- .../OptimizeLinqMethodCallAnalysis.cs | 128 +-- .../Analysis/OptimizeMethodCallAnalysis.cs | 34 +- ...OptimizeStringBuilderAppendCallAnalysis.cs | 78 +- .../RemoveRedundantAssignmentAnalyzer.cs | 22 +- .../RemoveRedundantBaseInterfaceAnalyzer.cs | 116 +-- .../Analysis/RemoveRedundantCastAnalyzer.cs | 36 +- .../RemoveRedundantConstructorAnalyzer.cs | 20 +- ...veRedundantDefaultSwitchSectionAnalyzer.cs | 18 +- ...RemoveRedundantOverridingMemberAnalyzer.cs | 224 ++--- .../RemoveRedundantParenthesesAnalyzer.cs | 180 ++-- .../RemoveRedundantToStringCallAnalysis.cs | 24 +- .../RemoveUnnecessaryBlankLineAnalyzer.cs | 32 +- .../SimplifyBooleanComparisonAnalysis.cs | 56 +- .../SimplifyCoalesceExpressionAnalyzer.cs | 26 +- .../Analysis/SimplifyCodeBranchingAnalyzer.cs | 60 +- .../SimplifyLogicalNegationAnalyzer.cs | 116 +-- ...eLineDocumentationCommentTriviaAnalyzer.cs | 110 +-- ...nericTypeShouldUseTypeParameterAnalyzer.cs | 120 +-- ...inedTypeParameterCheckedForNullAnalyzer.cs | 56 +- .../Analysis/UnnecessaryAssignmentAnalyzer.cs | 60 +- .../Analysis/UnnecessaryNullCheckAnalyzer.cs | 56 +- .../UnnecessaryUnsafeContextAnalyzer.cs | 20 +- .../UnusedMember/UnusedMemberAnalyzer.cs | 226 ++--- .../UnusedParameterAnalyzer.cs | 10 +- .../UnusedParameter/UnusedParameterWalker.cs | 26 +- ...eAnonymousFunctionOrMethodGroupAnalyzer.cs | 20 +- .../CSharp/Analysis/UseAsyncAwaitAnalyzer.cs | 18 +- .../Analysis/UseAutoPropertyAnalyzer.cs | 134 +-- .../UseBlockBodyOrExpressionBodyAnalyzer.cs | 28 +- .../Analysis/UseCompoundAssignmentAnalyzer.cs | 8 +- .../Analysis/UseConditionalAccessAnalyzer.cs | 94 +- .../Analysis/UseExceptionFilterAnalyzer.cs | 32 +- ...plicitTypeInsteadOfVarInForEachAnalyzer.cs | 36 +- .../UseGenericEventHandlerAnalyzer.cs | 26 +- ...tternMatchingInsteadOfIsAndCastAnalyzer.cs | 68 +- .../Analysis/UsePredefinedTypeAnalyzer.cs | 24 +- ...exInstanceInsteadOfStaticMethodAnalysis.cs | 28 +- src/Analyzers/CSharp/NodeSymbolInfo.cs | 14 +- .../CSharp/CSharpSyntaxFactsService.cs | 34 +- .../CSharp/CodeMetrics/CSharpLinesWalker.cs | 60 +- .../CodeMetrics/CSharpPhysicalLinesWalker.cs | 56 +- .../CSharp/Extensions/WorkspaceExtensions.cs | 72 +- .../CSharp/FindSymbols/LocalSymbolFinder.cs | 134 +-- .../CSharp/Spelling/CSharpSpellingWalker.cs | 196 ++-- .../CSharp/SyntaxInverter.cs | 132 +-- .../CSharp/SyntaxLogicalInverter.cs | 222 ++--- src/CSharp/CSharp/CSharpFacts.cs | 220 ++--- .../CSharp/CSharpOverriddenSymbolInfo.cs | 14 +- src/CSharp/CSharp/CSharpTypeAnalysis.cs | 310 +++--- src/CSharp/CSharp/CSharpUtility.cs | 106 +-- .../DocumentationCommentGenerator.cs | 22 +- src/CSharp/CSharp/ExpressionChain.Reversed.cs | 168 ++-- src/CSharp/CSharp/ExpressionChain.cs | 192 ++-- .../CSharp/Extensions/CSharpExtensions.cs | 260 ++--- .../CSharp/Extensions/SymbolExtensions.cs | 58 +- .../CSharp/Extensions/SyntaxExtensions.cs | 174 ++-- .../CSharp/MemberDeclarationComparer.cs | 22 +- .../CSharp/MemberDeclarationKindComparer.cs | 8 +- src/CSharp/CSharp/MethodChain.cs | 24 +- src/CSharp/CSharp/ModifierKindComparer.cs | 8 +- src/CSharp/CSharp/ModifierList.cs | 40 +- src/CSharp/CSharp/StringLiteralParser.cs | 308 +++--- src/CSharp/CSharp/StringLiteralTextBuilder.cs | 130 +-- src/CSharp/CSharp/Syntax/GenericInfo.cs | 42 +- .../Syntax/MemberDeclarationListInfo.cs | 242 ++--- src/CSharp/CSharp/Syntax/ModifierListInfo.cs | 426 ++++----- .../CSharp/Syntax/NullCheckExpressionInfo.cs | 294 +++--- src/CSharp/CSharp/Syntax/RegionInfo.cs | 22 +- .../SingleParameterLambdaExpressionInfo.cs | 46 +- .../StringConcatenationExpressionInfo.cs | 28 +- .../Syntax/TypeParameterConstraintInfo.cs | 112 +-- .../CSharp/Syntax/UsingDirectiveListInfo.cs | 72 +- src/CSharp/CSharp/Syntax/XmlElementInfo.cs | 24 +- src/CSharp/CSharp/SyntaxAccessibility.cs | 200 ++-- src/CSharp/CSharp/SyntaxRefactorings.cs | 88 +- .../SyntaxWalkers/AssignedExpressionWalker.cs | 20 +- .../MethodReferencedAsMethodGroupWalker.cs | 16 +- .../CSharp/SyntaxWalkers/StatementWalker.cs | 210 ++--- .../AttributeArgumentCodeFixProvider.cs | 20 +- .../CSharp/AttributeCodeFixProvider.cs | 16 +- .../CSharp/BinaryExpressionCodeFixProvider.cs | 46 +- .../InvocationExpressionCodeFixProvider.cs | 34 +- .../UsePatternMatchingCodeFixProvider.cs | 92 +- .../CSharp/InvocationExpressionAnalyzer.cs | 50 +- .../CSharp/NamedTypeSymbolAnalyzer.cs | 84 +- .../SimpleMemberAccessExpressionAnalyzer.cs | 64 +- .../CSharp/Syntax/IsKindExpressionInfo.cs | 102 +- .../CSharp/UsePatternMatchingAnalyzer.cs | 72 +- .../RoslynSymbolUtility.cs | 6 +- .../CodeFixes/AddBodyCodeFixProvider.cs | 266 +++--- .../AddReturnStatementCodeFixProvider.cs | 100 +- .../CodeFixes/ArgumentCodeFixProvider.cs | 158 ++-- .../CodeFixes/BaseListCodeFixProvider.cs | 120 +-- ...annotConvertArgumentTypeCodeFixProvider.cs | 130 +-- ...notImplicitlyConvertTypeCodeFixProvider.cs | 62 +- .../CodeFixes/ExpressionCodeFixProvider.cs | 876 ++++++++--------- .../IdentifierNameCodeFixProvider.cs | 130 +-- .../MemberDeclarationCodeFixProvider.cs | 520 +++++----- ...mberHidesInheritedMemberCodeFixProvider.cs | 36 +- .../CodeFixes/ModifiersCodeFixProvider.cs | 666 ++++++------- ...ObjectCreationExpressionCodeFixProvider.cs | 146 +-- .../CodeFixes/ParameterCodeFixProvider.cs | 78 +- ...tationFromAbstractMemberCodeFixProvider.cs | 120 +-- ...opertyOrFieldInitializerCodeFixProvider.cs | 76 +- .../ReturnStatementCodeFixProvider.cs | 108 +-- ...ustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs | 20 +- .../CodeFixes/SimpleNameCodeFixProvider.cs | 62 +- .../CodeFixes/StatementCodeFixProvider.cs | 130 +-- .../SyntaxErrorCharExpectedCodeFixProvider.cs | 30 +- .../CSharp/CodeFixes/TokenCodeFixProvider.cs | 890 +++++++++--------- .../TypeDeclarationCodeFixProvider.cs | 72 +- ...DoesNotContainDefinitionCodeFixProvider.cs | 114 +-- ...arameterConstraintClauseCodeFixProvider.cs | 82 +- .../TypeParameterConstraintCodeFixProvider.cs | 112 +-- .../UnreachableCodeCodeFixProvider.cs | 106 +-- .../CSharp/CodeFixes/UnsafeCodeFixProvider.cs | 166 ++-- ...UseNullForgivingOperatorCodeFixProvider.cs | 30 +- .../VariableDeclarationCodeFixProvider.cs | 98 +- .../ChangeMemberTypeRefactoring.cs | 34 +- ...geTypeAccordingToInitializerRefactoring.cs | 20 +- ...seYieldReturnInsteadOfReturnRefactoring.cs | 70 +- src/CommandLine/FindSymbols/SymbolFinder.cs | 76 +- .../FindSymbols/UnusedSymbolUtility.cs | 174 ++-- .../Html/SymbolDefinitionHtmlWriter.cs | 188 ++-- .../Json/SymbolDefinitionJsonWriter.cs | 42 +- src/CommandLine/ParseHelpers.cs | 56 +- .../Rename/CliSymbolRenameState.cs | 76 +- ...ExceptionToDocumentationCommentAnalysis.cs | 38 +- .../Analysis/BlockExpressionAnalysis.cs | 34 +- ...ExtensionMethodAsInstanceMethodAnalysis.cs | 26 +- .../Analysis/ChangeAccessibilityAnalysis.cs | 152 +-- src/Common/CSharp/Analysis/If/IfAnalysis.cs | 64 +- .../ReduceIfNestingAnalysis.cs | 280 +++--- .../Analysis/RemoveAsyncAwaitAnalysis.cs | 142 +-- .../RemoveRedundantReturnStatementAnalysis.cs | 32 +- .../RemoveRedundantStatementAnalysis`1.cs | 124 +-- .../UseConstantInsteadOfFieldAnalysis.cs | 62 +- .../UseMethodChainingAnalysis.cs | 40 +- src/Common/CSharp/IndentationAnalysis.cs | 196 ++-- src/Common/CSharp/TriviaBlock.cs | 194 ++-- src/Common/Configuration/ConfigMigrator.cs | 210 ++--- src/Common/RuleSetLoader.cs | 48 +- src/Core/CreateNameFromTypeSymbolHelper.cs | 58 +- src/Core/DiagnosticIdPrefix.cs | 216 ++--- src/Core/Extensions/EnumExtensions.cs | 46 +- src/Core/Extensions/SymbolExtensions.cs | 134 +-- src/Core/MetadataName.cs | 46 +- src/Core/OneOrMany`1.cs | 38 +- src/Documentation/DocumentationGenerator.cs | 812 ++++++++-------- src/Documentation/DocumentationResources.cs | 66 +- src/Documentation/DocumentationUtility.cs | 52 +- src/Documentation/DocumentationWriter.cs | 214 ++--- .../Extensions/SymbolExtensions.cs | 208 ++-- src/Documentation/Extensions/XmlExtensions.cs | 204 ++-- .../MemberSymbolEqualityComparer.cs | 164 ++-- src/Documentation/SymbolDefinitionDisplay.cs | 494 +++++----- src/Documentation/SymbolDefinitionWriter.cs | 172 ++-- .../SymbolDefinitionWriterHelpers.cs | 164 ++-- src/Documentation/SymbolXmlDocumentation.cs | 64 +- src/Documentation/TypeDocumentationModel.cs | 20 +- .../AccessorDeclarationCodeFixProvider.cs | 50 +- .../CSharp/AccessorListCodeFixProvider.cs | 16 +- .../CSharp/BlockCodeFixProvider.cs | 28 +- .../CSharp/CompilationUnitCodeFixProvider.cs | 64 +- .../CSharp/DirectiveTriviaCodeFixProvider.cs | 16 +- .../FixFormattingOfListCodeFixProvider.cs | 150 +-- .../CSharp/InitializerCodeFixProvider.cs | 18 +- .../LineIsTooLong/WrapLineNodeFinder.cs | 438 ++++----- ...izeWhitespaceAtEndOfFileCodeFixProvider.cs | 112 +-- .../CSharp/StatementCodeFixProvider.cs | 24 +- .../CSharp/SyntaxTokenCodeFixProvider.cs | 40 +- .../CSharp/SyntaxTriviaCodeFixProvider.cs | 16 +- .../NewLineCodeFixProvider.cs | 36 +- .../CSharp/AccessorListAnalyzer.cs | 74 +- ...eenClosingBraceAndNextStatementAnalyzer.cs | 50 +- ...rmattingOfBinaryExpressionChainAnalyzer.cs | 42 +- .../FixFormattingOfCallChainAnalyzer.cs | 48 +- .../CSharp/FixFormattingOfListAnalyzer.cs | 22 +- ...NewLineAfterOrBeforeEqualsTokenAnalyzer.cs | 38 +- ...enericParameterToDeclarationRefactoring.cs | 56 +- .../AddMemberToInterfaceRefactoring.cs | 136 +-- .../AddUsingDirectiveRefactoring.cs | 16 +- .../Refactorings/AttributeListRefactoring.cs | 16 +- .../CheckParameterForNullRefactoring.cs | 14 +- .../Refactorings/CommentTriviaRefactoring.cs | 16 +- ...ConvertBodyAndExpressionBodyRefactoring.cs | 182 ++-- .../ConvertIfToSwitchRefactoring.cs | 178 ++-- ...rpolatedStringToStringFormatRefactoring.cs | 74 +- ...bdaExpressionBodyToBlockBodyRefactoring.cs | 16 +- .../ConvertStringLiteralRefactoring.cs | 92 +- .../ConvertSwitchToIfRefactoring.cs | 86 +- .../ExtractConditionRefactoring.cs | 122 +-- ...yForDebuggerDisplayAttributeRefactoring.cs | 196 ++-- .../InlineDefinition/InlineRefactoring.cs | 20 +- .../InlineUsingStaticDirectiveRefactoring.cs | 16 +- .../IntroduceConstructorRefactoring.cs | 28 +- .../Refactorings/InvertIfRefactoring.cs | 24 +- .../InvertLinqMethodCallRefactoring.cs | 6 +- .../Refactorings/InvertOperatorRefactoring.cs | 8 +- .../LiteralExpressionRefactoring.cs | 44 +- .../MemberDeclarationRefactoring.cs | 328 +++---- .../ParenthesizeExpressionRefactoring.cs | 114 +-- .../PostfixUnaryExpressionRefactoring.cs | 20 +- .../PrefixUnaryExpressionRefactoring.cs | 20 +- .../CSharp/Refactorings/RefactoringContext.cs | 888 ++++++++--------- .../RemoveAllMemberDeclarationsRefactoring.cs | 40 +- .../RemoveAllStatementsRefactoring.cs | 40 +- .../RemoveAsyncAwaitRefactoring.cs | 90 +- .../Refactorings/RemoveBracesRefactoring.cs | 22 +- ...InstantiationOfLocalVariableRefactoring.cs | 54 +- .../SelectedMemberDeclarationsRefactoring.cs | 90 +- .../Refactorings/StatementRefactoring.cs | 116 +-- .../SwapBinaryOperandsRefactoring.cs | 24 +- .../UseElementAccessRefactoring.cs | 72 +- .../Refactorings/WrapCallChainRefactoring.cs | 38 +- src/Tests/CSharp.Tests/SyntaxKindTests.cs | 14 +- .../Extensions/TestExtensions.cs | 48 +- .../Testing/Text/TextProcessor.cs | 118 +-- .../CodeMetrics/VisualBasicLinesWalker.cs | 26 +- .../VisualBasicPhysicalLinesWalker.cs | 18 +- .../CSharp/CodeActionFactory.cs | 76 +- .../CodeFixes/ModifiersCodeFixRegistrator.cs | 36 +- .../CSharp/DocumentRefactorings.cs | 88 +- ...lementToDocumentationCommentRefactoring.cs | 74 +- ...ddParameterToInterfaceMemberRefactoring.cs | 46 +- ...ensionMethodAsInstanceMethodRefactoring.cs | 30 +- .../ChangeAccessibilityRefactoring.cs | 26 +- ...ertBlockBodyToExpressionBodyRefactoring.cs | 196 ++-- ...onditionalExpressionToIfElseRefactoring.cs | 28 +- ...ertExpressionBodyToBlockBodyRefactoring.cs | 174 ++-- ...asFlagCallToBitwiseOperationRefactoring.cs | 40 +- ...dStringToStringBuilderMethodRefactoring.cs | 124 +-- ...bdaBlockBodyToExpressionBodyRefactoring.cs | 48 +- .../CSharp/Refactorings/IfRefactoring.cs | 166 ++-- .../CSharp/Refactorings/RemoveAsyncAwait.cs | 72 +- .../CSharp/SyntaxFormatter.cs | 152 +-- .../MemberSymbolDefinitionComparer.cs | 60 +- .../Comparers/SymbolDefinitionComparer.cs | 90 +- src/Workspaces.Core/ConsoleUtility.cs | 260 ++--- src/Workspaces.Core/DiagnosticFormatter.cs | 134 +-- src/Workspaces.Core/Extensions/Extensions.cs | 166 ++-- .../IgnoredNameSymbolFilterRule.cs | 10 +- .../FindSymbols/SymbolFilterOptions.cs | 32 +- src/Workspaces.Core/Rename/SymbolProvider.cs | 42 +- .../Rename/SymbolRenameState.cs | 64 +- 334 files changed, 16688 insertions(+), 16631 deletions(-) diff --git a/.editorconfig b/.editorconfig index ac4d9df62d..f9ecc06957 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,12 +3,63 @@ # top-most EditorConfig file root = true +[*] +indent_style = space + # Code files [*.{cs,csx}] - -indent_style = space indent_size = 4 +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/csharp-formatting-options + +# New-line options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#new-line-options +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#indentation-options +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents_when_block = false + +# Spacing options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#spacing-options +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_after_comma = true +csharp_space_before_comma = false +csharp_space_after_dot = false +csharp_space_before_dot = false +csharp_space_after_semicolon_in_for_statement = true +csharp_space_before_semicolon_in_for_statement = false +csharp_space_around_declaration_statements = false +csharp_space_before_open_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_square_brackets = false + +# Wrap options +# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#wrap-options +csharp_preserve_single_line_statements = false +csharp_preserve_single_line_blocks = true + dotnet_sort_system_directives_first = true csharp_style_namespace_declarations = file_scoped:suggestion diff --git a/.gitignore b/.gitignore index 3a2238d6bf..aa3419f5f5 100644 --- a/.gitignore +++ b/.gitignore @@ -242,4 +242,6 @@ ModelManifest.xml .paket/paket.exe # FAKE - F# Make -.fake/ \ No newline at end of file +.fake/ + +.DS_Store \ No newline at end of file diff --git a/ChangeLog.md b/ChangeLog.md index bcf23fb26d..ddd32a8843 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix analyzer [RCS1213](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1213) ([PR](https://github.com/dotnet/roslynator/pull/1586)) +### Changed + +- Update whitespace formatting rules ([PR](https://github.com/dotnet/roslynator/pull/1576)) + ## [4.12.9] - 2024-10-25 ### Fixed diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddExceptionToDocumentationCommentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddExceptionToDocumentationCommentCodeFixProvider.cs index 4a43197e3e..8b7c0204f8 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddExceptionToDocumentationCommentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AddExceptionToDocumentationCommentCodeFixProvider.cs @@ -34,33 +34,33 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AddExceptionToDocumentationComment: + { + switch (node.Kind()) { - switch (node.Kind()) + case SyntaxKind.ThrowStatement: { - case SyntaxKind.ThrowStatement: - { - CodeAction codeAction = CodeAction.Create( - "Add exception to documentation comment", - ct => AddExceptionElementToDocumentationCommentRefactoring.RefactorAsync(context.Document, (ThrowStatementSyntax)node, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Add exception to documentation comment", + ct => AddExceptionElementToDocumentationCommentRefactoring.RefactorAsync(context.Document, (ThrowStatementSyntax)node, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case SyntaxKind.ThrowExpression: - { - CodeAction codeAction = CodeAction.Create( - "Add exception to documentation comment", - ct => AddExceptionElementToDocumentationCommentRefactoring.RefactorAsync(context.Document, (ThrowExpressionSyntax)node, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; } + case SyntaxKind.ThrowExpression: + { + CodeAction codeAction = CodeAction.Create( + "Add exception to documentation comment", + ct => AddExceptionElementToDocumentationCommentRefactoring.RefactorAsync(context.Document, (ThrowExpressionSyntax)node, ct), + GetEquivalenceKey(diagnostic)); - break; + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } + + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AssignmentExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AssignmentExpressionCodeFixProvider.cs index 6d50fd5faf..f94a3611c0 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AssignmentExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AssignmentExpressionCodeFixProvider.cs @@ -46,33 +46,33 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UseUnaryOperatorInsteadOfAssignment: - { - string operatorText = UseUnaryOperatorInsteadOfAssignmentAnalyzer.GetOperatorText(assignment); + { + string operatorText = UseUnaryOperatorInsteadOfAssignmentAnalyzer.GetOperatorText(assignment); - CodeAction codeAction = CodeAction.Create( - $"Use {operatorText} operator", - ct => UseUnaryOperatorInsteadOfAssignmentAsync(document, assignment, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Use {operatorText} operator", + ct => UseUnaryOperatorInsteadOfAssignmentAsync(document, assignment, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantDelegateCreation: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant delegate creation", - ct => - { - return RemoveRedundantDelegateCreationRefactoring.RefactorAsync( - document, - (ObjectCreationExpressionSyntax)assignment.Right, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant delegate creation", + ct => + { + return RemoveRedundantDelegateCreationRefactoring.RefactorAsync( + document, + (ObjectCreationExpressionSyntax)assignment.Right, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } @@ -116,32 +116,32 @@ List GetTrailingTrivia() { case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: - { - trivia.AddRange(assignment.OperatorToken.GetAllTrivia()); + { + trivia.AddRange(assignment.OperatorToken.GetAllTrivia()); - if (right?.IsMissing == false) - trivia.AddRange(right.GetLeadingAndTrailingTrivia()); + if (right?.IsMissing == false) + trivia.AddRange(right.GetLeadingAndTrailingTrivia()); - return trivia; - } + return trivia; + } } switch (right?.Kind()) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: - { - trivia.AddRange(assignment.OperatorToken.GetAllTrivia()); - - if (right?.IsMissing == false) - { - var binaryExpression = (BinaryExpressionSyntax)right; + { + trivia.AddRange(assignment.OperatorToken.GetAllTrivia()); - trivia.AddRange(binaryExpression.DescendantTrivia()); - } + if (right?.IsMissing == false) + { + var binaryExpression = (BinaryExpressionSyntax)right; - return trivia; + trivia.AddRange(binaryExpression.DescendantTrivia()); } + + return trivia; + } } throw new InvalidOperationException(); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidBoxingOfValueTypeCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidBoxingOfValueTypeCodeFixProvider.cs index de55625f88..cf82570bca 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidBoxingOfValueTypeCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AvoidBoxingOfValueTypeCodeFixProvider.cs @@ -36,17 +36,17 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AvoidBoxingOfValueType: - { - CodeAction codeAction = CodeAction.Create( - (expression.IsKind(SyntaxKind.CharacterLiteralExpression)) - ? "Use string literal instead of character literal" - : "Call 'ToString'", - ct => RefactorAsync(context.Document, expression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + (expression.IsKind(SyntaxKind.CharacterLiteralExpression)) + ? "Use string literal instead of character literal" + : "Call 'ToString'", + ct => RefactorAsync(context.Document, expression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AwaitExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AwaitExpressionCodeFixProvider.cs index 027c6e7395..6fc56ce528 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/AwaitExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/AwaitExpressionCodeFixProvider.cs @@ -69,21 +69,21 @@ private static Task AddCallToConfigureAwaitRefactorAsync( switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - leading = memberAccess.OperatorToken.LeadingTrivia; - break; - } + leading = memberAccess.OperatorToken.LeadingTrivia; + break; + } case SyntaxKind.InvocationExpression: - { - var invocation = (InvocationExpressionSyntax)expression; + { + var invocation = (InvocationExpressionSyntax)expression; - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocation); + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocation); - leading = invocationInfo.OperatorToken.LeadingTrivia; - break; - } + leading = invocationInfo.OperatorToken.LeadingTrivia; + break; + } } SyntaxTrivia last = leading.LastOrDefault(); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BaseArgumentListCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BaseArgumentListCodeFixProvider.cs index 277e13265e..7964b57b76 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BaseArgumentListCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BaseArgumentListCodeFixProvider.cs @@ -40,15 +40,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.OrderNamedArguments: - { - CodeAction codeAction = CodeAction.Create( - "Order arguments", - ct => OrderNamedArgumentsAsync(document, baseArgumentList, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Order arguments", + ct => OrderNamedArgumentsAsync(document, baseArgumentList, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs index 8f9946e7e3..04d7223fc1 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BinaryExpressionCodeFixProvider.cs @@ -56,204 +56,204 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.ConstantValuesShouldBePlacedOnRightSideOfComparisons: - { - CodeAction codeAction = CodeAction.Create( - "Swap operands", - ct => document.ReplaceNodeAsync(binaryExpression, SyntaxRefactorings.SwapBinaryOperands(binaryExpression), ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Swap operands", + ct => document.ReplaceNodeAsync(binaryExpression, SyntaxRefactorings.SwapBinaryOperands(binaryExpression), ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseStringIsNullOrEmptyMethod: - { - CodeAction codeAction = CodeAction.Create( - "Use 'string.IsNullOrEmpty' method", - ct => UseStringIsNullOrEmptyMethodAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use 'string.IsNullOrEmpty' method", + ct => UseStringIsNullOrEmptyMethodAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.SimplifyCoalesceExpression: - { - ExpressionSyntax expression = binaryExpression.Left; + { + ExpressionSyntax expression = binaryExpression.Left; - if (expression is null - || !context.Span.Contains(expression.Span)) - { - expression = binaryExpression.Right; - } + if (expression is null + || !context.Span.Contains(expression.Span)) + { + expression = binaryExpression.Right; + } - CodeAction codeAction = CodeAction.Create( - "Simplify coalesce expression", - ct => SimplifyCoalesceExpressionRefactoring.RefactorAsync(document, binaryExpression, expression, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Simplify coalesce expression", + ct => SimplifyCoalesceExpressionRefactoring.RefactorAsync(document, binaryExpression, expression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantAsOperator: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant 'as' operator", - ct => RemoveRedundantAsOperatorRefactoring.RefactorAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant 'as' operator", + ct => RemoveRedundantAsOperatorRefactoring.RefactorAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseStringLengthInsteadOfComparisonWithEmptyString: - { - CodeAction codeAction = CodeAction.Create( - "Use string.Length", - ct => UseStringLengthInsteadOfComparisonWithEmptyStringAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use string.Length", + ct => UseStringLengthInsteadOfComparisonWithEmptyStringAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UnconstrainedTypeParameterCheckedForNull: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(binaryExpression.Left, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(binaryExpression.Left, context.CancellationToken); - CodeAction codeAction = CodeAction.Create( - $"Use EqualityComparer<{typeSymbol.Name}>.Default", - ct => UnconstrainedTypeParameterCheckedForNullRefactoring.RefactorAsync(document, binaryExpression, typeSymbol, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Use EqualityComparer<{typeSymbol.Name}>.Default", + ct => UnconstrainedTypeParameterCheckedForNullRefactoring.RefactorAsync(document, binaryExpression, typeSymbol, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.ValueTypeObjectIsNeverEqualToNull: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(binaryExpression.Left, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(binaryExpression.Left, context.CancellationToken); - string title; + string title; - if (CSharpFacts.IsSimpleType(typeSymbol.SpecialType) - || typeSymbol.ContainsMember(WellKnownMemberNames.EqualityOperatorName)) - { - ExpressionSyntax expression = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); + if (CSharpFacts.IsSimpleType(typeSymbol.SpecialType) + || typeSymbol.ContainsMember(WellKnownMemberNames.EqualityOperatorName)) + { + ExpressionSyntax expression = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); - title = $"Replace 'null' with '{expression}'"; - } - else - { - title = $"Use EqualityComparer<{SymbolDisplay.ToMinimalDisplayString(typeSymbol, semanticModel, binaryExpression.Right.SpanStart, SymbolDisplayFormats.DisplayName)}>.Default"; - } + title = $"Replace 'null' with '{expression}'"; + } + else + { + title = $"Use EqualityComparer<{SymbolDisplay.ToMinimalDisplayString(typeSymbol, semanticModel, binaryExpression.Right.SpanStart, SymbolDisplayFormats.DisplayName)}>.Default"; + } - CodeAction codeAction = CodeAction.Create( - title, - ct => ValueTypeObjectIsNeverEqualToNullRefactoring.RefactorAsync(document, binaryExpression, typeSymbol, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + title, + ct => ValueTypeObjectIsNeverEqualToNullRefactoring.RefactorAsync(document, binaryExpression, typeSymbol, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.JoinStringExpressions: - { - CodeAction codeAction = CodeAction.Create( - "Join string expressions", - ct => JoinStringExpressionsRefactoring.RefactorAsync(document, binaryExpression, context.Span, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Join string expressions", + ct => JoinStringExpressionsRefactoring.RefactorAsync(document, binaryExpression, context.Span, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseExclusiveOrOperator: - { - CodeAction codeAction = CodeAction.Create( - "Use ^ operator", - ct => UseExclusiveOrOperatorRefactoring.RefactorAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use ^ operator", + ct => UseExclusiveOrOperatorRefactoring.RefactorAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UnnecessaryNullCheck: - { - CodeAction codeAction = CodeAction.Create( - "Remove unnecessary null check", - ct => RemoveUnnecessaryNullCheckAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove unnecessary null check", + ct => RemoveUnnecessaryNullCheckAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseShortCircuitingOperator: - { - SyntaxToken operatorToken = binaryExpression.OperatorToken; + { + SyntaxToken operatorToken = binaryExpression.OperatorToken; - SyntaxKind kind = binaryExpression.Kind(); + SyntaxKind kind = binaryExpression.Kind(); - SyntaxToken newToken = default; + SyntaxToken newToken = default; - if (kind == SyntaxKind.BitwiseAndExpression) - { - newToken = Token(operatorToken.LeadingTrivia, SyntaxKind.AmpersandAmpersandToken, operatorToken.TrailingTrivia); - } - else if (kind == SyntaxKind.BitwiseOrExpression) + if (kind == SyntaxKind.BitwiseAndExpression) + { + newToken = Token(operatorToken.LeadingTrivia, SyntaxKind.AmpersandAmpersandToken, operatorToken.TrailingTrivia); + } + else if (kind == SyntaxKind.BitwiseOrExpression) + { + newToken = Token(operatorToken.LeadingTrivia, SyntaxKind.BarBarToken, operatorToken.TrailingTrivia); + } + + CodeAction codeAction = CodeAction.Create( + $"Use '{newToken.ToString()}' operator", + ct => { - newToken = Token(operatorToken.LeadingTrivia, SyntaxKind.BarBarToken, operatorToken.TrailingTrivia); - } + BinaryExpressionSyntax newBinaryExpression = null; - CodeAction codeAction = CodeAction.Create( - $"Use '{newToken.ToString()}' operator", - ct => + if (kind == SyntaxKind.BitwiseAndExpression) { - BinaryExpressionSyntax newBinaryExpression = null; - - if (kind == SyntaxKind.BitwiseAndExpression) - { - newBinaryExpression = LogicalAndExpression(binaryExpression.Left, newToken, binaryExpression.Right); - } - else if (kind == SyntaxKind.BitwiseOrExpression) - { - newBinaryExpression = LogicalOrExpression(binaryExpression.Left, newToken, binaryExpression.Right); - } - - return document.ReplaceNodeAsync(binaryExpression, newBinaryExpression, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case DiagnosticIdentifiers.UnnecessaryOperator: - { - CodeAction codeAction = CodeAction.Create( - "Use '==' operator", - ct => + newBinaryExpression = LogicalAndExpression(binaryExpression.Left, newToken, binaryExpression.Right); + } + else if (kind == SyntaxKind.BitwiseOrExpression) { - SyntaxToken operatorToken = binaryExpression.OperatorToken; + newBinaryExpression = LogicalOrExpression(binaryExpression.Left, newToken, binaryExpression.Right); + } + + return document.ReplaceNodeAsync(binaryExpression, newBinaryExpression, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.UnnecessaryOperator: + { + CodeAction codeAction = CodeAction.Create( + "Use '==' operator", + ct => + { + SyntaxToken operatorToken = binaryExpression.OperatorToken; - BinaryExpressionSyntax newBinaryExpression = EqualsExpression( - binaryExpression.Left, - Token(operatorToken.LeadingTrivia, SyntaxKind.EqualsEqualsToken, operatorToken.TrailingTrivia), - binaryExpression.Right); + BinaryExpressionSyntax newBinaryExpression = EqualsExpression( + binaryExpression.Left, + Token(operatorToken.LeadingTrivia, SyntaxKind.EqualsEqualsToken, operatorToken.TrailingTrivia), + binaryExpression.Right); - return document.ReplaceNodeAsync(binaryExpression, newBinaryExpression, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(binaryExpression, newBinaryExpression, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.SimplifyNumericComparison: - { - CodeAction codeAction = CodeAction.Create( - "Simplify numeric comparison", - ct => SimplifyNumericComparisonAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Simplify numeric comparison", + ct => SimplifyNumericComparisonAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } @@ -342,20 +342,20 @@ private static async Task RemoveUnnecessaryNullCheckAsync( switch (right.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - newRight = TrueLiteralExpression().WithTriviaFrom(right); - break; - } + { + newRight = TrueLiteralExpression().WithTriviaFrom(right); + break; + } case SyntaxKind.LogicalNotExpression: - { - newRight = FalseLiteralExpression().WithTriviaFrom(right); - break; - } + { + newRight = FalseLiteralExpression().WithTriviaFrom(right); + break; + } default: - { - newRight = binaryExpression.Right; - break; - } + { + newRight = binaryExpression.Right; + break; + } } BinaryExpressionSyntax newBinaryExpression = BinaryExpression( diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs index e87ab3345c..28317bcedb 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/BlockCodeFixProvider.cs @@ -43,25 +43,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.SimplifyLazyInitialization: - { - CodeAction codeAction = CodeAction.Create( - "Simplify lazy initialization", - ct => SimplifyLazyInitializationAsync(document, block, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Simplify lazy initialization", + ct => SimplifyLazyInitializationAsync(document, block, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveUnnecessaryBracesInSwitchSection: - { - CodeAction codeAction = CodeAction.Create( - "Remove braces", - ct => RemoveBracesAsync(document, block, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove braces", + ct => RemoveBracesAsync(document, block, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ClassDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ClassDeclarationCodeFixProvider.cs index a0bec336f2..472a59c80b 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ClassDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ClassDeclarationCodeFixProvider.cs @@ -48,66 +48,66 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.MakeClassStatic: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ISymbol symbol = semanticModel.GetDeclaredSymbol(classDeclaration, context.CancellationToken); + ISymbol symbol = semanticModel.GetDeclaredSymbol(classDeclaration, context.CancellationToken); - ImmutableArray syntaxReferences = symbol.DeclaringSyntaxReferences; + ImmutableArray syntaxReferences = symbol.DeclaringSyntaxReferences; - if (!syntaxReferences.Any()) - break; + if (!syntaxReferences.Any()) + break; - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - ImmutableArray.CreateRange(syntaxReferences, f => f.GetSyntax()), - SyntaxKind.StaticKeyword, - title: "Make class static"); + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + ImmutableArray.CreateRange(syntaxReferences, f => f.GetSyntax()), + SyntaxKind.StaticKeyword, + title: "Make class static"); - break; - } + break; + } case DiagnosticIdentifiers.AddStaticModifierToAllPartialClassDeclarations: - { - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, classDeclaration, SyntaxKind.StaticKeyword); - break; - } + { + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, classDeclaration, SyntaxKind.StaticKeyword); + break; + } case DiagnosticIdentifiers.ImplementExceptionConstructors: - { - CodeAction codeAction = CodeAction.Create( - "Generate exception constructors", - ct => - { - return ImplementExceptionConstructorsAsync( - context.Document, - classDeclaration, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Generate exception constructors", + ct => + { + return ImplementExceptionConstructorsAsync( + context.Document, + classDeclaration, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseAttributeUsageAttribute: - { - CodeAction codeAction = CodeAction.Create( - "Use AttributeUsageAttribute", - ct => UseAttributeUsageAttributeAsync(context.Document, classDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use AttributeUsageAttribute", + ct => UseAttributeUsageAttributeAsync(context.Document, classDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.MakeClassSealed: - { - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - classDeclaration, - SyntaxKind.SealedKeyword); - - break; - } + { + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + classDeclaration, + SyntaxKind.SealedKeyword); + + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs index b529a189fe..5cdc6122b6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConditionalExpressionCodeFixProvider.cs @@ -49,64 +49,64 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UseCoalesceExpressionInsteadOfConditionalExpression: - { - CodeAction codeAction = CodeAction.Create( - "Use coalesce expression", - ct => - { - return SimplifyNullCheckRefactoring.RefactorAsync( - document, - conditionalExpression, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use coalesce expression", + ct => + { + return SimplifyNullCheckRefactoring.RefactorAsync( + document, + conditionalExpression, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.SimplifyConditionalExpression: - { - CodeAction codeAction = CodeAction.Create( - "Simplify conditional expression", - ct => SimplifyConditionalExpressionAsync(document, conditionalExpression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Simplify conditional expression", + ct => SimplifyConditionalExpressionAsync(document, conditionalExpression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseConditionalAccessInsteadOfConditionalExpression: - { - CodeAction codeAction = CodeAction.Create( - "Use conditional access", - ct => - { - return SimplifyNullCheckRefactoring.RefactorAsync( - document, - conditionalExpression, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use conditional access", + ct => + { + return SimplifyNullCheckRefactoring.RefactorAsync( + document, + conditionalExpression, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.AvoidNestedConditionalOperators: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - (CodeAction codeAction, CodeAction recursiveCodeAction) = ConvertConditionalExpressionToIfElseRefactoring.ComputeRefactoring( - document, - conditionalExpression, - data: default, - recursiveData: new CodeActionData(ConvertConditionalExpressionToIfElseRefactoring.Title, GetEquivalenceKey(diagnostic)), - semanticModel, - context.CancellationToken); - - if (recursiveCodeAction is not null) - context.RegisterCodeFix(recursiveCodeAction, diagnostic); - - break; - } + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + + (CodeAction codeAction, CodeAction recursiveCodeAction) = ConvertConditionalExpressionToIfElseRefactoring.ComputeRefactoring( + document, + conditionalExpression, + data: default, + recursiveData: new CodeActionData(ConvertConditionalExpressionToIfElseRefactoring.Title, GetEquivalenceKey(diagnostic)), + semanticModel, + context.CancellationToken); + + if (recursiveCodeAction is not null) + context.RegisterCodeFix(recursiveCodeAction, diagnostic); + + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConstructorDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConstructorDeclarationCodeFixProvider.cs index daa3e723c1..ae95e8e1d3 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConstructorDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ConstructorDeclarationCodeFixProvider.cs @@ -39,36 +39,36 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantBaseConstructorCall: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant base constructor call", - ct => RemoveRedundantBaseConstructorCallRefactoring.RefactorAsync(context.Document, constructor, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant base constructor call", + ct => RemoveRedundantBaseConstructorCallRefactoring.RefactorAsync(context.Document, constructor, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantConstructor: - { - CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( - context.Document, - constructor, - title: "Remove redundant constructor", - equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( + context.Document, + constructor, + title: "Remove redundant constructor", + equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.AbstractTypeShouldNotHavePublicConstructors: - { - CodeAction codeAction = CodeAction.Create( - "Change accessibility to 'protected'", - ct => AbstractTypeShouldNotHavePublicConstructorsRefactoring.RefactorAsync(context.Document, constructor, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Change accessibility to 'protected'", + ct => AbstractTypeShouldNotHavePublicConstructorsRefactoring.RefactorAsync(context.Document, constructor, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DefaultExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DefaultExpressionCodeFixProvider.cs index d0a60de8bf..2fe7a4c387 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DefaultExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DefaultExpressionCodeFixProvider.cs @@ -35,15 +35,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.SimplifyDefaultExpression: - { - CodeAction codeAction = CodeAction.Create( - "Simplify 'default' expression", - ct => SimplifyDefaultExpressionAsync(document, defaultExpression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Simplify 'default' expression", + ct => SimplifyDefaultExpressionAsync(document, defaultExpression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DestructorDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DestructorDeclarationCodeFixProvider.cs index 2d03642e56..8403c2d96f 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DestructorDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DestructorDeclarationCodeFixProvider.cs @@ -32,16 +32,16 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveEmptyDestructor: - { - CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( - context.Document, - destructor, - title: "Remove empty destructor", - equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( + context.Document, + destructor, + title: "Remove empty destructor", + equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DisposeResourceAsynchronouslyCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DisposeResourceAsynchronouslyCodeFixProvider.cs index 0d92721a74..8b55dd5c87 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DisposeResourceAsynchronouslyCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DisposeResourceAsynchronouslyCodeFixProvider.cs @@ -45,32 +45,32 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.DisposeResourceAsynchronously: + { + if (node is LocalDeclarationStatementSyntax localDeclaration) { - if (node is LocalDeclarationStatementSyntax localDeclaration) - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => RefactorAsync(document, localDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else if (node is UsingStatementSyntax usingStatement) - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => RefactorAsync(document, usingStatement, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - throw new InvalidOperationException(); - } - - break; + CodeAction codeAction = CodeAction.Create( + Title, + ct => RefactorAsync(document, localDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } + else if (node is UsingStatementSyntax usingStatement) + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => RefactorAsync(document, usingStatement, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } + else + { + throw new InvalidOperationException(); + } + + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentCodeFixProvider.cs index 86cc672162..ef75b0c39a 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentCodeFixProvider.cs @@ -31,19 +31,19 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.FileContainsNoCode: - { - CodeAction codeAction = CodeAction.Create( - "Remove file with no code", - ct => - { - ct.ThrowIfCancellationRequested(); - return RemoveFromSolutionAsync(context.Document); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove file with no code", + ct => + { + ct.ThrowIfCancellationRequested(); + return RemoveFromSolutionAsync(context.Document); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentationCommentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentationCommentCodeFixProvider.cs index 2baf4d5a51..7a4b1dd7f6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentationCommentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentationCommentCodeFixProvider.cs @@ -33,15 +33,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AddSummaryElementToDocumentationComment: - { - CodeAction codeAction = CodeAction.Create( - "Add summary element", - ct => AddSummaryToDocumentationCommentRefactoring.RefactorAsync(context.Document, documentationComment, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Add summary element", + ct => AddSummaryToDocumentationCommentRefactoring.RefactorAsync(context.Document, documentationComment, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ElseClauseCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ElseClauseCodeFixProvider.cs index d97ceff923..0b981b3149 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ElseClauseCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ElseClauseCodeFixProvider.cs @@ -39,25 +39,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveEmptyElseClause: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty 'else' clause", - ct => RemoveEmptyElseClauseAsync(context.Document, elseClause, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove empty 'else' clause", + ct => RemoveEmptyElseClauseAsync(context.Document, elseClause, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.MergeElseWithNestedIf: - { - CodeAction codeAction = CodeAction.Create( - "Remove braces", - ct => MergeElseWithNestedIfAsync(context.Document, elseClause, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove braces", + ct => MergeElseWithNestedIfAsync(context.Document, elseClause, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs index 178d692b11..212d524b72 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumDeclarationCodeFixProvider.cs @@ -47,68 +47,68 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.SortEnumMembers: - { - CodeAction codeAction = CodeAction.Create( - $"Sort '{enumDeclaration.Identifier}' members", - ct => SortEnumMembersAsync(document, enumDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + $"Sort '{enumDeclaration.Identifier}' members", + ct => SortEnumMembersAsync(document, enumDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.EnumShouldDeclareExplicitValues: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - INamedTypeSymbol enumSymbol = semanticModel.GetDeclaredSymbol(enumDeclaration, context.CancellationToken); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - EnumSymbolInfo enumInfo = EnumSymbolInfo.Create(enumSymbol); + INamedTypeSymbol enumSymbol = semanticModel.GetDeclaredSymbol(enumDeclaration, context.CancellationToken); - ImmutableArray values = enumInfo - .Fields - .Where(f => f.HasValue && ((EnumMemberDeclarationSyntax)f.Symbol.GetSyntax(context.CancellationToken)).EqualsValue is not null) - .Select(f => f.Value) - .ToImmutableArray(); + EnumSymbolInfo enumInfo = EnumSymbolInfo.Create(enumSymbol); - Optional optional = FlagsUtility.Instance.GetUniquePowerOfTwo(values); + ImmutableArray values = enumInfo + .Fields + .Where(f => f.HasValue && ((EnumMemberDeclarationSyntax)f.Symbol.GetSyntax(context.CancellationToken)).EqualsValue is not null) + .Select(f => f.Value) + .ToImmutableArray(); - if (!optional.HasValue - || !ConvertHelpers.CanConvertFromUInt64(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) - { - return; - } + Optional optional = FlagsUtility.Instance.GetUniquePowerOfTwo(values); - bool isFlags = enumSymbol.HasAttribute(MetadataNames.System_FlagsAttribute); + if (!optional.HasValue + || !ConvertHelpers.CanConvertFromUInt64(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) + { + return; + } - CodeAction codeAction = CodeAction.Create( - "Declare explicit values", - ct => DeclareExplicitValueAsync(document, enumDeclaration, enumSymbol, isFlags, useBitShift: false, values, semanticModel, ct), - GetEquivalenceKey(diagnostic)); + bool isFlags = enumSymbol.HasAttribute(MetadataNames.System_FlagsAttribute); - context.RegisterCodeFix(codeAction, diagnostic); + CodeAction codeAction = CodeAction.Create( + "Declare explicit values", + ct => DeclareExplicitValueAsync(document, enumDeclaration, enumSymbol, isFlags, useBitShift: false, values, semanticModel, ct), + GetEquivalenceKey(diagnostic)); - if (isFlags) - { - CodeAction codeAction2 = CodeAction.Create( - "Declare explicit values (and use '<<' operator)", - ct => DeclareExplicitValueAsync(document, enumDeclaration, enumSymbol, isFlags, useBitShift: true, values, semanticModel, ct), - GetEquivalenceKey(diagnostic, "BitShift")); + context.RegisterCodeFix(codeAction, diagnostic); - context.RegisterCodeFix(codeAction2, diagnostic); - } + if (isFlags) + { + CodeAction codeAction2 = CodeAction.Create( + "Declare explicit values (and use '<<' operator)", + ct => DeclareExplicitValueAsync(document, enumDeclaration, enumSymbol, isFlags, useBitShift: true, values, semanticModel, ct), + GetEquivalenceKey(diagnostic, "BitShift")); - break; + context.RegisterCodeFix(codeAction2, diagnostic); } + + break; + } case DiagnosticIdentifiers.UseBitShiftOperator: - { - CodeAction codeAction = CodeAction.Create( - "Use '<<' operator", - ct => UseBitShiftOperatorAsync(document, enumDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use '<<' operator", + ct => UseBitShiftOperatorAsync(document, enumDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs index c6795c2f89..277d07e8cb 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/EnumMemberDeclarationCodeFixProvider.cs @@ -46,64 +46,64 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.DeclareEnumValueAsCombinationOfNames: - { - CodeAction codeAction = CodeAction.Create( - "Declare value as combination of names", - ct => DeclareEnumValueAsCombinationOfNamesAsync(document, enumMemberDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Declare value as combination of names", + ct => DeclareEnumValueAsCombinationOfNamesAsync(document, enumMemberDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.DuplicateEnumValue: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + + var enumDeclaration = (EnumDeclarationSyntax)enumMemberDeclaration.Parent; - var enumDeclaration = (EnumDeclarationSyntax)enumMemberDeclaration.Parent; + IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(enumMemberDeclaration, context.CancellationToken); - IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(enumMemberDeclaration, context.CancellationToken); + EnumFieldSymbolInfo enumFieldSymbolInfo = EnumFieldSymbolInfo.Create(fieldSymbol); - EnumFieldSymbolInfo enumFieldSymbolInfo = EnumFieldSymbolInfo.Create(fieldSymbol); + string valueText = FindMemberByValue(enumDeclaration, enumFieldSymbolInfo, semanticModel, context.CancellationToken).Identifier.ValueText; - string valueText = FindMemberByValue(enumDeclaration, enumFieldSymbolInfo, semanticModel, context.CancellationToken).Identifier.ValueText; + CodeAction codeAction = CodeAction.Create( + $"Change enum value to '{valueText}'", + ct => ChangeEnumValueAsync(document, enumMemberDeclaration, valueText, ct), + GetEquivalenceKey(diagnostic)); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.NormalizeFormatOfEnumFlagValue: + { + EnumFlagValueStyle style = document.GetConfigOptions(enumMemberDeclaration.SyntaxTree).GetEnumFlagValueStyle(); + + if (style == EnumFlagValueStyle.ShiftOperator) + { CodeAction codeAction = CodeAction.Create( - $"Change enum value to '{valueText}'", - ct => ChangeEnumValueAsync(document, enumMemberDeclaration, valueText, ct), + "Use '<<' operator", + ct => UseBitShiftOperatorAsync(document, enumMemberDeclaration, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case DiagnosticIdentifiers.NormalizeFormatOfEnumFlagValue: + else if (style == EnumFlagValueStyle.DecimalNumber) + { + CodeAction codeAction = CodeAction.Create( + "Convert to decimal", + ct => ConvertToDecimalNumberAsync(document, enumMemberDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } + else { - EnumFlagValueStyle style = document.GetConfigOptions(enumMemberDeclaration.SyntaxTree).GetEnumFlagValueStyle(); - - if (style == EnumFlagValueStyle.ShiftOperator) - { - CodeAction codeAction = CodeAction.Create( - "Use '<<' operator", - ct => UseBitShiftOperatorAsync(document, enumMemberDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else if (style == EnumFlagValueStyle.DecimalNumber) - { - CodeAction codeAction = CodeAction.Create( - "Convert to decimal", - ct => ConvertToDecimalNumberAsync(document, enumMemberDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - throw new InvalidOperationException(); - } - - break; + throw new InvalidOperationException(); } + + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs index f0eecabcc4..3a39737672 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs @@ -43,80 +43,80 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AddOrRemoveParenthesesFromConditionInConditionalOperator: + { + if (expression is ParenthesizedExpressionSyntax parenthesizedExpression) { - if (expression is ParenthesizedExpressionSyntax parenthesizedExpression) - { - CodeAction codeAction = CodeActionFactory.RemoveParentheses(document, parenthesizedExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Parenthesize condition", - ct => ParenthesizeConditionOfConditionalExpressionAsync(document, expression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - - break; + CodeAction codeAction = CodeActionFactory.RemoveParentheses(document, parenthesizedExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } + else + { + CodeAction codeAction = CodeAction.Create( + "Parenthesize condition", + ct => ParenthesizeConditionOfConditionalExpressionAsync(document, expression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } + + break; + } case DiagnosticIdentifiers.ExpressionIsAlwaysEqualToTrueOrFalse: + { + if (expression.IsKind( + SyntaxKind.LessThanExpression, + SyntaxKind.LessThanOrEqualExpression, + SyntaxKind.GreaterThanExpression, + SyntaxKind.GreaterThanOrEqualExpression)) { - if (expression.IsKind( - SyntaxKind.LessThanExpression, - SyntaxKind.LessThanOrEqualExpression, - SyntaxKind.GreaterThanExpression, - SyntaxKind.GreaterThanOrEqualExpression)) - { - var binaryExpression = (BinaryExpressionSyntax)expression; - - LiteralExpressionSyntax newNode = BooleanLiteralExpression(binaryExpression.IsKind(SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanOrEqualExpression)); - - CodeAction codeAction = CodeAction.Create( - $"Replace expression with '{newNode}'", - ct => document.ReplaceNodeAsync(binaryExpression, newNode.WithTriviaFrom(binaryExpression), ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else if (diagnostic.Properties.TryGetValue("DoubleNaN", out string leftOrRight)) - { - var binaryExpression = (BinaryExpressionSyntax)expression; - - CodeAction codeAction = CodeAction.Create( - "Call 'IsNaN'", - ct => - { - ExpressionSyntax newExpression = SimpleMemberInvocationExpression( - CSharpTypeFactory.DoubleType(), - IdentifierName("IsNaN"), - Argument((leftOrRight == "Left") ? binaryExpression.Left.WithoutLeadingTrivia() : binaryExpression.Right.WithoutTrailingTrivia())); - - if (binaryExpression.IsKind(SyntaxKind.NotEqualsExpression)) - newExpression = LogicalNotExpression(newExpression); - - newExpression = newExpression.Parenthesize().WithTriviaFrom(binaryExpression); - - return document.ReplaceNodeAsync(binaryExpression, newExpression, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Remove null check", - ct => RemoveUnnecessaryNullCheckAsync(document, expression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - - break; + var binaryExpression = (BinaryExpressionSyntax)expression; + + LiteralExpressionSyntax newNode = BooleanLiteralExpression(binaryExpression.IsKind(SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanOrEqualExpression)); + + CodeAction codeAction = CodeAction.Create( + $"Replace expression with '{newNode}'", + ct => document.ReplaceNodeAsync(binaryExpression, newNode.WithTriviaFrom(binaryExpression), ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } + else if (diagnostic.Properties.TryGetValue("DoubleNaN", out string leftOrRight)) + { + var binaryExpression = (BinaryExpressionSyntax)expression; + + CodeAction codeAction = CodeAction.Create( + "Call 'IsNaN'", + ct => + { + ExpressionSyntax newExpression = SimpleMemberInvocationExpression( + CSharpTypeFactory.DoubleType(), + IdentifierName("IsNaN"), + Argument((leftOrRight == "Left") ? binaryExpression.Left.WithoutLeadingTrivia() : binaryExpression.Right.WithoutTrailingTrivia())); + + if (binaryExpression.IsKind(SyntaxKind.NotEqualsExpression)) + newExpression = LogicalNotExpression(newExpression); + + newExpression = newExpression.Parenthesize().WithTriviaFrom(binaryExpression); + + return document.ReplaceNodeAsync(binaryExpression, newExpression, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } + else + { + CodeAction codeAction = CodeAction.Create( + "Remove null check", + ct => RemoveUnnecessaryNullCheckAsync(document, expression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } + + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ForStatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ForStatementCodeFixProvider.cs index 10557bd452..702f05b0fc 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ForStatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ForStatementCodeFixProvider.cs @@ -33,21 +33,21 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AvoidUsageOfForStatementToCreateInfiniteLoop: - { - CodeAction codeAction = CodeAction.Create( - "Use while to create an infinite loop", - ct => - { - return AvoidUsageOfForStatementToCreateInfiniteLoopRefactoring.RefactorAsync( - context.Document, - forStatement, - ct); - }, - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use while to create an infinite loop", + ct => + { + return AvoidUsageOfForStatementToCreateInfiniteLoopRefactoring.RefactorAsync( + context.Document, + forStatement, + ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs index 972fef7562..776a450e41 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/IfStatementCodeFixProvider.cs @@ -53,86 +53,86 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.MergeIfWithNestedIf: - { - CodeAction codeAction = CodeAction.Create( - "Merge 'if' with nested 'if'", - ct => MergeIfWithNestedIfAsync(context.Document, ifStatement, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Merge 'if' with nested 'if'", + ct => MergeIfWithNestedIfAsync(context.Document, ifStatement, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseCoalesceExpressionInsteadOfIf: case DiagnosticIdentifiers.ConvertIfToReturnStatement: case DiagnosticIdentifiers.ConvertIfToAssignment: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - IfAnalysis analysis = IfAnalysis.Analyze( - ifStatement, - IfStatementAnalyzer.AnalysisOptions, - semanticModel, - context.CancellationToken) - .First(); - - CodeAction codeAction = CodeAction.Create( - analysis.Title, - ct => IfRefactoring.RefactorAsync(context.Document, analysis, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + + IfAnalysis analysis = IfAnalysis.Analyze( + ifStatement, + IfStatementAnalyzer.AnalysisOptions, + semanticModel, + context.CancellationToken) + .First(); + + CodeAction codeAction = CodeAction.Create( + analysis.Title, + ct => IfRefactoring.RefactorAsync(context.Document, analysis, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.ReduceIfNesting: - { - CodeAction codeAction = CodeAction.Create( - "Invert if", - ct => - { - return ReduceIfNestingRefactoring.RefactorAsync( - context.Document, - ifStatement, - (SyntaxKind)Enum.Parse(typeof(SyntaxKind), diagnostic.Properties["JumpKind"]), - recursive: false, - cancellationToken: ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Invert if", + ct => + { + return ReduceIfNestingRefactoring.RefactorAsync( + context.Document, + ifStatement, + (SyntaxKind)Enum.Parse(typeof(SyntaxKind), diagnostic.Properties["JumpKind"]), + recursive: false, + cancellationToken: ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseExceptionFilter: - { - CodeAction codeAction = CodeAction.Create( - "Use exception filter", - ct => - { - return UseExceptionFilterAsync( - context.Document, - ifStatement, - cancellationToken: ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use exception filter", + ct => + { + return UseExceptionFilterAsync( + context.Document, + ifStatement, + cancellationToken: ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.SimplifyArgumentNullCheck: - { - CodeAction codeAction = CodeAction.Create( - "Call ArgumentNullException.ThrowIfNull", - ct => - { - return CallArgumentNullExceptionThrowIfNullAsync( - context.Document, - ifStatement, - cancellationToken: ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Call ArgumentNullException.ThrowIfNull", + ct => + { + return CallArgumentNullExceptionThrowIfNullAsync( + context.Document, + ifStatement, + cancellationToken: ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ImplementNonGenericCounterpartCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ImplementNonGenericCounterpartCodeFixProvider.cs index 3f77553734..57310f56e9 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ImplementNonGenericCounterpartCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ImplementNonGenericCounterpartCodeFixProvider.cs @@ -203,75 +203,75 @@ private static async Task RefactorAsync( switch (interfaceName) { case "IComparable": - { - TypeSyntax type = interfaces - .First(f => f.HasMetadataName(MetadataNames.System_IComparable_T)) - .TypeArguments - .Single() - .ToTypeSyntax() - .WithSimplifierAnnotation(); + { + TypeSyntax type = interfaces + .First(f => f.HasMetadataName(MetadataNames.System_IComparable_T)) + .TypeArguments + .Single() + .ToTypeSyntax() + .WithSimplifierAnnotation(); - var rewriter = new AddTypeNameRewriter(type); + var rewriter = new AddTypeNameRewriter(type); - MethodDeclarationSyntax methodDeclaration = (explicitImplementation) ? _lazyIComparableCompareExplicit.Value : _lazyIComparableCompare.Value; + MethodDeclarationSyntax methodDeclaration = (explicitImplementation) ? _lazyIComparableCompareExplicit.Value : _lazyIComparableCompare.Value; - methodDeclaration = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); + methodDeclaration = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); - newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); + newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); - interfaceType = SyntaxFactory.ParseTypeName("global::System.IComparable").WithSimplifierAnnotation(); - break; - } + interfaceType = SyntaxFactory.ParseTypeName("global::System.IComparable").WithSimplifierAnnotation(); + break; + } case "IComparer": - { - TypeSyntax type = interfaces - .First(f => f.HasMetadataName(MetadataNames.System_Collections_Generic_IComparer_T)) - .TypeArguments - .Single() - .ToTypeSyntax() - .WithSimplifierAnnotation(); + { + TypeSyntax type = interfaces + .First(f => f.HasMetadataName(MetadataNames.System_Collections_Generic_IComparer_T)) + .TypeArguments + .Single() + .ToTypeSyntax() + .WithSimplifierAnnotation(); - var rewriter = new AddTypeNameRewriter(type); + var rewriter = new AddTypeNameRewriter(type); - MethodDeclarationSyntax methodDeclaration = (explicitImplementation) ? _lazyIComparerCompareExplicit.Value : _lazyIComparerCompare.Value; + MethodDeclarationSyntax methodDeclaration = (explicitImplementation) ? _lazyIComparerCompareExplicit.Value : _lazyIComparerCompare.Value; - methodDeclaration = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); + methodDeclaration = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); - newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); + newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); - interfaceType = SyntaxFactory.ParseTypeName("global::System.Collections.IComparer").WithSimplifierAnnotation(); - break; - } + interfaceType = SyntaxFactory.ParseTypeName("global::System.Collections.IComparer").WithSimplifierAnnotation(); + break; + } case "IEqualityComparer": - { - TypeSyntax type = interfaces - .First(f => f.HasMetadataName(MetadataNames.System_Collections_Generic_IEqualityComparer_T)) - .TypeArguments - .Single() - .ToTypeSyntax() - .WithSimplifierAnnotation(); + { + TypeSyntax type = interfaces + .First(f => f.HasMetadataName(MetadataNames.System_Collections_Generic_IEqualityComparer_T)) + .TypeArguments + .Single() + .ToTypeSyntax() + .WithSimplifierAnnotation(); - var rewriter = new AddTypeNameRewriter(type); + var rewriter = new AddTypeNameRewriter(type); - MethodDeclarationSyntax equalsMethod = (explicitImplementation) ? _lazyIEqualityComparerEqualsExplicit.Value : _lazyIEqualityComparerEquals.Value; + MethodDeclarationSyntax equalsMethod = (explicitImplementation) ? _lazyIEqualityComparerEqualsExplicit.Value : _lazyIEqualityComparerEquals.Value; - equalsMethod = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(equalsMethod); + equalsMethod = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(equalsMethod); - newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, equalsMethod); + newTypeDeclaration = MemberDeclarationInserter.Default.Insert(typeDeclaration, equalsMethod); - MethodDeclarationSyntax getHashCodeMethod = (explicitImplementation) ? _lazyIEqualityComparerGetHashCodeExplicit.Value : _lazyIEqualityComparerGetHashCode.Value; + MethodDeclarationSyntax getHashCodeMethod = (explicitImplementation) ? _lazyIEqualityComparerGetHashCodeExplicit.Value : _lazyIEqualityComparerGetHashCode.Value; - getHashCodeMethod = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(getHashCodeMethod); + getHashCodeMethod = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(getHashCodeMethod); - newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, getHashCodeMethod); + newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, getHashCodeMethod); - interfaceType = SyntaxFactory.ParseTypeName("global::System.Collections.IEqualityComparer").WithSimplifierAnnotation(); - break; - } + interfaceType = SyntaxFactory.ParseTypeName("global::System.Collections.IEqualityComparer").WithSimplifierAnnotation(); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } SimpleBaseTypeSyntax baseType = SyntaxFactory.SimpleBaseType(interfaceType); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InitializerCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InitializerCodeFixProvider.cs index 21dee779cc..c053a5e18c 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InitializerCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InitializerCodeFixProvider.cs @@ -33,22 +33,22 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantCommaInInitializer: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant comma", - ct => - { - ct.ThrowIfCancellationRequested(); - - InitializerExpressionSyntax newInitializer = RemoveTrailingComma(initializer); - - return context.Document.ReplaceNodeAsync(initializer, newInitializer, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant comma", + ct => + { + ct.ThrowIfCancellationRequested(); + + InitializerExpressionSyntax newInitializer = RemoveTrailingComma(initializer); + + return context.Document.ReplaceNodeAsync(initializer, newInitializer, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InterpolatedStringCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InterpolatedStringCodeFixProvider.cs index eaeabf700e..607cdc9095 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InterpolatedStringCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InterpolatedStringCodeFixProvider.cs @@ -41,40 +41,40 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UnnecessaryInterpolatedString: + { + if (ConvertInterpolatedStringToStringLiteralAnalysis.IsFixable(interpolatedString)) { - if (ConvertInterpolatedStringToStringLiteralAnalysis.IsFixable(interpolatedString)) - { - CodeAction codeAction = CodeAction.Create( - "Remove '$'", - ct => ConvertInterpolatedStringToStringLiteralRefactoring.RefactorAsync(document, interpolatedString, ct), - GetEquivalenceKey(diagnostic.Id)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - var interpolation = (InterpolationSyntax)interpolatedString.Contents[0]; - - CodeAction codeAction = CodeAction.Create( - $"Replace interpolated string with '{interpolation.Expression}'", - ct => UnnecessaryInterpolatedStringRefactoring.RefactorAsync(document, interpolatedString, ct), - GetEquivalenceKey(diagnostic.Id)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + CodeAction codeAction = CodeAction.Create( + "Remove '$'", + ct => ConvertInterpolatedStringToStringLiteralRefactoring.RefactorAsync(document, interpolatedString, ct), + GetEquivalenceKey(diagnostic.Id)); - break; + context.RegisterCodeFix(codeAction, diagnostic); } - case DiagnosticIdentifiers.ConvertInterpolatedStringToConcatenation: + else { + var interpolation = (InterpolationSyntax)interpolatedString.Contents[0]; + CodeAction codeAction = CodeAction.Create( - "Convert to concatenation", - ct => ConvertInterpolatedStringToConcatenationRefactoring.RefactorAsync(document, interpolatedString, ct), + $"Replace interpolated string with '{interpolation.Expression}'", + ct => UnnecessaryInterpolatedStringRefactoring.RefactorAsync(document, interpolatedString, ct), GetEquivalenceKey(diagnostic.Id)); context.RegisterCodeFix(codeAction, diagnostic); - break; } + + break; + } + case DiagnosticIdentifiers.ConvertInterpolatedStringToConcatenation: + { + CodeAction codeAction = CodeAction.Create( + "Convert to concatenation", + ct => ConvertInterpolatedStringToConcatenationRefactoring.RefactorAsync(document, interpolatedString, ct), + GetEquivalenceKey(diagnostic.Id)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InvocationExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InvocationExpressionCodeFixProvider.cs index 2c5a601e60..cfa10faa53 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/InvocationExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/InvocationExpressionCodeFixProvider.cs @@ -50,85 +50,85 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.CombineEnumerableWhereMethodChain: - { - CodeAction codeAction = CodeAction.Create( - "Combine 'Where' method chain", - ct => CombineEnumerableWhereMethodChainRefactoring.RefactorAsync(context.Document, invocation, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Combine 'Where' method chain", + ct => CombineEnumerableWhereMethodChainRefactoring.RefactorAsync(context.Document, invocation, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseCountOrLengthPropertyInsteadOfAnyMethod: - { - string propertyName = diagnostic.Properties["PropertyName"]; + { + string propertyName = diagnostic.Properties["PropertyName"]; - CodeAction codeAction = CodeAction.Create( - $"Use '{propertyName}' property instead of calling 'Any'", - ct => UseCountOrLengthPropertyInsteadOfAnyMethodRefactoring.RefactorAsync(context.Document, invocation, propertyName, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Use '{propertyName}' property instead of calling 'Any'", + ct => UseCountOrLengthPropertyInsteadOfAnyMethodRefactoring.RefactorAsync(context.Document, invocation, propertyName, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantToStringCall: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant 'ToString' call", - ct => context.Document.ReplaceNodeAsync(invocation, RemoveInvocation(invocation).WithFormatterAnnotation(), ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant 'ToString' call", + ct => context.Document.ReplaceNodeAsync(invocation, RemoveInvocation(invocation).WithFormatterAnnotation(), ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantStringToCharArrayCall: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant 'ToCharArray' call", - ct => context.Document.ReplaceNodeAsync(invocation, RemoveInvocation(invocation).WithFormatterAnnotation(), ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant 'ToCharArray' call", + ct => context.Document.ReplaceNodeAsync(invocation, RemoveInvocation(invocation).WithFormatterAnnotation(), ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.CallExtensionMethodAsInstanceMethod: - { - CodeAction codeAction = CodeAction.Create( - CallExtensionMethodAsInstanceMethodRefactoring.Title, - ct => CallExtensionMethodAsInstanceMethodRefactoring.RefactorAsync(context.Document, invocation, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + CallExtensionMethodAsInstanceMethodRefactoring.Title, + ct => CallExtensionMethodAsInstanceMethodRefactoring.RefactorAsync(context.Document, invocation, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.CallThenByInsteadOfOrderBy: - { - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocation); + { + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocation); - string oldName = invocationInfo.NameText; + string oldName = invocationInfo.NameText; - string newName = (string.Equals(oldName, "OrderBy", StringComparison.Ordinal)) - ? "ThenBy" - : "ThenByDescending"; + string newName = (string.Equals(oldName, "OrderBy", StringComparison.Ordinal)) + ? "ThenBy" + : "ThenByDescending"; - CodeAction codeAction = CodeAction.Create( - $"Call '{newName}' instead of '{oldName}'", - ct => CallThenByInsteadOfOrderByAsync(context.Document, invocation, newName, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Call '{newName}' instead of '{oldName}'", + ct => CallThenByInsteadOfOrderByAsync(context.Document, invocation, newName, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseStringInterpolationInsteadOfStringConcat: - { - CodeAction codeAction = CodeAction.Create( - "Use string interpolation", - ct => UseStringInterpolationInsteadOfStringConcatAsync(context.Document, invocation, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use string interpolation", + ct => UseStringInterpolationInsteadOfStringConcatAsync(context.Document, invocation, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/LocalDeclarationStatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/LocalDeclarationStatementCodeFixProvider.cs index ab1057011d..2c06bc1364 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/LocalDeclarationStatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/LocalDeclarationStatementCodeFixProvider.cs @@ -40,15 +40,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.InlineLocalVariable: - { - CodeAction codeAction = CodeAction.Create( - "Inline local variable", - ct => RefactorAsync(document, localDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Inline local variable", + ct => RefactorAsync(document, localDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } @@ -161,55 +161,55 @@ private static StatementSyntax GetStatementWithInlinedExpression(StatementSyntax switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: - { - var expressionStatement = (ExpressionStatementSyntax)statement; + { + var expressionStatement = (ExpressionStatementSyntax)statement; - var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; + var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; - AssignmentExpressionSyntax newAssignment = assignment.WithRight(expression.WithTriviaFrom(assignment.Right)); + AssignmentExpressionSyntax newAssignment = assignment.WithRight(expression.WithTriviaFrom(assignment.Right)); - return expressionStatement.WithExpression(newAssignment); - } + return expressionStatement.WithExpression(newAssignment); + } case SyntaxKind.LocalDeclarationStatement: - { - var localDeclaration = (LocalDeclarationStatementSyntax)statement; + { + var localDeclaration = (LocalDeclarationStatementSyntax)statement; - ExpressionSyntax value = localDeclaration - .Declaration - .Variables[0] - .Initializer - .Value; + ExpressionSyntax value = localDeclaration + .Declaration + .Variables[0] + .Initializer + .Value; - return statement.ReplaceNode(value, expression.WithTriviaFrom(value)); - } + return statement.ReplaceNode(value, expression.WithTriviaFrom(value)); + } case SyntaxKind.ReturnStatement: - { - var returnStatement = (ReturnStatementSyntax)statement; + { + var returnStatement = (ReturnStatementSyntax)statement; - return returnStatement.WithExpression(expression.WithTriviaFrom(returnStatement.Expression)); - } + return returnStatement.WithExpression(expression.WithTriviaFrom(returnStatement.Expression)); + } case SyntaxKind.YieldReturnStatement: - { - var yieldStatement = (YieldStatementSyntax)statement; + { + var yieldStatement = (YieldStatementSyntax)statement; - return yieldStatement.WithExpression(expression.WithTriviaFrom(yieldStatement.Expression)); - } + return yieldStatement.WithExpression(expression.WithTriviaFrom(yieldStatement.Expression)); + } case SyntaxKind.ForEachStatement: - { - var forEachStatement = (ForEachStatementSyntax)statement; + { + var forEachStatement = (ForEachStatementSyntax)statement; - return forEachStatement.WithExpression(expression.WithTriviaFrom(forEachStatement.Expression)); - } + return forEachStatement.WithExpression(expression.WithTriviaFrom(forEachStatement.Expression)); + } case SyntaxKind.SwitchStatement: - { - var switchStatement = (SwitchStatementSyntax)statement; + { + var switchStatement = (SwitchStatementSyntax)statement; - return switchStatement.WithExpression(expression.WithTriviaFrom(switchStatement.Expression)); - } + return switchStatement.WithExpression(expression.WithTriviaFrom(switchStatement.Expression)); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs index cca38609a9..665a1b8b13 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs @@ -51,134 +51,134 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantOverridingMember: - { - CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration(context.Document, memberDeclaration, equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration(context.Document, memberDeclaration, equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.AddOrRemoveAccessibilityModifiers: + { + if (diagnostic.Properties.TryGetValue(nameof(Accessibility), out string accessibilityText)) { - if (diagnostic.Properties.TryGetValue(nameof(Accessibility), out string accessibilityText)) - { - var accessibility = (Accessibility)Enum.Parse(typeof(Accessibility), accessibilityText); - - CodeAction codeAction = CodeAction.Create( - "Add accessibility modifiers", - ct => - { - MemberDeclarationSyntax newNode = SyntaxAccessibility.WithExplicitAccessibility(memberDeclaration, accessibility); - - return context.Document.ReplaceNodeAsync(memberDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Remove accessibility modifiers", - ct => - { - MemberDeclarationSyntax newNode = SyntaxAccessibility.WithoutExplicitAccessibility(memberDeclaration); + var accessibility = (Accessibility)Enum.Parse(typeof(Accessibility), accessibilityText); - return context.Document.ReplaceNodeAsync(memberDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - - break; - } - case DiagnosticIdentifiers.RemoveRedundantSealedModifier: - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, memberDeclaration, SyntaxKind.SealedKeyword); - break; - } - case DiagnosticIdentifiers.UnnecessarySemicolonAtEndOfDeclaration: - { CodeAction codeAction = CodeAction.Create( - "Remove unnecessary semicolon", - ct => RemoveSemicolonAtEndOfDeclarationRefactoring.RefactorAsync(context.Document, memberDeclaration, ct), + "Add accessibility modifiers", + ct => + { + MemberDeclarationSyntax newNode = SyntaxAccessibility.WithExplicitAccessibility(memberDeclaration, accessibility); + + return context.Document.ReplaceNodeAsync(memberDeclaration, newNode, ct); + }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case DiagnosticIdentifiers.OrderModifiers: + else { CodeAction codeAction = CodeAction.Create( - "Order modifiers", - ct => OrderModifiersAsync(context.Document, memberDeclaration, ct), + "Remove accessibility modifiers", + ct => + { + MemberDeclarationSyntax newNode = SyntaxAccessibility.WithoutExplicitAccessibility(memberDeclaration); + + return context.Document.ReplaceNodeAsync(memberDeclaration, newNode, ct); + }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } + + break; + } + case DiagnosticIdentifiers.RemoveRedundantSealedModifier: + { + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, memberDeclaration, SyntaxKind.SealedKeyword); + break; + } + case DiagnosticIdentifiers.UnnecessarySemicolonAtEndOfDeclaration: + { + CodeAction codeAction = CodeAction.Create( + "Remove unnecessary semicolon", + ct => RemoveSemicolonAtEndOfDeclarationRefactoring.RefactorAsync(context.Document, memberDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.OrderModifiers: + { + CodeAction codeAction = CodeAction.Create( + "Order modifiers", + ct => OrderModifiersAsync(context.Document, memberDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.MakeFieldReadOnly: - { - var fieldDeclaration = (FieldDeclarationSyntax)memberDeclaration; + { + var fieldDeclaration = (FieldDeclarationSyntax)memberDeclaration; - SeparatedSyntaxList declarators = fieldDeclaration.Declaration.Variables; + SeparatedSyntaxList declarators = fieldDeclaration.Declaration.Variables; - string title = (declarators.Count == 1) - ? $"Make '{declarators[0].Identifier.ValueText}' read-only" - : "Make fields read-only"; + string title = (declarators.Count == 1) + ? $"Make '{declarators[0].Identifier.ValueText}' read-only" + : "Make fields read-only"; - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, fieldDeclaration, SyntaxKind.ReadOnlyKeyword, title: title); - break; - } + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, fieldDeclaration, SyntaxKind.ReadOnlyKeyword, title: title); + break; + } case DiagnosticIdentifiers.UseConstantInsteadOfField: - { - CodeAction codeAction = CodeAction.Create( - "Use constant instead of field", - ct => UseConstantInsteadOfReadOnlyFieldRefactoring.RefactorAsync(context.Document, (FieldDeclarationSyntax)memberDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use constant instead of field", + ct => UseConstantInsteadOfReadOnlyFieldRefactoring.RefactorAsync(context.Document, (FieldDeclarationSyntax)memberDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseReadOnlyAutoProperty: - { - CodeAction codeAction = CodeAction.Create( - "Use read-only auto-property", - ct => UseReadOnlyAutoPropertyAsync(context.Document, (PropertyDeclarationSyntax)memberDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use read-only auto-property", + ct => UseReadOnlyAutoPropertyAsync(context.Document, (PropertyDeclarationSyntax)memberDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.ConvertCommentToDocumentationComment: - { - CodeAction codeAction = CodeAction.Create( - ConvertCommentToDocumentationCommentRefactoring.Title, - ct => ConvertCommentToDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, context.Span, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + ConvertCommentToDocumentationCommentRefactoring.Title, + ct => ConvertCommentToDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, context.Span, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.MakeMethodExtensionMethod: - { - var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; + { + var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; - CodeAction codeAction = CodeAction.Create( - "Make method an extension method", - ct => - { - ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0]; + CodeAction codeAction = CodeAction.Create( + "Make method an extension method", + ct => + { + ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0]; - ParameterSyntax newParameter = ModifierList.Insert(parameter, SyntaxKind.ThisKeyword); + ParameterSyntax newParameter = ModifierList.Insert(parameter, SyntaxKind.ThisKeyword); - return context.Document.ReplaceNodeAsync(parameter, newParameter, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(parameter, newParameter, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/NamespaceDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/NamespaceDeclarationCodeFixProvider.cs index 862ba5475d..de9393c474 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/NamespaceDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/NamespaceDeclarationCodeFixProvider.cs @@ -38,29 +38,29 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveEmptyNamespaceDeclaration: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty namespace declaration", - ct => context.Document.RemoveNodeAsync(namespaceDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty namespace declaration", + ct => context.Document.RemoveNodeAsync(namespaceDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.DeclareUsingDirectiveOnTopLevel: - { - string title = (namespaceDeclaration.Usings.Count == 1) - ? "Move using to top level" - : "Move usings to top level"; + { + string title = (namespaceDeclaration.Usings.Count == 1) + ? "Move using to top level" + : "Move usings to top level"; - CodeAction codeAction = CodeAction.Create( - title, - ct => DeclareUsingDirectiveOnTopLevelRefactoring.RefactorAsync(context.Document, namespaceDeclaration, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + title, + ct => DeclareUsingDirectiveOnTopLevelRefactoring.RefactorAsync(context.Document, namespaceDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs index dd81913b5a..f3acce2f8c 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs @@ -33,15 +33,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UseEventArgsEmpty: - { - CodeAction codeAction = CodeAction.Create( - "Use EventArgs.Empty", - ct => UseEventArgsEmptyRefactoring.RefactorAsync(context.Document, objectCreationExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use EventArgs.Empty", + ct => UseEventArgsEmptyRefactoring.RefactorAsync(context.Document, objectCreationExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeLinqMethodCallCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeLinqMethodCallCodeFixProvider.cs index 2a95dccacc..42226365b3 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeLinqMethodCallCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeLinqMethodCallCodeFixProvider.cs @@ -84,190 +84,190 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (invocationInfo.NameText) { case "Cast": - { - CodeAction codeAction = CodeAction.Create( - "Call 'OfType' instead of 'Where' and 'Cast'", - ct => CallOfTypeInsteadOfWhereAndCastAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallOfTypeInsteadOfWhereAndCast")); + { + CodeAction codeAction = CodeAction.Create( + "Call 'OfType' instead of 'Where' and 'Cast'", + ct => CallOfTypeInsteadOfWhereAndCastAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallOfTypeInsteadOfWhereAndCast")); - context.RegisterCodeFix(codeAction, diagnostic); - return; - } + context.RegisterCodeFix(codeAction, diagnostic); + return; + } case "Any": + { + CodeAction codeAction = CodeAction.Create( + "Combine 'Where' and 'Any'", + ct => CombineWhereAndAnyAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CombineWhereAndAny")); + + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case "ToList": + case "ToImmutableArray": + { + CodeAction codeAction = CodeAction.Create( + "Call 'ConvertAll'", + ct => CallConvertAllInsteadOfSelectAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallConvertAllInsteadOfSelect")); + + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case "OfType": + { + TypeSyntax typeArgument = ((GenericNameSyntax)invocationInfo.Name).TypeArgumentList.Arguments.Single(); + + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + if (semanticModel.GetTypeSymbol(typeArgument, cancellationToken).IsValueType) { CodeAction codeAction = CodeAction.Create( - "Combine 'Where' and 'Any'", - ct => CombineWhereAndAnyAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CombineWhereAndAny")); + "Remove redundant 'OfType' call", + ct => + { + ExpressionSyntax newNode = invocationInfo.Expression.WithTrailingTrivia(invocation.GetTrailingTrivia()); + return document.ReplaceNodeAsync(invocation, newNode, ct); + }, + GetEquivalenceKey(diagnostic, "RemoveRedundantOfTypeCall")); context.RegisterCodeFix(codeAction, diagnostic); - return; } - case "ToList": - case "ToImmutableArray": + else { CodeAction codeAction = CodeAction.Create( - "Call 'ConvertAll'", - ct => CallConvertAllInsteadOfSelectAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallConvertAllInsteadOfSelect")); + "Call 'Where' instead of 'OfType'", + ct => CallWhereInsteadOfOfTypeAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallWhereInsteadOfOfType")); context.RegisterCodeFix(codeAction, diagnostic); - return; } - case "OfType": - { - TypeSyntax typeArgument = ((GenericNameSyntax)invocationInfo.Name).TypeArgumentList.Arguments.Single(); - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + return; + } + case "Reverse": + { + CodeAction codeAction = CodeAction.Create( + "Call 'OrderByDescending'", + ct => CallOrderByDescendingInsteadOfOrderByAndReverseAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallOrderByDescendingInsteadOfOrderByAndReverse")); - if (semanticModel.GetTypeSymbol(typeArgument, cancellationToken).IsValueType) - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant 'OfType' call", - ct => - { - ExpressionSyntax newNode = invocationInfo.Expression.WithTrailingTrivia(invocation.GetTrailingTrivia()); - return document.ReplaceNodeAsync(invocation, newNode, ct); - }, - GetEquivalenceKey(diagnostic, "RemoveRedundantOfTypeCall")); + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case "Where": + { + SimpleMemberInvocationExpressionInfo invocationInfo2 = SimpleMemberInvocationExpressionInfo( + invocationInfo.Expression); - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Call 'Where' instead of 'OfType'", - ct => CallWhereInsteadOfOfTypeAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallWhereInsteadOfOfType")); + CodeAction codeAction = CodeAction.Create( + $"Call '{invocationInfo2.NameText}' and 'Where' in reverse order", + ct => CallOrderByAndWhereInReverseOrderAsync(document, invocationInfo, invocationInfo2, ct), + GetEquivalenceKey(diagnostic, "CallOrderByAndWhereInReverseOrder")); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case "Select": + { + CodeAction codeAction = CodeAction.Create( + "Call 'Cast' instead of 'Select'", + ct => CallCastInsteadOfSelectAsync(document, invocation, ct), + GetEquivalenceKey(diagnostic, "CallCastInsteadOfSelect")); - return; - } - case "Reverse": + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case "First": + { + if (diagnostic.Properties.TryGetValue("MethodName", out string methodName) + && methodName == "Peek") { CodeAction codeAction = CodeAction.Create( - "Call 'OrderByDescending'", - ct => CallOrderByDescendingInsteadOfOrderByAndReverseAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallOrderByDescendingInsteadOfOrderByAndReverse")); + "Call 'Peek' instead of 'First'", + ct => document.ReplaceNodeAsync(invocation, ChangeInvokedMethodName(invocation, "Peek"), ct), + GetEquivalenceKey(diagnostic, "CallPeekInsteadOfFirst")); context.RegisterCodeFix(codeAction, diagnostic); - return; } - case "Where": + else { - SimpleMemberInvocationExpressionInfo invocationInfo2 = SimpleMemberInvocationExpressionInfo( - invocationInfo.Expression); - CodeAction codeAction = CodeAction.Create( - $"Call '{invocationInfo2.NameText}' and 'Where' in reverse order", - ct => CallOrderByAndWhereInReverseOrderAsync(document, invocationInfo, invocationInfo2, ct), - GetEquivalenceKey(diagnostic, "CallOrderByAndWhereInReverseOrder")); + "Use [] instead of calling 'First'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfFirstAsync(context.Document, invocation, ct), + GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfFirst")); context.RegisterCodeFix(codeAction, diagnostic); - return; } - case "Select": - { - CodeAction codeAction = CodeAction.Create( - "Call 'Cast' instead of 'Select'", - ct => CallCastInsteadOfSelectAsync(document, invocation, ct), - GetEquivalenceKey(diagnostic, "CallCastInsteadOfSelect")); - context.RegisterCodeFix(codeAction, diagnostic); - return; - } - case "First": + return; + } + case "Count": + { + if (diagnostic.Properties.TryGetValue("PropertyName", out string propertyName)) { if (diagnostic.Properties.TryGetValue("MethodName", out string methodName) - && methodName == "Peek") + && methodName == "Sum") { CodeAction codeAction = CodeAction.Create( - "Call 'Peek' instead of 'First'", - ct => document.ReplaceNodeAsync(invocation, ChangeInvokedMethodName(invocation, "Peek"), ct), - GetEquivalenceKey(diagnostic, "CallPeekInsteadOfFirst")); + "Call 'Sum'", + ct => CallSumInsteadOfSelectManyAndCountAsync(document, invocationInfo, propertyName, ct), + GetEquivalenceKey(diagnostic, "CallSumInsteadOfSelectManyAndCount")); context.RegisterCodeFix(codeAction, diagnostic); } else { CodeAction codeAction = CodeAction.Create( - "Use [] instead of calling 'First'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfFirstAsync(context.Document, invocation, ct), - GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfFirst")); - - context.RegisterCodeFix(codeAction, diagnostic); - } - - return; - } - case "Count": - { - if (diagnostic.Properties.TryGetValue("PropertyName", out string propertyName)) - { - if (diagnostic.Properties.TryGetValue("MethodName", out string methodName) - && methodName == "Sum") - { - CodeAction codeAction = CodeAction.Create( - "Call 'Sum'", - ct => CallSumInsteadOfSelectManyAndCountAsync(document, invocationInfo, propertyName, ct), - GetEquivalenceKey(diagnostic, "CallSumInsteadOfSelectManyAndCount")); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - $"Use '{propertyName}' property instead of calling 'Count'", - ct => UseCountOrLengthPropertyInsteadOfCountMethodAsync(document, invocation, diagnostic.Properties["PropertyName"], ct), - GetEquivalenceKey(diagnostic, "UseCountOrLengthPropertyInsteadOfCountMethod")); - - context.RegisterCodeFix(codeAction, diagnostic); - } - } - else if (invocation.Parent is BinaryExpressionSyntax binaryExpression) - { - CodeAction codeAction = CodeAction.Create( - "Call 'Any' instead of 'Count'", - ct => CallAnyInsteadOfCountAsync(document, invocation, binaryExpression, ct), - GetEquivalenceKey(diagnostic, "CallAnyInsteadOfCount")); + $"Use '{propertyName}' property instead of calling 'Count'", + ct => UseCountOrLengthPropertyInsteadOfCountMethodAsync(document, invocation, diagnostic.Properties["PropertyName"], ct), + GetEquivalenceKey(diagnostic, "UseCountOrLengthPropertyInsteadOfCountMethod")); context.RegisterCodeFix(codeAction, diagnostic); } - - return; } - case "ElementAt": + else if (invocation.Parent is BinaryExpressionSyntax binaryExpression) { CodeAction codeAction = CodeAction.Create( - "Use [] instead of calling 'ElementAt'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfElementAtAsync(document, invocation, ct), - GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfElementAt")); + "Call 'Any' instead of 'Count'", + ct => CallAnyInsteadOfCountAsync(document, invocation, binaryExpression, ct), + GetEquivalenceKey(diagnostic, "CallAnyInsteadOfCount")); context.RegisterCodeFix(codeAction, diagnostic); - return; } + + return; + } + case "ElementAt": + { + CodeAction codeAction = CodeAction.Create( + "Use [] instead of calling 'ElementAt'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfElementAtAsync(document, invocation, ct), + GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfElementAt")); + + context.RegisterCodeFix(codeAction, diagnostic); + return; + } case "Last": - { - CodeAction codeAction = CodeAction.Create( - "Use [] instead of calling 'Last'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(document, invocation, ct), - GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfLast")); + { + CodeAction codeAction = CodeAction.Create( + "Use [] instead of calling 'Last'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(document, invocation, ct), + GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfLast")); - context.RegisterCodeFix(codeAction, diagnostic); - return; - } + context.RegisterCodeFix(codeAction, diagnostic); + return; + } case "OrderBy": - { - CodeAction codeAction = CodeAction.Create( - "Call 'Order' instead of 'OrderBy'", - ct => CallOrderInsteadOfOrderByIdentityAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallOrderInsteadOfOrderByIdentity")); + { + CodeAction codeAction = CodeAction.Create( + "Call 'Order' instead of 'OrderBy'", + ct => CallOrderInsteadOfOrderByIdentityAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallOrderInsteadOfOrderByIdentity")); - context.RegisterCodeFix(codeAction, diagnostic); - return; - } + context.RegisterCodeFix(codeAction, diagnostic); + return; + } } } else if (kind == SyntaxKind.ConditionalExpression) @@ -458,56 +458,56 @@ private static Task CallAnyInsteadOfCountAsync( switch (binaryExpression.Kind()) { case SyntaxKind.EqualsExpression: + { + // Count() == 0 >>> !Any() + newNode = ChangeInvokedMethodName(invocationExpression, "Any"); + newNode = LogicalNotExpression(newNode.Parenthesize()); + break; + } + case SyntaxKind.NotEqualsExpression: + { + // Count() != 0 >>> Any() + newNode = ChangeInvokedMethodName(invocationExpression, "Any"); + break; + } + case SyntaxKind.LessThanExpression: + case SyntaxKind.LessThanOrEqualExpression: + { + if (invocationExpression == left) { - // Count() == 0 >>> !Any() + // Count() < 1 >>> !Any() + // Count() <= 0 >>> !Any() newNode = ChangeInvokedMethodName(invocationExpression, "Any"); newNode = LogicalNotExpression(newNode.Parenthesize()); - break; } - case SyntaxKind.NotEqualsExpression: + else { - // Count() != 0 >>> Any() + // 0 < Count() >>> Any() + // 1 <= Count() >>> Any() newNode = ChangeInvokedMethodName(invocationExpression, "Any"); - break; } - case SyntaxKind.LessThanExpression: - case SyntaxKind.LessThanOrEqualExpression: - { - if (invocationExpression == left) - { - // Count() < 1 >>> !Any() - // Count() <= 0 >>> !Any() - newNode = ChangeInvokedMethodName(invocationExpression, "Any"); - newNode = LogicalNotExpression(newNode.Parenthesize()); - } - else - { - // 0 < Count() >>> Any() - // 1 <= Count() >>> Any() - newNode = ChangeInvokedMethodName(invocationExpression, "Any"); - } - break; - } + break; + } case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: + { + if (invocationExpression == left) { - if (invocationExpression == left) - { - // Count() > 0 >>> Any() - // Count() >= 1 >>> Any() - newNode = ChangeInvokedMethodName(invocationExpression, "Any"); - } - else - { - // 1 > Count() >>> !Any() - // 0 >= Count() >>> !Any() - newNode = ChangeInvokedMethodName(invocationExpression, "Any"); - newNode = LogicalNotExpression(newNode.Parenthesize()); - } - - break; + // Count() > 0 >>> Any() + // Count() >= 1 >>> Any() + newNode = ChangeInvokedMethodName(invocationExpression, "Any"); } + else + { + // 1 > Count() >>> !Any() + // 0 >= Count() >>> !Any() + newNode = ChangeInvokedMethodName(invocationExpression, "Any"); + newNode = LogicalNotExpression(newNode.Parenthesize()); + } + + break; + } } newNode = newNode diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeMethodCallCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeMethodCallCodeFixProvider.cs index 34d4bafcf7..4e8851a902 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeMethodCallCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeMethodCallCodeFixProvider.cs @@ -39,82 +39,82 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node.Kind()) { case SyntaxKind.InvocationExpression: + { + var invocationExpression = (InvocationExpressionSyntax)node; + + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); + + switch (invocationInfo.NameText) { - var invocationExpression = (InvocationExpressionSyntax)node; + case "Add": + { + CodeAction codeAction = CodeAction.Create( + "Call 'AddRange' instead of 'Add'", + ct => CallAddRangeInsteadOfAddAsync(document, invocationExpression, ct), + GetEquivalenceKey(diagnostic, "CallAddRangeInsteadOfAdd")); - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case "Compare": + { + CodeAction codeAction = CodeAction.Create( + "Call 'CompareOrdinal' instead of 'Compare'", + ct => CallCompareOrdinalInsteadOfCompareAsync(document, invocationInfo, ct), + GetEquivalenceKey(diagnostic, "CallCompareOrdinalInsteadOfCompare")); - switch (invocationInfo.NameText) + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case "Join": { - case "Add": - { - CodeAction codeAction = CodeAction.Create( - "Call 'AddRange' instead of 'Add'", - ct => CallAddRangeInsteadOfAddAsync(document, invocationExpression, ct), - GetEquivalenceKey(diagnostic, "CallAddRangeInsteadOfAdd")); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case "Compare": - { - CodeAction codeAction = CodeAction.Create( - "Call 'CompareOrdinal' instead of 'Compare'", - ct => CallCompareOrdinalInsteadOfCompareAsync(document, invocationInfo, ct), - GetEquivalenceKey(diagnostic, "CallCompareOrdinalInsteadOfCompare")); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case "Join": - { - CodeAction codeAction = CodeAction.Create( - "Call 'Concat' instead of 'Join'", - ct => CallStringConcatInsteadOfStringJoinAsync(document, invocationExpression, ct), - GetEquivalenceKey(diagnostic, "CallConcatInsteadOfJoin")); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case "Assert": - { - CodeAction codeAction = CodeAction.Create( - "Call 'Fail' instead of 'Assert'", - ct => CallDebugFailInsteadOfDebugAssertAsync(context.Document, invocationExpression, ct), - GetEquivalenceKey(diagnostic, "CallFailInsteadOfAssert")); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + CodeAction codeAction = CodeAction.Create( + "Call 'Concat' instead of 'Join'", + ct => CallStringConcatInsteadOfStringJoinAsync(document, invocationExpression, ct), + GetEquivalenceKey(diagnostic, "CallConcatInsteadOfJoin")); + + context.RegisterCodeFix(codeAction, diagnostic); + break; } + case "Assert": + { + CodeAction codeAction = CodeAction.Create( + "Call 'Fail' instead of 'Assert'", + ct => CallDebugFailInsteadOfDebugAssertAsync(context.Document, invocationExpression, ct), + GetEquivalenceKey(diagnostic, "CallFailInsteadOfAssert")); - break; + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } + + break; + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - var equalityExpression = (BinaryExpressionSyntax)node; + { + var equalityExpression = (BinaryExpressionSyntax)node; - CodeAction codeAction = CodeAction.Create( - "Call 'Equals' instead of 'Compare'", - ct => CallEqualsInsteadOfCompareAsync(document, equalityExpression, ct), - GetEquivalenceKey(diagnostic, "CallEqualsInsteadOfCompare")); + CodeAction codeAction = CodeAction.Create( + "Call 'Equals' instead of 'Compare'", + ct => CallEqualsInsteadOfCompareAsync(document, equalityExpression, ct), + GetEquivalenceKey(diagnostic, "CallEqualsInsteadOfCompare")); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)node; + { + var ifStatement = (IfStatementSyntax)node; - CodeAction codeAction = CodeAction.Create( - "Use [] instead of 'ContainsKey'", - ct => UseElementAccessInsteadOfContainsKeyAsync(document, ifStatement, ct), - GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfContainsKey")); + CodeAction codeAction = CodeAction.Create( + "Use [] instead of 'ContainsKey'", + ct => UseElementAccessInsteadOfContainsKeyAsync(document, ifStatement, ct), + GetEquivalenceKey(diagnostic, "UseElementAccessInsteadOfContainsKey")); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs index a7397f6851..5ab1c7dec6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OptimizeStringBuilderAppendCallCodeFixProvider.cs @@ -123,59 +123,59 @@ private static InvocationExpressionSyntax CreateInvocationExpression( switch (invocationInfo.NameText) { case "Substring": + { + SeparatedSyntaxList arguments = invocationInfo.Arguments; + + switch (arguments.Count) { - SeparatedSyntaxList arguments = invocationInfo.Arguments; + case 1: + { + ArgumentListSyntax argumentList = ArgumentList( + Argument(invocationInfo.Expression), + arguments[0], + Argument( + SubtractExpression( + SimpleMemberAccessExpression(invocationInfo.Expression, IdentifierName("Length")), + arguments[0].Expression.Parenthesize()))); + + return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); + } + case 2: + { + ArgumentListSyntax argumentList = ArgumentList( + Argument(invocationInfo.Expression), + arguments[0], + arguments[1] + ); - switch (arguments.Count) + return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); + } + default: { - case 1: - { - ArgumentListSyntax argumentList = ArgumentList( - Argument(invocationInfo.Expression), - arguments[0], - Argument( - SubtractExpression( - SimpleMemberAccessExpression(invocationInfo.Expression, IdentifierName("Length")), - arguments[0].Expression.Parenthesize()))); - - return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); - } - case 2: - { - ArgumentListSyntax argumentList = ArgumentList( - Argument(invocationInfo.Expression), - arguments[0], - arguments[1] - ); - - return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); - } - default: - { - throw new InvalidOperationException(); - } + throw new InvalidOperationException(); } } + } case "Remove": - { - SeparatedSyntaxList arguments = invocationInfo.Arguments; + { + SeparatedSyntaxList arguments = invocationInfo.Arguments; - ArgumentListSyntax argumentList = ArgumentList( - Argument(invocationInfo.Expression), - Argument(NumericLiteralExpression(0)), - arguments[0] - ); + ArgumentListSyntax argumentList = ArgumentList( + Argument(invocationInfo.Expression), + Argument(NumericLiteralExpression(0)), + arguments[0] + ); - return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); - } + return CreateNewInvocationExpression(outerInvocationExpression, "Append", argumentList); + } case "Format": - { - return CreateNewInvocationExpression(outerInvocationExpression, "AppendFormat", invocationInfo.ArgumentList); - } + { + return CreateNewInvocationExpression(outerInvocationExpression, "AppendFormat", invocationInfo.ArgumentList); + } case "Join": - { - return CreateNewInvocationExpression(outerInvocationExpression, "AppendJoin", invocationInfo.ArgumentList); - } + { + return CreateNewInvocationExpression(outerInvocationExpression, "AppendJoin", invocationInfo.ArgumentList); + } } SyntaxDebug.Fail(innerInvocationExpression); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs index 1c326c2f1d..9686fab0b3 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/OrderElementsInDocumentationCommentCodeFixProvider.cs @@ -68,21 +68,21 @@ SyntaxList GetNewContent() switch (SyntaxInfo.XmlElementInfo(xmlNode).GetTag()) { case XmlTag.Param: - { - SeparatedSyntaxList parameters = CSharpUtility.GetParameters(memberDeclaration); + { + SeparatedSyntaxList parameters = CSharpUtility.GetParameters(memberDeclaration); - return SortElements(parameters, content, firstIndex, XmlTag.Param, (nodes, name) => nodes.IndexOf(name)); - } + return SortElements(parameters, content, firstIndex, XmlTag.Param, (nodes, name) => nodes.IndexOf(name)); + } case XmlTag.TypeParam: - { - SeparatedSyntaxList typeParameters = CSharpUtility.GetTypeParameters(memberDeclaration); + { + SeparatedSyntaxList typeParameters = CSharpUtility.GetTypeParameters(memberDeclaration); - return SortElements(typeParameters, content, firstIndex, XmlTag.TypeParam, (nodes, name) => nodes.IndexOf(name)); - } + return SortElements(typeParameters, content, firstIndex, XmlTag.TypeParam, (nodes, name) => nodes.IndexOf(name)); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs index 339d1c0a88..acad348cd9 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs @@ -38,32 +38,32 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.OverridingMemberShouldNotChangeParamsModifier: + { + if (parameter.IsParams()) { - if (parameter.IsParams()) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, SyntaxKind.ParamsKeyword); - } - else - { - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, parameter, SyntaxKind.ParamsKeyword); - } - - break; + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, SyntaxKind.ParamsKeyword); + } + else + { + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, parameter, SyntaxKind.ParamsKeyword); } + + break; + } case DiagnosticIdentifiers.MakeParameterRefReadOnly: case DiagnosticIdentifiers.DoNotPassNonReadOnlyStructByReadOnlyReference: + { + if (parameter.Modifiers.Contains(SyntaxKind.InKeyword)) { - if (parameter.Modifiers.Contains(SyntaxKind.InKeyword)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, SyntaxKind.InKeyword); - } - else - { - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, parameter, SyntaxKind.InKeyword); - } - - break; + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, SyntaxKind.InKeyword); + } + else + { + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, parameter, SyntaxKind.InKeyword); } + + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterNameDiffersFromBaseCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterNameDiffersFromBaseCodeFixProvider.cs index 30128e3220..1b872b3fa3 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterNameDiffersFromBaseCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ParameterNameDiffersFromBaseCodeFixProvider.cs @@ -39,61 +39,61 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.ParameterNameDiffersFromBase: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - var parameterSymbol = (IParameterSymbol)semanticModel.GetDeclaredSymbol(parameter, context.CancellationToken); + var parameterSymbol = (IParameterSymbol)semanticModel.GetDeclaredSymbol(parameter, context.CancellationToken); - ISymbol containingSymbol = parameterSymbol.ContainingSymbol; + ISymbol containingSymbol = parameterSymbol.ContainingSymbol; - ISymbol baseParameterSymbol = null; + ISymbol baseParameterSymbol = null; - switch (containingSymbol.Kind) + switch (containingSymbol.Kind) + { + case SymbolKind.Method: { - case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)containingSymbol; + var methodSymbol = (IMethodSymbol)containingSymbol; - IMethodSymbol baseSymbol = methodSymbol.OverriddenMethod ?? methodSymbol.FindFirstImplementedInterfaceMember(); + IMethodSymbol baseSymbol = methodSymbol.OverriddenMethod ?? methodSymbol.FindFirstImplementedInterfaceMember(); - baseParameterSymbol = baseSymbol.Parameters[parameterSymbol.Ordinal]; - break; - } - case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)containingSymbol; + baseParameterSymbol = baseSymbol.Parameters[parameterSymbol.Ordinal]; + break; + } + case SymbolKind.Property: + { + var propertySymbol = (IPropertySymbol)containingSymbol; - IPropertySymbol baseSymbol = propertySymbol.OverriddenProperty ?? propertySymbol.FindFirstImplementedInterfaceMember(); + IPropertySymbol baseSymbol = propertySymbol.OverriddenProperty ?? propertySymbol.FindFirstImplementedInterfaceMember(); - baseParameterSymbol = baseSymbol.Parameters[parameterSymbol.Ordinal]; - break; - } + baseParameterSymbol = baseSymbol.Parameters[parameterSymbol.Ordinal]; + break; } + } - string oldName = parameterSymbol.Name; + string oldName = parameterSymbol.Name; - string newName = NameGenerator.Default.EnsureUniqueParameterName( - baseParameterSymbol.Name, - containingSymbol, - semanticModel, - cancellationToken: context.CancellationToken); + string newName = NameGenerator.Default.EnsureUniqueParameterName( + baseParameterSymbol.Name, + containingSymbol, + semanticModel, + cancellationToken: context.CancellationToken); - if (!string.Equals(newName, baseParameterSymbol.Name, StringComparison.Ordinal)) - break; + if (!string.Equals(newName, baseParameterSymbol.Name, StringComparison.Ordinal)) + break; - CodeAction codeAction = CodeAction.Create( - $"Rename '{oldName}' to '{newName}'", - ct => + CodeAction codeAction = CodeAction.Create( + $"Rename '{oldName}' to '{newName}'", + ct => #if ROSLYN_4_4 - Renamer.RenameSymbolAsync(context.Document.Solution(), parameterSymbol, default(SymbolRenameOptions), newName, ct), + Renamer.RenameSymbolAsync(context.Document.Solution(), parameterSymbol, default(SymbolRenameOptions), newName, ct), #else Renamer.RenameSymbolAsync(context.Document.Solution(), parameterSymbol, newName, default(Microsoft.CodeAnalysis.Options.OptionSet), ct), #endif - GetEquivalenceKey(diagnostic)); + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/PropertyDeclarationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/PropertyDeclarationCodeFixProvider.cs index 79645c4a95..f5189575fe 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/PropertyDeclarationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/PropertyDeclarationCodeFixProvider.cs @@ -33,15 +33,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantAutoPropertyInitialization: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant initialization", - ct => RemoveRedundantAutoPropertyInitializationRefactoring.RefactorAsync(context.Document, property, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant initialization", + ct => RemoveRedundantAutoPropertyInitializationRefactoring.RefactorAsync(context.Document, property, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveEmptySyntaxCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveEmptySyntaxCodeFixProvider.cs index 6518c01fd0..3e387d474f 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveEmptySyntaxCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveEmptySyntaxCodeFixProvider.cs @@ -60,57 +60,57 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node) { case DestructorDeclarationSyntax destructorDeclaration: - { - CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( - document, - destructorDeclaration, - title: "Remove empty destructor", - equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.RemoveMemberDeclaration( + document, + destructorDeclaration, + title: "Remove empty destructor", + equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case ElseClauseSyntax elseClause: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty 'else' clause", - ct => ElseClauseCodeFixProvider.RemoveEmptyElseClauseAsync(document, elseClause, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty 'else' clause", + ct => ElseClauseCodeFixProvider.RemoveEmptyElseClauseAsync(document, elseClause, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case FinallyClauseSyntax finallyClause: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty 'finally' clause", - ct => FinallyClauseCodeFixProvider.RemoveEmptyFinallyClauseAsync(document, finallyClause, ct), - equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty 'finally' clause", + ct => FinallyClauseCodeFixProvider.RemoveEmptyFinallyClauseAsync(document, finallyClause, ct), + equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case ObjectCreationExpressionSyntax objectCreationExpression: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty initializer", - ct => RemoveEmptyInitializerRefactoring.RefactorAsync(document, objectCreationExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty initializer", + ct => RemoveEmptyInitializerRefactoring.RefactorAsync(document, objectCreationExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } #if ROSLYN_4_0 case BaseNamespaceDeclarationSyntax namespaceDeclaration: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty namespace declaration", - ct => document.RemoveNodeAsync(namespaceDeclaration, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty namespace declaration", + ct => document.RemoveNodeAsync(namespaceDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } #else case NamespaceDeclarationSyntax namespaceDeclaration: { @@ -124,25 +124,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } #endif case RegionDirectiveTriviaSyntax regionDirective: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty region", - ct => RemoveEmptyRegionRefactoring.RefactorAsync(document, SyntaxInfo.RegionInfo(regionDirective), ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty region", + ct => RemoveEmptyRegionRefactoring.RefactorAsync(document, SyntaxInfo.RegionInfo(regionDirective), ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case EmptyStatementSyntax emptyStatement: - { - CodeAction codeAction = CodeAction.Create( - "Remove empty statement", - ct => RemoveEmptyStatementRefactoring.RefactorAsync(document, emptyStatement, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove empty statement", + ct => RemoveEmptyStatementRefactoring.RefactorAsync(document, emptyStatement, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs index c17a47edd5..99d3b1836b 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantAssignmentCodeFixProvider.cs @@ -40,27 +40,27 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantAssignment: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant assignment", - ct => + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant assignment", + ct => + { + if (node is VariableDeclaratorSyntax variableDeclarator) { - if (node is VariableDeclaratorSyntax variableDeclarator) - { - return RemoveRedundantAssignmentAfterLocalDeclarationAsync(document, variableDeclarator, ct); - } - else - { - var assignment = (AssignmentExpressionSyntax)node; - - return RemoveRedundantAssignmentBeforeReturnStatementAsync(document, assignment, ct); - } - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + return RemoveRedundantAssignmentAfterLocalDeclarationAsync(document, variableDeclarator, ct); + } + else + { + var assignment = (AssignmentExpressionSyntax)node; + + return RemoveRedundantAssignmentBeforeReturnStatementAsync(document, assignment, ct); + } + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantBooleanLiteralCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantBooleanLiteralCodeFixProvider.cs index 4d902b9194..2e01abf7e2 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantBooleanLiteralCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantBooleanLiteralCodeFixProvider.cs @@ -47,42 +47,42 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node.Kind()) { case SyntaxKind.TrueLiteralExpression: - { - RegisterCodeFix( - context, - node.ToString(), - ct => - { - return RemoveRedundantBooleanLiteralRefactoring.RefactorAsync( - context.Document, - (ForStatementSyntax)node.Parent, - ct); - }); + { + RegisterCodeFix( + context, + node.ToString(), + ct => + { + return RemoveRedundantBooleanLiteralRefactoring.RefactorAsync( + context.Document, + (ForStatementSyntax)node.Parent, + ct); + }); - break; - } + break; + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: - { - var binaryExpression = (BinaryExpressionSyntax)node; + { + var binaryExpression = (BinaryExpressionSyntax)node; - TextSpan span = RemoveRedundantBooleanLiteralAnalysis.GetSpanToRemove(binaryExpression, binaryExpression.Left, binaryExpression.Right); + TextSpan span = RemoveRedundantBooleanLiteralAnalysis.GetSpanToRemove(binaryExpression, binaryExpression.Left, binaryExpression.Right); - RegisterCodeFix( - context, - binaryExpression.ToString(span), - ct => - { - return RemoveRedundantBooleanLiteralRefactoring.RefactorAsync( - context.Document, - binaryExpression, - ct); - }); + RegisterCodeFix( + context, + binaryExpression.ToString(span), + ct => + { + return RemoveRedundantBooleanLiteralRefactoring.RefactorAsync( + context.Document, + binaryExpression, + ct); + }); - break; - } + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantCastCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantCastCodeFixProvider.cs index 9ae760fb6b..c9b9f9d6fd 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantCastCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveRedundantCastCodeFixProvider.cs @@ -32,25 +32,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node.Kind()) { case SyntaxKind.CastExpression: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant cast", - ct => RemoveRedundantCastRefactoring.RefactorAsync(context.Document, (CastExpressionSyntax)node, ct), - GetEquivalenceKey(DiagnosticIdentifiers.RemoveRedundantCast)); - - context.RegisterCodeFix(codeAction, context.Diagnostics); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant cast", + ct => RemoveRedundantCastRefactoring.RefactorAsync(context.Document, (CastExpressionSyntax)node, ct), + GetEquivalenceKey(DiagnosticIdentifiers.RemoveRedundantCast)); + + context.RegisterCodeFix(codeAction, context.Diagnostics); + break; + } case SyntaxKind.InvocationExpression: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant cast", - ct => RemoveRedundantCastRefactoring.RefactorAsync(context.Document, (InvocationExpressionSyntax)node, ct), - GetEquivalenceKey(DiagnosticIdentifiers.RemoveRedundantCast)); - - context.RegisterCodeFix(codeAction, context.Diagnostics); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant cast", + ct => RemoveRedundantCastRefactoring.RefactorAsync(context.Document, (InvocationExpressionSyntax)node, ct), + GetEquivalenceKey(DiagnosticIdentifiers.RemoveRedundantCast)); + + context.RegisterCodeFix(codeAction, context.Diagnostics); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveUnnecessaryElseCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveUnnecessaryElseCodeFixProvider.cs index f165370792..94a54aec7e 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveUnnecessaryElseCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/RemoveUnnecessaryElseCodeFixProvider.cs @@ -37,15 +37,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveUnnecessaryElse: - { - CodeAction codeAction = CodeAction.Create( - "Remove 'else'", - ct => RefactorAsync(context.Document, elseClause, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove 'else'", + ct => RefactorAsync(context.Document, elseClause, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ReturnCompletedTaskInsteadOfNullCodeFixProvider2.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ReturnCompletedTaskInsteadOfNullCodeFixProvider2.cs index ac2a3b2644..067d9fa1a8 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/ReturnCompletedTaskInsteadOfNullCodeFixProvider2.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/ReturnCompletedTaskInsteadOfNullCodeFixProvider2.cs @@ -127,43 +127,43 @@ SyntaxNode CreateNewNode(SyntaxNode node) switch (node) { case MethodDeclarationSyntax methodDeclaration: - { - return methodDeclaration - .WithExpressionBody(null) - .WithBody(Block(statements)); - } + { + return methodDeclaration + .WithExpressionBody(null) + .WithBody(Block(statements)); + } case LocalFunctionStatementSyntax localFunction: - { - return localFunction - .WithExpressionBody(null) - .WithBody(Block(statements)); - } + { + return localFunction + .WithExpressionBody(null) + .WithBody(Block(statements)); + } case PropertyDeclarationSyntax propertyDeclaration: - { - return propertyDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default(SyntaxToken)) - .WithAccessorList(AccessorList(GetAccessorDeclaration(Block(statements)))); - } + { + return propertyDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default(SyntaxToken)) + .WithAccessorList(AccessorList(GetAccessorDeclaration(Block(statements)))); + } case IndexerDeclarationSyntax indexerDeclaration: - { - return indexerDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default(SyntaxToken)) - .WithAccessorList(AccessorList(GetAccessorDeclaration(Block(statements)))); - } + { + return indexerDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default(SyntaxToken)) + .WithAccessorList(AccessorList(GetAccessorDeclaration(Block(statements)))); + } case AccessorDeclarationSyntax accessorDeclaration: - { - return accessorDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block(statements)); - } + { + return accessorDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block(statements)); + } default: - { - SyntaxDebug.Fail(node); - return node; - } + { + SyntaxDebug.Fail(node); + return node; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyCodeBranchingCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyCodeBranchingCodeFixProvider.cs index 7d2a2ff488..45c9bcc1ad 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyCodeBranchingCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyCodeBranchingCodeFixProvider.cs @@ -147,59 +147,59 @@ private static async Task RefactorAsync( switch (block.Parent) { case WhileStatementSyntax whileStatement: + { + if (statements.IsFirst(ifStatement)) { - if (statements.IsFirst(ifStatement)) - { - newNode = whileStatement.Update( - whileStatement.WhileKeyword, - whileStatement.OpenParenToken, - newCondition, - whileStatement.CloseParenToken, - newBlock); - } - else - { - newNode = DoStatement( - Token(whileStatement.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, whileStatement.CloseParenToken.TrailingTrivia), - newBlock.WithoutTrailingTrivia(), - Token(SyntaxKind.WhileKeyword), - OpenParenToken(), - newCondition, - CloseParenToken(), - SemicolonToken().WithTrailingTrivia(newBlock.GetTrailingTrivia())); - } - - break; + newNode = whileStatement.Update( + whileStatement.WhileKeyword, + whileStatement.OpenParenToken, + newCondition, + whileStatement.CloseParenToken, + newBlock); } + else + { + newNode = DoStatement( + Token(whileStatement.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, whileStatement.CloseParenToken.TrailingTrivia), + newBlock.WithoutTrailingTrivia(), + Token(SyntaxKind.WhileKeyword), + OpenParenToken(), + newCondition, + CloseParenToken(), + SemicolonToken().WithTrailingTrivia(newBlock.GetTrailingTrivia())); + } + + break; + } case DoStatementSyntax doStatement: + { + if (statements.IsLast(ifStatement)) { - if (statements.IsLast(ifStatement)) - { - newNode = doStatement.Update( - doStatement.DoKeyword, - newBlock, - doStatement.WhileKeyword, - doStatement.OpenParenToken, - newCondition, - doStatement.CloseParenToken, - doStatement.SemicolonToken); - } - else - { - newNode = WhileStatement( - Token(doStatement.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty), - OpenParenToken(), - newCondition, - Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia), - newBlock.WithTrailingTrivia(doStatement.GetTrailingTrivia())); - } - - break; + newNode = doStatement.Update( + doStatement.DoKeyword, + newBlock, + doStatement.WhileKeyword, + doStatement.OpenParenToken, + newCondition, + doStatement.CloseParenToken, + doStatement.SemicolonToken); } - default: + else { - throw new InvalidOperationException(); + newNode = WhileStatement( + Token(doStatement.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty), + OpenParenToken(), + newCondition, + Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia), + newBlock.WithTrailingTrivia(doStatement.GetTrailingTrivia())); } + + break; + } + default: + { + throw new InvalidOperationException(); + } } newNode = newNode.WithFormatterAnnotation(); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyLogicalNegationCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyLogicalNegationCodeFixProvider.cs index d441368b8f..491496373b 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyLogicalNegationCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SimplifyLogicalNegationCodeFixProvider.cs @@ -65,56 +65,56 @@ private static ExpressionSyntax GetNewNode(PrefixUnaryExpressionSyntax logicalNo { case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: - { - LiteralExpressionSyntax newNode = BooleanLiteralExpression(expression.Kind() == SyntaxKind.FalseLiteralExpression); + { + LiteralExpressionSyntax newNode = BooleanLiteralExpression(expression.Kind() == SyntaxKind.FalseLiteralExpression); - newNode = newNode.WithTriviaFrom(expression); + newNode = newNode.WithTriviaFrom(expression); - return operand.ReplaceNode(expression, newNode); - } + return operand.ReplaceNode(expression, newNode); + } case SyntaxKind.LogicalNotExpression: - { - return ((PrefixUnaryExpressionSyntax)expression).Operand; - } + { + return ((PrefixUnaryExpressionSyntax)expression).Operand; + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - BinaryExpressionSyntax newExpression = SyntaxLogicalInverter.GetInstance(document).InvertBinaryExpression((BinaryExpressionSyntax)expression); + { + BinaryExpressionSyntax newExpression = SyntaxLogicalInverter.GetInstance(document).InvertBinaryExpression((BinaryExpressionSyntax)expression); - return operand.ReplaceNode(expression, newExpression); - } + return operand.ReplaceNode(expression, newExpression); + } case SyntaxKind.InvocationExpression: - { - var invocationExpression = (InvocationExpressionSyntax)expression; + { + var invocationExpression = (InvocationExpressionSyntax)expression; - var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression; + var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression; - ExpressionSyntax lambdaExpression = invocationExpression.ArgumentList.Arguments[0].Expression.WalkDownParentheses(); + ExpressionSyntax lambdaExpression = invocationExpression.ArgumentList.Arguments[0].Expression.WalkDownParentheses(); - SingleParameterLambdaExpressionInfo lambdaInfo = SyntaxInfo.SingleParameterLambdaExpressionInfo(lambdaExpression); + SingleParameterLambdaExpressionInfo lambdaInfo = SyntaxInfo.SingleParameterLambdaExpressionInfo(lambdaExpression); - var logicalNot2 = (PrefixUnaryExpressionSyntax)SimplifyLogicalNegationAnalyzer.GetReturnExpression(lambdaInfo.Body).WalkDownParentheses(); + var logicalNot2 = (PrefixUnaryExpressionSyntax)SimplifyLogicalNegationAnalyzer.GetReturnExpression(lambdaInfo.Body).WalkDownParentheses(); - InvocationExpressionSyntax newNode = invocationExpression.ReplaceNode(logicalNot2, logicalNot2.Operand.WithTriviaFrom(logicalNot2)); + InvocationExpressionSyntax newNode = invocationExpression.ReplaceNode(logicalNot2, logicalNot2.Operand.WithTriviaFrom(logicalNot2)); - return SyntaxRefactorings.ChangeInvokedMethodName(newNode, (memberAccessExpression.Name.Identifier.ValueText == "All") ? "Any" : "All"); - } + return SyntaxRefactorings.ChangeInvokedMethodName(newNode, (memberAccessExpression.Name.Identifier.ValueText == "All") ? "Any" : "All"); + } case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; + { + var isPatternExpression = (IsPatternExpressionSyntax)expression; - var pattern = (ConstantPatternSyntax)isPatternExpression.Pattern; + var pattern = (ConstantPatternSyntax)isPatternExpression.Pattern; - UnaryPatternSyntax newPattern = NotPattern(pattern.WithoutTrivia()).WithTriviaFrom(pattern); + UnaryPatternSyntax newPattern = NotPattern(pattern.WithoutTrivia()).WithTriviaFrom(pattern); - return isPatternExpression.WithPattern(newPattern) - .PrependToLeadingTrivia(logicalNot.GetLeadingTrivia()) - .AppendToTrailingTrivia(logicalNot.GetTrailingTrivia()); - } + return isPatternExpression.WithPattern(newPattern) + .PrependToLeadingTrivia(logicalNot.GetLeadingTrivia()) + .AppendToTrailingTrivia(logicalNot.GetTrailingTrivia()); + } } return null; diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SingleLineDocumentationCommentTriviaCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SingleLineDocumentationCommentTriviaCodeFixProvider.cs index 2627640b1f..280ec56c7d 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SingleLineDocumentationCommentTriviaCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SingleLineDocumentationCommentTriviaCodeFixProvider.cs @@ -69,43 +69,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.FormatDocumentationCommentSummary: - { - XmlElementSyntax summaryElement = documentationComment.SummaryElement(); - - if (summaryElement?.StartTag?.IsMissing == false - && summaryElement.EndTag?.IsMissing == false - && summaryElement.IsSingleLine(includeExteriorTrivia: false, trim: false)) - { - CodeAction codeAction = CodeAction.Create( - "Format summary on multiple lines", - ct => FormatSummaryOnMultipleLinesAsync(context.Document, documentationComment, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - else - { - CodeAction codeAction = CodeAction.Create( - "Format summary on a single line", - ct => FormatSummaryOnSingleLineAsync(context.Document, documentationComment, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - - break; - } - case DiagnosticIdentifiers.FormatDocumentationSummaryOnSingleLine: - { - CodeAction codeAction = CodeAction.Create( - "Format summary on a single line", - ct => FormatSummaryOnSingleLineAsync(context.Document, documentationComment, ct), - GetEquivalenceKey(diagnostic)); + { + XmlElementSyntax summaryElement = documentationComment.SummaryElement(); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case DiagnosticIdentifiers.FormatDocumentationSummaryOnMultipleLines: + if (summaryElement?.StartTag?.IsMissing == false + && summaryElement.EndTag?.IsMissing == false + && summaryElement.IsSingleLine(includeExteriorTrivia: false, trim: false)) { CodeAction codeAction = CodeAction.Create( "Format summary on multiple lines", @@ -113,32 +82,63 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case DiagnosticIdentifiers.AddParamElementToDocumentationComment: + else { - var refactoring = new AddParamElementToDocumentationCommentRefactoring(); - CodeAction codeAction = CodeAction.Create( - "Add 'param' element", - ct => refactoring.RefactorAsync(context.Document, documentationComment, ct), + "Format summary on a single line", + ct => FormatSummaryOnSingleLineAsync(context.Document, documentationComment, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } + + break; + } + case DiagnosticIdentifiers.FormatDocumentationSummaryOnSingleLine: + { + CodeAction codeAction = CodeAction.Create( + "Format summary on a single line", + ct => FormatSummaryOnSingleLineAsync(context.Document, documentationComment, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.FormatDocumentationSummaryOnMultipleLines: + { + CodeAction codeAction = CodeAction.Create( + "Format summary on multiple lines", + ct => FormatSummaryOnMultipleLinesAsync(context.Document, documentationComment, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.AddParamElementToDocumentationComment: + { + var refactoring = new AddParamElementToDocumentationCommentRefactoring(); + + CodeAction codeAction = CodeAction.Create( + "Add 'param' element", + ct => refactoring.RefactorAsync(context.Document, documentationComment, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.AddTypeParamElementToDocumentationComment: - { - var refactoring = new AddTypeParamElementToDocumentationCommentRefactoring(); + { + var refactoring = new AddTypeParamElementToDocumentationCommentRefactoring(); - CodeAction codeAction = CodeAction.Create( - "Add 'typeparam' element", - ct => refactoring.RefactorAsync(context.Document, documentationComment, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Add 'typeparam' element", + ct => refactoring.RefactorAsync(context.Document, documentationComment, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs index fd6183f19c..e8beaa61fa 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs @@ -48,68 +48,68 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.InlineLazyInitialization: - { - CodeAction codeAction = CodeAction.Create( - "Inline lazy initialization", - ct => - { - return InlineLazyInitializationAsync( - context.Document, - (IfStatementSyntax)statement, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Inline lazy initialization", + ct => + { + return InlineLazyInitializationAsync( + context.Document, + (IfStatementSyntax)statement, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantDisposeOrCloseCall: - { - var expressionStatement = (ExpressionStatementSyntax)statement; - var invocation = (InvocationExpressionSyntax)expressionStatement.Expression; - var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; - - CodeAction codeAction = CodeAction.Create( - $"Remove redundant '{memberAccess.Name?.Identifier.ValueText}' call", - ct => RemoveRedundantDisposeOrCloseCallRefactoring.RefactorAsync(context.Document, expressionStatement, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + var expressionStatement = (ExpressionStatementSyntax)statement; + var invocation = (InvocationExpressionSyntax)expressionStatement.Expression; + var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; + + CodeAction codeAction = CodeAction.Create( + $"Remove redundant '{memberAccess.Name?.Identifier.ValueText}' call", + ct => RemoveRedundantDisposeOrCloseCallRefactoring.RefactorAsync(context.Document, expressionStatement, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveRedundantStatement: + { + CodeAction codeAction = CodeActionFactory.RemoveStatement( + context.Document, + statement, + title: $"Remove redundant {CSharpFacts.GetTitle(statement)}", + equivalenceKey: GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DiagnosticIdentifiers.UseMethodChaining: + { + var expressionStatement = (ExpressionStatementSyntax)statement; + + UseMethodChainingAnalysis analysis; + if (expressionStatement.Expression.Kind() == SyntaxKind.InvocationExpression) { - CodeAction codeAction = CodeActionFactory.RemoveStatement( - context.Document, - statement, - title: $"Remove redundant {CSharpFacts.GetTitle(statement)}", - equivalenceKey: GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; + analysis = UseMethodChainingAnalysis.WithoutAssignmentAnalysis; } - case DiagnosticIdentifiers.UseMethodChaining: + else { - var expressionStatement = (ExpressionStatementSyntax)statement; - - UseMethodChainingAnalysis analysis; - if (expressionStatement.Expression.Kind() == SyntaxKind.InvocationExpression) - { - analysis = UseMethodChainingAnalysis.WithoutAssignmentAnalysis; - } - else - { - analysis = UseMethodChainingAnalysis.WithAssignmentAnalysis; - } + analysis = UseMethodChainingAnalysis.WithAssignmentAnalysis; + } - CodeAction codeAction = CodeAction.Create( - "Use method chaining", - ct => UseMethodChainingRefactoring.RefactorAsync(context.Document, analysis, expressionStatement, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Use method chaining", + ct => UseMethodChainingRefactoring.RefactorAsync(context.Document, analysis, expressionStatement, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SwitchSectionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SwitchSectionCodeFixProvider.cs index 2291c55e65..d5709992f6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/SwitchSectionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/SwitchSectionCodeFixProvider.cs @@ -40,45 +40,45 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantDefaultSwitchSection: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant switch section", - ct => RemoveRedundantDefaultSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant switch section", + ct => RemoveRedundantDefaultSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.DefaultLabelShouldBeLastLabelInSwitchSection: - { - CodeAction codeAction = CodeAction.Create( - "Move default label to the last position", - ct => DefaultLabelShouldBeLastLabelInSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Move default label to the last position", + ct => DefaultLabelShouldBeLastLabelInSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.AddBracesToSwitchSectionWithMultipleStatements: - { - CodeAction codeAction = CodeAction.Create( - AddBracesToSwitchSectionRefactoring.Title, - ct => AddBracesToSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + AddBracesToSwitchSectionRefactoring.Title, + ct => AddBracesToSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.MergeSwitchSectionsWithEquivalentContent: - { - CodeAction codeAction = CodeAction.Create( - "Merge sections", - ct => MergeSwitchSectionsRefactoring.RefactorAsync(context.Document, switchSection, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Merge sections", + ct => MergeSwitchSectionsRefactoring.RefactorAsync(context.Document, switchSection, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs index 20b8b7f305..bcd4f67279 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs @@ -40,61 +40,61 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UnnecessaryNullForgivingOperator: - { - CodeAction codeAction = CodeAction.Create( - "Remove null-forgiving operator", - ct => + { + CodeAction codeAction = CodeAction.Create( + "Remove null-forgiving operator", + ct => + { + if (node.Parent is PropertyDeclarationSyntax propertyDeclaration) { - if (node.Parent is PropertyDeclarationSyntax propertyDeclaration) - { - SyntaxToken semicolonToken = propertyDeclaration.SemicolonToken; - - SyntaxToken token = propertyDeclaration.Initializer.GetFirstToken().GetPreviousToken(); - - SyntaxTriviaList newTrivia = token.TrailingTrivia - .AddRange(node.GetLeadingAndTrailingTrivia()) - .AddRange(semicolonToken.LeadingTrivia) - .EmptyIfWhitespace() - .AddRange(semicolonToken.TrailingTrivia); - - PropertyDeclarationSyntax newNode = propertyDeclaration - .ReplaceToken(token, token.WithTrailingTrivia(newTrivia)) - .WithInitializer(null) - .WithSemicolonToken(default); - - return document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); - } - else if (node.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) - { - var variableDeclarator = (VariableDeclaratorSyntax)node.Parent; - - SyntaxToken token = variableDeclarator.Initializer.GetFirstToken().GetPreviousToken(); - - SyntaxTriviaList newTrivia = token.TrailingTrivia - .AddRange(node.GetLeadingAndTrailingTrivia()) - .EmptyIfWhitespace(); - - VariableDeclaratorSyntax newNode = variableDeclarator - .ReplaceToken(token, token.WithTrailingTrivia(newTrivia)) - .WithInitializer(null); - - return document.ReplaceNodeAsync(variableDeclarator, newNode, ct); - } - else - { - var expression = (PostfixUnaryExpressionSyntax)node; - - ExpressionSyntax newExpression = expression.Operand - .AppendToTrailingTrivia(expression.OperatorToken.LeadingAndTrailingTrivia()); - - return document.ReplaceNodeAsync(expression, newExpression, ct); - } - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + SyntaxToken semicolonToken = propertyDeclaration.SemicolonToken; + + SyntaxToken token = propertyDeclaration.Initializer.GetFirstToken().GetPreviousToken(); + + SyntaxTriviaList newTrivia = token.TrailingTrivia + .AddRange(node.GetLeadingAndTrailingTrivia()) + .AddRange(semicolonToken.LeadingTrivia) + .EmptyIfWhitespace() + .AddRange(semicolonToken.TrailingTrivia); + + PropertyDeclarationSyntax newNode = propertyDeclaration + .ReplaceToken(token, token.WithTrailingTrivia(newTrivia)) + .WithInitializer(null) + .WithSemicolonToken(default); + + return document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); + } + else if (node.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) + { + var variableDeclarator = (VariableDeclaratorSyntax)node.Parent; + + SyntaxToken token = variableDeclarator.Initializer.GetFirstToken().GetPreviousToken(); + + SyntaxTriviaList newTrivia = token.TrailingTrivia + .AddRange(node.GetLeadingAndTrailingTrivia()) + .EmptyIfWhitespace(); + + VariableDeclaratorSyntax newNode = variableDeclarator + .ReplaceToken(token, token.WithTrailingTrivia(newTrivia)) + .WithInitializer(null); + + return document.ReplaceNodeAsync(variableDeclarator, newNode, ct); + } + else + { + var expression = (PostfixUnaryExpressionSyntax)node; + + ExpressionSyntax newExpression = expression.Operand + .AppendToTrailingTrivia(expression.OperatorToken.LeadingAndTrailingTrivia()); + + return document.ReplaceNodeAsync(expression, newExpression, ct); + } + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs index 196763c98d..91744bdc57 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/TypeParameterCodeFixProvider.cs @@ -33,15 +33,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UnusedTypeParameter: - { - CodeAction codeAction = CodeAction.Create( - $"Remove unused type parameter '{typeParameter.Identifier}'", - ct => UnusedParameterRefactoring.RefactorAsync(context.Document, typeParameter, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + $"Remove unused type parameter '{typeParameter.Identifier}'", + ct => UnusedParameterRefactoring.RefactorAsync(context.Document, typeParameter, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs index 03d6255ad4..4f8fdef206 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryAssignmentCodeFixProvider.cs @@ -44,25 +44,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (statement) { case IfStatementSyntax ifStatement: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => RefactorAsync(document, ifStatement, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => RefactorAsync(document, ifStatement, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case SwitchStatementSyntax switchStatement: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => RefactorAsync(document, switchStatement, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => RefactorAsync(document, switchStatement, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryEnumFlagCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryEnumFlagCodeFixProvider.cs index b25fa0a1d3..518a538f91 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryEnumFlagCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UnnecessaryEnumFlagCodeFixProvider.cs @@ -33,26 +33,26 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UnnecessaryEnumFlag: - { - CodeAction codeAction = CodeAction.Create( - "Remove unnecessary flag", - ct => - { - var bitwiseOr = (BinaryExpressionSyntax)memberAccessExpression.Parent; - - ExpressionSyntax newExpression = (bitwiseOr.Left == memberAccessExpression) - ? bitwiseOr.Right - : bitwiseOr.Left; - - newExpression = newExpression.WithTriviaFrom(bitwiseOr); - - return document.ReplaceNodeAsync(bitwiseOr, newExpression, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove unnecessary flag", + ct => + { + var bitwiseOr = (BinaryExpressionSyntax)memberAccessExpression.Parent; + + ExpressionSyntax newExpression = (bitwiseOr.Left == memberAccessExpression) + ? bitwiseOr.Right + : bitwiseOr.Left; + + newExpression = newExpression.WithTriviaFrom(bitwiseOr); + + return document.ReplaceNodeAsync(bitwiseOr, newExpression, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAsyncAwaitCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAsyncAwaitCodeFixProvider.cs index 801867c24c..b36dee155f 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAsyncAwaitCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAsyncAwaitCodeFixProvider.cs @@ -63,73 +63,73 @@ private static async Task RefactorAsync( switch (node) { case MethodDeclarationSyntax methodDeclaration: - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); - UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); + UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); - var newNode = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); + var newNode = (MethodDeclarationSyntax)rewriter.VisitMethodDeclaration(methodDeclaration); - newNode = ModifierList.Instance.Insert(newNode, SyntaxKind.AsyncKeyword); + newNode = ModifierList.Instance.Insert(newNode, SyntaxKind.AsyncKeyword); - return await document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken).ConfigureAwait(false); + } case LocalFunctionStatementSyntax localFunction: - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(localFunction, cancellationToken); - UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); + UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); - var newBody = (BlockSyntax)rewriter.VisitBlock(localFunction.Body); + var newBody = (BlockSyntax)rewriter.VisitBlock(localFunction.Body); - LocalFunctionStatementSyntax newNode = localFunction.WithBody(newBody); + LocalFunctionStatementSyntax newNode = localFunction.WithBody(newBody); - newNode = ModifierList.Instance.Insert(newNode, SyntaxKind.AsyncKeyword); + newNode = ModifierList.Instance.Insert(newNode, SyntaxKind.AsyncKeyword); - return await document.ReplaceNodeAsync(localFunction, newNode, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(localFunction, newNode, cancellationToken).ConfigureAwait(false); + } case SimpleLambdaExpressionSyntax lambda: - { - var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(lambda, cancellationToken); + { + var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(lambda, cancellationToken); - UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); + UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); - var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)lambda.Body); + var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)lambda.Body); - SimpleLambdaExpressionSyntax newNode = lambda - .WithBody(newBody) - .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); + SimpleLambdaExpressionSyntax newNode = lambda + .WithBody(newBody) + .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); - return await document.ReplaceNodeAsync(lambda, newNode, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(lambda, newNode, cancellationToken).ConfigureAwait(false); + } case ParenthesizedLambdaExpressionSyntax lambda: - { - var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(lambda, cancellationToken); + { + var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(lambda, cancellationToken); - UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); + UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); - var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)lambda.Body); + var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)lambda.Body); - ParenthesizedLambdaExpressionSyntax newNode = lambda - .WithBody(newBody) - .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); + ParenthesizedLambdaExpressionSyntax newNode = lambda + .WithBody(newBody) + .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); - return await document.ReplaceNodeAsync(lambda, newNode, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(lambda, newNode, cancellationToken).ConfigureAwait(false); + } case AnonymousMethodExpressionSyntax anonymousMethod: - { - var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(anonymousMethod, cancellationToken); + { + var methodSymbol = (IMethodSymbol)semanticModel.GetSymbol(anonymousMethod, cancellationToken); - UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); + UseAsyncAwaitRewriter rewriter = UseAsyncAwaitRewriter.Create(methodSymbol, semanticModel, node.SpanStart); - var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)anonymousMethod.Body); + var newBody = (BlockSyntax)rewriter.VisitBlock((BlockSyntax)anonymousMethod.Body); - AnonymousMethodExpressionSyntax newNode = anonymousMethod - .WithBody(newBody) - .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); + AnonymousMethodExpressionSyntax newNode = anonymousMethod + .WithBody(newBody) + .WithAsyncKeyword(Token(SyntaxKind.AsyncKeyword)); - return await document.ReplaceNodeAsync(anonymousMethod, newNode, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(anonymousMethod, newNode, cancellationToken).ConfigureAwait(false); + } } throw new InvalidOperationException(); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs index a8ecc9512f..cb1e2ae9a4 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseAutoPropertyCodeFixProvider.cs @@ -90,46 +90,46 @@ public static async Task RefactorAsync( switch (node.Kind()) { case SyntaxKind.IdentifierName: + { + SyntaxNode newNode = null; + + if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) + && ((MemberAccessExpressionSyntax)node.Parent).Name == node) { - SyntaxNode newNode = null; - - if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) - && ((MemberAccessExpressionSyntax)node.Parent).Name == node) - { - newNode = IdentifierName(propertyIdentifier); - } - else if (node.IsParentKind(SyntaxKind.NameMemberCref)) - { - newNode = IdentifierName(propertyIdentifier); - } - else if (propertySymbol.IsStatic) - { - newNode = SimpleMemberAccessExpression( - propertySymbol.ContainingType.ToTypeSyntax(), - (SimpleNameSyntax)ParseName(propertySymbol.ToDisplayString(SymbolDisplayFormats.DisplayName))) - .WithSimplifierAnnotation(); - } - else - { - newNode = IdentifierName(propertyIdentifier).QualifyWithThis(); - } - - return newNode.WithTriviaFrom(node); + newNode = IdentifierName(propertyIdentifier); } - case SyntaxKind.PropertyDeclaration: + else if (node.IsParentKind(SyntaxKind.NameMemberCref)) { - return CreateAutoProperty(propertyDeclaration, variableDeclarator.Initializer); + newNode = IdentifierName(propertyIdentifier); } - case SyntaxKind.VariableDeclarator: - case SyntaxKind.FieldDeclaration: + else if (propertySymbol.IsStatic) { - return node.WithAdditionalAnnotations(_removeAnnotation); + newNode = SimpleMemberAccessExpression( + propertySymbol.ContainingType.ToTypeSyntax(), + (SimpleNameSyntax)ParseName(propertySymbol.ToDisplayString(SymbolDisplayFormats.DisplayName))) + .WithSimplifierAnnotation(); } - default: + else { - SyntaxDebug.Fail(node); - return node; + newNode = IdentifierName(propertyIdentifier).QualifyWithThis(); } + + return newNode.WithTriviaFrom(node); + } + case SyntaxKind.PropertyDeclaration: + { + return CreateAutoProperty(propertyDeclaration, variableDeclarator.Initializer); + } + case SyntaxKind.VariableDeclarator: + case SyntaxKind.FieldDeclaration: + { + return node.WithAdditionalAnnotations(_removeAnnotation); + } + default: + { + SyntaxDebug.Fail(node); + return node; + } } }); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseCoalesceExpressionCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseCoalesceExpressionCodeFixProvider.cs index e93296cc56..015e26c723 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseCoalesceExpressionCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseCoalesceExpressionCodeFixProvider.cs @@ -75,61 +75,61 @@ private static async Task RefactorAsync( switch (statement) { case IfStatementSyntax ifStatement: - { - var expressionStatement = (ExpressionStatementSyntax)ifStatement.SingleNonBlockStatementOrDefault(); - - var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; + { + var expressionStatement = (ExpressionStatementSyntax)ifStatement.SingleNonBlockStatementOrDefault(); - ExpressionSyntax left = assignment.Left; - ExpressionSyntax right = assignment.Right; + var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; - BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( - left.WithoutLeadingTrivia().WithTrailingTrivia(Space), - right.WithLeadingTrivia(Space), - semanticModel.GetTypeSymbol(left, cancellationToken), - semanticModel.GetTypeSymbol(right, cancellationToken)); + ExpressionSyntax left = assignment.Left; + ExpressionSyntax right = assignment.Right; - AssignmentExpressionSyntax newAssignment = assignment.WithRight(coalesceExpression.WithTriviaFrom(right)); + BinaryExpressionSyntax coalesceExpression = CreateCoalesceExpression( + left.WithoutLeadingTrivia().WithTrailingTrivia(Space), + right.WithLeadingTrivia(Space), + semanticModel.GetTypeSymbol(left, cancellationToken), + semanticModel.GetTypeSymbol(right, cancellationToken)); - ExpressionStatementSyntax newNode = expressionStatement.WithExpression(newAssignment); + AssignmentExpressionSyntax newAssignment = assignment.WithRight(coalesceExpression.WithTriviaFrom(right)); - IEnumerable trivia = ifStatement.DescendantTrivia(TextSpan.FromBounds(ifStatement.SpanStart, expressionStatement.SpanStart)); + ExpressionStatementSyntax newNode = expressionStatement.WithExpression(newAssignment); - if (trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia())) - { - newNode = newNode.WithLeadingTrivia(ifStatement.GetLeadingTrivia()); - } - else - { - newNode = newNode - .WithLeadingTrivia(ifStatement.GetLeadingTrivia().Concat(trivia)) - .WithFormatterAnnotation(); - } + IEnumerable trivia = ifStatement.DescendantTrivia(TextSpan.FromBounds(ifStatement.SpanStart, expressionStatement.SpanStart)); - return await document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken).ConfigureAwait(false); - } - case ExpressionStatementSyntax expressionStatement: + if (trivia.All(f => f.IsWhitespaceOrEndOfLineTrivia())) { - var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; - - return await RefactorAsync(document, expressionStatement, (IfStatementSyntax)statements[index + 1], index, statementsInfo, assignment.Right, semanticModel, cancellationToken).ConfigureAwait(false); + newNode = newNode.WithLeadingTrivia(ifStatement.GetLeadingTrivia()); } - case LocalDeclarationStatementSyntax localDeclaration: + else { - ExpressionSyntax value = localDeclaration - .Declaration - .Variables[0] - .Initializer - .Value; - - return await RefactorAsync(document, localDeclaration, (IfStatementSyntax)statements[index + 1], index, statementsInfo, value, semanticModel, cancellationToken).ConfigureAwait(false); + newNode = newNode + .WithLeadingTrivia(ifStatement.GetLeadingTrivia().Concat(trivia)) + .WithFormatterAnnotation(); } + + return await document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken).ConfigureAwait(false); + } + case ExpressionStatementSyntax expressionStatement: + { + var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; + + return await RefactorAsync(document, expressionStatement, (IfStatementSyntax)statements[index + 1], index, statementsInfo, assignment.Right, semanticModel, cancellationToken).ConfigureAwait(false); + } + case LocalDeclarationStatementSyntax localDeclaration: + { + ExpressionSyntax value = localDeclaration + .Declaration + .Variables[0] + .Initializer + .Value; + + return await RefactorAsync(document, localDeclaration, (IfStatementSyntax)statements[index + 1], index, statementsInfo, value, semanticModel, cancellationToken).ConfigureAwait(false); + } default: - { - SyntaxDebug.Fail(statement); + { + SyntaxDebug.Fail(statement); - return document; - } + return document; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseConditionalAccessCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseConditionalAccessCodeFixProvider.cs index 365eebd20f..d43e2a8765 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseConditionalAccessCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseConditionalAccessCodeFixProvider.cs @@ -50,25 +50,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => UseConditionalAccessAsync(context.Document, (BinaryExpressionSyntax)node, ct), - GetEquivalenceKey(DiagnosticIdentifiers.UseConditionalAccess)); + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => UseConditionalAccessAsync(context.Document, (BinaryExpressionSyntax)node, ct), + GetEquivalenceKey(DiagnosticIdentifiers.UseConditionalAccess)); - context.RegisterCodeFix(codeAction, context.Diagnostics); - break; - } + context.RegisterCodeFix(codeAction, context.Diagnostics); + break; + } case SyntaxKind.IfStatement: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => UseConditionalAccessAsync(context.Document, (IfStatementSyntax)node, ct), - GetEquivalenceKey(DiagnosticIdentifiers.UseConditionalAccess)); + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => UseConditionalAccessAsync(context.Document, (IfStatementSyntax)node, ct), + GetEquivalenceKey(DiagnosticIdentifiers.UseConditionalAccess)); - context.RegisterCodeFix(codeAction, context.Diagnostics); - break; - } + context.RegisterCodeFix(codeAction, context.Diagnostics); + break; + } } } @@ -129,19 +129,19 @@ private static async Task UseConditionalAccessAsync( case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: - { - break; - } + { + break; + } case SyntaxKind.LogicalNotExpression: - { - builder.Append((kind == SyntaxKind.LogicalAndExpression) ? " == false" : " != true"); - break; - } + { + builder.Append((kind == SyntaxKind.LogicalAndExpression) ? " == false" : " != true"); + break; + } default: - { - builder.Append((kind == SyntaxKind.LogicalAndExpression) ? " == true" : " != false"); - break; - } + { + builder.Append((kind == SyntaxKind.LogicalAndExpression) ? " == true" : " != false"); + break; + } } if (parenDiff < 0) diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseEmptyStringLiteralOrStringEmptyCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseEmptyStringLiteralOrStringEmptyCodeFixProvider.cs index 4c704bd5c1..a2c49a1eec 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseEmptyStringLiteralOrStringEmptyCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseEmptyStringLiteralOrStringEmptyCodeFixProvider.cs @@ -42,32 +42,32 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)node; + { + var memberAccessExpression = (MemberAccessExpressionSyntax)node; - CodeAction codeAction = CodeAction.Create( - "Use empty string literal", - ct => UseEmptyStringLiteralInsteadOfStringEmptyAsync(document, memberAccessExpression, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Use empty string literal", + ct => UseEmptyStringLiteralInsteadOfStringEmptyAsync(document, memberAccessExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case SyntaxKind.StringLiteralExpression: case SyntaxKind.InterpolatedStringExpression: - { - CodeAction codeAction = CodeAction.Create( - "Use 'string.Empty'", - ct => UseStringEmptyInsteadOfEmptyStringLiteralAsync(document, (ExpressionSyntax)node, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Use 'string.Empty'", + ct => UseStringEmptyInsteadOfEmptyStringLiteralAsync(document, (ExpressionSyntax)node, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseExplicitTypeInsteadOfVarInForEachCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseExplicitTypeInsteadOfVarInForEachCodeFixProvider.cs index d5a4f06dd6..94ecd0c49f 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseExplicitTypeInsteadOfVarInForEachCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseExplicitTypeInsteadOfVarInForEachCodeFixProvider.cs @@ -47,32 +47,32 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node) { case ForEachStatementSyntax forEachStatement: - { - type = forEachStatement.Type; + { + type = forEachStatement.Type; - typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; - break; - } + typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; + break; + } case ForEachVariableStatementSyntax forEachVariableStatement: - { - var declarationExpression = (DeclarationExpressionSyntax)forEachVariableStatement.Variable; + { + var declarationExpression = (DeclarationExpressionSyntax)forEachVariableStatement.Variable; - type = declarationExpression.Type; + type = declarationExpression.Type; - typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; - break; - } + typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; + break; + } case DeclarationExpressionSyntax declarationExpression: - { - type = declarationExpression.Type; + { + type = declarationExpression.Type; - typeSymbol = semanticModel.GetTypeSymbol(declarationExpression, context.CancellationToken); - break; - } + typeSymbol = semanticModel.GetTypeSymbol(declarationExpression, context.CancellationToken); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } CodeAction codeAction = CodeActionFactory.UseExplicitType(document, type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic)); diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseStringComparisonCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseStringComparisonCodeFixProvider.cs index 9fb7bcf35e..31541b4103 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseStringComparisonCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseStringComparisonCodeFixProvider.cs @@ -50,62 +50,62 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - var binaryExpression = (BinaryExpressionSyntax)node; - - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(binaryExpression.Left.WalkDownParentheses()); + { + var binaryExpression = (BinaryExpressionSyntax)node; - if (!invocationInfo.Success) - invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo((InvocationExpressionSyntax)binaryExpression.Right.WalkDownParentheses()); + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(binaryExpression.Left.WalkDownParentheses()); - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (!invocationInfo.Success) + invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo((InvocationExpressionSyntax)binaryExpression.Right.WalkDownParentheses()); - INamedTypeSymbol comparisonSymbol = semanticModel.GetTypeByMetadataName("System.StringComparison"); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!invocationInfo.NameText.EndsWith("Invariant", StringComparison.Ordinal) - || !RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "InvariantCultureIgnoreCase")) - { - RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "OrdinalIgnoreCase"); - RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "CurrentCultureIgnoreCase"); - } + INamedTypeSymbol comparisonSymbol = semanticModel.GetTypeByMetadataName("System.StringComparison"); - break; - } - case SyntaxKind.InvocationExpression: + if (!invocationInfo.NameText.EndsWith("Invariant", StringComparison.Ordinal) + || !RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "InvariantCultureIgnoreCase")) { - var invocationExpression = (InvocationExpressionSyntax)node; + RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "OrdinalIgnoreCase"); + RegisterCodeFix(context, diagnostic, binaryExpression, comparisonSymbol, "CurrentCultureIgnoreCase"); + } - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); + break; + } + case SyntaxKind.InvocationExpression: + { + var invocationExpression = (InvocationExpressionSyntax)node; - SeparatedSyntaxList arguments = invocationInfo.Arguments; + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); - InvocationExpressionSyntax invocationExpression2; + SeparatedSyntaxList arguments = invocationInfo.Arguments; - if (arguments.Count == 1) - { - invocationExpression2 = (InvocationExpressionSyntax)invocationInfo.Expression; - } - else - { - invocationExpression2 = (arguments[0].Expression.WalkDownParentheses() as InvocationExpressionSyntax) - ?? (InvocationExpressionSyntax)arguments[1].Expression.WalkDownParentheses(); - } + InvocationExpressionSyntax invocationExpression2; - SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression2); + if (arguments.Count == 1) + { + invocationExpression2 = (InvocationExpressionSyntax)invocationInfo.Expression; + } + else + { + invocationExpression2 = (arguments[0].Expression.WalkDownParentheses() as InvocationExpressionSyntax) + ?? (InvocationExpressionSyntax)arguments[1].Expression.WalkDownParentheses(); + } - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SimpleMemberInvocationExpressionInfo invocationInfo2 = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression2); - INamedTypeSymbol comparisonSymbol = semanticModel.GetTypeByMetadataName("System.StringComparison"); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!invocationInfo2.NameText.EndsWith("Invariant", StringComparison.Ordinal) - || !RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "InvariantCultureIgnoreCase", semanticModel)) - { - RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "OrdinalIgnoreCase", semanticModel); - RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "CurrentCultureIgnoreCase", semanticModel); - } + INamedTypeSymbol comparisonSymbol = semanticModel.GetTypeByMetadataName("System.StringComparison"); - break; + if (!invocationInfo2.NameText.EndsWith("Invariant", StringComparison.Ordinal) + || !RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "InvariantCultureIgnoreCase", semanticModel)) + { + RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "OrdinalIgnoreCase", semanticModel); + RegisterCodeFix(context, diagnostic, invocationInfo, comparisonSymbol, "CurrentCultureIgnoreCase", semanticModel); } + + break; + } } } @@ -268,22 +268,22 @@ private static ArgumentSyntax CreateArgument(ExpressionSyntax expression) switch (expression.Kind()) { case SyntaxKind.StringLiteralExpression: - { - return Argument(expression); - } + { + return Argument(expression); + } case SyntaxKind.InvocationExpression: - { - var invocation = (InvocationExpressionSyntax)expression; + { + var invocation = (InvocationExpressionSyntax)expression; - var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; + var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; - return Argument(memberAccess.Expression).WithTriviaFrom(expression); - } + return Argument(memberAccess.Expression).WithTriviaFrom(expression); + } default: - { - SyntaxDebug.Fail(expression); - return Argument(expression); - } + { + SyntaxDebug.Fail(expression); + return Argument(expression); + } } } @@ -294,22 +294,22 @@ private static ArgumentSyntax CreateArgument(ArgumentSyntax argument) switch (expression.Kind()) { case SyntaxKind.StringLiteralExpression: - { - return argument; - } + { + return argument; + } case SyntaxKind.InvocationExpression: - { - var invocation = (InvocationExpressionSyntax)expression; + { + var invocation = (InvocationExpressionSyntax)expression; - var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; + var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; - return Argument(memberAccess.Expression).WithTriviaFrom(argument); - } + return Argument(memberAccess.Expression).WithTriviaFrom(argument); + } default: - { - SyntaxDebug.Fail(expression); - return argument; - } + { + SyntaxDebug.Fail(expression); + return argument; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarInsteadOfExplicitTypeCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarInsteadOfExplicitTypeCodeFixProvider.cs index 4ab4984c1a..8d0c40a20e 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarInsteadOfExplicitTypeCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarInsteadOfExplicitTypeCodeFixProvider.cs @@ -48,23 +48,23 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node) { case TypeSyntax type: - { - CodeAction codeAction = CodeActionFactory.ChangeTypeToVar(document, type, equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.ChangeTypeToVar(document, type, equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case TupleExpressionSyntax tupleExpression: - { - CodeAction codeAction = CodeActionFactory.ChangeTypeToVar(document, tupleExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeActionFactory.ChangeTypeToVar(document, tupleExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarOrExplicitTypeCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarOrExplicitTypeCodeFixProvider.cs index f2cf68dff3..3a480cb4fc 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarOrExplicitTypeCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/UseVarOrExplicitTypeCodeFixProvider.cs @@ -75,83 +75,83 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node) { case TupleExpressionSyntax tupleExpression: - { - CodeAction codeAction = ChangeTypeToVar(document, tupleExpression, equivalenceKey: GetEquivalenceKey(diagnostic, "ToImplicit")); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = ChangeTypeToVar(document, tupleExpression, equivalenceKey: GetEquivalenceKey(diagnostic, "ToImplicit")); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case VariableDeclarationSyntax variableDeclaration: + { + ExpressionSyntax value = variableDeclaration.Variables[0].Initializer.Value; + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(value, context.CancellationToken); + + if (typeSymbol is null) { - ExpressionSyntax value = variableDeclaration.Variables[0].Initializer.Value; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(value, context.CancellationToken); + var localSymbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], context.CancellationToken) as ILocalSymbol; - if (typeSymbol is null) + if (localSymbol is not null) { - var localSymbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], context.CancellationToken) as ILocalSymbol; - - if (localSymbol is not null) - { - typeSymbol = localSymbol.Type; - value = value.WalkDownParentheses(); - - Debug.Assert( - value.IsKind(SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression), - value.Kind().ToString()); - - if (value.IsKind(SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression)) - typeSymbol = typeSymbol.WithNullableAnnotation(NullableAnnotation.NotAnnotated); - } - else - { - SyntaxDebug.Fail(variableDeclaration.Variables[0]); - return; - } - } + typeSymbol = localSymbol.Type; + value = value.WalkDownParentheses(); - CodeAction codeAction = UseExplicitType(document, variableDeclaration.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case DeclarationExpressionSyntax declarationExpression: - { - ITypeSymbol typeSymbol = null; - if (declarationExpression.Parent is AssignmentExpressionSyntax assignment) - { - typeSymbol = semanticModel.GetTypeSymbol(assignment.Right, context.CancellationToken); - } - else if (declarationExpression.Parent is ArgumentSyntax argument) - { - IParameterSymbol parameterSymbol = DetermineParameterHelper.DetermineParameter(argument, semanticModel, cancellationToken: context.CancellationToken); - typeSymbol = parameterSymbol?.Type; - } + Debug.Assert( + value.IsKind(SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression), + value.Kind().ToString()); - if (typeSymbol is null) + if (value.IsKind(SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression)) + typeSymbol = typeSymbol.WithNullableAnnotation(NullableAnnotation.NotAnnotated); + } + else { - var localSymbol = semanticModel.GetDeclaredSymbol(declarationExpression.Designation, context.CancellationToken) as ILocalSymbol; - typeSymbol = (localSymbol?.Type) ?? semanticModel.GetTypeSymbol(declarationExpression, context.CancellationToken); + SyntaxDebug.Fail(variableDeclaration.Variables[0]); + return; } + } - CodeAction codeAction = UseExplicitType(document, declarationExpression.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); - context.RegisterCodeFix(codeAction, diagnostic); - break; + CodeAction codeAction = UseExplicitType(document, variableDeclaration.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case DeclarationExpressionSyntax declarationExpression: + { + ITypeSymbol typeSymbol = null; + if (declarationExpression.Parent is AssignmentExpressionSyntax assignment) + { + typeSymbol = semanticModel.GetTypeSymbol(assignment.Right, context.CancellationToken); } - case ForEachStatementSyntax forEachStatement: + else if (declarationExpression.Parent is ArgumentSyntax argument) { - ITypeSymbol typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; + IParameterSymbol parameterSymbol = DetermineParameterHelper.DetermineParameter(argument, semanticModel, cancellationToken: context.CancellationToken); + typeSymbol = parameterSymbol?.Type; + } - CodeAction codeAction = UseExplicitType(document, forEachStatement.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); - context.RegisterCodeFix(codeAction, diagnostic); - break; + if (typeSymbol is null) + { + var localSymbol = semanticModel.GetDeclaredSymbol(declarationExpression.Designation, context.CancellationToken) as ILocalSymbol; + typeSymbol = (localSymbol?.Type) ?? semanticModel.GetTypeSymbol(declarationExpression, context.CancellationToken); } + + CodeAction codeAction = UseExplicitType(document, declarationExpression.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case ForEachStatementSyntax forEachStatement: + { + ITypeSymbol typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; + + CodeAction codeAction = UseExplicitType(document, forEachStatement.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case ForEachVariableStatementSyntax forEachVariableStatement: - { - var declarationExpression = (DeclarationExpressionSyntax)forEachVariableStatement.Variable; - ITypeSymbol typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; + { + var declarationExpression = (DeclarationExpressionSyntax)forEachVariableStatement.Variable; + ITypeSymbol typeSymbol = semanticModel.GetForEachStatementInfo((CommonForEachStatementSyntax)node).ElementType; - CodeAction codeAction = UseExplicitType(document, declarationExpression.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + CodeAction codeAction = UseExplicitType(document, declarationExpression.Type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic, "ToExplicit")); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/VariableDeclaratorCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/VariableDeclaratorCodeFixProvider.cs index ec07cdc202..d61f1775f2 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/VariableDeclaratorCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/VariableDeclaratorCodeFixProvider.cs @@ -33,15 +33,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveRedundantFieldInitialization: - { - CodeAction codeAction = CodeAction.Create( - "Remove redundant initialization", - ct => RemoveRedundantFieldInitializationAsync(context.Document, declarator, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove redundant initialization", + ct => RemoveRedundantFieldInitializationAsync(context.Document, declarator, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/WhileStatementCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/WhileStatementCodeFixProvider.cs index c5add039c2..b72225f3a6 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/WhileStatementCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/WhileStatementCodeFixProvider.cs @@ -41,37 +41,37 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AvoidUsageOfWhileStatementToCreateInfiniteLoop: - { - CodeAction codeAction = CodeAction.Create( - "Convert to 'for'", - ct => - { - ForStatementSyntax forStatement = SyntaxRefactorings.ConvertWhileStatementToForStatement(whileStatement) - .WithFormatterAnnotation(); - - return document.ReplaceNodeAsync(whileStatement, forStatement, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Convert to 'for'", + ct => + { + ForStatementSyntax forStatement = SyntaxRefactorings.ConvertWhileStatementToForStatement(whileStatement) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(whileStatement, forStatement, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseForStatementInsteadOfWhileStatement: - { - CodeAction codeAction = CodeAction.Create( - "Convert to 'for'", - ct => - { - return ConvertWhileStatementToForStatementAsync( - document, - whileStatement, - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Convert to 'for'", + ct => + { + return ConvertWhileStatementToForStatementAsync( + document, + whileStatement, + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/CodeFixes/XmlNodeCodeFixProvider.cs b/src/Analyzers.CodeFixes/CSharp/CodeFixes/XmlNodeCodeFixProvider.cs index 1a715e415f..1991c8b92d 100644 --- a/src/Analyzers.CodeFixes/CSharp/CodeFixes/XmlNodeCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CSharp/CodeFixes/XmlNodeCodeFixProvider.cs @@ -45,33 +45,33 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case DiagnosticIdentifiers.UnusedElementInDocumentationComment: case DiagnosticIdentifiers.InvalidReferenceInDocumentationComment: - { - XmlElementInfo elementInfo = SyntaxInfo.XmlElementInfo(xmlNode); + { + XmlElementInfo elementInfo = SyntaxInfo.XmlElementInfo(xmlNode); - string name = elementInfo.LocalName; + string name = elementInfo.LocalName; - CodeAction codeAction = CodeAction.Create( - $"Remove '{name}' element", - ct => RemoveUnusedElementInDocumentationCommentAsync(document, elementInfo, ct), - GetEquivalenceKey(diagnostic, name)); + CodeAction codeAction = CodeAction.Create( + $"Remove '{name}' element", + ct => RemoveUnusedElementInDocumentationCommentAsync(document, elementInfo, ct), + GetEquivalenceKey(diagnostic, name)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.FixDocumentationCommentTag: - { - XmlElementInfo elementInfo = SyntaxInfo.XmlElementInfo(xmlNode); - - CodeAction codeAction = CodeAction.Create( - (elementInfo.GetTag() == XmlTag.C) - ? "Rename tag to 'code'" - : "Rename tag to 'c'", - ct => FixDocumentationCommentTagAsync(document, elementInfo, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + XmlElementInfo elementInfo = SyntaxInfo.XmlElementInfo(xmlNode); + + CodeAction codeAction = CodeAction.Create( + (elementInfo.GetTag() == XmlTag.C) + ? "Rename tag to 'code'" + : "Rename tag to 'c'", + ct => FixDocumentationCommentTagAsync(document, elementInfo, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/JoinStringExpressionsRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/JoinStringExpressionsRefactoring.cs index 8627e1e65d..7a0f371c73 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/JoinStringExpressionsRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/JoinStringExpressionsRefactoring.cs @@ -50,15 +50,15 @@ public static Task RefactorAsync( switch (expression.Kind()) { case SyntaxKind.StringLiteralExpression: - { - builder.Append((LiteralExpressionSyntax)expression); - break; - } + { + builder.Append((LiteralExpressionSyntax)expression); + break; + } case SyntaxKind.InterpolatedStringExpression: - { - builder.Append((InterpolatedStringExpressionSyntax)expression); - break; - } + { + builder.Append((InterpolatedStringExpressionSyntax)expression); + break; + } } } diff --git a/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveSemicolonAtEndOfDeclarationRefactoring.cs b/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveSemicolonAtEndOfDeclarationRefactoring.cs index 0cecb69afe..5df16872b6 100644 --- a/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveSemicolonAtEndOfDeclarationRefactoring.cs +++ b/src/Analyzers.CodeFixes/CSharp/Refactorings/RemoveSemicolonAtEndOfDeclarationRefactoring.cs @@ -25,40 +25,40 @@ private static MemberDeclarationSyntax GetNewMemberDeclaration(MemberDeclaration switch (memberDeclaration) { case NamespaceDeclarationSyntax declaration: - { - return declaration - .WithSemicolonToken(default(SyntaxToken)) - .WithCloseBraceToken(declaration.CloseBraceToken - .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); - } + { + return declaration + .WithSemicolonToken(default(SyntaxToken)) + .WithCloseBraceToken(declaration.CloseBraceToken + .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); + } case ClassDeclarationSyntax declaration: - { - return declaration - .WithSemicolonToken(default(SyntaxToken)) - .WithCloseBraceToken(declaration.CloseBraceToken - .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); - } + { + return declaration + .WithSemicolonToken(default(SyntaxToken)) + .WithCloseBraceToken(declaration.CloseBraceToken + .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); + } case InterfaceDeclarationSyntax declaration: - { - return declaration - .WithSemicolonToken(default(SyntaxToken)) - .WithCloseBraceToken(declaration.CloseBraceToken - .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); - } + { + return declaration + .WithSemicolonToken(default(SyntaxToken)) + .WithCloseBraceToken(declaration.CloseBraceToken + .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); + } case StructDeclarationSyntax declaration: - { - return declaration - .WithSemicolonToken(default(SyntaxToken)) - .WithCloseBraceToken(declaration.CloseBraceToken - .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); - } + { + return declaration + .WithSemicolonToken(default(SyntaxToken)) + .WithCloseBraceToken(declaration.CloseBraceToken + .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); + } case EnumDeclarationSyntax declaration: - { - return declaration - .WithSemicolonToken(default(SyntaxToken)) - .WithCloseBraceToken(declaration.CloseBraceToken - .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); - } + { + return declaration + .WithSemicolonToken(default(SyntaxToken)) + .WithCloseBraceToken(declaration.CloseBraceToken + .WithTrailingTrivia(GetNewTrailingTrivia(declaration.CloseBraceToken, declaration.SemicolonToken))); + } } return null; diff --git a/src/Analyzers.CodeFixes/CodeFixes/WhitespaceTriviaCodeFixProvider.cs b/src/Analyzers.CodeFixes/CodeFixes/WhitespaceTriviaCodeFixProvider.cs index 89a11baa0c..b5f8c0fc9d 100644 --- a/src/Analyzers.CodeFixes/CodeFixes/WhitespaceTriviaCodeFixProvider.cs +++ b/src/Analyzers.CodeFixes/CodeFixes/WhitespaceTriviaCodeFixProvider.cs @@ -45,25 +45,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.RemoveTrailingWhitespace: - { - CodeAction codeAction = CodeAction.Create( - "Remove trailing white-space", - ct => context.Document.WithTextChangeAsync(span, "", ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove trailing white-space", + ct => context.Document.WithTextChangeAsync(span, "", ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.RemoveUnnecessaryBlankLine: - { - CodeAction codeAction = CodeAction.Create( - "Remove blank line", - ct => context.Document.WithTextChangeAsync(span, "", ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Remove blank line", + ct => context.Document.WithTextChangeAsync(span, "", ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs index 7210738e69..14720c08d5 100644 --- a/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AddParagraphToDocumentationCommentAnalyzer.cs @@ -146,31 +146,31 @@ internal static (TextSpan span1, TextSpan span2, List spans) FindFixab switch (state) { case State.BeforeParagraph: - { - state = State.Paragraph; - index = node.SpanStart; - last = node; - break; - } + { + state = State.Paragraph; + index = node.SpanStart; + last = node; + break; + } case State.Paragraph: - { - last = node; - break; - } + { + last = node; + break; + } case State.NewLine: case State.WhiteSpaceAfterNewLine: - { - state = State.Paragraph; - last = node; - break; - } + { + state = State.Paragraph; + last = node; + break; + } case State.WhiteSpaceBetweenParagraphs: - { - state = State.Paragraph; - index2 = node.SpanStart; - last = node; - break; - } + { + state = State.Paragraph; + index2 = node.SpanStart; + last = node; + break; + } } } else if (kind == SyntaxKind.XmlText) @@ -184,112 +184,112 @@ internal static (TextSpan span1, TextSpan span2, List spans) FindFixab switch (token.Kind()) { case SyntaxKind.XmlTextLiteralToken: + { + switch (state) { - switch (state) + case State.BeforeParagraph: { - case State.BeforeParagraph: - { - if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) - { - state = State.Paragraph; - index = token.SpanStart; - last = token; - } - - break; - } - case State.Paragraph: - { - last = token; - break; - } - case State.NewLine: - { - if (StringUtility.IsEmptyOrWhitespace(token.ValueText)) - { - state = State.WhiteSpaceAfterNewLine; - } - else - { - state = State.Paragraph; - last = token; - } - - break; - } - case State.WhiteSpaceAfterNewLine: - { - if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) - { - state = State.Paragraph; - last = token; - } - - break; - } - case State.WhiteSpaceBetweenParagraphs: - { - if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) - { - state = State.Paragraph; - index2 = token.SpanStart; - last = token; - } - - break; - } + if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) + { + state = State.Paragraph; + index = token.SpanStart; + last = token; + } + + break; + } + case State.Paragraph: + { + last = token; + break; + } + case State.NewLine: + { + if (StringUtility.IsEmptyOrWhitespace(token.ValueText)) + { + state = State.WhiteSpaceAfterNewLine; + } + else + { + state = State.Paragraph; + last = token; + } + + break; } + case State.WhiteSpaceAfterNewLine: + { + if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) + { + state = State.Paragraph; + last = token; + } - break; + break; + } + case State.WhiteSpaceBetweenParagraphs: + { + if (!StringUtility.IsEmptyOrWhitespace(token.ValueText)) + { + state = State.Paragraph; + index2 = token.SpanStart; + last = token; + } + + break; + } } + + break; + } case SyntaxKind.XmlTextLiteralNewLineToken: + { + switch (state) { - switch (state) + case State.BeforeParagraph: { - case State.BeforeParagraph: - { - break; - } - case State.Paragraph: - { - state = State.NewLine; - break; - } - case State.NewLine: - case State.WhiteSpaceAfterNewLine: + break; + } + case State.Paragraph: + { + state = State.NewLine; + break; + } + case State.NewLine: + case State.WhiteSpaceAfterNewLine: + { + if (index2 != -1) + { + endIndex2 = last.Span.End; + + if (!stopOnFirstMatch) { - if (index2 != -1) - { - endIndex2 = last.Span.End; - - if (!stopOnFirstMatch) - { - if (spans is null) - spans = new List() { TextSpan.FromBounds(index, endIndex) }; - - spans.Add(TextSpan.FromBounds(index2, endIndex2)); - index = index2; - index2 = -1; - } - else - { - return (TextSpan.FromBounds(index, endIndex), TextSpan.FromBounds(index2, endIndex2), default); - } - } - - endIndex = last.Span.End; - last = default; - state = State.WhiteSpaceBetweenParagraphs; - break; + if (spans is null) + spans = new List() { TextSpan.FromBounds(index, endIndex) }; + + spans.Add(TextSpan.FromBounds(index2, endIndex2)); + index = index2; + index2 = -1; } - case State.WhiteSpaceBetweenParagraphs: + else { - break; + return (TextSpan.FromBounds(index, endIndex), TextSpan.FromBounds(index2, endIndex2), default); } - } + } - break; + endIndex = last.Span.End; + last = default; + state = State.WhiteSpaceBetweenParagraphs; + break; + } + case State.WhiteSpaceBetweenParagraphs: + { + break; + } } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs index f1e6d703ad..1b48a2c375 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidBoxingOfValueTypeAnalysis.cs @@ -29,46 +29,46 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv switch (parameters.Length) { case 1: + { + if (methodSymbol.IsName("Append")) { - if (methodSymbol.IsName("Append")) + ArgumentSyntax argument = invocationInfo.Arguments.SingleOrDefault(shouldThrow: false); + + if (argument is not null) { - ArgumentSyntax argument = invocationInfo.Arguments.SingleOrDefault(shouldThrow: false); + ExpressionSyntax expression = argument.Expression; - if (argument is not null) + if (!expression.IsKind(SyntaxKind.InterpolatedStringExpression, SyntaxKind.AddExpression) + && parameters[0].Type.IsObject() + && context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken)?.IsValueType == true) { - ExpressionSyntax expression = argument.Expression; - - if (!expression.IsKind(SyntaxKind.InterpolatedStringExpression, SyntaxKind.AddExpression) - && parameters[0].Type.IsObject() - && context.SemanticModel.GetTypeSymbol(expression, context.CancellationToken)?.IsValueType == true) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidBoxingOfValueType, argument); - return; - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidBoxingOfValueType, argument); + return; } } - - break; } + + break; + } case 2: + { + if (methodSymbol.IsName("Insert") + && parameters[0].Type.SpecialType == SpecialType.System_Int32 + && parameters[1].Type.SpecialType == SpecialType.System_Object) { - if (methodSymbol.IsName("Insert") - && parameters[0].Type.SpecialType == SpecialType.System_Int32 - && parameters[1].Type.SpecialType == SpecialType.System_Object) - { - SeparatedSyntaxList arguments = invocationInfo.Arguments; + SeparatedSyntaxList arguments = invocationInfo.Arguments; - if (arguments.Count == 2 - && context.SemanticModel - .GetTypeSymbol(arguments[1].Expression, context.CancellationToken) - .IsValueType) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidBoxingOfValueType, arguments[1]); - } + if (arguments.Count == 2 + && context.SemanticModel + .GetTypeSymbol(arguments[1].Expression, context.CancellationToken) + .IsValueType) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.AvoidBoxingOfValueType, arguments[1]); } - - break; } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs index f52f08a171..28cb7a7624 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs @@ -232,23 +232,23 @@ private static ExpressionSyntax GetAccessExpression(ExpressionSyntax expression) switch (parent?.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)parent; + { + var memberAccessExpression = (MemberAccessExpressionSyntax)parent; - if (expression == memberAccessExpression.Expression) - return memberAccessExpression; + if (expression == memberAccessExpression.Expression) + return memberAccessExpression; - break; - } + break; + } case SyntaxKind.ElementAccessExpression: - { - var elementAccess = (ElementAccessExpressionSyntax)parent; + { + var elementAccess = (ElementAccessExpressionSyntax)parent; - if (expression == elementAccess.Expression) - return elementAccess; + if (expression == elementAccess.Expression) + return elementAccess; - break; - } + break; + } } return null; diff --git a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs index 2d259b2120..13775d60fd 100644 --- a/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BinaryOperatorAnalyzer.cs @@ -273,40 +273,40 @@ private static bool IsCountOrLengthProperty( { case "Count": case "Length": + { + if (semanticModel.GetSymbol(expression, cancellationToken) is IPropertySymbol propertySymbol + && propertySymbol.Type.SpecialType == SpecialType.System_Int32) { - if (semanticModel.GetSymbol(expression, cancellationToken) is IPropertySymbol propertySymbol - && propertySymbol.Type.SpecialType == SpecialType.System_Int32) - { - INamedTypeSymbol containingType = propertySymbol.ContainingType?.OriginalDefinition; + INamedTypeSymbol containingType = propertySymbol.ContainingType?.OriginalDefinition; - switch (containingType?.SpecialType) + switch (containingType?.SpecialType) + { + case SpecialType.System_String: + case SpecialType.System_Array: + case SpecialType.System_Collections_Generic_ICollection_T: + case SpecialType.System_Collections_Generic_IList_T: + case SpecialType.System_Collections_Generic_IReadOnlyCollection_T: + case SpecialType.System_Collections_Generic_IReadOnlyList_T: + { + return true; + } + default: { - case SpecialType.System_String: - case SpecialType.System_Array: - case SpecialType.System_Collections_Generic_ICollection_T: - case SpecialType.System_Collections_Generic_IList_T: - case SpecialType.System_Collections_Generic_IReadOnlyCollection_T: - case SpecialType.System_Collections_Generic_IReadOnlyList_T: - { - return true; - } - default: - { - if (containingType?.ImplementsAny( - SpecialType.System_Collections_Generic_ICollection_T, - SpecialType.System_Collections_Generic_IReadOnlyCollection_T, - allInterfaces: true) == true) - { - return true; - } - - break; - } + if (containingType?.ImplementsAny( + SpecialType.System_Collections_Generic_ICollection_T, + SpecialType.System_Collections_Generic_IReadOnlyCollection_T, + allInterfaces: true) == true) + { + return true; + } + + break; } } - - break; } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs index 506712e068..369dc88516 100644 --- a/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/BooleanLiteralAnalyzer.cs @@ -198,15 +198,15 @@ private static void AnalyzeEqualsNotEquals( switch (AnalyzeExpression(right, context.SemanticModel, context.CancellationToken)) { case AnalysisResult.Boolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: true); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: true); + break; + } case AnalysisResult.LogicalNotWithNullableBoolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); + break; + } } } else if (leftKind == kind2) @@ -214,15 +214,15 @@ private static void AnalyzeEqualsNotEquals( switch (AnalyzeExpression(right, context.SemanticModel, context.CancellationToken)) { case AnalysisResult.Boolean: - { - RemoveRedundantBooleanLiteralAnalysis.ReportDiagnostic(context, binaryExpression, left, right); - break; - } + { + RemoveRedundantBooleanLiteralAnalysis.ReportDiagnostic(context, binaryExpression, left, right); + break; + } case AnalysisResult.LogicalNotWithNullableBoolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); + break; + } } } else @@ -234,15 +234,15 @@ private static void AnalyzeEqualsNotEquals( switch (AnalyzeExpression(left, context.SemanticModel, context.CancellationToken)) { case AnalysisResult.Boolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: true); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: true); + break; + } case AnalysisResult.LogicalNotWithNullableBoolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); + break; + } } } else if (rightKind == kind2) @@ -250,15 +250,15 @@ private static void AnalyzeEqualsNotEquals( switch (AnalyzeExpression(left, context.SemanticModel, context.CancellationToken)) { case AnalysisResult.Boolean: - { - RemoveRedundantBooleanLiteralAnalysis.ReportDiagnostic(context, binaryExpression, left, right); - break; - } + { + RemoveRedundantBooleanLiteralAnalysis.ReportDiagnostic(context, binaryExpression, left, right); + break; + } case AnalysisResult.LogicalNotWithNullableBoolean: - { - SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); - break; - } + { + SimplifyBooleanComparisonAnalysis.ReportDiagnostic(context, binaryExpression, left, right, fadeOut: false); + break; + } } } } @@ -289,42 +289,42 @@ private static AnalysisResult AnalyzeExpression( case SyntaxKind.FalseLiteralExpression: return AnalysisResult.BooleanLiteral; case SyntaxKind.LogicalNotExpression: - { - var logicalNot = (PrefixUnaryExpressionSyntax)expression; + { + var logicalNot = (PrefixUnaryExpressionSyntax)expression; - ExpressionSyntax operand = logicalNot.Operand; + ExpressionSyntax operand = logicalNot.Operand; - if (operand is not null) - { - ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(operand, cancellationToken).ConvertedType; + if (operand is not null) + { + ITypeSymbol typeSymbol = semanticModel.GetTypeInfo(operand, cancellationToken).ConvertedType; - if (typeSymbol is not null) + if (typeSymbol is not null) + { + if (typeSymbol.SpecialType == SpecialType.System_Boolean) + { + return AnalysisResult.Boolean; + } + else if (typeSymbol.IsNullableOf(SpecialType.System_Boolean)) { - if (typeSymbol.SpecialType == SpecialType.System_Boolean) - { - return AnalysisResult.Boolean; - } - else if (typeSymbol.IsNullableOf(SpecialType.System_Boolean)) - { - return AnalysisResult.LogicalNotWithNullableBoolean; - } + return AnalysisResult.LogicalNotWithNullableBoolean; } } - - break; } + + break; + } default: + { + if (semanticModel + .GetTypeInfo(expression, cancellationToken) + .ConvertedType? + .SpecialType == SpecialType.System_Boolean) { - if (semanticModel - .GetTypeInfo(expression, cancellationToken) - .ConvertedType? - .SpecialType == SpecialType.System_Boolean) - { - return AnalysisResult.Boolean; - } - - break; + return AnalysisResult.Boolean; } + + break; + } } return AnalysisResult.None; diff --git a/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs b/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs index fcea9c77bc..9fdd2157ac 100644 --- a/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/CallCastInsteadOfSelectAnalysis.cs @@ -76,17 +76,17 @@ internal static CastExpressionSyntax GetCastExpression(CSharpSyntaxNode node) switch (node.Kind()) { case SyntaxKind.CastExpression: - { - return (CastExpressionSyntax)node; - } + { + return (CastExpressionSyntax)node; + } case SyntaxKind.Block: - { - var block = (BlockSyntax)node; + { + var block = (BlockSyntax)node; - var returnStatement = block.Statements.SingleOrDefault(shouldThrow: false) as ReturnStatementSyntax; + var returnStatement = block.Statements.SingleOrDefault(shouldThrow: false) as ReturnStatementSyntax; - return returnStatement?.Expression as CastExpressionSyntax; - } + return returnStatement?.Expression as CastExpressionSyntax; + } } return null; diff --git a/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs index aba80b54fa..0211e7531c 100644 --- a/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/DefaultExpressionAnalyzer.cs @@ -50,120 +50,120 @@ public static void AnalyzeDefaultExpression(SyntaxNodeAnalysisContext context) switch (parent.Kind()) { case SyntaxKind.EqualsValueClause: - { - parent = parent.Parent; + { + parent = parent.Parent; - switch (parent.Kind()) + switch (parent.Kind()) + { + case SyntaxKind.Parameter: { - case SyntaxKind.Parameter: - { - ReportDiagnostic(); - return; - } - case SyntaxKind.VariableDeclarator: - { - return; - } - default: - { - Debug.WriteLine($"{parent.Kind()} {parent}"); - return; - } + ReportDiagnostic(); + return; + } + case SyntaxKind.VariableDeclarator: + { + return; + } + default: + { + Debug.WriteLine($"{parent.Kind()} {parent}"); + return; } } + } case SyntaxKind.ConditionalExpression: - { - var conditionalExpression = (ConditionalExpressionSyntax)parent; + { + var conditionalExpression = (ConditionalExpressionSyntax)parent; - ExpressionSyntax expression2 = (conditionalExpression.WhenTrue == expression) - ? conditionalExpression.WhenFalse - : conditionalExpression.WhenTrue; + ExpressionSyntax expression2 = (conditionalExpression.WhenTrue == expression) + ? conditionalExpression.WhenFalse + : conditionalExpression.WhenTrue; - if (expression2.IsKind(SyntaxKind.ThrowExpression)) - return; + if (expression2.IsKind(SyntaxKind.ThrowExpression)) + return; - TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken); + TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken); - ITypeSymbol type = typeInfo.Type; - ITypeSymbol convertedType = typeInfo.ConvertedType; + ITypeSymbol type = typeInfo.Type; + ITypeSymbol convertedType = typeInfo.ConvertedType; - if (!SymbolEqualityComparer.Default.Equals(type, convertedType)) - return; - - ITypeSymbol type2 = context.SemanticModel.GetTypeSymbol(expression2, context.CancellationToken); + if (!SymbolEqualityComparer.Default.Equals(type, convertedType)) + return; - if (!SymbolEqualityComparer.Default.Equals(type, type2)) - return; + ITypeSymbol type2 = context.SemanticModel.GetTypeSymbol(expression2, context.CancellationToken); - ReportDiagnostic(); + if (!SymbolEqualityComparer.Default.Equals(type, type2)) return; - } + + ReportDiagnostic(); + return; + } case SyntaxKind.ArrowExpressionClause: case SyntaxKind.CoalesceExpression: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.SimpleAssignmentExpression: - { - if (parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) - return; - - if (parent is BinaryExpressionSyntax coalesceExpression - && coalesceExpression.Left == defaultExpression) - { - return; - } + { + if (parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) + return; - TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken); + if (parent is BinaryExpressionSyntax coalesceExpression + && coalesceExpression.Left == defaultExpression) + { + return; + } - if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) - return; + TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken); - if (parent.IsKind(SyntaxKind.ReturnStatement) - && IsTypeInferredFromDefaultExpression(context, parent)) - { - return; - } + if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) + return; - ReportDiagnostic(); + if (parent.IsKind(SyntaxKind.ReturnStatement) + && IsTypeInferredFromDefaultExpression(context, parent)) + { return; } + + ReportDiagnostic(); + return; + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; - - TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); + { + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) - return; + TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); - IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol((ExpressionSyntax)parent, cancellationToken); + if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) + return; - if (methodSymbol is null) - return; + IMethodSymbol methodSymbol = semanticModel.GetMethodSymbol((ExpressionSyntax)parent, cancellationToken); - SyntaxNode newNode = parent.ReplaceNode(defaultExpression, CSharpFactory.DefaultLiteralExpression()); + if (methodSymbol is null) + return; - IMethodSymbol newMethodSymbol = semanticModel.GetSpeculativeMethodSymbol(parent.SpanStart, newNode); + SyntaxNode newNode = parent.ReplaceNode(defaultExpression, CSharpFactory.DefaultLiteralExpression()); - if (!SymbolEqualityComparer.Default.Equals(methodSymbol, newMethodSymbol)) - return; + IMethodSymbol newMethodSymbol = semanticModel.GetSpeculativeMethodSymbol(parent.SpanStart, newNode); - ReportDiagnostic(); + if (!SymbolEqualityComparer.Default.Equals(methodSymbol, newMethodSymbol)) return; - } + + ReportDiagnostic(); + return; + } case SyntaxKind.Argument: case SyntaxKind.ConstantPattern: case SyntaxKind.CaseSwitchLabel: - { - return; - } + { + return; + } default: - { - Debug.WriteLine($"{parent.Kind()} {parent}"); - return; - } + { + Debug.WriteLine($"{parent.Kind()} {parent}"); + return; + } } void ReportDiagnostic() diff --git a/src/Analyzers/CSharp/Analysis/FileContainsNoCodeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/FileContainsNoCodeAnalyzer.cs index e7362d43c3..09e0ddbeb2 100644 --- a/src/Analyzers/CSharp/Analysis/FileContainsNoCodeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/FileContainsNoCodeAnalyzer.cs @@ -49,24 +49,24 @@ private static void AnalyzeCompilationUnit(SyntaxNodeAnalysisContext context) case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: case SyntaxKind.EndIfDirectiveTrivia: - { - return true; - } + { + return true; + } case SyntaxKind.PragmaWarningDirectiveTrivia: - { - var pragma = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); + { + var pragma = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); - foreach (ExpressionSyntax errorCode in pragma.ErrorCodes) + foreach (ExpressionSyntax errorCode in pragma.ErrorCodes) + { + if (errorCode is IdentifierNameSyntax identifierName + && string.Equals(identifierName.Identifier.ValueText, DiagnosticRules.FileContainsNoCode.Id, StringComparison.OrdinalIgnoreCase)) { - if (errorCode is IdentifierNameSyntax identifierName - && string.Equals(identifierName.Identifier.ValueText, DiagnosticRules.FileContainsNoCode.Id, StringComparison.OrdinalIgnoreCase)) - { - return true; - } + return true; } - - break; } + + break; + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/FixDocumentationCommentTagAnalysis.cs b/src/Analyzers/CSharp/Analysis/FixDocumentationCommentTagAnalysis.cs index fa5ca2fe44..0700716cd9 100644 --- a/src/Analyzers/CSharp/Analysis/FixDocumentationCommentTagAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/FixDocumentationCommentTagAnalysis.cs @@ -26,28 +26,28 @@ public static void Analyze(SyntaxNodeAnalysisContext context, XmlElementInfo ele switch (elementInfo2.GetTag()) { case XmlTag.C: - { - AnalyzeCElement(context, elementInfo2); - break; - } + { + AnalyzeCElement(context, elementInfo2); + break; + } case XmlTag.Code: - { - AnalyzeCodeElement(context, elementInfo2); - break; - } + { + AnalyzeCodeElement(context, elementInfo2); + break; + } case XmlTag.List: - { - AnalyzeList(context, elementInfo2); - break; - } + { + AnalyzeList(context, elementInfo2); + break; + } case XmlTag.Para: case XmlTag.ParamRef: case XmlTag.See: case XmlTag.TypeParamRef: - { - Analyze(context, elementInfo2); - break; - } + { + Analyze(context, elementInfo2); + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs b/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs index 234e9188c4..6c1e5af742 100644 --- a/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/IfStatementAnalyzer.cs @@ -82,29 +82,29 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IfAnalysisKind.IfElseToReturnWithCoalesceExpression: case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression: case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression: - { - if (DiagnosticRules.UseCoalesceExpressionInsteadOfIf.IsEffective(context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseCoalesceExpressionInsteadOfIf, ifStatement); + { + if (DiagnosticRules.UseCoalesceExpressionInsteadOfIf.IsEffective(context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseCoalesceExpressionInsteadOfIf, ifStatement); - break; - } + break; + } case IfAnalysisKind.IfElseToReturnWithExpression: case IfAnalysisKind.IfElseToYieldReturnWithExpression: case IfAnalysisKind.IfReturnToReturnWithExpression: - { - if (DiagnosticRules.ConvertIfToReturnStatement.IsEffective(context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.ConvertIfToReturnStatement, ifStatement); + { + if (DiagnosticRules.ConvertIfToReturnStatement.IsEffective(context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.ConvertIfToReturnStatement, ifStatement); - break; - } + break; + } case IfAnalysisKind.IfElseToAssignmentWithExpression: case IfAnalysisKind.IfElseToAssignmentWithCondition: - { - if (DiagnosticRules.ConvertIfToAssignment.IsEffective(context)) - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.ConvertIfToAssignment, ifStatement); + { + if (DiagnosticRules.ConvertIfToAssignment.IsEffective(context)) + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.ConvertIfToAssignment, ifStatement); - break; - } + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs index cb0da58ca1..bd2bf24a1f 100644 --- a/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/InlineLocalVariableAnalyzer.cs @@ -89,137 +89,137 @@ private static void AnalyzeLocalDeclarationStatement(SyntaxNodeAnalysisContext c switch (nextStatement.Kind()) { case SyntaxKind.ExpressionStatement: - { - Analyze(context, statements, localDeclarationInfo, index, (ExpressionStatementSyntax)nextStatement); - break; - } + { + Analyze(context, statements, localDeclarationInfo, index, (ExpressionStatementSyntax)nextStatement); + break; + } case SyntaxKind.LocalDeclarationStatement: - { - Analyze(context, statements, localDeclarationInfo, index, (LocalDeclarationStatementSyntax)nextStatement); - break; - } + { + Analyze(context, statements, localDeclarationInfo, index, (LocalDeclarationStatementSyntax)nextStatement); + break; + } case SyntaxKind.ReturnStatement: + { + var returnStatement = (ReturnStatementSyntax)nextStatement; + + if (!returnStatement.SpanOrLeadingTriviaContainsDirectives()) { - var returnStatement = (ReturnStatementSyntax)nextStatement; + ExpressionSyntax expression = returnStatement.Expression; - if (!returnStatement.SpanOrLeadingTriviaContainsDirectives()) + if (expression?.Kind() == SyntaxKind.IdentifierName) { - ExpressionSyntax expression = returnStatement.Expression; - - if (expression?.Kind() == SyntaxKind.IdentifierName) - { - var identifierName = (IdentifierNameSyntax)expression; + var identifierName = (IdentifierNameSyntax)expression; - if (string.Equals(localDeclarationInfo.IdentifierText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) - ReportDiagnostic(context, localDeclarationInfo, expression); - } + if (string.Equals(localDeclarationInfo.IdentifierText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) + ReportDiagnostic(context, localDeclarationInfo, expression); } - - break; } + + break; + } case SyntaxKind.YieldReturnStatement: + { + var yieldStatement = (YieldStatementSyntax)nextStatement; + + if (index == statements.Count - 2 + && !yieldStatement.SpanOrLeadingTriviaContainsDirectives()) { - var yieldStatement = (YieldStatementSyntax)nextStatement; + ExpressionSyntax expression = yieldStatement.Expression; - if (index == statements.Count - 2 - && !yieldStatement.SpanOrLeadingTriviaContainsDirectives()) + if (expression?.Kind() == SyntaxKind.IdentifierName) { - ExpressionSyntax expression = yieldStatement.Expression; - - if (expression?.Kind() == SyntaxKind.IdentifierName) - { - var identifierName = (IdentifierNameSyntax)expression; + var identifierName = (IdentifierNameSyntax)expression; - if (string.Equals(localDeclarationInfo.IdentifierText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) - ReportDiagnostic(context, localDeclarationInfo, expression); - } + if (string.Equals(localDeclarationInfo.IdentifierText, identifierName.Identifier.ValueText, StringComparison.Ordinal)) + ReportDiagnostic(context, localDeclarationInfo, expression); } - - break; } - case SyntaxKind.ForEachStatement: - { - if (value.WalkDownParentheses().IsKind(SyntaxKind.AwaitExpression)) - return; - if (!value.IsSingleLine()) - return; + break; + } + case SyntaxKind.ForEachStatement: + { + if (value.WalkDownParentheses().IsKind(SyntaxKind.AwaitExpression)) + return; - if (value.IsKind(SyntaxKind.ArrayInitializerExpression)) - return; + if (!value.IsSingleLine()) + return; - var forEachStatement = (ForEachStatementSyntax)nextStatement; + if (value.IsKind(SyntaxKind.ArrayInitializerExpression)) + return; - ISymbol localSymbol = GetLocalSymbol(localDeclarationInfo, forEachStatement.Expression, context.SemanticModel, context.CancellationToken); + var forEachStatement = (ForEachStatementSyntax)nextStatement; - if (localSymbol?.IsErrorType() != false) - return; + ISymbol localSymbol = GetLocalSymbol(localDeclarationInfo, forEachStatement.Expression, context.SemanticModel, context.CancellationToken); - ContainsLocalOrParameterReferenceWalker walker = null; + if (localSymbol?.IsErrorType() != false) + return; - try - { - walker = ContainsLocalOrParameterReferenceWalker.GetInstance(localSymbol, context.SemanticModel, context.CancellationToken); + ContainsLocalOrParameterReferenceWalker walker = null; - walker.Visit(forEachStatement.Statement); + try + { + walker = ContainsLocalOrParameterReferenceWalker.GetInstance(localSymbol, context.SemanticModel, context.CancellationToken); - if (!walker.Result - && index < statements.Count - 2) - { - walker.VisitList(statements, index + 2); - } + walker.Visit(forEachStatement.Statement); - if (!walker.Result) - ReportDiagnostic(context, localDeclarationInfo, forEachStatement.Expression); - } - finally + if (!walker.Result + && index < statements.Count - 2) { - if (walker is not null) - ContainsLocalOrParameterReferenceWalker.Free(walker); + walker.VisitList(statements, index + 2); } - break; + if (!walker.Result) + ReportDiagnostic(context, localDeclarationInfo, forEachStatement.Expression); } - case SyntaxKind.SwitchStatement: + finally { - if (value.WalkDownParentheses().IsKind(SyntaxKind.AwaitExpression)) - return; + if (walker is not null) + ContainsLocalOrParameterReferenceWalker.Free(walker); + } - if (!value.IsSingleLine()) - return; + break; + } + case SyntaxKind.SwitchStatement: + { + if (value.WalkDownParentheses().IsKind(SyntaxKind.AwaitExpression)) + return; - var switchStatement = (SwitchStatementSyntax)nextStatement; + if (!value.IsSingleLine()) + return; - ISymbol localSymbol = GetLocalSymbol(localDeclarationInfo, switchStatement.Expression, context.SemanticModel, context.CancellationToken); + var switchStatement = (SwitchStatementSyntax)nextStatement; - if (localSymbol?.IsErrorType() != false) - return; + ISymbol localSymbol = GetLocalSymbol(localDeclarationInfo, switchStatement.Expression, context.SemanticModel, context.CancellationToken); - ContainsLocalOrParameterReferenceWalker walker = null; + if (localSymbol?.IsErrorType() != false) + return; - try - { - walker = ContainsLocalOrParameterReferenceWalker.GetInstance(localSymbol, context.SemanticModel, context.CancellationToken); + ContainsLocalOrParameterReferenceWalker walker = null; - walker.VisitList(switchStatement.Sections); + try + { + walker = ContainsLocalOrParameterReferenceWalker.GetInstance(localSymbol, context.SemanticModel, context.CancellationToken); - if (!walker.Result - && index < statements.Count - 2) - { - walker.VisitList(statements, index + 2); - } + walker.VisitList(switchStatement.Sections); - if (!walker.Result) - ReportDiagnostic(context, localDeclarationInfo, switchStatement.Expression); - } - finally + if (!walker.Result + && index < statements.Count - 2) { - if (walker is not null) - ContainsLocalOrParameterReferenceWalker.Free(walker); + walker.VisitList(statements, index + 2); } - break; + if (!walker.Result) + ReportDiagnostic(context, localDeclarationInfo, switchStatement.Expression); + } + finally + { + if (walker is not null) + ContainsLocalOrParameterReferenceWalker.Free(walker); } + + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs index e4fa8490ae..e62689a676 100644 --- a/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/InvocationExpressionAnalyzer.cs @@ -78,357 +78,357 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex switch (argumentCount) { case 0: + { + switch (methodName) { - switch (methodName) + case "Any": { - case "Any": - { - if (DiagnosticRules.UseCountOrLengthPropertyInsteadOfAnyMethod.IsEffective(context)) - UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.Analyze(context, invocationInfo); + if (DiagnosticRules.UseCountOrLengthPropertyInsteadOfAnyMethod.IsEffective(context)) + UseCountOrLengthPropertyInsteadOfAnyMethodAnalysis.Analyze(context, invocationInfo); - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - { - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - OptimizeLinqMethodCallAnalysis.AnalyzeAny(context, invocationInfo); - } + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + { + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); + OptimizeLinqMethodCallAnalysis.AnalyzeAny(context, invocationInfo); + } - break; - } - case "Cast": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndCast(context, invocationInfo); + break; + } + case "Cast": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndCast(context, invocationInfo); - if (DiagnosticRules.RemoveRedundantCast.IsEffective(context)) - RemoveRedundantCastAnalyzer.Analyze(context, invocationInfo); + if (DiagnosticRules.RemoveRedundantCast.IsEffective(context)) + RemoveRedundantCastAnalyzer.Analyze(context, invocationInfo); - break; - } - case "Count": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) - && !OptimizeLinqMethodCallAnalysis.AnalyzeSelectManyAndCount(context, invocationInfo)) - { - OptimizeLinqMethodCallAnalysis.AnalyzeCount(context, invocationInfo); - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - } - - break; - } - case "First": + break; + } + case "Count": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) + && !OptimizeLinqMethodCallAnalysis.AnalyzeSelectManyAndCount(context, invocationInfo)) + { + OptimizeLinqMethodCallAnalysis.AnalyzeCount(context, invocationInfo); + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); + } + + break; + } + case "First": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + { + if (!invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) + && UseElementAccessAnalysis.IsFixableFirst(invocationInfo, context.SemanticModel, context.CancellationToken)) { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - { - if (!invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) - && UseElementAccessAnalysis.IsFixableFirst(invocationInfo, context.SemanticModel, context.CancellationToken)) - { - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseElementAccess, - Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); - } - - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - OptimizeLinqMethodCallAnalysis.AnalyzeFirst(context, invocationInfo); - } - - break; + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseElementAccess, + Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); } - case "Average": - case "Max": - case "Min": - case "Sum": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndAverageOrMinOrMaxOrSum(context, invocationInfo); - break; - } - case "Reverse": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndReverse(context, invocationInfo); + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); + OptimizeLinqMethodCallAnalysis.AnalyzeFirst(context, invocationInfo); + } - break; - } - case "ToString": - { - if (DiagnosticRules.RemoveRedundantToStringCall.IsEffective(context)) - RemoveRedundantToStringCallAnalysis.Analyze(context, invocationInfo); + break; + } + case "Average": + case "Max": + case "Min": + case "Sum": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndAverageOrMinOrMaxOrSum(context, invocationInfo); - if (DiagnosticRules.UseNameOfOperator.IsEffective(context) - && ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp6) - { - UseNameOfOperatorAnalyzer.Analyze(context, invocationInfo); - } + break; + } + case "Reverse": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndReverse(context, invocationInfo); - break; - } - case "ToList": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndToList(context, invocationInfo); + break; + } + case "ToString": + { + if (DiagnosticRules.RemoveRedundantToStringCall.IsEffective(context)) + RemoveRedundantToStringCallAnalysis.Analyze(context, invocationInfo); - break; - } - case "ToLower": - case "ToLowerInvariant": - case "ToUpper": - case "ToUpperInvariant": - { - if (DiagnosticRules.UseStringComparison.IsEffective(context)) - UseStringComparisonAnalysis.Analyze(context, invocationInfo); + if (DiagnosticRules.UseNameOfOperator.IsEffective(context) + && ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp6) + { + UseNameOfOperatorAnalyzer.Analyze(context, invocationInfo); + } - break; - } - case "FirstOrDefault": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - { - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); - } + break; + } + case "ToList": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeSelectAndToList(context, invocationInfo); - break; - } - case "Last": + break; + } + case "ToLower": + case "ToLowerInvariant": + case "ToUpper": + case "ToUpperInvariant": + { + if (DiagnosticRules.UseStringComparison.IsEffective(context)) + UseStringComparisonAnalysis.Analyze(context, invocationInfo); + + break; + } + case "FirstOrDefault": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + { + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); + OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); + } + + break; + } + case "Last": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + { + if (!invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) + && UseElementAccessAnalysis.IsFixableLast(invocationInfo, context.SemanticModel, context.CancellationToken)) { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - { - if (!invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) - && UseElementAccessAnalysis.IsFixableLast(invocationInfo, context.SemanticModel, context.CancellationToken)) - { - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseElementAccess, - Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); - } - - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - } - - break; + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseElementAccess, + Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); } - case "LastOrDefault": - case "LongCount": - case "Single": - case "SingleOrDefault": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - break; - } - case "OfType": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) - && !invocation.SpanContainsDirectives()) - { - OptimizeLinqMethodCallAnalysis.AnalyzeOfType(context, invocationInfo); - } + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); + } - break; - } - case "ToCharArray": - { - if (DiagnosticRules.RemoveRedundantStringToCharArrayCall.IsEffective(context)) - RemoveRedundantStringToCharArrayCallAnalysis.Analyze(context, invocationInfo); + break; + } + case "LastOrDefault": + case "LongCount": + case "Single": + case "SingleOrDefault": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeWhere(context, invocationInfo); - break; - } + break; + } + case "OfType": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) + && !invocation.SpanContainsDirectives()) + { + OptimizeLinqMethodCallAnalysis.AnalyzeOfType(context, invocationInfo); + } + + break; } + case "ToCharArray": + { + if (DiagnosticRules.RemoveRedundantStringToCharArrayCall.IsEffective(context)) + RemoveRedundantStringToCharArrayCallAnalysis.Analyze(context, invocationInfo); - break; + break; + } } + + break; + } case 1: + { + switch (methodName) { - switch (methodName) + case "Add": { - case "Add": - { - if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) - OptimizeMethodCallAnalysis.OptimizeAdd(context, invocationInfo); + if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) + OptimizeMethodCallAnalysis.OptimizeAdd(context, invocationInfo); - break; - } - case "All": - case "Any": - { - if (DiagnosticRules.SimplifyLogicalNegation.IsEffective(context)) - SimplifyLogicalNegationAnalyzer.Analyze(context, invocationInfo); + break; + } + case "All": + case "Any": + { + if (DiagnosticRules.SimplifyLogicalNegation.IsEffective(context)) + SimplifyLogicalNegationAnalyzer.Analyze(context, invocationInfo); - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) - && !invocation.SpanContainsDirectives()) - { - OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndAny(context, invocationInfo); - } + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) + && !invocation.SpanContainsDirectives()) + { + OptimizeLinqMethodCallAnalysis.AnalyzeWhereAndAny(context, invocationInfo); + } - break; - } - case "ContainsKey": - { - if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) - OptimizeMethodCallAnalysis.OptimizeDictionaryContainsKey(context, invocationInfo); + break; + } + case "ContainsKey": + { + if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) + OptimizeMethodCallAnalysis.OptimizeDictionaryContainsKey(context, invocationInfo); - break; - } - case "ElementAt": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) - && !invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) - && UseElementAccessAnalysis.IsFixableElementAt(invocationInfo, context.SemanticModel, context.CancellationToken)) - { - DiagnosticHelpers.ReportDiagnostic( - context, - DiagnosticRules.UseElementAccess, - Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); - } - - break; - } - case "FirstOrDefault": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); + break; + } + case "ElementAt": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context) + && !invocationInfo.Expression.IsKind(SyntaxKind.ElementAccessExpression, SyntaxKind.InvocationExpression) + && UseElementAccessAnalysis.IsFixableElementAt(invocationInfo, context.SemanticModel, context.CancellationToken)) + { + DiagnosticHelpers.ReportDiagnostic( + context, + DiagnosticRules.UseElementAccess, + Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(invocationInfo.Name.SpanStart, invocationInfo.ArgumentList.Span.End))); + } + + break; + } + case "FirstOrDefault": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeFirstOrDefault(context, invocationInfo); - break; - } - case "GetValueOrDefault": - { - if (DiagnosticRules.UseCoalesceExpression.IsEffective(context) - && invocationInfo.Name.IsKind(SyntaxKind.IdentifierName) - && !invocation.IsParentKind(SyntaxKind.InvocationExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) - && context.SemanticModel - .GetMethodSymbol(invocationInfo.InvocationExpression, context.CancellationToken)? - .ContainingType - .OriginalDefinition - .SpecialType == SpecialType.System_Nullable_T) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseCoalesceExpression, invocationInfo.Name); - } - - break; - } - case "Where": - { - if (DiagnosticRules.CombineEnumerableWhereMethodChain.IsEffective(context)) - CombineEnumerableWhereMethodChainAnalysis.Analyze(context, invocationInfo); + break; + } + case "GetValueOrDefault": + { + if (DiagnosticRules.UseCoalesceExpression.IsEffective(context) + && invocationInfo.Name.IsKind(SyntaxKind.IdentifierName) + && !invocation.IsParentKind(SyntaxKind.InvocationExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) + && context.SemanticModel + .GetMethodSymbol(invocationInfo.InvocationExpression, context.CancellationToken)? + .ContainingType + .OriginalDefinition + .SpecialType == SpecialType.System_Nullable_T) + { + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseCoalesceExpression, invocationInfo.Name); + } + + break; + } + case "Where": + { + if (DiagnosticRules.CombineEnumerableWhereMethodChain.IsEffective(context)) + CombineEnumerableWhereMethodChainAnalysis.Analyze(context, invocationInfo); - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndWhere(context, invocationInfo); + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeOrderByAndWhere(context, invocationInfo); - break; - } - case "Select": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); + break; + } + case "Select": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); - break; - } - case "OrderBy": - { - if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) - CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); + break; + } + case "OrderBy": + { + if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) + CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - OptimizeLinqMethodCallAnalysis.AnalyzeOrderByIdentity(context, invocationInfo); + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + OptimizeLinqMethodCallAnalysis.AnalyzeOrderByIdentity(context, invocationInfo); - break; - } + break; } - - break; } + + break; + } case 2: + { + switch (invocationInfo.NameText) { - switch (invocationInfo.NameText) + case "IsMatch": + case "Match": + case "Matches": + case "Split": { - case "IsMatch": - case "Match": - case "Matches": - case "Split": - { - if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) - && !invocation.SpanContainsDirectives()) - { - UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); - } + if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) + && !invocation.SpanContainsDirectives()) + { + UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); + } - break; - } - case "Select": - { - if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) - CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); - - break; - } - case "OrderBy": - { - if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) - CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); + break; + } + case "Select": + { + if (DiagnosticRules.OptimizeLinqMethodCall.IsEffective(context)) + CallCastInsteadOfSelectAnalysis.Analyze(context, invocationInfo); - break; - } + break; } + case "OrderBy": + { + if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) + CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); - break; + break; + } } + + break; + } case 3: + { + switch (invocationInfo.NameText) { - switch (invocationInfo.NameText) + case "IsMatch": + case "Match": + case "Matches": + case "Split": + case "Replace": { - case "IsMatch": - case "Match": - case "Matches": - case "Split": - case "Replace": - { - if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) - && !invocation.SpanContainsDirectives()) - { - UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); - } + if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) + && !invocation.SpanContainsDirectives()) + { + UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); + } - break; - } - case "OrderBy": - { - if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) - CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); - - break; - } - case "Compare": - { - if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) - OptimizeMethodCallAnalysis.OptimizeStringCompare(context, invocationInfo); + break; + } + case "OrderBy": + { + if (DiagnosticRules.CallThenByInsteadOfOrderBy.IsEffective(context)) + CallThenByInsteadOfOrderByAnalysis.Analyze(context, invocationInfo); - break; - } + break; } + case "Compare": + { + if (DiagnosticRules.OptimizeMethodCall.IsEffective(context)) + OptimizeMethodCallAnalysis.OptimizeStringCompare(context, invocationInfo); - break; + break; + } } + + break; + } case 4: + { + switch (invocationInfo.NameText) { - switch (invocationInfo.NameText) + case "Replace": { - case "Replace": - { - if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) - && !invocation.SpanContainsDirectives()) - { - UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); - } + if (DiagnosticRules.UseRegexInstanceInsteadOfStaticMethod.IsEffective(context) + && !invocation.SpanContainsDirectives()) + { + UseRegexInstanceInsteadOfStaticMethodAnalysis.Analyze(context, invocationInfo); + } - break; - } + break; } - - break; } + + break; + } } switch (methodName) @@ -437,66 +437,66 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex case "FirstOrDefault": case "LastOrDefault": case "SingleOrDefault": - { - if (DiagnosticRules.AvoidNullReferenceException.IsEffective(context)) - AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); + { + if (DiagnosticRules.AvoidNullReferenceException.IsEffective(context)) + AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); - break; - } + break; + } case "Append": case "AppendLine": case "AppendFormat": case "Insert": - { - if (DiagnosticRules.OptimizeStringBuilderAppendCall.IsEffective(context)) - OptimizeStringBuilderAppendCallAnalysis.Analyze(context, invocationInfo); + { + if (DiagnosticRules.OptimizeStringBuilderAppendCall.IsEffective(context)) + OptimizeStringBuilderAppendCallAnalysis.Analyze(context, invocationInfo); - if (DiagnosticRules.AvoidBoxingOfValueType.IsEffective(context)) - AvoidBoxingOfValueTypeAnalysis.Analyze(context, invocationInfo); + if (DiagnosticRules.AvoidBoxingOfValueType.IsEffective(context)) + AvoidBoxingOfValueTypeAnalysis.Analyze(context, invocationInfo); - break; - } + break; + } case "Assert": + { + if (DiagnosticRules.OptimizeMethodCall.IsEffective(context) + && (argumentCount >= 1 && argumentCount <= 3)) { - if (DiagnosticRules.OptimizeMethodCall.IsEffective(context) - && (argumentCount >= 1 && argumentCount <= 3)) - { - OptimizeMethodCallAnalysis.OptimizeDebugAssert(context, invocationInfo); - } - - break; + OptimizeMethodCallAnalysis.OptimizeDebugAssert(context, invocationInfo); } + + break; + } case "Join": + { + if (DiagnosticRules.OptimizeMethodCall.IsEffective(context) + && argumentCount >= 2) { - if (DiagnosticRules.OptimizeMethodCall.IsEffective(context) - && argumentCount >= 2) - { - OptimizeMethodCallAnalysis.OptimizeStringJoin(context, invocationInfo); - } - - break; + OptimizeMethodCallAnalysis.OptimizeStringJoin(context, invocationInfo); } + + break; + } case "Concat": + { + if (DiagnosticRules.UseStringInterpolationInsteadOfStringConcat.IsEffective(context) + && argumentCount > 1) { - if (DiagnosticRules.UseStringInterpolationInsteadOfStringConcat.IsEffective(context) - && argumentCount > 1) - { - UseStringInterpolationInsteadOfStringConcatAnalysis.Analyze(context, invocationInfo); - } - - break; + UseStringInterpolationInsteadOfStringConcatAnalysis.Analyze(context, invocationInfo); } + + break; + } default: + { + if (methodName.Length > "OrDefault".Length + && methodName.EndsWith("OrDefault", StringComparison.Ordinal) + && DiagnosticRules.AvoidNullReferenceException.IsEffective(context)) { - if (methodName.Length > "OrDefault".Length - && methodName.EndsWith("OrDefault", StringComparison.Ordinal) - && DiagnosticRules.AvoidNullReferenceException.IsEffective(context)) - { - AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); - } - - break; + AvoidNullReferenceExceptionAnalyzer.Analyze(context, invocationInfo); } + + break; + } } if (DiagnosticRules.UseMethodChaining.IsEffective(context) diff --git a/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs index e24210d159..cbe8bd8b2f 100644 --- a/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/JoinStringExpressionsAnalyzer.cs @@ -63,108 +63,108 @@ private static void AnalyzeAddExpression(SyntaxNodeAnalysisContext context) switch (expression.Kind()) { case SyntaxKind.StringLiteralExpression: - { - StringLiteralExpressionInfo stringLiteral = SyntaxInfo.StringLiteralExpressionInfo(expression); + { + StringLiteralExpressionInfo stringLiteral = SyntaxInfo.StringLiteralExpressionInfo(expression); - bool isVerbatim2 = stringLiteral.IsVerbatim; + bool isVerbatim2 = stringLiteral.IsVerbatim; - if (firstExpression is null) - { - firstExpression = expression; - isLiteral = true; - isVerbatim = isVerbatim2; + if (firstExpression is null) + { + firstExpression = expression; + isLiteral = true; + isVerbatim = isVerbatim2; - if (isVerbatim) - startLine = expression.SyntaxTree.GetLineSpan(expression.GetSpan()).StartLine(); - } - else if (!isLiteral - || isVerbatim != isVerbatim2 - || (!isVerbatim && !CheckHexadecimalEscapeSequence(stringLiteral))) - { - if (lastExpression is not null) - Analyze(context, firstExpression, lastExpression, isVerbatim); + if (isVerbatim) + startLine = expression.SyntaxTree.GetLineSpan(expression.GetSpan()).StartLine(); + } + else if (!isLiteral + || isVerbatim != isVerbatim2 + || (!isVerbatim && !CheckHexadecimalEscapeSequence(stringLiteral))) + { + if (lastExpression is not null) + Analyze(context, firstExpression, lastExpression, isVerbatim); - firstExpression = null; - lastExpression = null; - } - else + firstExpression = null; + lastExpression = null; + } + else + { + lastExpression = expression; + + if (isVerbatim) { - lastExpression = expression; + FileLinePositionSpan lineSpan = expression.SyntaxTree.GetLineSpan(expression.GetSpan()); - if (isVerbatim) + if (startLine != lineSpan.EndLine()) { - FileLinePositionSpan lineSpan = expression.SyntaxTree.GetLineSpan(expression.GetSpan()); - - if (startLine != lineSpan.EndLine()) - { - firstExpression = null; - lastExpression = null; - } - else - { - startLine = lineSpan.StartLine(); - } + firstExpression = null; + lastExpression = null; + } + else + { + startLine = lineSpan.StartLine(); } } - - break; } + + break; + } case SyntaxKind.InterpolatedStringExpression: - { - var interpolatedString = ((InterpolatedStringExpressionSyntax)expression); + { + var interpolatedString = ((InterpolatedStringExpressionSyntax)expression); - bool isVerbatim2 = interpolatedString.IsVerbatim(); + bool isVerbatim2 = interpolatedString.IsVerbatim(); - if (firstExpression is null) - { - firstExpression = expression; - isLiteral = false; - isVerbatim = isVerbatim2; + if (firstExpression is null) + { + firstExpression = expression; + isLiteral = false; + isVerbatim = isVerbatim2; - if (isVerbatim) - startLine = expression.SyntaxTree.GetLineSpan(expression.GetSpan()).StartLine(); - } - else if (isLiteral - || isVerbatim != isVerbatim2 - || (!isVerbatim && !CheckHexadecimalEscapeSequence(interpolatedString))) - { - if (lastExpression is not null) - Analyze(context, firstExpression, lastExpression, isVerbatim); + if (isVerbatim) + startLine = expression.SyntaxTree.GetLineSpan(expression.GetSpan()).StartLine(); + } + else if (isLiteral + || isVerbatim != isVerbatim2 + || (!isVerbatim && !CheckHexadecimalEscapeSequence(interpolatedString))) + { + if (lastExpression is not null) + Analyze(context, firstExpression, lastExpression, isVerbatim); - firstExpression = null; - lastExpression = null; - } - else + firstExpression = null; + lastExpression = null; + } + else + { + lastExpression = expression; + + if (isVerbatim) { - lastExpression = expression; + FileLinePositionSpan lineSpan = expression.SyntaxTree.GetLineSpan(expression.GetSpan()); - if (isVerbatim) + if (startLine != lineSpan.EndLine()) { - FileLinePositionSpan lineSpan = expression.SyntaxTree.GetLineSpan(expression.GetSpan()); - - if (startLine != lineSpan.EndLine()) - { - firstExpression = null; - lastExpression = null; - } - else - { - startLine = lineSpan.StartLine(); - } + firstExpression = null; + lastExpression = null; + } + else + { + startLine = lineSpan.StartLine(); } } - - break; } + + break; + } default: - { - if (lastExpression is not null) - Analyze(context, firstExpression, lastExpression, isVerbatim); + { + if (lastExpression is not null) + Analyze(context, firstExpression, lastExpression, isVerbatim); - firstExpression = null; - lastExpression = null; - break; - } + firstExpression = null; + lastExpression = null; + break; + } } } @@ -243,23 +243,27 @@ private static bool CheckHexadecimalEscapeSequence(string text, int start, int l case 'r': case 't': case 'v': - { - break; - } + { + break; + } case 'u': - { - pos += 4; - break; - } + { + pos += 4; + break; + } case 'U': - { - pos += 8; - break; - } + { + pos += 8; + break; + } case 'x': + { + pos++; + + if (pos < text.Length + && StringUtility.IsHexadecimalDigit(text[pos])) { pos++; - if (pos < text.Length && StringUtility.IsHexadecimalDigit(text[pos])) { @@ -271,27 +275,23 @@ private static bool CheckHexadecimalEscapeSequence(string text, int start, int l if (pos < text.Length && StringUtility.IsHexadecimalDigit(text[pos])) { - pos++; - if (pos < text.Length - && StringUtility.IsHexadecimalDigit(text[pos])) - { - break; - } + break; } } } + } - if (pos == start + length) - return false; + if (pos == start + length) + return false; - pos--; - break; - } + pos--; + break; + } default: - { - Debug.Fail(text[pos].ToString()); - return false; - } + { + Debug.Fail(text[pos].ToString()); + return false; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs index 59557ba8ea..e1d4f5921b 100644 --- a/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeClassStaticAnalyzer.cs @@ -106,65 +106,65 @@ public static bool AnalyzeMembers(ImmutableArray members) switch (memberSymbol.Kind) { case SymbolKind.ErrorType: - { - return false; - } + { + return false; + } case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)memberSymbol; + { + var namedTypeSymbol = (INamedTypeSymbol)memberSymbol; - switch (namedTypeSymbol.TypeKind) + switch (namedTypeSymbol.TypeKind) + { + case TypeKind.Unknown: + case TypeKind.Error: { - case TypeKind.Unknown: - case TypeKind.Error: - { - return false; - } - case TypeKind.Class: - case TypeKind.Delegate: - case TypeKind.Enum: - case TypeKind.Interface: - case TypeKind.Struct: - { - if (memberSymbol.DeclaredAccessibility.ContainsProtected()) - return false; - - break; - } - default: - { - Debug.Fail(namedTypeSymbol.TypeKind.ToString()); - break; - } + return false; } + case TypeKind.Class: + case TypeKind.Delegate: + case TypeKind.Enum: + case TypeKind.Interface: + case TypeKind.Struct: + { + if (memberSymbol.DeclaredAccessibility.ContainsProtected()) + return false; - break; + break; + } + default: + { + Debug.Fail(namedTypeSymbol.TypeKind.ToString()); + break; + } } + + break; + } default: - { - Debug.Assert(memberSymbol.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), memberSymbol.Kind.ToString()); + { + Debug.Assert(memberSymbol.IsKind(SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property), memberSymbol.Kind.ToString()); - if (memberSymbol.DeclaredAccessibility.ContainsProtected()) - return false; + if (memberSymbol.DeclaredAccessibility.ContainsProtected()) + return false; - if (!memberSymbol.IsImplicitlyDeclared) + if (!memberSymbol.IsImplicitlyDeclared) + { + if (memberSymbol.IsStatic) { - if (memberSymbol.IsStatic) - { - if (memberSymbol.Kind == SymbolKind.Method - && ((IMethodSymbol)memberSymbol).MethodKind.Is(MethodKind.UserDefinedOperator, MethodKind.Conversion)) - { - return false; - } - } - else + if (memberSymbol.Kind == SymbolKind.Method + && ((IMethodSymbol)memberSymbol).MethodKind.Is(MethodKind.UserDefinedOperator, MethodKind.Conversion)) { return false; } } - - break; + else + { + return false; + } } + + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs index 49665c5c9e..bc574183f6 100644 --- a/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MakeMemberReadOnly/MakeMemberReadOnlyAnalyzer.cs @@ -93,61 +93,61 @@ private static void AnalyzeTypeDeclaration( switch (memberDeclaration.Kind()) { case SyntaxKind.PropertyDeclaration: - { - if (skipProperty) - break; + { + if (skipProperty) + break; - var propertyDeclaration = (PropertyDeclarationSyntax)memberDeclaration; + var propertyDeclaration = (PropertyDeclarationSyntax)memberDeclaration; - AccessorDeclarationSyntax setter = propertyDeclaration.Setter(); + AccessorDeclarationSyntax setter = propertyDeclaration.Setter(); + + if (setter?.IsKind(SyntaxKind.InitAccessorDeclaration) == false + && setter.BodyOrExpressionBody() is null + && !setter.AttributeLists.Any() + && !setter.SpanContainsDirectives()) + { + IPropertySymbol propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); - if (setter?.IsKind(SyntaxKind.InitAccessorDeclaration) == false - && setter.BodyOrExpressionBody() is null - && !setter.AttributeLists.Any() - && !setter.SpanContainsDirectives()) + IMethodSymbol setMethod = propertySymbol.SetMethod; + + if (setMethod?.DeclaredAccessibility == Accessibility.Private + && setMethod.GetAttributes().IsEmpty + && !propertySymbol.IsIndexer + && !propertySymbol.IsReadOnly + && ValidateType(propertySymbol.Type) + && propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty + && AnalyzePropertyAttributes(propertySymbol)) { - IPropertySymbol propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); - - IMethodSymbol setMethod = propertySymbol.SetMethod; - - if (setMethod?.DeclaredAccessibility == Accessibility.Private - && setMethod.GetAttributes().IsEmpty - && !propertySymbol.IsIndexer - && !propertySymbol.IsReadOnly - && ValidateType(propertySymbol.Type) - && propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty - && AnalyzePropertyAttributes(propertySymbol)) - { - symbols[propertySymbol.Name] = (propertyDeclaration, propertySymbol); - } + symbols[propertySymbol.Name] = (propertyDeclaration, propertySymbol); } - - break; } + + break; + } case SyntaxKind.FieldDeclaration: - { - if (skipField) - break; + { + if (skipField) + break; - var fieldDeclaration = (FieldDeclarationSyntax)memberDeclaration; + var fieldDeclaration = (FieldDeclarationSyntax)memberDeclaration; - foreach (VariableDeclaratorSyntax declarator in fieldDeclaration.Declaration.Variables) + foreach (VariableDeclaratorSyntax declarator in fieldDeclaration.Declaration.Variables) + { + if (context.SemanticModel.GetDeclaredSymbol(declarator, context.CancellationToken) is IFieldSymbol fieldSymbol + && !fieldSymbol.IsConst + && fieldSymbol.DeclaredAccessibility == Accessibility.Private + && !fieldSymbol.IsReadOnly + && !fieldSymbol.IsVolatile + && ValidateType(fieldSymbol.Type) + && (context.IsUnityCodeAnalysisEnabled() != true + || !fieldSymbol.HasAttribute(UnityEngine_SerializeField))) { - if (context.SemanticModel.GetDeclaredSymbol(declarator, context.CancellationToken) is IFieldSymbol fieldSymbol - && !fieldSymbol.IsConst - && fieldSymbol.DeclaredAccessibility == Accessibility.Private - && !fieldSymbol.IsReadOnly - && !fieldSymbol.IsVolatile - && ValidateType(fieldSymbol.Type) - && (context.IsUnityCodeAnalysisEnabled() != true - || !fieldSymbol.HasAttribute(UnityEngine_SerializeField))) - { - symbols[fieldSymbol.Name] = (declarator, fieldSymbol); - } + symbols[fieldSymbol.Name] = (declarator, fieldSymbol); } - - break; } + + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs index 96b2a5d605..865a7b0afe 100644 --- a/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MarkLocalVariableAsConst/MarkLocalVariableAsConstAnalyzer.cs @@ -143,19 +143,19 @@ private static bool HasConstantValue( switch (typeSymbol.SpecialType) { case SpecialType.System_Boolean: - { - if (CSharpFacts.IsBooleanLiteralExpression(expression.Kind())) - return true; + { + if (CSharpFacts.IsBooleanLiteralExpression(expression.Kind())) + return true; - break; - } + break; + } case SpecialType.System_Char: - { - if (expression.IsKind(SyntaxKind.CharacterLiteralExpression)) - return true; + { + if (expression.IsKind(SyntaxKind.CharacterLiteralExpression)) + return true; - break; - } + break; + } case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: @@ -167,24 +167,24 @@ private static bool HasConstantValue( case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: - { - if (expression.IsKind(SyntaxKind.NumericLiteralExpression)) - return true; + { + if (expression.IsKind(SyntaxKind.NumericLiteralExpression)) + return true; - break; - } + break; + } case SpecialType.System_String: + { + switch (expression.Kind()) { - switch (expression.Kind()) - { - case SyntaxKind.StringLiteralExpression: - return true; - case SyntaxKind.InterpolatedStringExpression: - return false; - } - - break; + case SyntaxKind.StringLiteralExpression: + return true; + case SyntaxKind.InterpolatedStringExpression: + return false; } + + break; + } } return semanticModel.HasConstantValue(expression, cancellationToken); diff --git a/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs b/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs index 9f1fc9d6a5..785ec88e7c 100644 --- a/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/MergeSwitchSectionsAnalyzer.cs @@ -108,21 +108,21 @@ private static bool AreEquivalentJumpStatements(StatementSyntax statement1, Stat switch (statement1) { case BreakStatementSyntax _: - { - return statement2.Kind() == SyntaxKind.BreakStatement; - } + { + return statement2.Kind() == SyntaxKind.BreakStatement; + } case ReturnStatementSyntax returnStatement: - { - return returnStatement.Expression is null - && (statement2 is ReturnStatementSyntax returnStatement2) - && returnStatement2.Expression is null; - } + { + return returnStatement.Expression is null + && (statement2 is ReturnStatementSyntax returnStatement2) + && returnStatement2.Expression is null; + } case ThrowStatementSyntax throwStatement: - { - return throwStatement.Expression is null - && (statement2 is ThrowStatementSyntax throwStatement2) - && throwStatement2.Expression is null; - } + { + return throwStatement.Expression is null + && (statement2 is ThrowStatementSyntax throwStatement2) + && throwStatement2.Expression is null; + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/NamedTypeSymbolAnalyzer.cs b/src/Analyzers/CSharp/Analysis/NamedTypeSymbolAnalyzer.cs index d9c5365e6a..9618cc41ac 100644 --- a/src/Analyzers/CSharp/Analysis/NamedTypeSymbolAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/NamedTypeSymbolAnalyzer.cs @@ -64,47 +64,47 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) switch (interfaceSymbol.MetadataName) { case "IComparable": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_IComparable)) - fIComparable = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_IComparable)) + fIComparable = true; - break; - } + break; + } case "IComparable`1": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_IComparable_T)) - fIComparableOfT = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_IComparable_T)) + fIComparableOfT = true; - break; - } + break; + } case "IComparer": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_IComparer)) - fIComparer = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_IComparer)) + fIComparer = true; - break; - } + break; + } case "IComparer`1": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_Generic_IComparer_T)) - fIComparerOfT = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_Generic_IComparer_T)) + fIComparerOfT = true; - break; - } + break; + } case "IEqualityComparer": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_IEqualityComparer)) - fIEqualityComparer = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_IEqualityComparer)) + fIEqualityComparer = true; - break; - } + break; + } case "IEqualityComparer`1": - { - if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_Generic_IEqualityComparer_T)) - fIEqualityComparerOfT = true; + { + if (interfaceSymbol.HasMetadataName(MetadataNames.System_Collections_Generic_IEqualityComparer_T)) + fIEqualityComparerOfT = true; - break; - } + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitArrayCreationAnalysis.cs b/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitArrayCreationAnalysis.cs index 5bf7c44c28..dfddbadd5d 100644 --- a/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitArrayCreationAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitArrayCreationAnalysis.cs @@ -49,104 +49,104 @@ public override void AnalyzeExplicitCreation(ref SyntaxNodeAnalysisContext conte switch (parent.Kind()) { case SyntaxKind.EqualsValueClause: + { + parent = parent.Parent; + + SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration), parent); + + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { parent = parent.Parent; - SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration), parent); - - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax variableDeclaration) { - parent = parent.Parent; + SyntaxDebug.Assert(variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), variableDeclaration.Parent); - if (parent is VariableDeclarationSyntax variableDeclaration) + if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) { - SyntaxDebug.Assert(variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), variableDeclaration.Parent); - - if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) - { - AnalyzeExplicitObvious(ref context); - } - else if (variableDeclaration.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) + AnalyzeExplicitObvious(ref context); + } + else if (variableDeclaration.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) + { + if (context.UseVarInsteadOfImplicitObjectCreation() != true) { - if (context.UseVarInsteadOfImplicitObjectCreation() != true) - { - bool isVar = variableDeclaration.Type.IsVar; - AnalyzeExplicit(ref context, isObvious: !isVar, allowCollectionExpression: !isVar); - } + bool isVar = variableDeclaration.Type.IsVar; + AnalyzeExplicit(ref context, isObvious: !isVar, allowCollectionExpression: !isVar); } } } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { - AnalyzeExplicitObvious(ref context); - } - - break; } - case SyntaxKind.ArrowExpressionClause: + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) { - TypeSyntax type = DetermineReturnType(parent.Parent); + AnalyzeExplicitObvious(ref context); + } - if (type is not null) - AnalyzeExplicitObvious(ref context); + break; + } + case SyntaxKind.ArrowExpressionClause: + { + TypeSyntax type = DetermineReturnType(parent.Parent); - break; - } + if (type is not null) + AnalyzeExplicitObvious(ref context); + + break; + } case SyntaxKind.ReturnStatement: + { + if (style == TypeStyle.Implicit + || IsSingleReturnStatement(parent)) { - if (style == TypeStyle.Implicit - || IsSingleReturnStatement(parent)) + for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) { - for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) - { - if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) - return; + if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) + return; - TypeSyntax type = DetermineReturnType(node); + TypeSyntax type = DetermineReturnType(node); - if (type is not null) - { - AnalyzeExplicit(ref context, isObvious: IsSingleReturnStatement(parent)); - return; - } + if (type is not null) + { + AnalyzeExplicit(ref context, isObvious: IsSingleReturnStatement(parent)); + return; } } - - break; } + + break; + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: + { + AnalyzeExplicitNotObvious(ref context); + break; + } + case SyntaxKind.CoalesceExpression: + { + if (style == TypeStyle.Implicit) { AnalyzeExplicitNotObvious(ref context); - break; } - case SyntaxKind.CoalesceExpression: + else if (style == TypeStyle.ImplicitWhenTypeIsObvious + && parent.IsParentKind(SyntaxKind.EqualsValueClause)) { - if (style == TypeStyle.Implicit) + if (parent.Parent.Parent is VariableDeclaratorSyntax variableDeclarator) { - AnalyzeExplicitNotObvious(ref context); - } - else if (style == TypeStyle.ImplicitWhenTypeIsObvious - && parent.IsParentKind(SyntaxKind.EqualsValueClause)) - { - if (parent.Parent.Parent is VariableDeclaratorSyntax variableDeclarator) - { - if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration - && variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) - { - AnalyzeExplicitObvious(ref context); - } - } - else if (parent.Parent.Parent is PropertyDeclarationSyntax) + if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration + && variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) { AnalyzeExplicitObvious(ref context); } } - - break; + else if (parent.Parent.Parent is PropertyDeclarationSyntax) + { + AnalyzeExplicitObvious(ref context); + } } + + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitCreationAnalysis.cs b/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitCreationAnalysis.cs index fc8bacb661..61b2aafb27 100644 --- a/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitCreationAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/ObjectCreation/ImplicitOrExplicitCreationAnalysis.cs @@ -75,226 +75,226 @@ public virtual void AnalyzeExplicitCreation(ref SyntaxNodeAnalysisContext contex { case SyntaxKind.ThrowExpression: case SyntaxKind.ThrowStatement: + { + if (context.SemanticModel + .GetTypeSymbol(expression, context.CancellationToken)? + .HasMetadataName(MetadataNames.System_Exception) == true) { - if (context.SemanticModel - .GetTypeSymbol(expression, context.CancellationToken)? - .HasMetadataName(MetadataNames.System_Exception) == true) - { - ReportExplicitToImplicit(ref context); - } - - break; + ReportExplicitToImplicit(ref context); } + + break; + } case SyntaxKind.EqualsValueClause: + { + parent = parent.Parent; + + SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration), parent); + + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { parent = parent.Parent; - SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration), parent); - - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax variableDeclaration) { - parent = parent.Parent; + SyntaxDebug.Assert(variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), variableDeclaration.Parent); - if (parent is VariableDeclarationSyntax variableDeclaration) + if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) { - SyntaxDebug.Assert(variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), variableDeclaration.Parent); - - if (variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) - { - AnalyzeType(ref context, expression, variableDeclaration.Type); - } - else if (variableDeclaration.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) + AnalyzeType(ref context, expression, variableDeclaration.Type); + } + else if (variableDeclaration.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) + { + if (context.UseVarInsteadOfImplicitObjectCreation() == false) { - if (context.UseVarInsteadOfImplicitObjectCreation() == false) + if (variableDeclaration.Type.IsVar) + { + ReportExplicitToImplicit(ref context); + } + else { - if (variableDeclaration.Type.IsVar) - { - ReportExplicitToImplicit(ref context); - } - else - { - AnalyzeType(ref context, expression, variableDeclaration.Type); - } + AnalyzeType(ref context, expression, variableDeclaration.Type); } } } } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { - AnalyzeType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); - } - - break; } - case SyntaxKind.ArrowExpressionClause: + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) { - TypeSyntax type = DetermineReturnType(parent.Parent); + AnalyzeType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); + } - SyntaxDebug.Assert(type is not null, parent); + break; + } + case SyntaxKind.ArrowExpressionClause: + { + TypeSyntax type = DetermineReturnType(parent.Parent); - if (type is not null) - AnalyzeType(ref context, expression, type); + SyntaxDebug.Assert(type is not null, parent); - break; - } + if (type is not null) + AnalyzeType(ref context, expression, type); + + break; + } case SyntaxKind.ArrayInitializerExpression: + { + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ArrayCreationExpression, SyntaxKind.ImplicitArrayCreationExpression, SyntaxKind.EqualsValueClause, SyntaxKind.ImplicitStackAllocArrayCreationExpression), parent.Parent); + + if (parent.IsParentKind(SyntaxKind.ArrayCreationExpression)) { - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ArrayCreationExpression, SyntaxKind.ImplicitArrayCreationExpression, SyntaxKind.EqualsValueClause, SyntaxKind.ImplicitStackAllocArrayCreationExpression), parent.Parent); + var arrayCreationExpression = (ArrayCreationExpressionSyntax)parent.Parent; - if (parent.IsParentKind(SyntaxKind.ArrayCreationExpression)) - { - var arrayCreationExpression = (ArrayCreationExpressionSyntax)parent.Parent; + AnalyzeType(ref context, expression, arrayCreationExpression.Type.ElementType); + } + else if (parent.IsParentKind(SyntaxKind.EqualsValueClause)) + { + parent = parent.Parent.Parent; - AnalyzeType(ref context, expression, arrayCreationExpression.Type.ElementType); - } - else if (parent.IsParentKind(SyntaxKind.EqualsValueClause)) + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { - parent = parent.Parent.Parent; + parent = parent.Parent; - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax variableDeclaration) { - parent = parent.Parent; - - if (parent is VariableDeclarationSyntax variableDeclaration) + if (parent.IsParentKind(SyntaxKind.FieldDeclaration)) { - if (parent.IsParentKind(SyntaxKind.FieldDeclaration)) - { + AnalyzeArrayType(ref context, expression, variableDeclaration.Type); + } + else if (parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) + { + if (!variableDeclaration.Type.IsVar) AnalyzeArrayType(ref context, expression, variableDeclaration.Type); - } - else if (parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement)) - { - if (!variableDeclaration.Type.IsVar) - AnalyzeArrayType(ref context, expression, variableDeclaration.Type); - } } } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { - AnalyzeArrayType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); - } } - - break; + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) + { + AnalyzeArrayType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); + } } + + break; + } case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: + { + if (style != TypeStyle.Implicit + && !IsSingleReturnStatement(parent)) { - if (style != TypeStyle.Implicit - && !IsSingleReturnStatement(parent)) - { - return; - } + return; + } - for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) - { - if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) - return; + for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) + { + if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) + return; - TypeSyntax type = DetermineReturnType(node); + TypeSyntax type = DetermineReturnType(node); - if (type is not null) + if (type is not null) + { + if (parent.IsKind(SyntaxKind.YieldReturnStatement)) { - if (parent.IsKind(SyntaxKind.YieldReturnStatement)) - { - ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(type, context.CancellationToken); + ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(type, context.CancellationToken); - if (typeSymbol?.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) - { - var ienumerableOfT = (INamedTypeSymbol)typeSymbol; + if (typeSymbol?.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) + { + var ienumerableOfT = (INamedTypeSymbol)typeSymbol; - ITypeSymbol typeSymbol2 = ienumerableOfT.TypeArguments.Single(); + ITypeSymbol typeSymbol2 = ienumerableOfT.TypeArguments.Single(); - AnalyzeTypeSymbol(ref context, expression, typeSymbol2); - } - } - else - { - AnalyzeType(ref context, expression, type); + AnalyzeTypeSymbol(ref context, expression, typeSymbol2); } - - return; } - } + else + { + AnalyzeType(ref context, expression, type); + } - break; + return; + } } + + break; + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: + { + if (style == TypeStyle.Implicit) { - if (style == TypeStyle.Implicit) - { - var assignment = (AssignmentExpressionSyntax)parent; - AnalyzeExpression(ref context, expression, assignment.Left); - } - - break; + var assignment = (AssignmentExpressionSyntax)parent; + AnalyzeExpression(ref context, expression, assignment.Left); } + + break; + } case SyntaxKind.CoalesceExpression: + { + if (style == TypeStyle.Implicit) { - if (style == TypeStyle.Implicit) - { - var coalesceExpression = (BinaryExpressionSyntax)parent; - AnalyzeExpression(ref context, expression, coalesceExpression.Left); - } - else if (style == TypeStyle.ImplicitWhenTypeIsObvious - && parent.IsParentKind(SyntaxKind.EqualsValueClause)) + var coalesceExpression = (BinaryExpressionSyntax)parent; + AnalyzeExpression(ref context, expression, coalesceExpression.Left); + } + else if (style == TypeStyle.ImplicitWhenTypeIsObvious + && parent.IsParentKind(SyntaxKind.EqualsValueClause)) + { + if (parent.Parent.Parent is VariableDeclaratorSyntax variableDeclarator) { - if (parent.Parent.Parent is VariableDeclaratorSyntax variableDeclarator) - { - if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration - && variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) - { - AnalyzeType(ref context, expression, variableDeclaration.Type); - } - } - else if (parent.Parent.Parent is PropertyDeclarationSyntax propertyDeclaration) + if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration + && variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration)) { - AnalyzeType(ref context, expression, propertyDeclaration.Type); + AnalyzeType(ref context, expression, variableDeclaration.Type); } } - - break; + else if (parent.Parent.Parent is PropertyDeclarationSyntax propertyDeclaration) + { + AnalyzeType(ref context, expression, propertyDeclaration.Type); + } } + + break; + } case SyntaxKind.CollectionInitializerExpression: + { + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression, SyntaxKind.SimpleAssignmentExpression), parent.Parent); + + parent = parent.Parent; + if (parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression)) { - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression, SyntaxKind.SimpleAssignmentExpression), parent.Parent); + SyntaxNode parentObjectCreation = parent; parent = parent.Parent; - if (parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression)) + if (parent.IsKind(SyntaxKind.EqualsValueClause)) { - SyntaxNode parentObjectCreation = parent; - parent = parent.Parent; - if (parent.IsKind(SyntaxKind.EqualsValueClause)) + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { parent = parent.Parent; - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax variableDeclaration + && parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement)) { - parent = parent.Parent; - if (parent is VariableDeclarationSyntax variableDeclaration - && parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement)) + if (parentObjectCreation is ExpressionSyntax parentObjectCreationExpression) { - if (parentObjectCreation is ExpressionSyntax parentObjectCreationExpression) - { - AnalyzeExpression(ref context, expression, parentObjectCreationExpression, extractGenericType: true); - } - else - { - AnalyzeType(ref context, expression, variableDeclaration.Type, extractGenericType: true); - } + AnalyzeExpression(ref context, expression, parentObjectCreationExpression, extractGenericType: true); + } + else + { + AnalyzeType(ref context, expression, variableDeclaration.Type, extractGenericType: true); } - } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { - AnalyzeType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); } } + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) + { + AnalyzeType(ref context, expression, ((PropertyDeclarationSyntax)parent).Type); + } } - - break; } + + break; + } } } @@ -316,176 +316,176 @@ protected void AnalyzeImplicit(ref SyntaxNodeAnalysisContext context) { case SyntaxKind.ThrowExpression: case SyntaxKind.ThrowStatement: + { + if (style == TypeStyle.Explicit + && context.SemanticModel.GetTypeSymbol(context.Node, context.CancellationToken)? + .HasMetadataName(MetadataNames.System_Exception) == true) { - if (style == TypeStyle.Explicit - && context.SemanticModel.GetTypeSymbol(context.Node, context.CancellationToken)? - .HasMetadataName(MetadataNames.System_Exception) == true) - { - ReportImplicitToExplicit(ref context); - } - - break; + ReportImplicitToExplicit(ref context); } + + break; + } case SyntaxKind.EqualsValueClause: + { + parent = parent.Parent; + + SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration, SyntaxKind.Parameter), parent); + + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { parent = parent.Parent; - SyntaxDebug.Assert(parent.IsKind(SyntaxKind.VariableDeclarator, SyntaxKind.PropertyDeclaration, SyntaxKind.Parameter), parent); - - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax variableDeclaration) { - parent = parent.Parent; - - if (parent is VariableDeclarationSyntax variableDeclaration) - { - bool isVar = variableDeclaration.Type.IsVar; + bool isVar = variableDeclaration.Type.IsVar; #if ROSLYN_4_7 - SyntaxDebug.Assert(!isVar || context.Node.IsKind(SyntaxKind.CollectionExpression, SyntaxKind.ImplicitArrayCreationExpression), variableDeclaration); + SyntaxDebug.Assert(!isVar || context.Node.IsKind(SyntaxKind.CollectionExpression, SyntaxKind.ImplicitArrayCreationExpression), variableDeclaration); #else SyntaxDebug.Assert(!isVar || context.Node.IsKind(SyntaxKind.ImplicitArrayCreationExpression), variableDeclaration); #endif - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), parent.Parent); + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), parent.Parent); - if (!AnalyzeImplicit(ref context, isObvious: !isVar, allowCollectionExpression: !isVar) - && parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement) - && variableDeclaration.Variables.Count == 1 - && !isVar - && context.UseVarInsteadOfImplicitObjectCreation() == true) - { - ReportVarToExplicit(ref context, variableDeclaration.Type); - } + if (!AnalyzeImplicit(ref context, isObvious: !isVar, allowCollectionExpression: !isVar) + && parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement) + && variableDeclaration.Variables.Count == 1 + && !isVar + && context.UseVarInsteadOfImplicitObjectCreation() == true) + { + ReportVarToExplicit(ref context, variableDeclaration.Type); } } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { - AnalyzeImplicitObvious(ref context); - } - - break; } - case SyntaxKind.ArrowExpressionClause: + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) { - if (style == TypeStyle.Explicit) - { - TypeSyntax type = DetermineReturnType(parent.Parent); + AnalyzeImplicitObvious(ref context); + } - SyntaxDebug.Assert(type is not null, parent); + break; + } + case SyntaxKind.ArrowExpressionClause: + { + if (style == TypeStyle.Explicit) + { + TypeSyntax type = DetermineReturnType(parent.Parent); - if (type is not null) - AnalyzeImplicitObvious(ref context); - } + SyntaxDebug.Assert(type is not null, parent); - break; + if (type is not null) + AnalyzeImplicitObvious(ref context); } + + break; + } case SyntaxKind.ArrayInitializerExpression: - { - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ArrayCreationExpression, SyntaxKind.ImplicitArrayCreationExpression, SyntaxKind.EqualsValueClause), parent.Parent); + { + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ArrayCreationExpression, SyntaxKind.ImplicitArrayCreationExpression, SyntaxKind.EqualsValueClause), parent.Parent); - if (parent.IsParentKind(SyntaxKind.ArrayCreationExpression)) - AnalyzeImplicitObvious(ref context); + if (parent.IsParentKind(SyntaxKind.ArrayCreationExpression)) + AnalyzeImplicitObvious(ref context); - break; - } + break; + } case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: + { + if (style != TypeStyle.Explicit + && (style != TypeStyle.ImplicitWhenTypeIsObvious || IsSingleReturnStatement(parent))) { - if (style != TypeStyle.Explicit - && (style != TypeStyle.ImplicitWhenTypeIsObvious || IsSingleReturnStatement(parent))) - { - return; - } + return; + } - for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) - { - if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) - return; + for (SyntaxNode node = parent.Parent; node is not null; node = node.Parent) + { + if (CSharpFacts.IsAnonymousFunctionExpression(node.Kind())) + return; - TypeSyntax type = DetermineReturnType(node); + TypeSyntax type = DetermineReturnType(node); - if (type is not null) + if (type is not null) + { + if (parent.IsKind(SyntaxKind.YieldReturnStatement)) { - if (parent.IsKind(SyntaxKind.YieldReturnStatement)) - { - ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(type, context.CancellationToken); + ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(type, context.CancellationToken); - if (typeSymbol?.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) - AnalyzeImplicitNotObvious(ref context); - } - else - { - AnalyzeImplicit(ref context, isObvious: IsSingleReturnStatement(parent)); - } + if (typeSymbol?.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) + AnalyzeImplicitNotObvious(ref context); + } + else + { + AnalyzeImplicit(ref context, isObvious: IsSingleReturnStatement(parent)); } } - - break; } + + break; + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: - { - AnalyzeImplicitNotObvious(ref context); - break; - } + { + AnalyzeImplicitNotObvious(ref context); + break; + } case SyntaxKind.CoalesceExpression: + { + if (parent.IsParentKind(SyntaxKind.EqualsValueClause)) { - if (parent.IsParentKind(SyntaxKind.EqualsValueClause)) + switch (parent.Parent.Parent) { - switch (parent.Parent.Parent) + case VariableDeclaratorSyntax variableDeclarator: { - case VariableDeclaratorSyntax variableDeclarator: - { - if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration) - AnalyzeImplicit(ref context, isObvious: !variableDeclaration.Type.IsVar); + if (variableDeclarator.Parent is VariableDeclarationSyntax variableDeclaration) + AnalyzeImplicit(ref context, isObvious: !variableDeclaration.Type.IsVar); - return; - } - case PropertyDeclarationSyntax: - { - AnalyzeImplicitObvious(ref context); - return; - } + return; + } + case PropertyDeclarationSyntax: + { + AnalyzeImplicitObvious(ref context); + return; } } - - AnalyzeImplicitNotObvious(ref context); - break; } + + AnalyzeImplicitNotObvious(ref context); + break; + } case SyntaxKind.CollectionInitializerExpression: - { - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression, SyntaxKind.SimpleAssignmentExpression), parent.Parent); + { + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression, SyntaxKind.SimpleAssignmentExpression), parent.Parent); - if (style != TypeStyle.Explicit) - return; + if (style != TypeStyle.Explicit) + return; + parent = parent.Parent; + if (parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression)) + { parent = parent.Parent; - if (parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ImplicitObjectCreationExpression)) + if (parent.IsKind(SyntaxKind.EqualsValueClause)) { parent = parent.Parent; - if (parent.IsKind(SyntaxKind.EqualsValueClause)) + if (parent.IsKind(SyntaxKind.VariableDeclarator)) { parent = parent.Parent; - if (parent.IsKind(SyntaxKind.VariableDeclarator)) + if (parent is VariableDeclarationSyntax) { - parent = parent.Parent; - if (parent is VariableDeclarationSyntax) - { - SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), parent.Parent); + SyntaxDebug.Assert(parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement), parent.Parent); - AnalyzeImplicitObvious(ref context); - } - } - else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) - { AnalyzeImplicitObvious(ref context); } } + else if (parent.IsKind(SyntaxKind.PropertyDeclaration)) + { + AnalyzeImplicitObvious(ref context); + } } - - break; } + + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs index 80b18066a1..d756eb5d96 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeLinqMethodCallAnalysis.cs @@ -168,33 +168,33 @@ private static void SimplifyLinqMethodChain( switch (methodName) { case "Where": - { - if (!SymbolUtility.IsLinqWhere(methodSymbol2, allowImmutableArrayExtension: true)) - return; + { + if (!SymbolUtility.IsLinqWhere(methodSymbol2, allowImmutableArrayExtension: true)) + return; - break; - } + break; + } case "Select": + { + if (!SymbolUtility.IsLinqSelect(methodSymbol2, allowImmutableArrayExtension: true)) + return; + + if (invocationInfo.NameText == "ToList" + && semanticModel + .GetTypeSymbol(invocationInfo2.Expression, cancellationToken)? + .OriginalDefinition + .HasMetadataName(MetadataNames.System_Collections_Generic_List_T) != true) { - if (!SymbolUtility.IsLinqSelect(methodSymbol2, allowImmutableArrayExtension: true)) - return; - - if (invocationInfo.NameText == "ToList" - && semanticModel - .GetTypeSymbol(invocationInfo2.Expression, cancellationToken)? - .OriginalDefinition - .HasMetadataName(MetadataNames.System_Collections_Generic_List_T) != true) - { - return; - } - - break; - } - default: - { - Debug.Fail(methodName); return; } + + break; + } + default: + { + Debug.Fail(methodName); + return; + } } TextSpan span = TextSpan.FromBounds(invocationInfo2.Name.SpanStart, invocation.Span.End); @@ -519,55 +519,55 @@ public static void AnalyzeCount(SyntaxNodeAnalysisContext context, in SimpleMemb { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: + { + var equalsExpression = (BinaryExpressionSyntax)parent; + + if (equalsExpression.Left == invocationExpression) { - var equalsExpression = (BinaryExpressionSyntax)parent; - - if (equalsExpression.Left == invocationExpression) - { - if (equalsExpression.Right.IsNumericLiteralExpression("0")) - ReportNameWithArgumentList(context, invocationInfo); - } - else if (equalsExpression.Left.IsNumericLiteralExpression("0")) - { + if (equalsExpression.Right.IsNumericLiteralExpression("0")) ReportNameWithArgumentList(context, invocationInfo); - } - - break; } + else if (equalsExpression.Left.IsNumericLiteralExpression("0")) + { + ReportNameWithArgumentList(context, invocationInfo); + } + + break; + } case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: + { + var binaryExpression = (BinaryExpressionSyntax)parent; + + if (binaryExpression.Left == invocationExpression) { - var binaryExpression = (BinaryExpressionSyntax)parent; - - if (binaryExpression.Left == invocationExpression) - { - if (binaryExpression.Right.IsNumericLiteralExpression("0")) - ReportNameWithArgumentList(context, invocationInfo); - } - else if (binaryExpression.Left.IsNumericLiteralExpression("1")) - { + if (binaryExpression.Right.IsNumericLiteralExpression("0")) ReportNameWithArgumentList(context, invocationInfo); - } - - break; } + else if (binaryExpression.Left.IsNumericLiteralExpression("1")) + { + ReportNameWithArgumentList(context, invocationInfo); + } + + break; + } case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanExpression: + { + var binaryExpression = (BinaryExpressionSyntax)parent; + + if (binaryExpression.Left == invocationExpression) { - var binaryExpression = (BinaryExpressionSyntax)parent; - - if (binaryExpression.Left == invocationExpression) - { - if (binaryExpression.Right.IsNumericLiteralExpression("1")) - ReportNameWithArgumentList(context, invocationInfo); - } - else if (binaryExpression.Left.IsNumericLiteralExpression("0")) - { + if (binaryExpression.Right.IsNumericLiteralExpression("1")) ReportNameWithArgumentList(context, invocationInfo); - } - - break; } + else if (binaryExpression.Left.IsNumericLiteralExpression("0")) + { + ReportNameWithArgumentList(context, invocationInfo); + } + + break; + } } bool CanBeReplacedWithMemberAccessExpression(ExpressionSyntax e) @@ -577,14 +577,14 @@ bool CanBeReplacedWithMemberAccessExpression(ExpressionSyntax e) switch (p.Kind()) { case SyntaxKind.ExpressionStatement: - { - return false; - } + { + return false; + } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: - { - return semanticModel.GetMethodSymbol((LambdaExpressionSyntax)p, cancellationToken)?.ReturnType.IsVoid() == false; - } + { + return semanticModel.GetMethodSymbol((LambdaExpressionSyntax)p, cancellationToken)?.ReturnType.IsVoid() == false; + } } return true; diff --git a/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs index a0de789691..e858959a7e 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeMethodCallAnalysis.cs @@ -267,30 +267,30 @@ IfStatementSyntax GetIfStatement() switch (parent.Kind()) { case SyntaxKind.LogicalNotExpression: - { - var logicalNot = (PrefixUnaryExpressionSyntax)parent; - - isNegation = true; + { + var logicalNot = (PrefixUnaryExpressionSyntax)parent; - if (logicalNot.IsParentKind(SyntaxKind.IfStatement)) - { - var ifStatement2 = (IfStatementSyntax)logicalNot.Parent; + isNegation = true; - if (ifStatement2.Condition == logicalNot) - return ifStatement2; - } + if (logicalNot.IsParentKind(SyntaxKind.IfStatement)) + { + var ifStatement2 = (IfStatementSyntax)logicalNot.Parent; - break; + if (ifStatement2.Condition == logicalNot) + return ifStatement2; } + + break; + } case SyntaxKind.IfStatement: - { - var ifStatement2 = (IfStatementSyntax)parent; + { + var ifStatement2 = (IfStatementSyntax)parent; - if (ifStatement2.Condition == invocationExpression) - return ifStatement2; + if (ifStatement2.Condition == invocationExpression) + return ifStatement2; - break; - } + break; + } } return null; diff --git a/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs index 809c8cefae..3224ab1d7a 100644 --- a/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/OptimizeStringBuilderAppendCallAnalysis.cs @@ -93,55 +93,55 @@ public static void Analyze(SyntaxNodeAnalysisContext context, in SimpleMemberInv switch (methodSymbol2.Name) { case "Substring": - { - ImmutableArray parameters = methodSymbol2.Parameters; + { + ImmutableArray parameters = methodSymbol2.Parameters; - switch (parameters.Length) + switch (parameters.Length) + { + case 1: { - case 1: - { - if (parameters[0].Type.SpecialType == SpecialType.System_Int32 - && invocationInfo2.Expression.IsKind(SyntaxKind.IdentifierName) - && context.SemanticModel.GetSymbol(invocationInfo2.Expression, context.CancellationToken).IsKind(SymbolKind.Field, SymbolKind.Local, SymbolKind.Parameter)) - { - ReportDiagnostic(argument); - } - - break; - } - case 2: - { - if (parameters[0].Type.SpecialType == SpecialType.System_Int32 - && parameters[1].Type.SpecialType == SpecialType.System_Int32) - { - ReportDiagnostic(argument); - } - - break; - } + if (parameters[0].Type.SpecialType == SpecialType.System_Int32 + && invocationInfo2.Expression.IsKind(SyntaxKind.IdentifierName) + && context.SemanticModel.GetSymbol(invocationInfo2.Expression, context.CancellationToken).IsKind(SymbolKind.Field, SymbolKind.Local, SymbolKind.Parameter)) + { + ReportDiagnostic(argument); + } + + break; } + case 2: + { + if (parameters[0].Type.SpecialType == SpecialType.System_Int32 + && parameters[1].Type.SpecialType == SpecialType.System_Int32) + { + ReportDiagnostic(argument); + } - break; + break; + } } + + break; + } case "Remove": - { - if (methodSymbol2.HasSingleParameter(SpecialType.System_Int32)) - ReportDiagnostic(argument); + { + if (methodSymbol2.HasSingleParameter(SpecialType.System_Int32)) + ReportDiagnostic(argument); - break; - } + break; + } case "Format": - { - ReportDiagnostic(argument); - break; - } + { + ReportDiagnostic(argument); + break; + } case "Join": - { - if (methodSymbol.ContainingType.ContainsMember("AppendJoin")) - ReportDiagnostic(argument); + { + if (methodSymbol.ContainingType.ContainsMember("AppendJoin")) + ReportDiagnostic(argument); - break; - } + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs index 306a7ebf39..8d07b9c910 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantAssignmentAnalyzer.cs @@ -208,20 +208,20 @@ private static void AnalyzeSimpleAssignment(SyntaxNodeAnalysisContext context) switch (symbol?.Kind) { case SymbolKind.Local: - { - break; - } + { + break; + } case SymbolKind.Parameter: - { - if (((IParameterSymbol)symbol).RefKind != RefKind.None) - return; + { + if (((IParameterSymbol)symbol).RefKind != RefKind.None) + return; - break; - } + break; + } default: - { - return; - } + { + return; + } } if (IsAssignedInsideAnonymousFunctionButDeclaredOutsideOfIt()) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs index 5f673d1154..5d817dccda 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantBaseInterfaceAnalyzer.cs @@ -160,35 +160,35 @@ bool IsExplicitlyImplemented(ISymbol interfaceSymbol) switch (member.Kind) { case SymbolKind.Event: + { + foreach (IEventSymbol eventSymbol in ((IEventSymbol)member).ExplicitInterfaceImplementations) { - foreach (IEventSymbol eventSymbol in ((IEventSymbol)member).ExplicitInterfaceImplementations) - { - if (SymbolEqualityComparer.Default.Equals(eventSymbol.ContainingType, interfaceSymbol)) - return true; - } - - break; + if (SymbolEqualityComparer.Default.Equals(eventSymbol.ContainingType, interfaceSymbol)) + return true; } + + break; + } case SymbolKind.Method: + { + foreach (IMethodSymbol methodSymbol in ((IMethodSymbol)member).ExplicitInterfaceImplementations) { - foreach (IMethodSymbol methodSymbol in ((IMethodSymbol)member).ExplicitInterfaceImplementations) - { - if (SymbolEqualityComparer.Default.Equals(methodSymbol.ContainingType, interfaceSymbol)) - return true; - } - - break; + if (SymbolEqualityComparer.Default.Equals(methodSymbol.ContainingType, interfaceSymbol)) + return true; } + + break; + } case SymbolKind.Property: + { + foreach (IPropertySymbol propertySymbol in ((IPropertySymbol)member).ExplicitInterfaceImplementations) { - foreach (IPropertySymbol propertySymbol in ((IPropertySymbol)member).ExplicitInterfaceImplementations) - { - if (SymbolEqualityComparer.Default.Equals(propertySymbol.ContainingType, interfaceSymbol)) - return true; - } - - break; + if (SymbolEqualityComparer.Default.Equals(propertySymbol.ContainingType, interfaceSymbol)) + return true; } + + break; + } } } @@ -224,59 +224,59 @@ private static bool IsImplementedWithNewKeyword( switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; + { + var methodDeclaration = (MethodDeclarationSyntax)node; - if (methodDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) - return true; + if (methodDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) + return true; - break; - } + break; + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; - if (propertyDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) - return true; + if (propertyDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) + return true; - break; - } + break; + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - if (indexerDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) - return true; + if (indexerDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) + return true; - break; - } + break; + } case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)node; + { + var eventDeclaration = (EventDeclarationSyntax)node; - if (eventDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) - return true; + if (eventDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) + return true; - break; - } + break; + } case SyntaxKind.VariableDeclarator: + { + if (node.IsParentKind(SyntaxKind.VariableDeclaration) + && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration)) { - if (node.IsParentKind(SyntaxKind.VariableDeclaration) - && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration)) - { - var eventFieldDeclaration = (EventFieldDeclarationSyntax)node.Parent.Parent; + var eventFieldDeclaration = (EventFieldDeclarationSyntax)node.Parent.Parent; - if (eventFieldDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) - return true; - } - - break; + if (eventFieldDeclaration.Modifiers.Contains(SyntaxKind.NewKeyword)) + return true; } + + break; + } default: - { - SyntaxDebug.Fail(node); - return true; - } + { + SyntaxDebug.Fail(node); + return true; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs index 535fbfb29b..94ec41f05c 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantCastAnalyzer.cs @@ -130,30 +130,30 @@ private static bool CheckExplicitImplementation(ITypeSymbol typeSymbol, ISymbol switch (implementation.Kind) { case SymbolKind.Property: + { + foreach (IPropertySymbol propertySymbol in ((IPropertySymbol)implementation).ExplicitInterfaceImplementations) { - foreach (IPropertySymbol propertySymbol in ((IPropertySymbol)implementation).ExplicitInterfaceImplementations) - { - if (SymbolEqualityComparer.Default.Equals(propertySymbol.OriginalDefinition, symbol.OriginalDefinition)) - return false; - } - - break; + if (SymbolEqualityComparer.Default.Equals(propertySymbol.OriginalDefinition, symbol.OriginalDefinition)) + return false; } + + break; + } case SymbolKind.Method: + { + foreach (IMethodSymbol methodSymbol in ((IMethodSymbol)implementation).ExplicitInterfaceImplementations) { - foreach (IMethodSymbol methodSymbol in ((IMethodSymbol)implementation).ExplicitInterfaceImplementations) - { - if (SymbolEqualityComparer.Default.Equals(methodSymbol.OriginalDefinition, symbol.OriginalDefinition)) - return false; - } - - break; + if (SymbolEqualityComparer.Default.Equals(methodSymbol.OriginalDefinition, symbol.OriginalDefinition)) + return false; } + + break; + } default: - { - Debug.Fail(implementation.Kind.ToString()); - return false; - } + { + Debug.Fail(implementation.Kind.ToString()); + return false; + } } return true; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs index 59f91e88e2..19dd637bc5 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantConstructorAnalyzer.cs @@ -100,19 +100,19 @@ private static bool CheckStructWithFieldInitializer(ConstructorDeclarationSyntax switch (member) { case PropertyDeclarationSyntax property: - { - return property.Initializer is null; - } + { + return property.Initializer is null; + } case FieldDeclarationSyntax field: + { + foreach (VariableDeclaratorSyntax declarator in field.Declaration.Variables) { - foreach (VariableDeclaratorSyntax declarator in field.Declaration.Variables) - { - if (declarator.Initializer is not null) - return false; - } - - break; + if (declarator.Initializer is not null) + return false; } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs index 2f1eb94eb2..8bf98bec04 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantDefaultSwitchSectionAnalyzer.cs @@ -68,16 +68,16 @@ private static bool ContainsOnlyBreakStatement(SwitchSectionSyntax switchSection switch (statement?.Kind()) { case SyntaxKind.Block: - { - return ((BlockSyntax)statement) - .Statements - .SingleOrDefault(shouldThrow: false)? - .Kind() == SyntaxKind.BreakStatement; - } + { + return ((BlockSyntax)statement) + .Statements + .SingleOrDefault(shouldThrow: false)? + .Kind() == SyntaxKind.BreakStatement; + } case SyntaxKind.BreakStatement: - { - return true; - } + { + return true; + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs index a0f961f875..669af8488d 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantOverridingMemberAnalyzer.cs @@ -122,15 +122,15 @@ private static bool CheckModifiers(SyntaxTokenList modifiers) switch (modifier.Kind()) { case SyntaxKind.OverrideKeyword: - { - isOverride = true; - break; - } + { + isOverride = true; + break; + } case SyntaxKind.SealedKeyword: case SyntaxKind.PartialKeyword: - { - return false; - } + { + return false; + } } } @@ -302,86 +302,86 @@ internal static bool IsFixable( switch (accessor.Kind()) { case SyntaxKind.GetAccessorDeclaration: - { - ExpressionSyntax expression = GetGetAccessorExpression(accessor); + { + ExpressionSyntax expression = GetGetAccessorExpression(accessor); - if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) != true) - return false; + if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) != true) + return false; - var memberAccess = (MemberAccessExpressionSyntax)expression; + var memberAccess = (MemberAccessExpressionSyntax)expression; - if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) - return false; + if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) + return false; - SimpleNameSyntax simpleName = memberAccess.Name; + SimpleNameSyntax simpleName = memberAccess.Name; - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (propertySymbol is null) - return false; + if (propertySymbol is null) + return false; - IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty is null) - return false; + if (overriddenProperty is null) + return false; - ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); - return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol); - } + return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol); + } case SyntaxKind.SetAccessorDeclaration: - { - ExpressionSyntax expression = GetSetAccessorExpression(accessor); + { + ExpressionSyntax expression = GetSetAccessorExpression(accessor); - SimpleAssignmentExpressionInfo assignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); + SimpleAssignmentExpressionInfo assignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); - if (!assignment.Success) - return false; + if (!assignment.Success) + return false; - if (assignment.Left.Kind() != SyntaxKind.SimpleMemberAccessExpression) - return false; + if (assignment.Left.Kind() != SyntaxKind.SimpleMemberAccessExpression) + return false; - var memberAccess = (MemberAccessExpressionSyntax)assignment.Left; + var memberAccess = (MemberAccessExpressionSyntax)assignment.Left; - if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) - return false; + if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) + return false; - if (assignment.Right.Kind() != SyntaxKind.IdentifierName) - return false; + if (assignment.Right.Kind() != SyntaxKind.IdentifierName) + return false; - var identifierName = (IdentifierNameSyntax)assignment.Right; + var identifierName = (IdentifierNameSyntax)assignment.Right; - if (identifierName.Identifier.ValueText != "value") - return false; + if (identifierName.Identifier.ValueText != "value") + return false; - SimpleNameSyntax simpleName = memberAccess.Name; + SimpleNameSyntax simpleName = memberAccess.Name; - if (simpleName is null) - return false; + if (simpleName is null) + return false; - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); - if (propertySymbol is null) - return false; + if (propertySymbol is null) + return false; - IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty is null) - return false; + if (overriddenProperty is null) + return false; - ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); - return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol); - } + return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol); + } case SyntaxKind.UnknownAccessorDeclaration: - { - return false; - } + { + return false; + } default: - { - SyntaxDebug.Fail(accessor); - return false; - } + { + SyntaxDebug.Fail(accessor); + return false; + } } } @@ -434,87 +434,87 @@ internal static bool IsFixable( switch (accessor.Kind()) { case SyntaxKind.GetAccessorDeclaration: - { - ExpressionSyntax expression = GetGetAccessorExpression(accessor); + { + ExpressionSyntax expression = GetGetAccessorExpression(accessor); - if (expression is not ElementAccessExpressionSyntax elementAccess) - return false; + if (expression is not ElementAccessExpressionSyntax elementAccess) + return false; - if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) - return false; + if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) + return false; - if (elementAccess.ArgumentList is null) - return false; + if (elementAccess.ArgumentList is null) + return false; - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - if (propertySymbol is null) - return false; + if (propertySymbol is null) + return false; - IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty is null) - return false; + if (overriddenProperty is null) + return false; - ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); - return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol) - && CheckParameters(indexerDeclaration.ParameterList, elementAccess.ArgumentList, semanticModel, cancellationToken) - && CheckDefaultValues(propertySymbol.Parameters, overriddenProperty.Parameters); - } + return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol) + && CheckParameters(indexerDeclaration.ParameterList, elementAccess.ArgumentList, semanticModel, cancellationToken) + && CheckDefaultValues(propertySymbol.Parameters, overriddenProperty.Parameters); + } case SyntaxKind.SetAccessorDeclaration: - { - ExpressionSyntax expression = GetSetAccessorExpression(accessor); + { + ExpressionSyntax expression = GetSetAccessorExpression(accessor); - SimpleAssignmentExpressionInfo assignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); + SimpleAssignmentExpressionInfo assignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); - if (!assignment.Success) - return false; + if (!assignment.Success) + return false; - if (assignment.Left.Kind() != SyntaxKind.ElementAccessExpression) - return false; + if (assignment.Left.Kind() != SyntaxKind.ElementAccessExpression) + return false; - var elementAccess = (ElementAccessExpressionSyntax)assignment.Left; + var elementAccess = (ElementAccessExpressionSyntax)assignment.Left; - if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) - return false; + if (elementAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) + return false; - if (elementAccess.ArgumentList is null) - return false; + if (elementAccess.ArgumentList is null) + return false; - if (assignment.Right.Kind() != SyntaxKind.IdentifierName) - return false; + if (assignment.Right.Kind() != SyntaxKind.IdentifierName) + return false; - var identifierName = (IdentifierNameSyntax)assignment.Right; + var identifierName = (IdentifierNameSyntax)assignment.Right; - if (identifierName.Identifier.ValueText != "value") - return false; + if (identifierName.Identifier.ValueText != "value") + return false; - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(indexerDeclaration, cancellationToken); - if (propertySymbol is null) - return false; + if (propertySymbol is null) + return false; - IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; + IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; - if (overriddenProperty is null) - return false; + if (overriddenProperty is null) + return false; - ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); + ISymbol symbol = semanticModel.GetSymbol(elementAccess, cancellationToken); - return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol) - && CheckParameters(indexerDeclaration.ParameterList, elementAccess.ArgumentList, semanticModel, cancellationToken) - && CheckDefaultValues(propertySymbol.Parameters, overriddenProperty.Parameters); - } + return SymbolEqualityComparer.Default.Equals(overriddenProperty, symbol) + && CheckParameters(indexerDeclaration.ParameterList, elementAccess.ArgumentList, semanticModel, cancellationToken) + && CheckDefaultValues(propertySymbol.Parameters, overriddenProperty.Parameters); + } case SyntaxKind.UnknownAccessorDeclaration: - { - return false; - } + { + return false; + } default: - { - SyntaxDebug.Fail(accessor); - return false; - } + { + SyntaxDebug.Fail(accessor); + return false; + } } } diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs index cb92ba36b2..8714052693 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantParenthesesAnalyzer.cs @@ -83,10 +83,10 @@ private static void AnalyzeParenthesizedExpression(SyntaxNodeAnalysisContext con case SyntaxKind.IfStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ArrayRankSpecifier: - { - ReportDiagnostic(context, parenthesizedExpression); - break; - } + { + ReportDiagnostic(context, parenthesizedExpression); + break; + } case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanOrEqualExpression: @@ -94,15 +94,15 @@ private static void AnalyzeParenthesizedExpression(SyntaxNodeAnalysisContext con case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.SimpleMemberAccessExpression: + { + if (expression.IsKind(SyntaxKind.IdentifierName) + || expression is LiteralExpressionSyntax) { - if (expression.IsKind(SyntaxKind.IdentifierName) - || expression is LiteralExpressionSyntax) - { - ReportDiagnostic(context, parenthesizedExpression); - } - - break; + ReportDiagnostic(context, parenthesizedExpression); } + + break; + } case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: @@ -115,40 +115,40 @@ private static void AnalyzeParenthesizedExpression(SyntaxNodeAnalysisContext con case SyntaxKind.BitwiseOrExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: - { - SyntaxKind kind = expression.Kind(); - - if (kind == SyntaxKind.IdentifierName - || expression is LiteralExpressionSyntax) - { - ReportDiagnostic(context, parenthesizedExpression); - } - else if (kind == parentKind - && ((BinaryExpressionSyntax)parent).Left == parenthesizedExpression) - { - ReportDiagnostic(context, parenthesizedExpression); - } + { + SyntaxKind kind = expression.Kind(); - break; + if (kind == SyntaxKind.IdentifierName + || expression is LiteralExpressionSyntax) + { + ReportDiagnostic(context, parenthesizedExpression); + } + else if (kind == parentKind + && ((BinaryExpressionSyntax)parent).Left == parenthesizedExpression) + { + ReportDiagnostic(context, parenthesizedExpression); } + + break; + } case SyntaxKind.LogicalNotExpression: + { + switch (expression.Kind()) { - switch (expression.Kind()) + case SyntaxKind.IdentifierName: + case SyntaxKind.GenericName: + case SyntaxKind.InvocationExpression: + case SyntaxKind.SimpleMemberAccessExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.ConditionalAccessExpression: { - case SyntaxKind.IdentifierName: - case SyntaxKind.GenericName: - case SyntaxKind.InvocationExpression: - case SyntaxKind.SimpleMemberAccessExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.ConditionalAccessExpression: - { - ReportDiagnostic(context, parenthesizedExpression); - break; - } + ReportDiagnostic(context, parenthesizedExpression); + break; } - - break; } + + break; + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: @@ -160,76 +160,76 @@ private static void AnalyzeParenthesizedExpression(SyntaxNodeAnalysisContext con case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: + { + if (((AssignmentExpressionSyntax)parent).Left == parenthesizedExpression) { - if (((AssignmentExpressionSyntax)parent).Left == parenthesizedExpression) - { - ReportDiagnostic(context, parenthesizedExpression); - } - else if (expression.IsKind(SyntaxKind.IdentifierName) - || expression is LiteralExpressionSyntax) - { - ReportDiagnostic(context, parenthesizedExpression); - } - - break; + ReportDiagnostic(context, parenthesizedExpression); } - case SyntaxKind.Interpolation: + else if (expression.IsKind(SyntaxKind.IdentifierName) + || expression is LiteralExpressionSyntax) { - if (!expression.IsKind(SyntaxKind.ConditionalExpression) - && !expression.DescendantNodes().Any(f => f.IsKind(SyntaxKind.AliasQualifiedName)) - && ((InterpolationSyntax)parent).Expression == parenthesizedExpression) - { - ReportDiagnostic(context, parenthesizedExpression); - } + ReportDiagnostic(context, parenthesizedExpression); + } - break; + break; + } + case SyntaxKind.Interpolation: + { + if (!expression.IsKind(SyntaxKind.ConditionalExpression) + && !expression.DescendantNodes().Any(f => f.IsKind(SyntaxKind.AliasQualifiedName)) + && ((InterpolationSyntax)parent).Expression == parenthesizedExpression) + { + ReportDiagnostic(context, parenthesizedExpression); } + + break; + } case SyntaxKind.AwaitExpression: - { - if (parenthesizedExpression.Expression.IsKind(SyntaxKind.SwitchExpression)) - return; + { + if (parenthesizedExpression.Expression.IsKind(SyntaxKind.SwitchExpression)) + return; - if (CSharpFacts.GetOperatorPrecedence(expression.Kind()) <= CSharpFacts.GetOperatorPrecedence(SyntaxKind.AwaitExpression)) - ReportDiagnostic(context, parenthesizedExpression); + if (CSharpFacts.GetOperatorPrecedence(expression.Kind()) <= CSharpFacts.GetOperatorPrecedence(SyntaxKind.AwaitExpression)) + ReportDiagnostic(context, parenthesizedExpression); - break; - } + break; + } case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: - { - if (expression is not AssignmentExpressionSyntax) - ReportDiagnostic(context, parenthesizedExpression); + { + if (expression is not AssignmentExpressionSyntax) + ReportDiagnostic(context, parenthesizedExpression); - break; - } + break; + } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: + { + switch (parent.Parent.Kind()) { - switch (parent.Parent.Kind()) + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.ArrowExpressionClause: + case SyntaxKind.Argument: + case SyntaxKind.ReturnStatement: + case SyntaxKind.YieldReturnStatement: + case SyntaxKind.SimpleAssignmentExpression: + case SyntaxKind.AddAssignmentExpression: + case SyntaxKind.SubtractAssignmentExpression: { - case SyntaxKind.ParenthesizedExpression: - case SyntaxKind.ArrowExpressionClause: - case SyntaxKind.Argument: - case SyntaxKind.ReturnStatement: - case SyntaxKind.YieldReturnStatement: - case SyntaxKind.SimpleAssignmentExpression: - case SyntaxKind.AddAssignmentExpression: - case SyntaxKind.SubtractAssignmentExpression: - { - ReportDiagnostic(context, parenthesizedExpression); - break; - } + ReportDiagnostic(context, parenthesizedExpression); + break; + } #if DEBUG - default: - { - SyntaxDebug.Fail(parent.Parent); - break; - } -#endif + default: + { + SyntaxDebug.Fail(parent.Parent); + break; } - - break; +#endif } + + break; + } } static void ReportDiagnostic(SyntaxNodeAnalysisContext context, ParenthesizedExpressionSyntax parenthesizedExpression) diff --git a/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs b/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs index d5d9c9410e..eb3d30cb5e 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveRedundantToStringCallAnalysis.cs @@ -63,19 +63,19 @@ private static bool IsFixable( switch (expression.Parent.Kind()) { case SyntaxKind.Interpolation: - { - return IsNotHidden(methodSymbol, containingType); - } + { + return IsNotHidden(methodSymbol, containingType); + } case SyntaxKind.AddExpression: - { - var addExpression = (BinaryExpressionSyntax)expression.Parent; - if (addExpression.Right == expression) - return semanticModel.GetTypeInfo(addExpression.Left, cancellationToken).Type?.SpecialType == SpecialType.System_String; - - return semanticModel.GetTypeInfo(addExpression.Right, cancellationToken).Type?.SpecialType == SpecialType.System_String - && (addExpression.Right.WalkDownParentheses() is not InvocationExpressionSyntax invocationExpression2 - || !IsToString(semanticModel.GetMethodSymbol(invocationExpression2, cancellationToken))); - } + { + var addExpression = (BinaryExpressionSyntax)expression.Parent; + if (addExpression.Right == expression) + return semanticModel.GetTypeInfo(addExpression.Left, cancellationToken).Type?.SpecialType == SpecialType.System_String; + + return semanticModel.GetTypeInfo(addExpression.Right, cancellationToken).Type?.SpecialType == SpecialType.System_String + && (addExpression.Right.WalkDownParentheses() is not InvocationExpressionSyntax invocationExpression2 + || !IsToString(semanticModel.GetMethodSymbol(invocationExpression2, cancellationToken))); + } } } } diff --git a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs index bd640c9351..19a17032bc 100644 --- a/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/RemoveUnnecessaryBlankLineAnalyzer.cs @@ -629,28 +629,28 @@ private static void AnalyzeEmptyBraces( switch (en.Current.Kind()) { case SyntaxKind.EndOfLineTrivia: - { - SyntaxTrivia endOfLine = en.Current; + { + SyntaxTrivia endOfLine = en.Current; - if (isEnd) + if (isEnd) + { + while (en.MoveNext()) { - while (en.MoveNext()) - { - if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) - return null; - } + if (!en.Current.IsWhitespaceOrEndOfLineTrivia()) + return null; } - - return TextSpan.FromBounds(triviaList.Span.Start, endOfLine.Span.End); } + + return TextSpan.FromBounds(triviaList.Span.Start, endOfLine.Span.End); + } case SyntaxKind.WhitespaceTrivia: - { - break; - } + { + break; + } default: - { - return null; - } + { + return null; + } } } diff --git a/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs b/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs index 2e14b40d12..b5e2527ebd 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyBooleanComparisonAnalysis.cs @@ -35,43 +35,43 @@ public static void ReportDiagnostic( switch (binaryExpression.Kind()) { case SyntaxKind.EqualsExpression: + { + if (left.IsKind(SyntaxKind.FalseLiteralExpression)) { - if (left.IsKind(SyntaxKind.FalseLiteralExpression)) - { - DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, left); + DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, left); - if (right.IsKind(SyntaxKind.LogicalNotExpression)) - DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)right).OperatorToken); - } - else if (right.IsKind(SyntaxKind.FalseLiteralExpression)) - { - DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, right); - - if (left.IsKind(SyntaxKind.LogicalNotExpression)) - DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)left).OperatorToken); - } + if (right.IsKind(SyntaxKind.LogicalNotExpression)) + DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)right).OperatorToken); + } + else if (right.IsKind(SyntaxKind.FalseLiteralExpression)) + { + DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, right); - break; + if (left.IsKind(SyntaxKind.LogicalNotExpression)) + DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)left).OperatorToken); } + + break; + } case SyntaxKind.NotEqualsExpression: + { + if (left.IsKind(SyntaxKind.TrueLiteralExpression)) { - if (left.IsKind(SyntaxKind.TrueLiteralExpression)) - { - DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, left); + DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, left); - if (right.IsKind(SyntaxKind.LogicalNotExpression)) - DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)right).OperatorToken); - } - else if (right.IsKind(SyntaxKind.TrueLiteralExpression)) - { - DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, right); - - if (left.IsKind(SyntaxKind.LogicalNotExpression)) - DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)left).OperatorToken); - } + if (right.IsKind(SyntaxKind.LogicalNotExpression)) + DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)right).OperatorToken); + } + else if (right.IsKind(SyntaxKind.TrueLiteralExpression)) + { + DiagnosticHelpers.ReportNode(context, fadeOutDescriptor, right); - break; + if (left.IsKind(SyntaxKind.LogicalNotExpression)) + DiagnosticHelpers.ReportToken(context, fadeOutDescriptor, ((PrefixUnaryExpressionSyntax)left).OperatorToken); } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs index 60db7bf295..d99c23bbbe 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyCoalesceExpressionAnalyzer.cs @@ -98,12 +98,12 @@ private static BinaryExpressionPart GetRedundantPart( case SyntaxKind.NullLiteralExpression: return BinaryExpressionPart.Left; case SyntaxKind.DefaultExpression: - { - if (IsDefaultOfReferenceOrNullableType((DefaultExpressionSyntax)left, semanticModel, cancellationToken)) - return BinaryExpressionPart.Left; + { + if (IsDefaultOfReferenceOrNullableType((DefaultExpressionSyntax)left, semanticModel, cancellationToken)) + return BinaryExpressionPart.Left; - break; - } + break; + } } Optional optional = semanticModel.GetConstantValue(left, cancellationToken); @@ -134,16 +134,16 @@ private static BinaryExpressionPart GetRedundantPart( switch (rightKind) { case SyntaxKind.NullLiteralExpression: - { - return BinaryExpressionPart.Right; - } + { + return BinaryExpressionPart.Right; + } case SyntaxKind.DefaultExpression: - { - if (IsDefaultOfReferenceOrNullableType((DefaultExpressionSyntax)right, semanticModel, cancellationToken)) - return BinaryExpressionPart.Right; + { + if (IsDefaultOfReferenceOrNullableType((DefaultExpressionSyntax)right, semanticModel, cancellationToken)) + return BinaryExpressionPart.Right; - break; - } + break; + } } if (leftKind == rightKind diff --git a/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs index 1e48b9154e..dd0e3b4cd4 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyCodeBranchingAnalyzer.cs @@ -184,40 +184,40 @@ private static bool IsFixableIfElseWithReturnOrContinueInsideIf(IfStatementSynta case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: - { - //void M() - //{ - // if (x) - // { - // return; - // } - // else - // { - // M(); - // } - - return ifStatement.SingleNonBlockStatementOrDefault() is ReturnStatementSyntax returnStatement - && returnStatement.Expression is null; - } + { + //void M() + //{ + // if (x) + // { + // return; + // } + // else + // { + // M(); + // } + + return ifStatement.SingleNonBlockStatementOrDefault() is ReturnStatementSyntax returnStatement + && returnStatement.Expression is null; + } case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: - { - //while (x) - //{ - // if (y) - // { - // continue; - // } - // else - // { - // M(); - // } - //} - - return ifStatement.SingleNonBlockStatementOrDefault().IsKind(SyntaxKind.ContinueStatement); - } + { + //while (x) + //{ + // if (y) + // { + // continue; + // } + // else + // { + // M(); + // } + //} + + return ifStatement.SingleNonBlockStatementOrDefault().IsKind(SyntaxKind.ContinueStatement); + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs index 4bc933e2ee..68a314b09c 100644 --- a/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SimplifyLogicalNegationAnalyzer.cs @@ -47,66 +47,66 @@ private static void AnalyzeLogicalNotExpression(SyntaxNodeAnalysisContext contex case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.LogicalNotExpression: - { - ReportDiagnostic(); - break; - } + { + ReportDiagnostic(); + break; + } case SyntaxKind.EqualsExpression: - { - MemberDeclarationSyntax memberDeclaration = logicalNot.FirstAncestor(); - - if (memberDeclaration is OperatorDeclarationSyntax operatorDeclaration - && operatorDeclaration.OperatorToken.IsKind(SyntaxKind.ExclamationEqualsToken)) - { - return; - } + { + MemberDeclarationSyntax memberDeclaration = logicalNot.FirstAncestor(); - ReportDiagnostic(); - break; - } - case SyntaxKind.NotEqualsExpression: + if (memberDeclaration is OperatorDeclarationSyntax operatorDeclaration + && operatorDeclaration.OperatorToken.IsKind(SyntaxKind.ExclamationEqualsToken)) { - MemberDeclarationSyntax memberDeclaration = logicalNot.FirstAncestor(); + return; + } - if (memberDeclaration is OperatorDeclarationSyntax operatorDeclaration - && operatorDeclaration.OperatorToken.IsKind(SyntaxKind.EqualsEqualsToken)) - { - return; - } + ReportDiagnostic(); + break; + } + case SyntaxKind.NotEqualsExpression: + { + MemberDeclarationSyntax memberDeclaration = logicalNot.FirstAncestor(); - ReportDiagnostic(); - break; + if (memberDeclaration is OperatorDeclarationSyntax operatorDeclaration + && operatorDeclaration.OperatorToken.IsKind(SyntaxKind.EqualsEqualsToken)) + { + return; } + + ReportDiagnostic(); + break; + } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - var binaryExpression = (BinaryExpressionSyntax)expression; - - if (IsNumericType(binaryExpression.Left, context.SemanticModel, context.CancellationToken) - && IsNumericType(binaryExpression.Right, context.SemanticModel, context.CancellationToken)) - { - ReportDiagnostic(); - } + { + var binaryExpression = (BinaryExpressionSyntax)expression; - break; + if (IsNumericType(binaryExpression.Left, context.SemanticModel, context.CancellationToken) + && IsNumericType(binaryExpression.Right, context.SemanticModel, context.CancellationToken)) + { + ReportDiagnostic(); } + + break; + } case SyntaxKind.IsPatternExpression: + { + if (((CSharpParseOptions)expression.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9) { - if (((CSharpParseOptions)expression.SyntaxTree.Options).LanguageVersion >= LanguageVersion.CSharp9) - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; + var isPatternExpression = (IsPatternExpressionSyntax)expression; - if (isPatternExpression.Pattern is ConstantPatternSyntax constantPattern - && constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) - { - ReportDiagnostic(); - } + if (isPatternExpression.Pattern is ConstantPatternSyntax constantPattern + && constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) + { + ReportDiagnostic(); } - - break; } + + break; + } } void ReportDiagnostic() @@ -136,25 +136,25 @@ public static bool IsNumericType(ExpressionSyntax expression, SemanticModel sema case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: - { - return true; - } + { + return true; + } case SpecialType.System_Single: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - return optional.HasValue - && optional.Value is float value - && !float.IsNaN(value); - } + return optional.HasValue + && optional.Value is float value + && !float.IsNaN(value); + } case SpecialType.System_Double: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - return optional.HasValue - && optional.Value is double value - && !double.IsNaN(value); - } + return optional.HasValue + && optional.Value is double value + && !double.IsNaN(value); + } } } diff --git a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs index 8b4e2d5883..fe08518d82 100644 --- a/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/SingleLineDocumentationCommentTriviaAnalyzer.cs @@ -83,89 +83,89 @@ private static void AnalyzeSingleLineDocumentationCommentTrivia(SyntaxNodeAnalys { case XmlTag.Include: case XmlTag.Exclude: - { - if (isFirst) - containsIncludeOrExclude = true; + { + if (isFirst) + containsIncludeOrExclude = true; - break; - } + break; + } case XmlTag.InheritDoc: - { - containsInheritDoc = true; - break; - } + { + containsInheritDoc = true; + break; + } case XmlTag.Content: - { - containsContentElement = true; - break; - } + { + containsContentElement = true; + break; + } case XmlTag.Summary: - { - if (info.IsContentEmptyOrWhitespace) - ReportDiagnosticIfEffective(context, DiagnosticRules.AddSummaryToDocumentationComment, info.Element); + { + if (info.IsContentEmptyOrWhitespace) + ReportDiagnosticIfEffective(context, DiagnosticRules.AddSummaryToDocumentationComment, info.Element); - containsSummaryElement = true; + containsSummaryElement = true; - if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) - FixDocumentationCommentTagAnalysis.Analyze(context, info); + if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) + FixDocumentationCommentTagAnalysis.Analyze(context, info); - break; - } + break; + } case XmlTag.Example: case XmlTag.Remarks: case XmlTag.Returns: case XmlTag.Value: - { - if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) - FixDocumentationCommentTagAnalysis.Analyze(context, info); + { + if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) + FixDocumentationCommentTagAnalysis.Analyze(context, info); - AnalyzeUnusedElement(context, info, tag); - break; - } + AnalyzeUnusedElement(context, info, tag); + break; + } case XmlTag.List: - { - if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) - FixDocumentationCommentTagAnalysis.Analyze(context, info); + { + if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) + FixDocumentationCommentTagAnalysis.Analyze(context, info); - break; - } + break; + } case XmlTag.Exception: case XmlTag.Permission: - { - if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) - FixDocumentationCommentTagAnalysis.Analyze(context, info); + { + if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) + FixDocumentationCommentTagAnalysis.Analyze(context, info); - AnalyzeUnusedElement(context, info, tag, checkAttributes: true); - break; - } + AnalyzeUnusedElement(context, info, tag, checkAttributes: true); + break; + } case XmlTag.Param: case XmlTag.TypeParam: - { - if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) - FixDocumentationCommentTagAnalysis.Analyze(context, info); + { + if (fixDocumentationCommentTagEnabled ??= DiagnosticRules.FixDocumentationCommentTag.IsEffective(context)) + FixDocumentationCommentTagAnalysis.Analyze(context, info); - AnalyzeUnusedElement(context, info, tag); - break; - } + AnalyzeUnusedElement(context, info, tag); + break; + } case XmlTag.SeeAlso: - { - AnalyzeUnusedElement(context, info, tag, checkAttributes: true); - break; - } + { + AnalyzeUnusedElement(context, info, tag, checkAttributes: true); + break; + } case XmlTag.C: case XmlTag.Code: case XmlTag.Para: case XmlTag.ParamRef: case XmlTag.See: case XmlTag.TypeParamRef: - { - break; - } + { + break; + } default: - { - SyntaxDebug.Fail(content[i]); - break; - } + { + SyntaxDebug.Fail(content[i]); + break; + } } if (isFirst) diff --git a/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs index 56654183c8..6ad454e183 100644 --- a/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/StaticMemberInGenericTypeShouldUseTypeParameterAnalyzer.cs @@ -67,72 +67,72 @@ private static void AnalyzeNamedType(SymbolAnalysisContext context) switch (member.Kind) { case SymbolKind.Event: - { - var eventSymbol = (IEventSymbol)member; + { + var eventSymbol = (IEventSymbol)member; - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - if (!ContainsAnyTypeParameter(typeParameters, eventSymbol.Type)) - ReportDiagnostic(context, eventSymbol); + if (!ContainsAnyTypeParameter(typeParameters, eventSymbol.Type)) + ReportDiagnostic(context, eventSymbol); - break; - } + break; + } case SymbolKind.Field: - { - var fieldSymbol = (IFieldSymbol)member; + { + var fieldSymbol = (IFieldSymbol)member; - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - if (!ContainsAnyTypeParameter(typeParameters, fieldSymbol.Type) - && !IsTypeParameterReferenced( - typeParameters, - (fieldSymbol.GetSyntax(context.CancellationToken) as VariableDeclaratorSyntax)?.Initializer?.Value)) - { - ReportDiagnostic(context, fieldSymbol); - } - - break; + if (!ContainsAnyTypeParameter(typeParameters, fieldSymbol.Type) + && !IsTypeParameterReferenced( + typeParameters, + (fieldSymbol.GetSyntax(context.CancellationToken) as VariableDeclaratorSyntax)?.Initializer?.Value)) + { + ReportDiagnostic(context, fieldSymbol); } + + break; + } case SymbolKind.Method: + { + var methodSymbol = (IMethodSymbol)member; + + if (methodSymbol.MethodKind == MethodKind.Ordinary) { - var methodSymbol = (IMethodSymbol)member; + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - if (methodSymbol.MethodKind == MethodKind.Ordinary) + if (!ContainsAnyTypeParameter(typeParameters, methodSymbol.ReturnType) + && !ContainsAnyTypeParameter(typeParameters, methodSymbol.Parameters)) { - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; - - if (!ContainsAnyTypeParameter(typeParameters, methodSymbol.ReturnType) - && !ContainsAnyTypeParameter(typeParameters, methodSymbol.Parameters)) - { - ReportDiagnostic(context, methodSymbol); - } + ReportDiagnostic(context, methodSymbol); } - - break; } + + break; + } case SymbolKind.Property: + { + var propertySymbol = (IPropertySymbol)member; + + if (!propertySymbol.IsIndexer) { - var propertySymbol = (IPropertySymbol)member; + if (typeParameters.IsDefault) + typeParameters = namedType.TypeParameters; - if (!propertySymbol.IsIndexer) + if (!ContainsAnyTypeParameter(typeParameters, propertySymbol.Type) + && !IsTypeParameterReferenced( + typeParameters, + (propertySymbol.GetSyntax(context.CancellationToken) as PropertyDeclarationSyntax)?.Initializer?.Value)) { - if (typeParameters.IsDefault) - typeParameters = namedType.TypeParameters; - - if (!ContainsAnyTypeParameter(typeParameters, propertySymbol.Type) - && !IsTypeParameterReferenced( - typeParameters, - (propertySymbol.GetSyntax(context.CancellationToken) as PropertyDeclarationSyntax)?.Initializer?.Value)) - { - ReportDiagnostic(context, propertySymbol); - } + ReportDiagnostic(context, propertySymbol); } - - break; } + + break; + } } } } @@ -190,23 +190,23 @@ private static bool ContainsAnyTypeParameter( switch (typeSymbol.Kind) { case SymbolKind.TypeParameter: + { + foreach (ITypeParameterSymbol typeParameter in typeParameters) { - foreach (ITypeParameterSymbol typeParameter in typeParameters) - { - if (SymbolEqualityComparer.Default.Equals(typeParameter, typeSymbol)) - return true; - } - - return false; + if (SymbolEqualityComparer.Default.Equals(typeParameter, typeSymbol)) + return true; } + + return false; + } case SymbolKind.ArrayType: - { - return ContainsAnyTypeParameter(typeParameters, ((IArrayTypeSymbol)typeSymbol).ElementType); - } + { + return ContainsAnyTypeParameter(typeParameters, ((IArrayTypeSymbol)typeSymbol).ElementType); + } case SymbolKind.NamedType: - { - return ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeSymbol).TypeArguments); - } + { + return ContainsAnyTypeParameter(typeParameters, ((INamedTypeSymbol)typeSymbol).TypeArguments); + } } Debug.Assert(typeSymbol.Kind == SymbolKind.ErrorType, typeSymbol.Kind.ToString()); diff --git a/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs index ea4f1d33e7..633511ca87 100644 --- a/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnconstrainedTypeParameterCheckedForNullAnalyzer.cs @@ -95,44 +95,44 @@ private static bool VerifyConstraint(ImmutableArray constraintTypes switch (type.TypeKind) { case TypeKind.Class: - { - if (!allowReference) - return false; + { + if (!allowReference) + return false; - break; - } + break; + } case TypeKind.Struct: - { - if (allowValueType) - return false; + { + if (allowValueType) + return false; - break; - } + break; + } case TypeKind.Interface: - { - break; - } + { + break; + } case TypeKind.TypeParameter: - { - var typeParameterSymbol = (ITypeParameterSymbol)type; + { + var typeParameterSymbol = (ITypeParameterSymbol)type; - if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) - return false; + if (!CheckConstraint(typeParameterSymbol, allowReference, allowValueType, allowConstructor)) + return false; - if (!VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor)) - return false; + if (!VerifyConstraint(typeParameterSymbol.ConstraintTypes, allowReference, allowValueType, allowConstructor)) + return false; - break; - } + break; + } case TypeKind.Error: - { - return false; - } + { + return false; + } default: - { - Debug.Fail(type.TypeKind.ToString()); - return false; - } + { + Debug.Fail(type.TypeKind.ToString()); + return false; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs index 44050ef0d4..b8592e821a 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryAssignmentAnalyzer.cs @@ -133,23 +133,23 @@ private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) switch (statements.Last().Kind()) { case SyntaxKind.ThrowStatement: - { - continue; - } + { + continue; + } case SyntaxKind.BreakStatement: - { - if (statements.Count == 1 - || !IsSymbolAssignedInStatementWithCorrectType(symbol, statements.LastButOne(), semanticModel, returnTypeSymbol, cancellationToken)) - { - return; - } - - break; - } - default: + { + if (statements.Count == 1 + || !IsSymbolAssignedInStatementWithCorrectType(symbol, statements.LastButOne(), semanticModel, returnTypeSymbol, cancellationToken)) { return; } + + break; + } + default: + { + return; + } } } @@ -176,32 +176,32 @@ private static bool IsLocalDeclaredInScopeOrNonRefOrOutParameterOfEnclosingSymbo switch (symbol.Kind) { case SymbolKind.Local: - { - var localSymbol = (ILocalSymbol)symbol; + { + var localSymbol = (ILocalSymbol)symbol; - var localDeclarationStatement = localSymbol.GetSyntax(cancellationToken).Parent.Parent as LocalDeclarationStatementSyntax; + var localDeclarationStatement = localSymbol.GetSyntax(cancellationToken).Parent.Parent as LocalDeclarationStatementSyntax; - return localDeclarationStatement?.Parent == containingNode; - } + return localDeclarationStatement?.Parent == containingNode; + } case SymbolKind.Parameter: + { + var parameterSymbol = (IParameterSymbol)symbol; + + if (parameterSymbol.RefKind == RefKind.None) { - var parameterSymbol = (IParameterSymbol)symbol; + ISymbol enclosingSymbol = semanticModel.GetEnclosingSymbol(containingNode.SpanStart, cancellationToken); - if (parameterSymbol.RefKind == RefKind.None) + if (enclosingSymbol is not null) { - ISymbol enclosingSymbol = semanticModel.GetEnclosingSymbol(containingNode.SpanStart, cancellationToken); - - if (enclosingSymbol is not null) - { - ImmutableArray parameters = enclosingSymbol.ParametersOrDefault(); + ImmutableArray parameters = enclosingSymbol.ParametersOrDefault(); - return !parameters.IsDefault - && parameters.Contains(parameterSymbol); - } + return !parameters.IsDefault + && parameters.Contains(parameterSymbol); } - - break; } + + break; + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs index d990bd7b4d..b28ee83dbe 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryNullCheckAnalyzer.cs @@ -60,33 +60,33 @@ private static void AnalyzeLogicalAndExpression(SyntaxNodeAnalysisContext contex switch (right.Kind()) { case SyntaxKind.LogicalNotExpression: - { - var logicalNot = (PrefixUnaryExpressionSyntax)right; + { + var logicalNot = (PrefixUnaryExpressionSyntax)right; - Analyze(nullCheck.Expression, logicalNot.Operand?.WalkDownParentheses(), null); - break; - } + Analyze(nullCheck.Expression, logicalNot.Operand?.WalkDownParentheses(), null); + break; + } case SyntaxKind.EqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - BinaryExpressionInfo binaryExpressionInfo = SyntaxInfo.BinaryExpressionInfo((BinaryExpressionSyntax)right); + { + BinaryExpressionInfo binaryExpressionInfo = SyntaxInfo.BinaryExpressionInfo((BinaryExpressionSyntax)right); - if (!binaryExpressionInfo.Success) - break; + if (!binaryExpressionInfo.Success) + break; - ExpressionSyntax left = binaryExpressionInfo.Left; + ExpressionSyntax left = binaryExpressionInfo.Left; - Analyze(nullCheck.Expression, left, binaryExpressionInfo.Right); - break; - } + Analyze(nullCheck.Expression, left, binaryExpressionInfo.Right); + break; + } case SyntaxKind.SimpleMemberAccessExpression: - { - AnalyzeSimpleMemberAccessExpression(nullCheck.Expression, (MemberAccessExpressionSyntax)right, null); - break; - } + { + AnalyzeSimpleMemberAccessExpression(nullCheck.Expression, (MemberAccessExpressionSyntax)right, null); + break; + } } void Analyze(ExpressionSyntax expression1, ExpressionSyntax expression2, ExpressionSyntax expression3) @@ -118,21 +118,21 @@ void AnalyzeSimpleMemberAccessExpression(ExpressionSyntax expression, MemberAcce case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: - { - break; - } + { + break; + } case SyntaxKind.NullLiteralExpression: case SyntaxKind.DefaultLiteralExpression: - { - return; - } + { + return; + } default: - { - if (context.SemanticModel.GetTypeSymbol(expression3, context.CancellationToken).IsNullableType()) - return; + { + if (context.SemanticModel.GetTypeSymbol(expression3, context.CancellationToken).IsNullableType()) + return; - break; - } + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs index 22115bffd3..e0efd1f808 100644 --- a/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnnecessaryUnsafeContextAnalyzer.cs @@ -182,19 +182,19 @@ private static bool AncestorContainsUnsafeModifier(SyntaxNode node) case UnsafeStatementSyntax: return true; case MemberDeclarationSyntax memberDeclarationSyntax: - { - if (memberDeclarationSyntax.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) - return true; + { + if (memberDeclarationSyntax.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) + return true; - break; - } + break; + } case LocalFunctionStatementSyntax localFunctionStatement: - { - if (localFunctionStatement.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) - return true; + { + if (localFunctionStatement.Modifiers.Contains(SyntaxKind.UnsafeKeyword)) + return true; - break; - } + break; + } } node = node.Parent; diff --git a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs index 6bdc0e5239..ac71ac28ba 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedMember/UnusedMemberAnalyzer.cs @@ -89,112 +89,112 @@ private static void AnalyzeTypeDeclaration(SyntaxNodeAnalysisContext context) switch (member) { case DelegateDeclarationSyntax declaration: + { + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) { - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); - - walker.AddDelegate(declaration.Identifier.ValueText, declaration); - } + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - break; + walker.AddDelegate(declaration.Identifier.ValueText, declaration); } + + break; + } case EventDeclarationSyntax declaration: + { + if (declaration.ExplicitInterfaceSpecifier is null + && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) { - if (declaration.ExplicitInterfaceSpecifier is null - && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); - - walker.AddNode(declaration.Identifier.ValueText, declaration); - } + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - break; + walker.AddNode(declaration.Identifier.ValueText, declaration); } + + break; + } case EventFieldDeclarationSyntax declaration: + { + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) { - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); - - walker.AddNodes(declaration.Declaration); - } + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - break; + walker.AddNodes(declaration.Declaration); } + + break; + } case FieldDeclarationSyntax declaration: + { + SyntaxTokenList modifiers = declaration.Modifiers; + + if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) { - SyntaxTokenList modifiers = declaration.Modifiers; + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - if (SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); + walker.AddNodes(declaration.Declaration, isConst: modifiers.Contains(SyntaxKind.ConstKeyword)); + } - walker.AddNodes(declaration.Declaration, isConst: modifiers.Contains(SyntaxKind.ConstKeyword)); - } + break; + } + case MethodDeclarationSyntax declaration: + { + SyntaxTokenList modifiers = declaration.Modifiers; + if (declaration.ExplicitInterfaceSpecifier is not null + || declaration.AttributeLists.Any() + || SyntaxAccessibility.Instance.GetAccessibility(declaration) != Accessibility.Private) + { break; } - case MethodDeclarationSyntax declaration: - { - SyntaxTokenList modifiers = declaration.Modifiers; - - if (declaration.ExplicitInterfaceSpecifier is not null - || declaration.AttributeLists.Any() - || SyntaxAccessibility.Instance.GetAccessibility(declaration) != Accessibility.Private) - { - break; - } - string methodName = declaration.Identifier.ValueText; + string methodName = declaration.Identifier.ValueText; - if (IsMainMethod(declaration, modifiers, methodName)) - break; + if (IsMainMethod(declaration, modifiers, methodName)) + break; - if ((declaration.ReturnsVoid() - || (methodName == "Start" - && semanticModel.GetDeclaredSymbol(declaration, cancellationToken)?.ReturnType.SpecialType == SpecialType.System_Collections_IEnumerator)) - && context.IsUnityCodeAnalysisEnabled() == true) + if ((declaration.ReturnsVoid() + || (methodName == "Start" + && semanticModel.GetDeclaredSymbol(declaration, cancellationToken)?.ReturnType.SpecialType == SpecialType.System_Collections_IEnumerator)) + && context.IsUnityCodeAnalysisEnabled() == true) + { + if (canContainUnityScriptMethods is null) { - if (canContainUnityScriptMethods is null) - { - if (declarationSymbol is null) - declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken); + if (declarationSymbol is null) + declarationSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken); - canContainUnityScriptMethods = declarationSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); - } + canContainUnityScriptMethods = declarationSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); + } - if (canContainUnityScriptMethods == true - && UnityScriptMethods.MethodNames.Contains(methodName)) - { - break; - } + if (canContainUnityScriptMethods == true + && UnityScriptMethods.MethodNames.Contains(methodName)) + { + break; } + } - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - walker.AddNode(methodName, declaration); + walker.AddNode(methodName, declaration); - break; - } + break; + } case PropertyDeclarationSyntax declaration: + { + if (declaration.ExplicitInterfaceSpecifier is null + && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) { - if (declaration.ExplicitInterfaceSpecifier is null - && SyntaxAccessibility.Instance.GetAccessibility(declaration) == Accessibility.Private) - { - if (walker is null) - walker = UnusedMemberWalker.GetInstance(); - - walker.AddNode(declaration.Identifier.ValueText, declaration); - } + if (walker is null) + walker = UnusedMemberWalker.GetInstance(); - break; + walker.AddNode(declaration.Identifier.ValueText, declaration); } + + break; + } } } @@ -275,66 +275,66 @@ private static void RemoveMethodsAndPropertiesThatAreInDebuggerDisplayAttributeV switch (value[i]) { case '{': - { - i++; + { + i++; - int startIndex = i; + int startIndex = i; - while (i < length) + while (i < length) + { + char ch = value[i]; + + if (ch == '}' + || ch == ',' + || ch == '(') { - char ch = value[i]; + int nameLength = i - startIndex; - if (ch == '}' - || ch == ',' - || ch == '(') + if (nameLength > 0) { - int nameLength = i - startIndex; - - if (nameLength > 0) + for (int j = nodes.Count - 1; j >= 0; j--) { - for (int j = nodes.Count - 1; j >= 0; j--) - { - NodeSymbolInfo nodeSymbolInfo = nodes[j]; + NodeSymbolInfo nodeSymbolInfo = nodes[j]; - if (nodeSymbolInfo.CanBeInDebuggerDisplayAttribute - && string.CompareOrdinal(nodeSymbolInfo.Name, 0, value, startIndex, nameLength) == 0) - { - nodes.RemoveAt(j); + if (nodeSymbolInfo.CanBeInDebuggerDisplayAttribute + && string.CompareOrdinal(nodeSymbolInfo.Name, 0, value, startIndex, nameLength) == 0) + { + nodes.RemoveAt(j); - if (nodes.Count == 0) - return; - } + if (nodes.Count == 0) + return; } } + } - if (ch != '}') + if (ch != '}') + { + i++; + + while (i < length + && value[i] != '}') { i++; - - while (i < length - && value[i] != '}') - { - i++; - } } - - break; } - i++; + break; } - break; + i++; } + + break; + } case '}': - { - return; - } + { + return; + } case '\\': - { - i++; - break; - } + { + i++; + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs index 05d6fc4efa..196d82024b 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterAnalyzer.cs @@ -467,11 +467,11 @@ private static bool ContainsOnlyThrowNewExpression(CSharpSyntaxNode node) case SyntaxKind.ArrowExpressionClause: return ContainsOnlyThrowNewExpression((ArrowExpressionClauseSyntax)node); case SyntaxKind.AccessorList: - { - return ((AccessorListSyntax)node) - .Accessors - .All(f => ContainsOnlyThrowNewExpression(f.BodyOrExpressionBody())); - } + { + return ((AccessorListSyntax)node) + .Accessors + .All(f => ContainsOnlyThrowNewExpression(f.BodyOrExpressionBody())); + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs index a9dbf72438..bd3bf1bf89 100644 --- a/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs +++ b/src/Analyzers/CSharp/Analysis/UnusedParameter/UnusedParameterWalker.cs @@ -74,10 +74,10 @@ protected override void VisitType(TypeSyntax node) switch (node.Kind()) { case SyntaxKind.ArrayType: - { - VisitArrayType((ArrayTypeSyntax)node); - break; - } + { + VisitArrayType((ArrayTypeSyntax)node); + break; + } case SyntaxKind.AliasQualifiedName: case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: @@ -88,17 +88,17 @@ protected override void VisitType(TypeSyntax node) case SyntaxKind.QualifiedName: case SyntaxKind.RefType: case SyntaxKind.TupleType: - { - if (IsAnyTypeParameter) - Visit(node); + { + if (IsAnyTypeParameter) + Visit(node); - break; - } + break; + } default: - { - Visit(node); - break; - } + { + Visit(node); + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs index e322ca3b40..82dc6bfdec 100644 --- a/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAnonymousFunctionOrMethodGroupAnalyzer.cs @@ -483,18 +483,18 @@ private static bool IsSimpleInvocation(ExpressionSyntax expression) switch (expression?.Kind()) { case SyntaxKind.IdentifierName: - { - return true; - } + { + return true; + } case SyntaxKind.SimpleMemberAccessExpression: - { - expression = ((MemberAccessExpressionSyntax)expression).Expression; - break; - } + { + expression = ((MemberAccessExpressionSyntax)expression).Expression; + break; + } default: - { - return false; - } + { + return false; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs index 68d16c9fb5..f112cce386 100644 --- a/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAsyncAwaitAnalyzer.cs @@ -289,17 +289,17 @@ private bool IsCompletedTask(ExpressionSyntax expression) case "FromCanceled": case "FromException": case "FromResult": + { + if (SemanticModel.GetSymbol(expression, CancellationToken) is IMethodSymbol methodSymbol + && (methodSymbol.Arity == 0 || methodSymbol.Arity == 1) + && methodSymbol.Parameters.Length == 1 + && IsTaskOrTaskOrT(methodSymbol.ContainingType)) { - if (SemanticModel.GetSymbol(expression, CancellationToken) is IMethodSymbol methodSymbol - && (methodSymbol.Arity == 0 || methodSymbol.Arity == 1) - && methodSymbol.Parameters.Length == 1 - && IsTaskOrTaskOrT(methodSymbol.ContainingType)) - { - return true; - } - - break; + return true; } + + break; + } } } } diff --git a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs index 16db72c43d..b9ece75fc0 100644 --- a/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseAutoPropertyAnalyzer.cs @@ -174,16 +174,16 @@ void FadeOut(AccessorDeclarationSyntax accessor) switch (body.Statements[0]) { case ReturnStatementSyntax returnStatement: - { - DiagnosticHelpers.ReportToken(context, DiagnosticRules.UseAutoPropertyFadeOut, returnStatement.ReturnKeyword); - DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, returnStatement.Expression); - break; - } + { + DiagnosticHelpers.ReportToken(context, DiagnosticRules.UseAutoPropertyFadeOut, returnStatement.ReturnKeyword); + DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, returnStatement.Expression); + break; + } case ExpressionStatementSyntax expressionStatement: - { - DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, expressionStatement.Expression); - break; - } + { + DiagnosticHelpers.ReportNode(context, DiagnosticRules.UseAutoPropertyFadeOut, expressionStatement.Expression); + break; + } } CSharpDiagnosticHelpers.ReportBraces(context, DiagnosticRules.UseAutoPropertyFadeOut, body); @@ -382,23 +382,23 @@ private static IdentifierNameSyntax GetIdentifierNameFromExpression(ExpressionSy switch (expression?.Kind()) { case SyntaxKind.IdentifierName: - { - return (IdentifierNameSyntax)expression; - } + { + return (IdentifierNameSyntax)expression; + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; - - if (memberAccess.Expression?.Kind() == SyntaxKind.ThisExpression) - { - SimpleNameSyntax name = memberAccess.Name; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - if (name.IsKind(SyntaxKind.IdentifierName)) - return (IdentifierNameSyntax)name; - } + if (memberAccess.Expression?.Kind() == SyntaxKind.ThisExpression) + { + SimpleNameSyntax name = memberAccess.Name; - break; + if (name.IsKind(SyntaxKind.IdentifierName)) + return (IdentifierNameSyntax)name; } + + break; + } } return null; @@ -493,31 +493,31 @@ public override void VisitArgument(ArgumentSyntax node) switch (expression?.Kind()) { case SyntaxKind.IdentifierName: - { - if (IsBackingFieldReference((IdentifierNameSyntax)expression)) - Success = false; + { + if (IsBackingFieldReference((IdentifierNameSyntax)expression)) + Success = false; - return; - } + return; + } case SyntaxKind.SimpleMemberAccessExpression: + { + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + + if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression)) { - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + SimpleNameSyntax name = memberAccessExpression.Name; - if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression)) + if (name.IsKind(SyntaxKind.IdentifierName)) { - SimpleNameSyntax name = memberAccessExpression.Name; + if (IsBackingFieldReference((IdentifierNameSyntax)name)) + Success = false; - if (name.IsKind(SyntaxKind.IdentifierName)) - { - if (IsBackingFieldReference((IdentifierNameSyntax)name)) - Success = false; - - return; - } + return; } - - break; } + + break; + } } } @@ -586,47 +586,47 @@ private bool IsAssigned(ExpressionSyntax expression) switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - expression = memberAccessExpression.Expression; + { + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + expression = memberAccessExpression.Expression; - break; - } + break; + } case SyntaxKind.ElementAccessExpression: - { - var elementAccessExpression = (ElementAccessExpressionSyntax)expression; - expression = elementAccessExpression.Expression; + { + var elementAccessExpression = (ElementAccessExpressionSyntax)expression; + expression = elementAccessExpression.Expression; - break; - } + break; + } default: - { - return false; - } + { + return false; + } } switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = ((MemberAccessExpressionSyntax)expression); - - if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression) - && memberAccessExpression.Name.IsKind(SyntaxKind.IdentifierName) - && IsBackingFieldReference((IdentifierNameSyntax)memberAccessExpression.Name)) - { - return true; - } + { + var memberAccessExpression = ((MemberAccessExpressionSyntax)expression); - break; + if (memberAccessExpression.Expression.IsKind(SyntaxKind.ThisExpression) + && memberAccessExpression.Name.IsKind(SyntaxKind.IdentifierName) + && IsBackingFieldReference((IdentifierNameSyntax)memberAccessExpression.Name)) + { + return true; } + + break; + } case SyntaxKind.IdentifierName: - { - if (IsBackingFieldReference((IdentifierNameSyntax)expression)) - return true; + { + if (IsBackingFieldReference((IdentifierNameSyntax)expression)) + return true; - break; - } + break; + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs index 5a7fdffa5a..eba7ac0be5 100644 --- a/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseBlockBodyOrExpressionBodyAnalyzer.cs @@ -596,24 +596,24 @@ private static void AnalyzeAccessorDeclarationBlock( switch (accessorList.Parent.Kind()) { case SyntaxKind.PropertyDeclaration: - { - if (accessor.SyntaxTree.IsMultiLineSpan(((PropertyDeclarationSyntax)accessorList.Parent).HeaderSpan())) - return; + { + if (accessor.SyntaxTree.IsMultiLineSpan(((PropertyDeclarationSyntax)accessorList.Parent).HeaderSpan())) + return; - break; - } + break; + } case SyntaxKind.IndexerDeclaration: - { - if (accessor.SyntaxTree.IsMultiLineSpan(((IndexerDeclarationSyntax)accessorList.Parent).HeaderSpan())) - return; + { + if (accessor.SyntaxTree.IsMultiLineSpan(((IndexerDeclarationSyntax)accessorList.Parent).HeaderSpan())) + return; - break; - } + break; + } default: - { - SyntaxDebug.Fail(accessorList.Parent); - break; - } + { + SyntaxDebug.Fail(accessorList.Parent); + break; + } } return; diff --git a/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs index 9ecb9b53f5..98188c8f55 100644 --- a/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseCompoundAssignmentAnalyzer.cs @@ -107,10 +107,10 @@ bool CanBeReplacedWithCompoundAssignment(ExpressionSyntax expression) case SyntaxKind.RightShiftExpression: return true; case SyntaxKind.CoalesceExpression: - { - return ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp8 - && !((BinaryExpressionSyntax)expression).Right.IsKind(SyntaxKind.ThrowExpression); - } + { + return ((CSharpCompilation)context.Compilation).LanguageVersion >= LanguageVersion.CSharp8 + && !((BinaryExpressionSyntax)expression).Right.IsKind(SyntaxKind.ThrowExpression); + } } return false; diff --git a/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs index 9c8eb47639..d9d2fc3925 100644 --- a/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseConditionalAccessAnalyzer.cs @@ -276,72 +276,72 @@ private static bool ValidateRightExpression( case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.EqualsExpression: - { - ITypeSymbol leftTypeSymbol = semanticModel.GetTypeSymbol(((BinaryExpressionSyntax)expression).Left, cancellationToken); + { + ITypeSymbol leftTypeSymbol = semanticModel.GetTypeSymbol(((BinaryExpressionSyntax)expression).Left, cancellationToken); - if (leftTypeSymbol.IsErrorType()) - return false; + if (leftTypeSymbol.IsErrorType()) + return false; - if (leftTypeSymbol.IsValueType && !CSharpFacts.IsPredefinedType(leftTypeSymbol.SpecialType)) - { - // If the LHS is a ValueTypes then making the expression conditional would change the type of the expression - // and hence we would call a different overload (a valid overload may not exists) - return false; - } + if (leftTypeSymbol.IsValueType && !CSharpFacts.IsPredefinedType(leftTypeSymbol.SpecialType)) + { + // If the LHS is a ValueTypes then making the expression conditional would change the type of the expression + // and hence we would call a different overload (a valid overload may not exists) + return false; + } - expression = ((BinaryExpressionSyntax)expression) - .Right? - .WalkDownParentheses(); + expression = ((BinaryExpressionSyntax)expression) + .Right? + .WalkDownParentheses(); - if (expression is null) - return false; + if (expression is null) + return false; - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - return optional.HasValue - && optional.Value is not null; - } + return optional.HasValue + && optional.Value is not null; + } case SyntaxKind.NotEqualsExpression: - { - return ((BinaryExpressionSyntax)expression) - .Right? - .WalkDownParentheses() - .Kind() == SyntaxKind.NullLiteralExpression; - } + { + return ((BinaryExpressionSyntax)expression) + .Right? + .WalkDownParentheses() + .Kind() == SyntaxKind.NullLiteralExpression; + } case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; - - PatternSyntax pattern = isPatternExpression.Pattern; + { + var isPatternExpression = (IsPatternExpressionSyntax)expression; - if (pattern is ConstantPatternSyntax constantPattern) - { - return !constantPattern.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); - } - else if (pattern.IsKind(SyntaxKind.NotPattern)) - { - pattern = ((UnaryPatternSyntax)pattern).Pattern; + PatternSyntax pattern = isPatternExpression.Pattern; - // x != null && x.P is not T; - if (pattern is ConstantPatternSyntax constantPattern2) - return constantPattern2.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); - } + if (pattern is ConstantPatternSyntax constantPattern) + { + return !constantPattern.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); + } + else if (pattern.IsKind(SyntaxKind.NotPattern)) + { + pattern = ((UnaryPatternSyntax)pattern).Pattern; - return true; + // x != null && x.P is not T; + if (pattern is ConstantPatternSyntax constantPattern2) + return constantPattern2.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression); } + + return true; + } case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: - { - return true; - } + { + return true; + } default: - { - return false; - } + { + return false; + } } } else if (binaryExpressionKind == SyntaxKind.LogicalOrExpression) diff --git a/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs index 4bbbedf379..d1235fa538 100644 --- a/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExceptionFilterAnalyzer.cs @@ -111,25 +111,25 @@ public override void VisitInvocationExpression(InvocationExpressionSyntax node) switch (node.Expression) { case SimpleNameSyntax simpleName: - { - AnalyzeSimpleName(simpleName); - break; - } + { + AnalyzeSimpleName(simpleName); + break; + } case MemberBindingExpressionSyntax memberBindingExpression: - { - AnalyzeSimpleName(memberBindingExpression.Name); - break; - } + { + AnalyzeSimpleName(memberBindingExpression.Name); + break; + } case MemberAccessExpressionSyntax memberAccessExpression: - { - AnalyzeSimpleName(memberAccessExpression.Name); - break; - } + { + AnalyzeSimpleName(memberAccessExpression.Name); + break; + } default: - { - SyntaxDebug.Fail(node); - break; - } + { + SyntaxDebug.Fail(node); + break; + } } base.VisitInvocationExpression(node); diff --git a/src/Analyzers/CSharp/Analysis/UseExplicitTypeInsteadOfVarInForEachAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseExplicitTypeInsteadOfVarInForEachAnalyzer.cs index 03d96629cf..addd1a6e40 100644 --- a/src/Analyzers/CSharp/Analysis/UseExplicitTypeInsteadOfVarInForEachAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseExplicitTypeInsteadOfVarInForEachAnalyzer.cs @@ -54,30 +54,30 @@ private static void AnalyzeForEachVariableStatement(SyntaxNodeAnalysisContext co switch (forEachStatement.Variable) { case DeclarationExpressionSyntax declarationExpression: - { - if (CSharpTypeAnalysis.IsImplicitThatCanBeExplicit(forEachStatement, context.SemanticModel)) - ReportDiagnostic(context, declarationExpression.Type); + { + if (CSharpTypeAnalysis.IsImplicitThatCanBeExplicit(forEachStatement, context.SemanticModel)) + ReportDiagnostic(context, declarationExpression.Type); - break; - } + break; + } case TupleExpressionSyntax tupleExpression: + { + foreach (ArgumentSyntax argument in tupleExpression.Arguments) { - foreach (ArgumentSyntax argument in tupleExpression.Arguments) - { - if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) - continue; - - if (CSharpTypeAnalysis.IsImplicitThatCanBeExplicit(declarationExpression, context.SemanticModel, context.CancellationToken)) - ReportDiagnostic(context, declarationExpression.Type); - } + if (argument.Expression is not DeclarationExpressionSyntax declarationExpression) + continue; - break; + if (CSharpTypeAnalysis.IsImplicitThatCanBeExplicit(declarationExpression, context.SemanticModel, context.CancellationToken)) + ReportDiagnostic(context, declarationExpression.Type); } + + break; + } default: - { - SyntaxDebug.Assert(forEachStatement.ContainsDiagnostics, forEachStatement.Variable); - break; - } + { + SyntaxDebug.Assert(forEachStatement.ContainsDiagnostics, forEachStatement.Variable); + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs index 3a67732256..e16eb80042 100644 --- a/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UseGenericEventHandlerAnalyzer.cs @@ -93,22 +93,22 @@ private static TypeSyntax GetTypeSyntax(SyntaxNode node) switch (node) { case EventDeclarationSyntax eventDeclaration: - { - return eventDeclaration.Type; - } + { + return eventDeclaration.Type; + } case VariableDeclaratorSyntax declarator: - { - if (declarator.Parent is VariableDeclarationSyntax declaration) - return declaration.Type; + { + if (declarator.Parent is VariableDeclarationSyntax declaration) + return declaration.Type; - SyntaxDebug.Fail(declarator.Parent); - break; - } + SyntaxDebug.Fail(declarator.Parent); + break; + } default: - { - SyntaxDebug.Fail(node); - break; - } + { + SyntaxDebug.Fail(node); + break; + } } return null; diff --git a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs index d75db13e60..ced4beb69f 100644 --- a/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UsePatternMatching/UsePatternMatchingInsteadOfIsAndCastAnalyzer.cs @@ -76,56 +76,56 @@ private static void AnalyzeIsExpression(SyntaxNodeAnalysisContext context) switch (node.Kind()) { case SyntaxKind.LogicalAndExpression: - { - var logicalAnd = (BinaryExpressionSyntax)node; + { + var logicalAnd = (BinaryExpressionSyntax)node; - if (left != logicalAnd.Left) - return; + if (left != logicalAnd.Left) + return; - ExpressionSyntax right = logicalAnd.Right; + ExpressionSyntax right = logicalAnd.Right; - if (right is null) - return; + if (right is null) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (semanticModel.GetTypeSymbol(isExpressionInfo.Type, cancellationToken).IsNullableType()) - return; + if (semanticModel.GetTypeSymbol(isExpressionInfo.Type, cancellationToken).IsNullableType()) + return; - if (logicalAnd.Parent.IsInExpressionTree(semanticModel, cancellationToken)) - return; + if (logicalAnd.Parent.IsInExpressionTree(semanticModel, cancellationToken)) + return; - if (!IsFixable(right, identifierName, semanticModel, cancellationToken)) - return; + if (!IsFixable(right, identifierName, semanticModel, cancellationToken)) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast, logicalAnd); - break; - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast, logicalAnd); + break; + } case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)node; + { + var ifStatement = (IfStatementSyntax)node; - if (left != ifStatement.Condition) - return; + if (left != ifStatement.Condition) + return; - StatementSyntax statement = ifStatement.Statement; + StatementSyntax statement = ifStatement.Statement; - if (statement is null) - return; + if (statement is null) + return; - SemanticModel semanticModel = context.SemanticModel; - CancellationToken cancellationToken = context.CancellationToken; + SemanticModel semanticModel = context.SemanticModel; + CancellationToken cancellationToken = context.CancellationToken; - if (semanticModel.GetTypeSymbol(isExpressionInfo.Type, cancellationToken).IsNullableType()) - return; + if (semanticModel.GetTypeSymbol(isExpressionInfo.Type, cancellationToken).IsNullableType()) + return; - if (!IsFixable(statement, identifierName, semanticModel, cancellationToken)) - return; + if (!IsFixable(statement, identifierName, semanticModel, cancellationToken)) + return; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast, ifStatement.Condition); - break; - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePatternMatchingInsteadOfIsAndCast, ifStatement.Condition); + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs b/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs index a035737989..c6003c3365 100644 --- a/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/UsePredefinedTypeAnalyzer.cs @@ -81,22 +81,22 @@ private static void AnalyzeXmlCrefAttribute(SyntaxNodeAnalysisContext context) switch (cref?.Kind()) { case SyntaxKind.NameMemberCref: - { - Analyze(context, cref, (NameMemberCrefSyntax)cref); - break; - } + { + Analyze(context, cref, (NameMemberCrefSyntax)cref); + break; + } case SyntaxKind.QualifiedCref: - { - var qualifiedCref = (QualifiedCrefSyntax)cref; - - MemberCrefSyntax memberCref = qualifiedCref.Member; + { + var qualifiedCref = (QualifiedCrefSyntax)cref; - if (memberCref?.IsKind(SyntaxKind.NameMemberCref) != true) - break; + MemberCrefSyntax memberCref = qualifiedCref.Member; - Analyze(context, cref, (NameMemberCrefSyntax)memberCref); + if (memberCref?.IsKind(SyntaxKind.NameMemberCref) != true) break; - } + + Analyze(context, cref, (NameMemberCrefSyntax)memberCref); + break; + } } } diff --git a/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs b/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs index 5730ba69f3..df35f31959 100644 --- a/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs +++ b/src/Analyzers/CSharp/Analysis/UseRegexInstanceInsteadOfStaticMethodAnalysis.cs @@ -70,25 +70,25 @@ bool ValidateArgument(ArgumentSyntax argument) switch (symbol.Kind) { case SymbolKind.Field: - { - return ((IFieldSymbol)symbol).HasConstantValue; - } + { + return ((IFieldSymbol)symbol).HasConstantValue; + } case SymbolKind.Method: - { - if (((IMethodSymbol)symbol).MethodKind != MethodKind.BuiltinOperator) - return false; + { + if (((IMethodSymbol)symbol).MethodKind != MethodKind.BuiltinOperator) + return false; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken); - if (typeSymbol is null) - return false; + if (typeSymbol is null) + return false; - return typeSymbol.HasMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions); - } + return typeSymbol.HasMetadataName(MetadataNames.System_Text_RegularExpressions_RegexOptions); + } default: - { - return false; - } + { + return false; + } } } } diff --git a/src/Analyzers/CSharp/NodeSymbolInfo.cs b/src/Analyzers/CSharp/NodeSymbolInfo.cs index 5fcbb9eb80..a267ab7cea 100644 --- a/src/Analyzers/CSharp/NodeSymbolInfo.cs +++ b/src/Analyzers/CSharp/NodeSymbolInfo.cs @@ -37,15 +37,15 @@ internal bool CanBeInDebuggerDisplayAttribute { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: - { - return true; - } + { + return true; + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)Node; + { + var methodDeclaration = (MethodDeclarationSyntax)Node; - return methodDeclaration.ParameterList?.Parameters.Count == 0; - } + return methodDeclaration.ParameterList?.Parameters.Count == 0; + } } return false; diff --git a/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs b/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs index a95b095ecb..58618b01ec 100644 --- a/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs +++ b/src/CSharp.Workspaces/CSharp/CSharpSyntaxFactsService.cs @@ -89,31 +89,31 @@ public bool AreEquivalent(SyntaxTree oldTree, SyntaxTree newTree) case SyntaxKind.EventDeclaration: case SyntaxKind.Parameter: case SyntaxKind.ForEachStatement: - { - return parent; - } + { + return parent; + } case SyntaxKind.IdentifierName: + { + parent = parent.Parent; + + if (parent.IsKind(SyntaxKind.NameEquals)) { parent = parent.Parent; - if (parent.IsKind(SyntaxKind.NameEquals)) + if (parent.IsKind( + SyntaxKind.UsingDirective, + SyntaxKind.AnonymousObjectMemberDeclarator)) { - parent = parent.Parent; - - if (parent.IsKind( - SyntaxKind.UsingDirective, - SyntaxKind.AnonymousObjectMemberDeclarator)) - { - return parent; - } - - SyntaxDebug.Fail(parent); - - return null; + return parent; } - return parent; + SyntaxDebug.Fail(parent); + + return null; } + + return parent; + } } SyntaxDebug.Fail(parent); diff --git a/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpLinesWalker.cs b/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpLinesWalker.cs index d464762af5..ad60f4bc2b 100644 --- a/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpLinesWalker.cs +++ b/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpLinesWalker.cs @@ -42,47 +42,47 @@ public override void VisitTrivia(SyntaxTrivia trivia) switch (trivia.Kind()) { case SyntaxKind.SingleLineCommentTrivia: - { - TextSpan span = trivia.Span; - - TextLine line = Lines.GetLineFromPosition(span.Start); + { + TextSpan span = trivia.Span; - if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) - { - CommentLineCount++; - } + TextLine line = Lines.GetLineFromPosition(span.Start); - break; - } - case SyntaxKind.SingleLineDocumentationCommentTrivia: + if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) { - CommentLineCount += Lines.GetLineCount(trivia.Span) - 1; - break; + CommentLineCount++; } + + break; + } + case SyntaxKind.SingleLineDocumentationCommentTrivia: + { + CommentLineCount += Lines.GetLineCount(trivia.Span) - 1; + break; + } case SyntaxKind.MultiLineCommentTrivia: - { - TextSpan span = trivia.Span; + { + TextSpan span = trivia.Span; - TextLine line = Lines.GetLineFromPosition(span.Start); + TextLine line = Lines.GetLineFromPosition(span.Start); - if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) - { - int lineCount = Lines.GetLineCount(trivia.Span); + if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) + { + int lineCount = Lines.GetLineCount(trivia.Span); - if (lineCount == 1 - || line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(Lines.GetLineFromPosition(span.End).End, span.End))) - { - CommentLineCount += lineCount; - } + if (lineCount == 1 + || line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(Lines.GetLineFromPosition(span.End).End, span.End))) + { + CommentLineCount += lineCount; } - - break; } + + break; + } case SyntaxKind.MultiLineDocumentationCommentTrivia: - { - CommentLineCount += Lines.GetLineCount(trivia.Span); - break; - } + { + CommentLineCount += Lines.GetLineCount(trivia.Span); + break; + } } } diff --git a/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpPhysicalLinesWalker.cs b/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpPhysicalLinesWalker.cs index 4d0bb1cc73..99d260c7d9 100644 --- a/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpPhysicalLinesWalker.cs +++ b/src/CSharp.Workspaces/CSharp/CodeMetrics/CSharpPhysicalLinesWalker.cs @@ -137,24 +137,24 @@ bool AnalyzeLeadingTrivia(in SyntaxTriviaList leadingTrivia) switch (en.Current.Kind()) { case SyntaxKind.EndOfLineTrivia: - { - return true; - } + { + return true; + } case SyntaxKind.WhitespaceTrivia: - { - break; - } + { + break; + } case SyntaxKind.MultiLineCommentTrivia: - { - if (tree.IsMultiLineSpan(en.Current.Span, CancellationToken)) - return true; + { + if (tree.IsMultiLineSpan(en.Current.Span, CancellationToken)) + return true; - break; - } + break; + } default: - { - return false; - } + { + return false; + } } } @@ -171,24 +171,24 @@ bool AnalyzeTrailingTrivia(in SyntaxTriviaList trailingTrivia) { case SyntaxKind.EndOfLineTrivia: case SyntaxKind.SingleLineCommentTrivia: - { - return true; - } + { + return true; + } case SyntaxKind.WhitespaceTrivia: - { - break; - } + { + break; + } case SyntaxKind.MultiLineCommentTrivia: - { - if (tree.IsMultiLineSpan(en.Current.Span, CancellationToken)) - return true; + { + if (tree.IsMultiLineSpan(en.Current.Span, CancellationToken)) + return true; - break; - } + break; + } default: - { - return false; - } + { + return false; + } } } diff --git a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs index ba06589f76..1c41668170 100644 --- a/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs +++ b/src/CSharp.Workspaces/CSharp/Extensions/WorkspaceExtensions.cs @@ -86,64 +86,64 @@ internal static Task RemoveMemberAsync( switch (parent?.Kind()) { case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)parent; + { + var compilationUnit = (CompilationUnitSyntax)parent; - return document.ReplaceNodeAsync(compilationUnit, SyntaxRefactorings.RemoveMember(compilationUnit, member), cancellationToken); - } + return document.ReplaceNodeAsync(compilationUnit, SyntaxRefactorings.RemoveMember(compilationUnit, member), cancellationToken); + } case SyntaxKind.NamespaceDeclaration: - { - var namespaceDeclaration = (NamespaceDeclarationSyntax)parent; + { + var namespaceDeclaration = (NamespaceDeclarationSyntax)parent; - return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)parent; + { + var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)parent; - return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(namespaceDeclaration, SyntaxRefactorings.RemoveMember(namespaceDeclaration, member), cancellationToken); + } #endif case SyntaxKind.ClassDeclaration: - { - var classDeclaration = (ClassDeclarationSyntax)parent; + { + var classDeclaration = (ClassDeclarationSyntax)parent; - return document.ReplaceNodeAsync(classDeclaration, SyntaxRefactorings.RemoveMember(classDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(classDeclaration, SyntaxRefactorings.RemoveMember(classDeclaration, member), cancellationToken); + } case SyntaxKind.StructDeclaration: - { - var structDeclaration = (StructDeclarationSyntax)parent; + { + var structDeclaration = (StructDeclarationSyntax)parent; - return document.ReplaceNodeAsync(structDeclaration, SyntaxRefactorings.RemoveMember(structDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(structDeclaration, SyntaxRefactorings.RemoveMember(structDeclaration, member), cancellationToken); + } case SyntaxKind.InterfaceDeclaration: - { - var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; + { + var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; - return document.ReplaceNodeAsync(interfaceDeclaration, SyntaxRefactorings.RemoveMember(interfaceDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(interfaceDeclaration, SyntaxRefactorings.RemoveMember(interfaceDeclaration, member), cancellationToken); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var recordDeclaration = (RecordDeclarationSyntax)parent; + { + var recordDeclaration = (RecordDeclarationSyntax)parent; - return document.ReplaceNodeAsync(recordDeclaration, SyntaxRefactorings.RemoveMember(recordDeclaration, member), cancellationToken); - } + return document.ReplaceNodeAsync(recordDeclaration, SyntaxRefactorings.RemoveMember(recordDeclaration, member), cancellationToken); + } case SyntaxKind.EnumDeclaration: - { - var enumDeclaration = (EnumDeclarationSyntax)parent; + { + var enumDeclaration = (EnumDeclarationSyntax)parent; - return document.ReplaceNodeAsync(enumDeclaration, SyntaxRefactorings.RemoveMember(enumDeclaration, (EnumMemberDeclarationSyntax)member), cancellationToken); - } + return document.ReplaceNodeAsync(enumDeclaration, SyntaxRefactorings.RemoveMember(enumDeclaration, (EnumMemberDeclarationSyntax)member), cancellationToken); + } default: - { - SyntaxDebug.Assert(parent is null, parent); + { + SyntaxDebug.Assert(parent is null, parent); - return document.RemoveNodeAsync(member, SyntaxRefactorings.DefaultRemoveOptions, cancellationToken); - } + return document.RemoveNodeAsync(member, SyntaxRefactorings.DefaultRemoveOptions, cancellationToken); + } } } diff --git a/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs b/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs index 7313707aff..6b847bc86b 100644 --- a/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs +++ b/src/CSharp.Workspaces/CSharp/FindSymbols/LocalSymbolFinder.cs @@ -21,99 +21,99 @@ public static ImmutableArray FindLocalSymbols( switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: - { - var constructor = (ConstructorDeclarationSyntax)node; - walker.Visit(constructor.BodyOrExpressionBody()); + { + var constructor = (ConstructorDeclarationSyntax)node; + walker.Visit(constructor.BodyOrExpressionBody()); - break; - } + break; + } case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)node; - - if (eventDeclaration.AccessorList is not null) - { - foreach (AccessorDeclarationSyntax accessor in eventDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); - } + { + var eventDeclaration = (EventDeclarationSyntax)node; - break; - } - case SyntaxKind.IndexerDeclaration: + if (eventDeclaration.AccessorList is not null) { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + foreach (AccessorDeclarationSyntax accessor in eventDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); + } - if (indexerDeclaration.AccessorList is not null) - { - foreach (AccessorDeclarationSyntax accessor in indexerDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); - } + break; + } + case SyntaxKind.IndexerDeclaration: + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - break; + if (indexerDeclaration.AccessorList is not null) + { + foreach (AccessorDeclarationSyntax accessor in indexerDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); } + + break; + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; + { + var methodDeclaration = (MethodDeclarationSyntax)node; - walker.Visit(methodDeclaration.BodyOrExpressionBody()); + walker.Visit(methodDeclaration.BodyOrExpressionBody()); - break; - } + break; + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; - - ArrowExpressionClauseSyntax? expressionBody = propertyDeclaration.ExpressionBody; + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; - if (expressionBody is not null) - { - walker.Visit(expressionBody); - } - else if (propertyDeclaration.AccessorList is not null) - { - foreach (AccessorDeclarationSyntax accessor in propertyDeclaration.AccessorList.Accessors) - walker.Visit(accessor.BodyOrExpressionBody()); - } + ArrowExpressionClauseSyntax? expressionBody = propertyDeclaration.ExpressionBody; - break; + if (expressionBody is not null) + { + walker.Visit(expressionBody); } - case SyntaxKind.VariableDeclarator: + else if (propertyDeclaration.AccessorList is not null) { - var declarator = (VariableDeclaratorSyntax)node; + foreach (AccessorDeclarationSyntax accessor in propertyDeclaration.AccessorList.Accessors) + walker.Visit(accessor.BodyOrExpressionBody()); + } - ExpressionSyntax? expression = declarator.Initializer?.Value; + break; + } + case SyntaxKind.VariableDeclarator: + { + var declarator = (VariableDeclaratorSyntax)node; - if (expression is not null) - walker.Visit(expression); + ExpressionSyntax? expression = declarator.Initializer?.Value; - break; - } + if (expression is not null) + walker.Visit(expression); + + break; + } case SyntaxKind.OperatorDeclaration: - { - var declaration = (OperatorDeclarationSyntax)node; + { + var declaration = (OperatorDeclarationSyntax)node; - walker.Visit(declaration.BodyOrExpressionBody()); - break; - } + walker.Visit(declaration.BodyOrExpressionBody()); + break; + } case SyntaxKind.ConversionOperatorDeclaration: - { - var declaration = (ConversionOperatorDeclarationSyntax)node; + { + var declaration = (ConversionOperatorDeclarationSyntax)node; - walker.Visit(declaration.BodyOrExpressionBody()); - break; - } + walker.Visit(declaration.BodyOrExpressionBody()); + break; + } case SyntaxKind.Parameter: case SyntaxKind.RecordDeclaration: - { - break; - } + { + break; + } default: - { - SyntaxDebug.Fail(node); + { + SyntaxDebug.Fail(node); - walker.Visit(node); - break; - } + walker.Visit(node); + break; + } } return walker.Definitions.ToImmutableArray(); diff --git a/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs b/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs index c4a0220a87..b04113e31b 100644 --- a/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs +++ b/src/CSharp.Workspaces/CSharp/Spelling/CSharpSpellingWalker.cs @@ -59,35 +59,35 @@ public override void VisitTrivia(SyntaxTrivia trivia) { case SyntaxKind.SingleLineCommentTrivia: case SyntaxKind.MultiLineCommentTrivia: - { - if (ShouldVisit(SpellingScopeFilter.NonDocumentationComment)) - AnalyzeText(trivia.ToString(), trivia.SyntaxTree!, trivia.Span); + { + if (ShouldVisit(SpellingScopeFilter.NonDocumentationComment)) + AnalyzeText(trivia.ToString(), trivia.SyntaxTree!, trivia.Span); - break; - } + break; + } case SyntaxKind.SingleLineDocumentationCommentTrivia: case SyntaxKind.MultiLineDocumentationCommentTrivia: - { - if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) - base.VisitTrivia(trivia); + { + if (ShouldVisit(SpellingScopeFilter.DocumentationComment)) + base.VisitTrivia(trivia); - break; - } + break; + } case SyntaxKind.RegionDirectiveTrivia: case SyntaxKind.EndRegionDirectiveTrivia: - { - if (ShouldVisit(SpellingScopeFilter.Region)) - base.VisitTrivia(trivia); + { + if (ShouldVisit(SpellingScopeFilter.Region)) + base.VisitTrivia(trivia); - break; - } + break; + } case SyntaxKind.PreprocessingMessageTrivia: - { - Debug.Assert(ShouldVisit(SpellingScopeFilter.Region)); + { + Debug.Assert(ShouldVisit(SpellingScopeFilter.Region)); - AnalyzeText(trivia.ToString(), trivia.SyntaxTree!, trivia.Span); - break; - } + AnalyzeText(trivia.ToString(), trivia.SyntaxTree!, trivia.Span); + break; + } } } @@ -120,82 +120,82 @@ public override void VisitTupleType(TupleTypeSyntax node) { case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.UsingStatement: - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.FieldDeclaration: - { - if (ShouldVisitFieldDeclaration(containingNode)) - base.VisitTupleType(node); + { + if (ShouldVisitFieldDeclaration(containingNode)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.ReturnType)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.ReturnType)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Event)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Event)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.ClassDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Class)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Class)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.StructDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Struct)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Struct)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.InterfaceDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Interface)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Interface)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - if (ShouldVisit(SpellingScopeFilter.Record)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Record)) + base.VisitTupleType(node); - break; - } + break; + } case SyntaxKind.Parameter: - { - if (ShouldVisit(SpellingScopeFilter.Parameter)) - base.VisitTupleType(node); + { + if (ShouldVisit(SpellingScopeFilter.Parameter)) + base.VisitTupleType(node); - break; - } + break; + } default: - { - SyntaxDebug.Fail(containingNode); - break; - } + { + SyntaxDebug.Fail(containingNode); + break; + } } } @@ -246,31 +246,31 @@ public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) case SyntaxKind.UsingStatement: case SyntaxKind.ForStatement: case SyntaxKind.FixedStatement: - { - if (ShouldVisit(SpellingScopeFilter.LocalVariable)) - AnalyzeIdentifier(node.Identifier); + { + if (ShouldVisit(SpellingScopeFilter.LocalVariable)) + AnalyzeIdentifier(node.Identifier); - break; - } + break; + } case SyntaxKind.FieldDeclaration: - { - if (ShouldVisitFieldDeclaration(containingNode)) - AnalyzeIdentifier(node.Identifier); + { + if (ShouldVisitFieldDeclaration(containingNode)) + AnalyzeIdentifier(node.Identifier); - break; - } + break; + } case SyntaxKind.EventFieldDeclaration: - { - if (ShouldVisit(SpellingScopeFilter.Event)) - AnalyzeIdentifier(node.Identifier); + { + if (ShouldVisit(SpellingScopeFilter.Event)) + AnalyzeIdentifier(node.Identifier); - break; - } + break; + } default: - { - SyntaxDebug.Fail(containingNode); - break; - } + { + SyntaxDebug.Fail(containingNode); + break; + } } base.VisitVariableDeclarator(node); @@ -316,19 +316,19 @@ private void VisitName(NameSyntax node) switch (node) { case IdentifierNameSyntax identifierName: - { - AnalyzeIdentifier(identifierName.Identifier); - break; - } + { + AnalyzeIdentifier(identifierName.Identifier); + break; + } case QualifiedNameSyntax qualifiedName: - { - VisitName(qualifiedName.Left); + { + VisitName(qualifiedName.Left); - if (qualifiedName.Right is IdentifierNameSyntax identifierName) - AnalyzeIdentifier(identifierName.Identifier); + if (qualifiedName.Right is IdentifierNameSyntax identifierName) + AnalyzeIdentifier(identifierName.Identifier); - break; - } + break; + } } } diff --git a/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs b/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs index cd73a238a1..79d63bd3a2 100644 --- a/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs +++ b/src/CSharp.Workspaces/CSharp/SyntaxInverter.cs @@ -78,55 +78,55 @@ private static ExpressionSyntax LogicallyInvertImpl( case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.IdentifierName: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.LogicalNotExpression: - { - return ((PrefixUnaryExpressionSyntax)expression).Operand; - } + { + return ((PrefixUnaryExpressionSyntax)expression).Operand; + } case SyntaxKind.CastExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - return (semanticModel is not null) - ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) - : DefaultInvert(expression); - } + { + return (semanticModel is not null) + ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) + : DefaultInvert(expression); + } case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression); + } case SyntaxKind.BitwiseAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.ExclusiveOrExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.BitwiseOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.ConditionalExpression: - { - return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: @@ -138,39 +138,39 @@ private static ExpressionSyntax LogicallyInvertImpl( case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.TrueLiteralExpression: - { - return FalseLiteralExpression(); - } + { + return FalseLiteralExpression(); + } case SyntaxKind.FalseLiteralExpression: - { - return TrueLiteralExpression(); - } + { + return TrueLiteralExpression(); + } case SyntaxKind.ParenthesizedExpression: - { - var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; + { + var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; - ExpressionSyntax expression2 = parenthesizedExpression.Expression; + ExpressionSyntax expression2 = parenthesizedExpression.Expression; - if (expression2 is null) - return parenthesizedExpression; + if (expression2 is null) + return parenthesizedExpression; - if (expression2.IsMissing) - return parenthesizedExpression; + if (expression2.IsMissing) + return parenthesizedExpression; - ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); + ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); - newExpression = newExpression.WithTriviaFrom(expression2); + newExpression = newExpression.WithTriviaFrom(expression2); - return parenthesizedExpression.WithExpression(newExpression); - } + return parenthesizedExpression.WithExpression(newExpression); + } case SyntaxKind.AwaitExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } } Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); @@ -258,20 +258,20 @@ private static ExpressionSyntax TryCreateExpressionWithoutConditionalAccess(Cond switch (conditionalAccess.WhenNotNull) { case MemberBindingExpressionSyntax memberBinding: - { - return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); - } + { + return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); + } case ElementBindingExpressionSyntax elementBinding: - { - return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); - } + { + return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + } case InvocationExpressionSyntax invocation: - { - if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) - return null; + { + if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) + return null; - return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); - } + return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); + } } return null; diff --git a/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs b/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs index cc6d043fa2..42a3dfd511 100644 --- a/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs +++ b/src/CSharp.Workspaces/CSharp/SyntaxLogicalInverter.cs @@ -92,94 +92,94 @@ private ExpressionSyntax LogicallyInvertImpl( case SyntaxKind.UncheckedExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.ConditionalAccessExpression: - { - return DefaultInvert(expression, false); - } + { + return DefaultInvert(expression, false); + } case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.AnonymousObjectCreationExpression: case SyntaxKind.TypeOfExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.LogicalNotExpression: - { - return ((PrefixUnaryExpressionSyntax)expression).Operand; - } + { + return ((PrefixUnaryExpressionSyntax)expression).Operand; + } case SyntaxKind.CastExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - return (semanticModel is not null) - ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) - : DefaultInvert(expression); - } + { + return (semanticModel is not null) + ? InvertLessThanOrGreaterThan((BinaryExpressionSyntax)expression, semanticModel, cancellationToken) + : DefaultInvert(expression); + } case SyntaxKind.IsExpression: + { + if (semanticModel is null) + return DefaultInvert(expression); + + var isExpression = (BinaryExpressionSyntax)expression; + var rightTypeSymbol = (ITypeSymbol)semanticModel.GetSymbol(isExpression.Right, cancellationToken)!; + + TypeSyntax type = rightTypeSymbol.ToTypeSyntax(); + + if (SymbolEqualityComparer.Default.Equals( + semanticModel.GetSpeculativeSymbolInfo(isExpression.SpanStart, isExpression.Right, SpeculativeBindingOption.BindAsExpression).Symbol, + semanticModel.GetSpeculativeSymbolInfo(isExpression.SpanStart, isExpression.Right, SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol)) { - if (semanticModel is null) - return DefaultInvert(expression); - - var isExpression = (BinaryExpressionSyntax)expression; - var rightTypeSymbol = (ITypeSymbol)semanticModel.GetSymbol(isExpression.Right, cancellationToken)!; - - TypeSyntax type = rightTypeSymbol.ToTypeSyntax(); - - if (SymbolEqualityComparer.Default.Equals( - semanticModel.GetSpeculativeSymbolInfo(isExpression.SpanStart, isExpression.Right, SpeculativeBindingOption.BindAsExpression).Symbol, - semanticModel.GetSpeculativeSymbolInfo(isExpression.SpanStart, isExpression.Right, SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol)) - { - type = type.WithSimplifierAnnotation(); - } - - return (Options.UseNotPattern) - ? IsPatternExpression( - isExpression.Left, - isExpression.OperatorToken.WithTrailingTrivia(Space), - UnaryPattern( - Token(SyntaxKind.NotKeyword) - .WithTrailingTrivia(isExpression.OperatorToken.TrailingTrivia), - TypePattern(type))) - : DefaultInvert(expression); + type = type.WithSimplifierAnnotation(); } + + return (Options.UseNotPattern) + ? IsPatternExpression( + isExpression.Left, + isExpression.OperatorToken.WithTrailingTrivia(Space), + UnaryPattern( + Token(SyntaxKind.NotKeyword) + .WithTrailingTrivia(isExpression.OperatorToken.TrailingTrivia), + TypePattern(type))) + : DefaultInvert(expression); + } case SyntaxKind.AsExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.IsPatternExpression: - { - return (Options.UseNotPattern) - ? InvertIsPattern((IsPatternExpressionSyntax)expression) - : DefaultInvert(expression); - } + { + return (Options.UseNotPattern) + ? InvertIsPattern((IsPatternExpressionSyntax)expression) + : DefaultInvert(expression); + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression); + } case SyntaxKind.BitwiseAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.ExclusiveOrExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.BitwiseOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: - { - return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertBinaryExpression((BinaryExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.ConditionalExpression: - { - return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); - } + { + return InvertConditionalExpression((ConditionalExpressionSyntax)expression, semanticModel, cancellationToken); + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: @@ -191,56 +191,56 @@ private ExpressionSyntax LogicallyInvertImpl( case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.TrueLiteralExpression: - { - return FalseLiteralExpression(); - } + { + return FalseLiteralExpression(); + } case SyntaxKind.FalseLiteralExpression: - { - return TrueLiteralExpression(); - } + { + return TrueLiteralExpression(); + } case SyntaxKind.ParenthesizedExpression: - { - var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; + { + var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression; - ExpressionSyntax expression2 = parenthesizedExpression.Expression; + ExpressionSyntax expression2 = parenthesizedExpression.Expression; - if (expression2 is null) - return parenthesizedExpression; + if (expression2 is null) + return parenthesizedExpression; - if (expression2.IsMissing) - return parenthesizedExpression; + if (expression2.IsMissing) + return parenthesizedExpression; - ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); + ExpressionSyntax newExpression = LogicallyInvertImpl(expression2, semanticModel, cancellationToken); - newExpression = newExpression.WithTriviaFrom(expression2); + newExpression = newExpression.WithTriviaFrom(expression2); - return parenthesizedExpression.WithExpression(newExpression); - } + return parenthesizedExpression.WithExpression(newExpression); + } case SyntaxKind.AwaitExpression: - { - return DefaultInvert(expression); - } + { + return DefaultInvert(expression); + } case SyntaxKind.CoalesceExpression: + { + var binaryExpression = (BinaryExpressionSyntax)expression; + if (binaryExpression.Right.IsKind(SyntaxKind.FalseLiteralExpression)) { - var binaryExpression = (BinaryExpressionSyntax)expression; - if (binaryExpression.Right.IsKind(SyntaxKind.FalseLiteralExpression)) - { - // !(x ?? false) === (x != true) - return NotEqualsExpression(binaryExpression.Left, TrueLiteralExpression()); - } - - if (binaryExpression.Right.IsKind(SyntaxKind.TrueLiteralExpression)) - { - // !(x ?? true) === (x == false) - return EqualsExpression(binaryExpression.Left, FalseLiteralExpression()); - } + // !(x ?? false) === (x != true) + return NotEqualsExpression(binaryExpression.Left, TrueLiteralExpression()); + } - return DefaultInvert(expression); + if (binaryExpression.Right.IsKind(SyntaxKind.TrueLiteralExpression)) + { + // !(x ?? true) === (x == false) + return EqualsExpression(binaryExpression.Left, FalseLiteralExpression()); } + + return DefaultInvert(expression); + } } Debug.Fail($"Logical inversion of unknown kind '{expression.Kind()}'"); @@ -328,20 +328,20 @@ private ExpressionSyntax InvertLessThanGreaterThan( switch (conditionalAccess.WhenNotNull) { case MemberBindingExpressionSyntax memberBinding: - { - return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); - } + { + return SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name); + } case ElementBindingExpressionSyntax elementBinding: - { - return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); - } + { + return ElementAccessExpression(conditionalAccess.Expression, elementBinding.ArgumentList); + } case InvocationExpressionSyntax invocation: - { - if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) - return null; + { + if (invocation.Expression is not MemberBindingExpressionSyntax memberBinding) + return null; - return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); - } + return InvocationExpression(SimpleMemberAccessExpression(conditionalAccess.Expression, memberBinding.Name), invocation.ArgumentList); + } } return null; diff --git a/src/CSharp/CSharp/CSharpFacts.cs b/src/CSharp/CSharp/CSharpFacts.cs index c28d0a3d27..58d77e11e3 100644 --- a/src/CSharp/CSharp/CSharpFacts.cs +++ b/src/CSharp/CSharp/CSharpFacts.cs @@ -113,17 +113,17 @@ internal static string GetTitle(SyntaxNode node) case SyntaxKind.Parameter: return "parameter"; default: - { - SyntaxDebug.Fail(node); + { + SyntaxDebug.Fail(node); - if (node is StatementSyntax) - return "statement"; + if (node is StatementSyntax) + return "statement"; - if (node is MemberDeclarationSyntax) - return "member"; + if (node is MemberDeclarationSyntax) + return "member"; - throw new ArgumentException("", nameof(node)); - } + throw new ArgumentException("", nameof(node)); + } } } @@ -577,135 +577,135 @@ internal static bool ExistsImplicitNumericConversion(SpecialType from, SpecialTy switch (from) { case SpecialType.System_Char: + { + switch (to) { - switch (to) - { - case SpecialType.System_UInt16: - case SpecialType.System_Int32: - case SpecialType.System_UInt32: - case SpecialType.System_Int64: - case SpecialType.System_UInt64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_SByte: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int16: - case SpecialType.System_Int32: - case SpecialType.System_Int64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int16: + case SpecialType.System_Int32: + case SpecialType.System_Int64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_Byte: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int16: - case SpecialType.System_UInt16: - case SpecialType.System_Int32: - case SpecialType.System_UInt32: - case SpecialType.System_Int64: - case SpecialType.System_UInt64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_Int16: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int32: - case SpecialType.System_Int64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int32: + case SpecialType.System_Int64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_UInt16: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int32: - case SpecialType.System_UInt32: - case SpecialType.System_Int64: - case SpecialType.System_UInt64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_Int32: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_UInt32: + { + switch (to) { - switch (to) - { - case SpecialType.System_Int64: - case SpecialType.System_UInt64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_Int64: case SpecialType.System_UInt64: + { + switch (to) { - switch (to) - { - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_Decimal: - return true; - } - - break; + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_Decimal: + return true; } + + break; + } case SpecialType.System_Single: + { + switch (to) { - switch (to) - { - case SpecialType.System_Double: - return true; - } - - break; + case SpecialType.System_Double: + return true; } + + break; + } } return false; diff --git a/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs b/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs index 1e90dcbbc5..208659acac 100644 --- a/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs +++ b/src/CSharp/CSharp/CSharpOverriddenSymbolInfo.cs @@ -24,14 +24,14 @@ public static bool CanCreate(SyntaxNode node) case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: - { - return true; - } + { + return true; + } case SyntaxKind.VariableDeclarator: - { - return node.IsParentKind(SyntaxKind.VariableDeclaration) - && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); - } + { + return node.IsParentKind(SyntaxKind.VariableDeclaration) + && node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); + } } return false; diff --git a/src/CSharp/CSharp/CSharpTypeAnalysis.cs b/src/CSharp/CSharp/CSharpTypeAnalysis.cs index 5cc0145b0f..e5e23408c3 100644 --- a/src/CSharp/CSharp/CSharpTypeAnalysis.cs +++ b/src/CSharp/CSharp/CSharpTypeAnalysis.cs @@ -174,20 +174,20 @@ public static bool IsExplicitThatCanBeImplicit( case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FixedStatement: - { - return false; - } + { + return false; + } case SyntaxKind.LocalDeclarationStatement: - { - if (((LocalDeclarationStatementSyntax)variableDeclaration.Parent).IsConst) - return false; + { + if (((LocalDeclarationStatementSyntax)variableDeclaration.Parent).IsConst) + return false; - break; - } + break; + } case null: - { - return false; - } + { + return false; + } } Debug.Assert(variableDeclaration.Variables.Any()); @@ -276,76 +276,76 @@ public static bool IsTypeObvious(ExpressionSyntax expression, ITypeSymbol? typeS case SyntaxKind.CastExpression: case SyntaxKind.AsExpression: case SyntaxKind.DefaultExpression: - { - return typeSymbol is null - || GetEqualityComparer(includeNullability).Equals( - typeSymbol, - semanticModel.GetTypeSymbol(expression, cancellationToken)); - } + { + return typeSymbol is null + || GetEqualityComparer(includeNullability).Equals( + typeSymbol, + semanticModel.GetTypeSymbol(expression, cancellationToken)); + } case SyntaxKind.ImplicitArrayCreationExpression: - { - var implicitArrayCreation = (ImplicitArrayCreationExpressionSyntax)expression; - - SeparatedSyntaxList expressions = implicitArrayCreation.Initializer?.Expressions ?? default; + { + var implicitArrayCreation = (ImplicitArrayCreationExpressionSyntax)expression; - if (!expressions.Any()) - return false; + SeparatedSyntaxList expressions = implicitArrayCreation.Initializer?.Expressions ?? default; - if (typeSymbol is not null) - { - var arrayTypeSymbol = semanticModel.GetTypeSymbol(implicitArrayCreation, cancellationToken) as IArrayTypeSymbol; + if (!expressions.Any()) + return false; - if (!GetEqualityComparer(includeNullability).Equals(typeSymbol, arrayTypeSymbol)) - return false; + if (typeSymbol is not null) + { + var arrayTypeSymbol = semanticModel.GetTypeSymbol(implicitArrayCreation, cancellationToken) as IArrayTypeSymbol; - typeSymbol = arrayTypeSymbol.ElementType; - } + if (!GetEqualityComparer(includeNullability).Equals(typeSymbol, arrayTypeSymbol)) + return false; - foreach (ExpressionSyntax expression2 in expressions) - { - if (!IsTypeObvious(expression2, typeSymbol, includeNullability, semanticModel, cancellationToken)) - return false; - } + typeSymbol = arrayTypeSymbol.ElementType; + } - return true; + foreach (ExpressionSyntax expression2 in expressions) + { + if (!IsTypeObvious(expression2, typeSymbol, includeNullability, semanticModel, cancellationToken)) + return false; } + + return true; + } case SyntaxKind.SimpleMemberAccessExpression: - { - ISymbol? symbol = semanticModel.GetSymbol(expression, cancellationToken); + { + ISymbol? symbol = semanticModel.GetSymbol(expression, cancellationToken); - return symbol?.Kind == SymbolKind.Field - && symbol.ContainingType?.TypeKind == TypeKind.Enum; - } + return symbol?.Kind == SymbolKind.Field + && symbol.ContainingType?.TypeKind == TypeKind.Enum; + } case SyntaxKind.InvocationExpression: + { + if (typeSymbol is not null) { - if (typeSymbol is not null) + var invocationExpression = (InvocationExpressionSyntax)expression; + if (invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { - var invocationExpression = (InvocationExpressionSyntax)expression; - if (invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) - { - ISymbol? symbol = semanticModel.GetSymbol(expression, cancellationToken); + ISymbol? symbol = semanticModel.GetSymbol(expression, cancellationToken); - if (symbol?.IsStatic == true - && string.Equals(symbol.Name, "Parse", StringComparison.Ordinal) - && GetEqualityComparer(includeNullability).Equals( - ((IMethodSymbol)symbol).ReturnType, - typeSymbol)) - { - var simpleMemberAccess = (MemberAccessExpressionSyntax)invocationExpression.Expression; + if (symbol?.IsStatic == true + && string.Equals(symbol.Name, "Parse", StringComparison.Ordinal) + && GetEqualityComparer(includeNullability).Equals( + ((IMethodSymbol)symbol).ReturnType, + typeSymbol)) + { + var simpleMemberAccess = (MemberAccessExpressionSyntax)invocationExpression.Expression; - ISymbol? symbol2 = semanticModel.GetSymbol(simpleMemberAccess.Expression, cancellationToken); + ISymbol? symbol2 = semanticModel.GetSymbol(simpleMemberAccess.Expression, cancellationToken); - if (SymbolEqualityComparer.Default.Equals(symbol2, typeSymbol) - && semanticModel.GetAliasInfo(simpleMemberAccess.Expression, cancellationToken) is null) - { - return true; - } + if (SymbolEqualityComparer.Default.Equals(symbol2, typeSymbol) + && semanticModel.GetAliasInfo(simpleMemberAccess.Expression, cancellationToken) is null) + { + return true; } } } - - break; } + + break; + } } return false; @@ -439,50 +439,50 @@ public static bool IsImplicitThatCanBeExplicit( switch (declarationExpression.Designation) { case SingleVariableDesignationSyntax singleVariableDesignation: - { - return IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation); - } + { + return IsLocalThatSupportsExplicitDeclaration(singleVariableDesignation); + } case DiscardDesignationSyntax discardDesignation: - { - return IsLocalThatSupportsExplicitDeclaration(discardDesignation); - } + { + return IsLocalThatSupportsExplicitDeclaration(discardDesignation); + } case ParenthesizedVariableDesignationSyntax parenthesizedVariableDesignation: + { + foreach (VariableDesignationSyntax variableDesignation in parenthesizedVariableDesignation.Variables) { - foreach (VariableDesignationSyntax variableDesignation in parenthesizedVariableDesignation.Variables) - { - if (variableDesignation is not SingleVariableDesignationSyntax) - return false; + if (variableDesignation is not SingleVariableDesignationSyntax) + return false; - if (!IsLocalThatSupportsExplicitDeclaration(variableDesignation)) - return false; - } + if (!IsLocalThatSupportsExplicitDeclaration(variableDesignation)) + return false; + } - if (declarationExpression.Parent is AssignmentExpressionSyntax assignmentExpression - && declarationExpression == assignmentExpression.Left) - { - ExpressionSyntax expression = assignmentExpression.Right; + if (declarationExpression.Parent is AssignmentExpressionSyntax assignmentExpression + && declarationExpression == assignmentExpression.Left) + { + ExpressionSyntax expression = assignmentExpression.Right; - if (expression is not null) + if (expression is not null) + { + switch (typeAppearance) { - switch (typeAppearance) - { - case TypeAppearance.Obvious: - return !IsTypeObvious(expression, semanticModel, cancellationToken); - case TypeAppearance.NotObvious: - return IsTypeObvious(expression, semanticModel, cancellationToken); - } - - Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); + case TypeAppearance.Obvious: + return !IsTypeObvious(expression, semanticModel, cancellationToken); + case TypeAppearance.NotObvious: + return IsTypeObvious(expression, semanticModel, cancellationToken); } - } - return true; + Debug.Assert(typeAppearance == TypeAppearance.None, typeAppearance.ToString()); + } } + + return true; + } default: - { - SyntaxDebug.Fail(declarationExpression.Designation); - return false; - } + { + SyntaxDebug.Fail(declarationExpression.Designation); + return false; + } } bool IsLocalThatSupportsExplicitDeclaration(VariableDesignationSyntax variableDesignation) @@ -568,23 +568,23 @@ static bool AnalyzeArgument(ArgumentSyntax argument, SemanticModel semanticModel case SyntaxKind.GenericName: return true; case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; + { + var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; - if (memberAccess.Name.IsKind(SyntaxKind.IdentifierName)) - return false; + if (memberAccess.Name.IsKind(SyntaxKind.IdentifierName)) + return false; - if (memberAccess.Name.IsKind(SyntaxKind.GenericName)) - return true; + if (memberAccess.Name.IsKind(SyntaxKind.GenericName)) + return true; - Debug.Fail(memberAccess.Name.Kind().ToString()); - break; - } + Debug.Fail(memberAccess.Name.Kind().ToString()); + break; + } default: - { - Debug.Fail(invocation.Expression.Kind().ToString()); - break; - } + { + Debug.Fail(invocation.Expression.Kind().ToString()); + break; + } } } } @@ -610,17 +610,17 @@ public static bool IsExplicitThatCanBeImplicit( switch (tupleExpression.Parent?.Kind()) { case SyntaxKind.SimpleAssignmentExpression: - { - var assignment = (AssignmentExpressionSyntax)tupleExpression.Parent; + { + var assignment = (AssignmentExpressionSyntax)tupleExpression.Parent; - return IsExplicitThatCanBeImplicit(tupleExpression, assignment, typeAppearance, semanticModel, cancellationToken); - } + return IsExplicitThatCanBeImplicit(tupleExpression, assignment, typeAppearance, semanticModel, cancellationToken); + } case SyntaxKind.ForEachVariableStatement: - { - var forEachStatement = (ForEachVariableStatementSyntax)tupleExpression.Parent; + { + var forEachStatement = (ForEachVariableStatementSyntax)tupleExpression.Parent; - return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); - } + return IsExplicitThatCanBeImplicit(tupleExpression, forEachStatement, semanticModel); + } #if DEBUG case SyntaxKind.Argument: case SyntaxKind.ArrayInitializerExpression: @@ -636,20 +636,20 @@ public static bool IsExplicitThatCanBeImplicit( case SyntaxKind.YieldReturnStatement: case SyntaxKind.ConditionalExpression: case SyntaxKind.ComplexElementInitializerExpression: - { - SyntaxDebug.Assert(tupleExpression.ContainsDiagnostics || !tupleExpression.Arguments.Any(f => f.Expression.IsKind(SyntaxKind.DeclarationExpression)), tupleExpression); - return false; - } + { + SyntaxDebug.Assert(tupleExpression.ContainsDiagnostics || !tupleExpression.Arguments.Any(f => f.Expression.IsKind(SyntaxKind.DeclarationExpression)), tupleExpression); + return false; + } #endif case null: - { - return false; - } + { + return false; + } default: - { - SyntaxDebug.Fail(tupleExpression.Parent); - return false; - } + { + SyntaxDebug.Fail(tupleExpression.Parent); + return false; + } } } @@ -784,49 +784,49 @@ public static TypeAnalysis AnalyzeType(ForEachVariableStatementSyntax forEachSta switch (forEachStatement.Variable) { case DeclarationExpressionSyntax declarationExpression: - { - TypeSyntax type = declarationExpression.Type; + { + TypeSyntax type = declarationExpression.Type; - Debug.Assert(type is not null); + Debug.Assert(type is not null); - if (type is null) - return default; + if (type is null) + return default; - SyntaxDebug.Assert(type.IsVar, type); + SyntaxDebug.Assert(type.IsVar, type); - if (type.IsVar) - flags |= TypeAnalysisFlags.Implicit; + if (type.IsVar) + flags |= TypeAnalysisFlags.Implicit; - break; - } + break; + } case TupleExpressionSyntax tupleExpression: + { + foreach (ArgumentSyntax argument in tupleExpression.Arguments) { - foreach (ArgumentSyntax argument in tupleExpression.Arguments) + SyntaxDebug.Assert(argument.Expression.IsKind(SyntaxKind.DeclarationExpression), argument.Expression); + + if (argument.Expression is DeclarationExpressionSyntax declarationExpression) { - SyntaxDebug.Assert(argument.Expression.IsKind(SyntaxKind.DeclarationExpression), argument.Expression); + TypeSyntax type = declarationExpression.Type; - if (argument.Expression is DeclarationExpressionSyntax declarationExpression) + if (type.IsVar) { - TypeSyntax type = declarationExpression.Type; - - if (type.IsVar) - { - flags |= TypeAnalysisFlags.Implicit; - } - else - { - flags |= TypeAnalysisFlags.Explicit; - } + flags |= TypeAnalysisFlags.Implicit; + } + else + { + flags |= TypeAnalysisFlags.Explicit; } } - - break; } + + break; + } default: - { - SyntaxDebug.Fail(forEachStatement.Variable); - return default; - } + { + SyntaxDebug.Fail(forEachStatement.Variable); + return default; + } } ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); diff --git a/src/CSharp/CSharp/CSharpUtility.cs b/src/CSharp/CSharp/CSharpUtility.cs index ee75ed74ee..6954116817 100644 --- a/src/CSharp/CSharp/CSharpUtility.cs +++ b/src/CSharp/CSharp/CSharpUtility.cs @@ -109,22 +109,22 @@ public static bool IsNamespaceInScope( switch (ancestor) { case NamespaceDeclarationSyntax namespaceDeclaration: + { + if (IsNamespace(namespaceSymbol, namespaceDeclaration.Name, semanticModel, cancellationToken) + || IsNamespace(namespaceSymbol, namespaceDeclaration.Usings, semanticModel, cancellationToken)) { - if (IsNamespace(namespaceSymbol, namespaceDeclaration.Name, semanticModel, cancellationToken) - || IsNamespace(namespaceSymbol, namespaceDeclaration.Usings, semanticModel, cancellationToken)) - { - return true; - } - - break; + return true; } + + break; + } case CompilationUnitSyntax compilationUnit: - { - if (IsNamespace(namespaceSymbol, compilationUnit.Usings, semanticModel, cancellationToken)) - return true; + { + if (IsNamespace(namespaceSymbol, compilationUnit.Usings, semanticModel, cancellationToken)) + return true; - break; - } + break; + } } } @@ -327,18 +327,18 @@ public static bool IsStringLiteralConcatenation(BinaryExpressionSyntax binaryExp switch (left?.Kind()) { case SyntaxKind.StringLiteralExpression: - { - return true; - } + { + return true; + } case SyntaxKind.AddExpression: - { - binaryExpression = (BinaryExpressionSyntax)left; - break; - } + { + binaryExpression = (BinaryExpressionSyntax)left; + break; + } default: - { - return false; - } + { + return false; + } } } } @@ -493,31 +493,31 @@ public static bool IsPartOfExpressionThatMustBeConstant(ExpressionSyntax express return false; #if DEBUG default: + { + if (parent is ExpressionSyntax) + break; + + switch (parent.Kind()) { - if (parent is ExpressionSyntax) + case SyntaxKind.Argument: + case SyntaxKind.ArgumentList: + case SyntaxKind.BracketedArgumentList: + case SyntaxKind.EqualsValueClause: + case SyntaxKind.Interpolation: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.VariableDeclarator: + { break; - - switch (parent.Kind()) + } + default: { - case SyntaxKind.Argument: - case SyntaxKind.ArgumentList: - case SyntaxKind.BracketedArgumentList: - case SyntaxKind.EqualsValueClause: - case SyntaxKind.Interpolation: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.VariableDeclarator: - { - break; - } - default: - { - SyntaxDebug.Fail(parent); - break; - } + SyntaxDebug.Fail(parent); + break; } - - break; } + + break; + } #endif } } @@ -568,20 +568,20 @@ public static bool IsConditionallyAccessed(SyntaxNode node) case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.InvocationExpression: - { - break; - } + { + break; + } case SyntaxKind.ConditionalAccessExpression: - { - if (((ConditionalAccessExpressionSyntax)parent).WhenNotNull == prev) - return true; + { + if (((ConditionalAccessExpressionSyntax)parent).WhenNotNull == prev) + return true; - break; - } + break; + } default: - { - return false; - } + { + return false; + } } prev = parent; diff --git a/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs b/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs index 6fe58f2b3a..df62e6c1bd 100644 --- a/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs +++ b/src/CSharp/CSharp/Documentation/DocumentationCommentGenerator.cs @@ -602,22 +602,22 @@ internal static DocumentationCommentData GenerateFromBase(ConstructorDeclaration { case "member": case "doc": + { + try { - try - { - return reader.ReadInnerXml(); - } - catch (XmlException ex) - { - Debug.Fail(symbol.ToDisplayString() + "\r\n\r\n" + ex.Message + "\r\n\r\n" + xml); - return null; - } + return reader.ReadInnerXml(); } - default: + catch (XmlException ex) { - Debug.Fail(reader.Name); + Debug.Fail(symbol.ToDisplayString() + "\r\n\r\n" + ex.Message + "\r\n\r\n" + xml); return null; } + } + default: + { + Debug.Fail(reader.Name); + return null; + } } } } diff --git a/src/CSharp/CSharp/ExpressionChain.Reversed.cs b/src/CSharp/CSharp/ExpressionChain.Reversed.cs index 80f99ed451..ddfd975c1f 100644 --- a/src/CSharp/CSharp/ExpressionChain.Reversed.cs +++ b/src/CSharp/CSharp/ExpressionChain.Reversed.cs @@ -134,124 +134,124 @@ public bool MoveNext() switch (_state) { case State.Start: + { + if (_chain.BinaryExpression is null) + return false; + + if (_chain.Span is null) { - if (_chain.BinaryExpression is null) - return false; + _current = _chain.BinaryExpression.Right; + _state = State.Right; + return true; + } - if (_chain.Span is null) - { - _current = _chain.BinaryExpression.Right; - _state = State.Right; - return true; - } + ExpressionSyntax right = _chain.BinaryExpression.Right; - ExpressionSyntax right = _chain.BinaryExpression.Right; + TextSpan span = _chain.Span.Value; - TextSpan span = _chain.Span.Value; + if (IsInSpan(span, right.Span)) + { + _current = right; + _state = State.Right; + return true; + } - if (IsInSpan(span, right.Span)) - { - _current = right; - _state = State.Right; - return true; - } + BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; - BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; + ExpressionSyntax left; - ExpressionSyntax left; + while (true) + { + left = binaryExpression.Left; - while (true) + if (left.RawKind == binaryExpression.RawKind) { - left = binaryExpression.Left; + binaryExpression = (BinaryExpressionSyntax)left; + right = binaryExpression.Right; - if (left.RawKind == binaryExpression.RawKind) + if (IsInSpan(span, right.Span)) { - binaryExpression = (BinaryExpressionSyntax)left; - right = binaryExpression.Right; - - if (IsInSpan(span, right.Span)) - { - _current = right; - _state = State.Right; - return true; - } - } - else if (IsInSpan(span, left.Span)) - { - _current = left; - _state = State.Left; + _current = right; + _state = State.Right; return true; } - else - { - _state = State.Left; - return false; - } + } + else if (IsInSpan(span, left.Span)) + { + _current = left; + _state = State.Left; + return true; + } + else + { + _state = State.Left; + return false; } } + } case State.Right: - { - var binaryExpression = (BinaryExpressionSyntax)_current!.Parent!; + { + var binaryExpression = (BinaryExpressionSyntax)_current!.Parent!; - ExpressionSyntax left = binaryExpression.Left; + ExpressionSyntax left = binaryExpression.Left; - if (_chain.Span is null) + if (_chain.Span is null) + { + if (left.RawKind == binaryExpression.RawKind) { - if (left.RawKind == binaryExpression.RawKind) - { - binaryExpression = (BinaryExpressionSyntax)left; + binaryExpression = (BinaryExpressionSyntax)left; - _current = binaryExpression.Right; - _state = State.Right; - } - else - { - _current = left; - _state = State.Left; - } - - return true; + _current = binaryExpression.Right; + _state = State.Right; } else { - TextSpan span = _chain.Span.Value; + _current = left; + _state = State.Left; + } - if (left.RawKind == binaryExpression.RawKind) - { - binaryExpression = (BinaryExpressionSyntax)left; + return true; + } + else + { + TextSpan span = _chain.Span.Value; - ExpressionSyntax right = binaryExpression.Right; + if (left.RawKind == binaryExpression.RawKind) + { + binaryExpression = (BinaryExpressionSyntax)left; - if (IsInSpan(span, right.Span)) - { - _current = right; - _state = State.Right; - return true; - } - } + ExpressionSyntax right = binaryExpression.Right; - if (IsInSpan(span, left.Span)) + if (IsInSpan(span, right.Span)) { - _current = left; - _state = State.Left; + _current = right; + _state = State.Right; return true; } - else - { - _current = null; - _state = State.Left; - return false; - } + } + + if (IsInSpan(span, left.Span)) + { + _current = left; + _state = State.Left; + return true; + } + else + { + _current = null; + _state = State.Left; + return false; } } + } case State.Left: - { - return false; - } + { + return false; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/CSharp/CSharp/ExpressionChain.cs b/src/CSharp/CSharp/ExpressionChain.cs index e003988f9b..74816d50dc 100644 --- a/src/CSharp/CSharp/ExpressionChain.cs +++ b/src/CSharp/CSharp/ExpressionChain.cs @@ -179,71 +179,39 @@ public bool MoveNext() switch (_state) { case State.Start: - { - if (_chain.BinaryExpression is null) - return false; - - BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; - - ExpressionSyntax left = binaryExpression.Left; - - if (_chain.Span is null) - { - _last = binaryExpression.Right; - - while (left.RawKind == binaryExpression.RawKind) - { - binaryExpression = (BinaryExpressionSyntax)left; - left = binaryExpression.Left; - } + { + if (_chain.BinaryExpression is null) + return false; - _current = left; - _state = State.Left; - return true; - } + BinaryExpressionSyntax binaryExpression = _chain.BinaryExpression; - ExpressionSyntax right = binaryExpression.Right; + ExpressionSyntax left = binaryExpression.Left; - TextSpan span = _chain.Span.Value; + if (_chain.Span is null) + { + _last = binaryExpression.Right; - if (IsInSpan(span, right.Span)) + while (left.RawKind == binaryExpression.RawKind) { - _last = right; + binaryExpression = (BinaryExpressionSyntax)left; + left = binaryExpression.Left; } - else - { - while (true) - { - left = binaryExpression.Left; - if (left.RawKind == binaryExpression.RawKind) - { - binaryExpression = (BinaryExpressionSyntax)left; - right = binaryExpression.Right; - - if (IsInSpan(span, right.Span)) - { - _last = right; - break; - } - } - else if (IsInSpan(span, left.Span)) - { - _last = left; - _current = _last; - _state = State.Left; - return true; - } - else - { - _state = State.End; - return false; - } - } - } + _current = left; + _state = State.Left; + return true; + } + + ExpressionSyntax right = binaryExpression.Right; - ExpressionSyntax first = _last; + TextSpan span = _chain.Span.Value; + if (IsInSpan(span, right.Span)) + { + _last = right; + } + else + { while (true) { left = binaryExpression.Left; @@ -255,66 +223,98 @@ public bool MoveNext() if (IsInSpan(span, right.Span)) { - first = right; - } - else - { + _last = right; break; } } + else if (IsInSpan(span, left.Span)) + { + _last = left; + _current = _last; + _state = State.Left; + return true; + } else { - if (IsInSpan(span, left.Span)) - { - _current = left; - _state = State.Left; - return true; - } - - break; + _state = State.End; + return false; } } + } - _current = first; - _state = State.Right; + ExpressionSyntax first = _last; - return true; - } - case State.Right: + while (true) { - if (_current == _last) - { - _current = null; - _last = null; - _state = State.End; - return false; - } + left = binaryExpression.Left; - _current = ((BinaryExpressionSyntax)_current!.Parent!.Parent!).Right; - return true; - } - case State.Left: - { - if (_current == _last) + if (left.RawKind == binaryExpression.RawKind) { - _current = null; - _last = null; - _state = State.End; - return false; + binaryExpression = (BinaryExpressionSyntax)left; + right = binaryExpression.Right; + + if (IsInSpan(span, right.Span)) + { + first = right; + } + else + { + break; + } } + else + { + if (IsInSpan(span, left.Span)) + { + _current = left; + _state = State.Left; + return true; + } - _current = ((BinaryExpressionSyntax)_current!.Parent!).Right; - _state = State.Right; - return true; + break; + } } - case State.End: + + _current = first; + _state = State.Right; + + return true; + } + case State.Right: + { + if (_current == _last) { + _current = null; + _last = null; + _state = State.End; return false; } - default: + + _current = ((BinaryExpressionSyntax)_current!.Parent!.Parent!).Right; + return true; + } + case State.Left: + { + if (_current == _last) { - throw new InvalidOperationException(); + _current = null; + _last = null; + _state = State.End; + return false; } + + _current = ((BinaryExpressionSyntax)_current!.Parent!).Right; + _state = State.Right; + return true; + } + case State.End: + { + return false; + } + default: + { + throw new InvalidOperationException(); + } } } diff --git a/src/CSharp/CSharp/Extensions/CSharpExtensions.cs b/src/CSharp/CSharp/Extensions/CSharpExtensions.cs index 97c59893c9..f7b7eacef3 100644 --- a/src/CSharp/CSharp/Extensions/CSharpExtensions.cs +++ b/src/CSharp/CSharp/Extensions/CSharpExtensions.cs @@ -277,47 +277,143 @@ public static bool IsDefaultValue( switch (expression.WalkDownParentheses().Kind()) { case SyntaxKind.NullLiteralExpression: - { - return typeSymbol.IsReferenceTypeOrNullableType(); - } + { + return typeSymbol.IsReferenceTypeOrNullableType(); + } case SyntaxKind.DefaultLiteralExpression: - { - return true; - } + { + return true; + } case SyntaxKind.DefaultExpression: - { - var defaultExpression = (DefaultExpressionSyntax)expression; + { + var defaultExpression = (DefaultExpressionSyntax)expression; - TypeSyntax type = defaultExpression.Type; + TypeSyntax type = defaultExpression.Type; - return type is not null - && SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(type, cancellationToken)); - } + return type is not null + && SymbolEqualityComparer.Default.Equals(typeSymbol, semanticModel.GetTypeSymbol(type, cancellationToken)); + } } switch (typeSymbol.SpecialType) { case SpecialType.System_Void: - { - return false; - } + { + return false; + } case SpecialType.System_Boolean: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - return optional.HasValue - && optional.Value is bool value - && !value; - } + return optional.HasValue + && optional.Value is bool value + && !value; + } case SpecialType.System_Char: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - return optional.HasValue - && optional.Value is char value - && value == '\0'; - } + return optional.HasValue + && optional.Value is char value + && value == '\0'; + } case SpecialType.System_SByte: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is sbyte value + && value == 0; + } + case SpecialType.System_Byte: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is byte value + && value == 0; + } + case SpecialType.System_Int16: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is short value + && value == 0; + } + case SpecialType.System_UInt16: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is ushort value + && value == 0; + } + case SpecialType.System_Int32: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is int value + && value == 0; + } + case SpecialType.System_UInt32: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is uint value + && value == 0; + } + case SpecialType.System_Int64: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is long value + && value == 0; + } + case SpecialType.System_UInt64: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is ulong value + && value == 0; + } + case SpecialType.System_Decimal: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is decimal value + && value == 0; + } + case SpecialType.System_Single: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is float value + && value == 0; + } + case SpecialType.System_Double: + { + Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); + + return optional.HasValue + && optional.Value is double value + && value == 0; + } + } + + if (typeSymbol.TypeKind == TypeKind.Enum) + { + var enumSymbol = (INamedTypeSymbol)typeSymbol; + + switch (enumSymbol.EnumUnderlyingType!.SpecialType) + { + case SpecialType.System_SByte: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -325,7 +421,7 @@ public static bool IsDefaultValue( && optional.Value is sbyte value && value == 0; } - case SpecialType.System_Byte: + case SpecialType.System_Byte: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -333,7 +429,7 @@ public static bool IsDefaultValue( && optional.Value is byte value && value == 0; } - case SpecialType.System_Int16: + case SpecialType.System_Int16: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -341,7 +437,7 @@ public static bool IsDefaultValue( && optional.Value is short value && value == 0; } - case SpecialType.System_UInt16: + case SpecialType.System_UInt16: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -349,7 +445,7 @@ public static bool IsDefaultValue( && optional.Value is ushort value && value == 0; } - case SpecialType.System_Int32: + case SpecialType.System_Int32: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -357,7 +453,7 @@ public static bool IsDefaultValue( && optional.Value is int value && value == 0; } - case SpecialType.System_UInt32: + case SpecialType.System_UInt32: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -365,7 +461,7 @@ public static bool IsDefaultValue( && optional.Value is uint value && value == 0; } - case SpecialType.System_Int64: + case SpecialType.System_Int64: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -373,7 +469,7 @@ public static bool IsDefaultValue( && optional.Value is long value && value == 0; } - case SpecialType.System_UInt64: + case SpecialType.System_UInt64: { Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); @@ -381,102 +477,6 @@ public static bool IsDefaultValue( && optional.Value is ulong value && value == 0; } - case SpecialType.System_Decimal: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is decimal value - && value == 0; - } - case SpecialType.System_Single: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is float value - && value == 0; - } - case SpecialType.System_Double: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is double value - && value == 0; - } - } - - if (typeSymbol.TypeKind == TypeKind.Enum) - { - var enumSymbol = (INamedTypeSymbol)typeSymbol; - - switch (enumSymbol.EnumUnderlyingType!.SpecialType) - { - case SpecialType.System_SByte: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is sbyte value - && value == 0; - } - case SpecialType.System_Byte: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is byte value - && value == 0; - } - case SpecialType.System_Int16: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is short value - && value == 0; - } - case SpecialType.System_UInt16: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is ushort value - && value == 0; - } - case SpecialType.System_Int32: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is int value - && value == 0; - } - case SpecialType.System_UInt32: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is uint value - && value == 0; - } - case SpecialType.System_Int64: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is long value - && value == 0; - } - case SpecialType.System_UInt64: - { - Optional optional = semanticModel.GetConstantValue(expression, cancellationToken); - - return optional.HasValue - && optional.Value is ulong value - && value == 0; - } } Debug.Fail(enumSymbol.EnumUnderlyingType.SpecialType.ToString()); diff --git a/src/CSharp/CSharp/Extensions/SymbolExtensions.cs b/src/CSharp/CSharp/Extensions/SymbolExtensions.cs index 9e9c4076d2..e0e870d1ed 100644 --- a/src/CSharp/CSharp/Extensions/SymbolExtensions.cs +++ b/src/CSharp/CSharp/Extensions/SymbolExtensions.cs @@ -35,41 +35,41 @@ internal static ImmutableArray ToDisplayParts(this INamedType switch (typeSymbol.DeclaredAccessibility) { case Accessibility.Public: - { - AddKeyword(SyntaxKind.PublicKeyword); - break; - } + { + AddKeyword(SyntaxKind.PublicKeyword); + break; + } case Accessibility.ProtectedOrInternal: - { - AddKeyword(SyntaxKind.ProtectedKeyword); - AddKeyword(SyntaxKind.InternalKeyword); - break; - } + { + AddKeyword(SyntaxKind.ProtectedKeyword); + AddKeyword(SyntaxKind.InternalKeyword); + break; + } case Accessibility.Internal: - { - AddKeyword(SyntaxKind.InternalKeyword); - break; - } + { + AddKeyword(SyntaxKind.InternalKeyword); + break; + } case Accessibility.Protected: - { - AddKeyword(SyntaxKind.ProtectedKeyword); - break; - } + { + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + } case Accessibility.ProtectedAndInternal: - { - AddKeyword(SyntaxKind.PrivateKeyword); - AddKeyword(SyntaxKind.ProtectedKeyword); - break; - } + { + AddKeyword(SyntaxKind.PrivateKeyword); + AddKeyword(SyntaxKind.ProtectedKeyword); + break; + } case Accessibility.Private: - { - AddKeyword(SyntaxKind.PrivateKeyword); - break; - } + { + AddKeyword(SyntaxKind.PrivateKeyword); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs b/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs index 2c827c279b..ca946bbba5 100644 --- a/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs +++ b/src/CSharp/CSharp/Extensions/SyntaxExtensions.cs @@ -473,55 +473,55 @@ internal static TextSpan HeaderSpan(this DestructorDeclarationSyntax destructorD { case SyntaxKind.IfDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: + { + while (true) { - while (true) - { - d = d.GetNextPossiblyRelatedDirective(); + d = d.GetNextPossiblyRelatedDirective(); - if (d is null) - break; + if (d is null) + break; - if (d.IsKind( - SyntaxKind.ElifDirectiveTrivia, - SyntaxKind.ElseDirectiveTrivia, - SyntaxKind.EndIfDirectiveTrivia)) - { - return d; - } + if (d.IsKind( + SyntaxKind.ElifDirectiveTrivia, + SyntaxKind.ElseDirectiveTrivia, + SyntaxKind.EndIfDirectiveTrivia)) + { + return d; } - - break; } + + break; + } case SyntaxKind.ElseDirectiveTrivia: + { + while (true) { - while (true) - { - d = d.GetNextPossiblyRelatedDirective(); + d = d.GetNextPossiblyRelatedDirective(); - if (d is null) - break; - - if (d.Kind() == SyntaxKind.EndIfDirectiveTrivia) - return d; - } + if (d is null) + break; - break; + if (d.Kind() == SyntaxKind.EndIfDirectiveTrivia) + return d; } + + break; + } case SyntaxKind.RegionDirectiveTrivia: + { + while (true) { - while (true) - { - d = d.GetNextPossiblyRelatedDirective(); - - if (d is null) - break; + d = d.GetNextPossiblyRelatedDirective(); - if (d.Kind() == SyntaxKind.EndRegionDirectiveTrivia) - return d; - } + if (d is null) + break; - break; + if (d.Kind() == SyntaxKind.EndRegionDirectiveTrivia) + return d; } + + break; + } } return null; @@ -540,25 +540,25 @@ internal static TextSpan HeaderSpan(this DestructorDeclarationSyntax destructorD switch (d.Kind()) { case SyntaxKind.IfDirectiveTrivia: + { + do { - do - { - d = d.GetNextRelatedDirective(); - } - while (d is not null && d.Kind() != SyntaxKind.EndIfDirectiveTrivia); - - continue; + d = d.GetNextRelatedDirective(); } + while (d is not null && d.Kind() != SyntaxKind.EndIfDirectiveTrivia); + + continue; + } case SyntaxKind.RegionDirectiveTrivia: + { + do { - do - { - d = d.GetNextRelatedDirective(); - } - while (d is not null && d.Kind() != SyntaxKind.EndRegionDirectiveTrivia); - - continue; + d = d.GetNextRelatedDirective(); } + while (d is not null && d.Kind() != SyntaxKind.EndRegionDirectiveTrivia); + + continue; + } } } @@ -2903,47 +2903,47 @@ public static bool IsInExpressionTree( { case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: + { + if (semanticModel + .GetTypeInfo(current, cancellationToken) + .ConvertedType? + .OriginalDefinition + .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true) { - if (semanticModel - .GetTypeInfo(current, cancellationToken) - .ConvertedType? - .OriginalDefinition - .HasMetadataName(MetadataNames.System_Linq_Expressions_Expression_T) == true) - { - return true; - } - - break; + return true; } + + break; + } case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: case SyntaxKind.GroupClause: case SyntaxKind.SelectClause: - { - SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(current, cancellationToken); + { + SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(current, cancellationToken); - if (IsMethodThatAcceptsExpressionAsFirstParameter(symbolInfo)) - return true; + if (IsMethodThatAcceptsExpressionAsFirstParameter(symbolInfo)) + return true; - break; - } + break; + } case SyntaxKind.FromClause: case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: case SyntaxKind.LetClause: case SyntaxKind.OrderByClause: case SyntaxKind.WhereClause: - { - QueryClauseInfo clauseInfo = semanticModel.GetQueryClauseInfo((QueryClauseSyntax)current, cancellationToken); - - if (IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.CastInfo) - || IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.OperationInfo)) - { - return true; - } + { + QueryClauseInfo clauseInfo = semanticModel.GetQueryClauseInfo((QueryClauseSyntax)current, cancellationToken); - break; + if (IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.CastInfo) + || IsMethodThatAcceptsExpressionAsFirstParameter(clauseInfo.OperationInfo)) + { + return true; } + + break; + } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.Block: @@ -3008,9 +3008,9 @@ public static bool IsInExpressionTree( case SyntaxKind.WhenClause: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ThisConstructorInitializer: - { - return false; - } + { + return false; + } #if DEBUG case SyntaxKind.Argument: case SyntaxKind.ArgumentList: @@ -3023,14 +3023,14 @@ public static bool IsInExpressionTree( case SyntaxKind.VariableDeclarator: case SyntaxKind.QueryBody: case SyntaxKind.AnonymousObjectMemberDeclarator: - { - break; - } + { + break; + } default: - { - SyntaxDebug.Assert(current is ExpressionSyntax, current); - break; - } + { + SyntaxDebug.Assert(current is ExpressionSyntax, current); + break; + } #endif } } @@ -3846,10 +3846,10 @@ internal static TypeDeclarationSyntax WithMembers(this TypeDeclarationSyntax typ case SyntaxKind.InterfaceDeclaration: return ((InterfaceDeclarationSyntax)typeDeclaration).WithMembers(newMembers); default: - { - SyntaxDebug.Fail(typeDeclaration); - return typeDeclaration; - } + { + SyntaxDebug.Fail(typeDeclaration); + return typeDeclaration; + } } } #endregion TypeDeclarationSyntax diff --git a/src/CSharp/CSharp/MemberDeclarationComparer.cs b/src/CSharp/CSharp/MemberDeclarationComparer.cs index 8dde045ca0..f81694e18c 100644 --- a/src/CSharp/CSharp/MemberDeclarationComparer.cs +++ b/src/CSharp/CSharp/MemberDeclarationComparer.cs @@ -66,10 +66,10 @@ internal static bool CanBeSortedByName(SyntaxKind kind) case SyntaxKind.IncompleteMember: return false; default: - { - Debug.Fail($"unknown member '{kind}'"); - return false; - } + { + Debug.Fail($"unknown member '{kind}'"); + return false; + } } } @@ -111,9 +111,9 @@ public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y switch (member.Kind()) { case SyntaxKind.FieldDeclaration: - { - return ((FieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; - } + { + return ((FieldDeclarationSyntax)member).Declaration?.Variables.FirstOrDefault()?.Identifier.ValueText; + } case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)member).Identifier.ValueText; case SyntaxKind.DelegateDeclaration: @@ -148,10 +148,10 @@ public override int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y case SyntaxKind.IncompleteMember: return ""; default: - { - Debug.Fail($"unknown member '{member.Kind()}'"); - return ""; - } + { + Debug.Fail($"unknown member '{member.Kind()}'"); + return ""; + } } } } diff --git a/src/CSharp/CSharp/MemberDeclarationKindComparer.cs b/src/CSharp/CSharp/MemberDeclarationKindComparer.cs index 7607c49bc9..0d79dbbeb5 100644 --- a/src/CSharp/CSharp/MemberDeclarationKindComparer.cs +++ b/src/CSharp/CSharp/MemberDeclarationKindComparer.cs @@ -60,10 +60,10 @@ public virtual int GetRank(SyntaxKind kind) case SyntaxKind.IncompleteMember: return 19; default: - { - Debug.Fail($"unknown member '{kind}'"); - return MemberDeclarationComparer.MaxRank; - } + { + Debug.Fail($"unknown member '{kind}'"); + return MemberDeclarationComparer.MaxRank; + } } } } diff --git a/src/CSharp/CSharp/MethodChain.cs b/src/CSharp/CSharp/MethodChain.cs index 5bd6f3dab6..9fbd9b2c98 100644 --- a/src/CSharp/CSharp/MethodChain.cs +++ b/src/CSharp/CSharp/MethodChain.cs @@ -111,23 +111,23 @@ public bool MoveNext() switch (parent?.Kind()) { case SyntaxKind.ConditionalAccessExpression: - { - var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; + { + var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; - if (conditionalAccess.WhenNotNull == node) - return conditionalAccess.Expression; + if (conditionalAccess.WhenNotNull == node) + return conditionalAccess.Expression; - break; - } + break; + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)parent; + { + var memberAccess = (MemberAccessExpressionSyntax)parent; - if (memberAccess.Name == node) - return memberAccess.Expression; + if (memberAccess.Name == node) + return memberAccess.Expression; - break; - } + break; + } } return null; diff --git a/src/CSharp/CSharp/ModifierKindComparer.cs b/src/CSharp/CSharp/ModifierKindComparer.cs index de90b1adc8..98ad98a869 100644 --- a/src/CSharp/CSharp/ModifierKindComparer.cs +++ b/src/CSharp/CSharp/ModifierKindComparer.cs @@ -68,10 +68,10 @@ public virtual int GetRank(SyntaxKind kind) case SyntaxKind.InKeyword: return 220; default: - { - Debug.Fail($"unknown modifier '{kind}'"); - return ModifierComparer.MaxRank; - } + { + Debug.Fail($"unknown modifier '{kind}'"); + return ModifierComparer.MaxRank; + } } } } diff --git a/src/CSharp/CSharp/ModifierList.cs b/src/CSharp/CSharp/ModifierList.cs index 70adac6549..5391366133 100644 --- a/src/CSharp/CSharp/ModifierList.cs +++ b/src/CSharp/CSharp/ModifierList.cs @@ -81,33 +81,33 @@ internal static SyntaxNode Insert(SyntaxNode node, Accessibility accessibility, switch (accessibility) { case Accessibility.Private: - { - return Insert(node, SyntaxKind.PrivateKeyword, comparer); - } + { + return Insert(node, SyntaxKind.PrivateKeyword, comparer); + } case Accessibility.Protected: - { - return Insert(node, SyntaxKind.ProtectedKeyword, comparer); - } + { + return Insert(node, SyntaxKind.ProtectedKeyword, comparer); + } case Accessibility.ProtectedAndInternal: - { - node = Insert(node, SyntaxKind.PrivateKeyword, comparer); + { + node = Insert(node, SyntaxKind.PrivateKeyword, comparer); - return Insert(node, SyntaxKind.ProtectedKeyword, comparer); - } + return Insert(node, SyntaxKind.ProtectedKeyword, comparer); + } case Accessibility.Internal: - { - return Insert(node, SyntaxKind.InternalKeyword, comparer); - } + { + return Insert(node, SyntaxKind.InternalKeyword, comparer); + } case Accessibility.Public: - { - return Insert(node, SyntaxKind.PublicKeyword, comparer); - } + { + return Insert(node, SyntaxKind.PublicKeyword, comparer); + } case Accessibility.ProtectedOrInternal: - { - node = Insert(node, SyntaxKind.ProtectedKeyword, comparer); + { + node = Insert(node, SyntaxKind.ProtectedKeyword, comparer); - return Insert(node, SyntaxKind.InternalKeyword, comparer); - } + return Insert(node, SyntaxKind.InternalKeyword, comparer); + } } return node; diff --git a/src/CSharp/CSharp/StringLiteralParser.cs b/src/CSharp/CSharp/StringLiteralParser.cs index 189950fb36..afb507a96d 100644 --- a/src/CSharp/CSharp/StringLiteralParser.cs +++ b/src/CSharp/CSharp/StringLiteralParser.cs @@ -68,155 +68,155 @@ private static StringLiteralParserResult ParseRegular( switch (text[pos]) { case '\'': - { - ch = '\''; - break; - } + { + ch = '\''; + break; + } case '\"': - { - ch = '\"'; - break; - } + { + ch = '\"'; + break; + } case '\\': - { - ch = '\\'; - break; - } + { + ch = '\\'; + break; + } case '0': - { - ch = '\0'; - break; - } + { + ch = '\0'; + break; + } case 'a': - { - ch = '\a'; - break; - } + { + ch = '\a'; + break; + } case 'b': - { - ch = '\b'; - break; - } + { + ch = '\b'; + break; + } case 'f': - { - ch = '\f'; - break; - } + { + ch = '\f'; + break; + } case 'n': - { - ch = '\n'; - break; - } + { + ch = '\n'; + break; + } case 'r': - { - ch = '\r'; - break; - } + { + ch = '\r'; + break; + } case 't': - { - ch = '\t'; - break; - } + { + ch = '\t'; + break; + } case 'u': - { - pos++; - - if (pos + 3 >= text.Length) - return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); + { + pos++; - if (uint.TryParse(text.Substring(pos, 4), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) - { - ch = (char)result; - pos += 3; - } - else - { - return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); - } + if (pos + 3 >= text.Length) + return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); - break; + if (uint.TryParse(text.Substring(pos, 4), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) + { + ch = (char)result; + pos += 3; } - case 'U': + else { - pos++; + return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); + } - if (pos + 7 >= text.Length) - return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); + break; + } + case 'U': + { + pos++; - if (uint.TryParse(text.Substring(pos, 8), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) - { - if (result > 0xffff) - return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); + if (pos + 7 >= text.Length) + return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); - ch = (char)result; - pos += 7; - } - else - { + if (uint.TryParse(text.Substring(pos, 8), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) + { + if (result > 0xffff) return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); - } - break; + ch = (char)result; + pos += 7; } - case 'v': + else { - ch = '\v'; - break; + return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); } + + break; + } + case 'v': + { + ch = '\v'; + break; + } case 'x': - { - var sb2 = new StringBuilder(10); - pos++; + { + var sb2 = new StringBuilder(10); + pos++; - if (pos >= text.Length) - return Fail(throwOnError, MissingEscapeSequenceMessage); + if (pos >= text.Length) + return Fail(throwOnError, MissingEscapeSequenceMessage); - ch = text[pos]; - if (IsHexadecimalDigit(ch)) + ch = text[pos]; + if (IsHexadecimalDigit(ch)) + { + sb2.Append(ch); + pos++; + if (pos < text.Length) { - sb2.Append(ch); - pos++; - if (pos < text.Length) + ch = text[pos]; + if (IsHexadecimalDigit(ch)) { - ch = text[pos]; - if (IsHexadecimalDigit(ch)) + sb2.Append(ch); + pos++; + if (pos < text.Length) { - sb2.Append(ch); - pos++; - if (pos < text.Length) + ch = text[pos]; + if (IsHexadecimalDigit(ch)) { - ch = text[pos]; - if (IsHexadecimalDigit(ch)) + sb2.Append(ch); + pos++; + if (pos < text.Length) { - sb2.Append(ch); - pos++; - if (pos < text.Length) + ch = text[pos]; + if (IsHexadecimalDigit(ch)) { - ch = text[pos]; - if (IsHexadecimalDigit(ch)) - { - sb2.Append(ch); - pos++; - } + sb2.Append(ch); + pos++; } } } } } } - else - { - return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); - } - - ch = (char)int.Parse(sb2.ToString(), NumberStyles.HexNumber); - pos--; - break; } - default: + else { return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); } + + ch = (char)int.Parse(sb2.ToString(), NumberStyles.HexNumber); + pos--; + break; + } + default: + { + return Fail(throwOnError, UnrecognizedEscapeSequenceMessage); + } } } else if (isInterpolatedText) @@ -346,55 +346,59 @@ private static bool CanExtractSpanFromRegular( case 'r': case 't': case 'v': - { - if (IsOverlap(span, pos)) - return false; + { + if (IsOverlap(span, pos)) + return false; - break; - } + break; + } case 'u': - { - if (pos + 4 >= text.Length) - return false; + { + if (pos + 4 >= text.Length) + return false; - if (!uint.TryParse(text.Substring(pos + 1, 4), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint _)) - return false; + if (!uint.TryParse(text.Substring(pos + 1, 4), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint _)) + return false; - if (IsOverlap(span, startPos, 6)) - return false; + if (IsOverlap(span, startPos, 6)) + return false; - pos += 4; + pos += 4; - break; - } + break; + } case 'U': - { - if (pos + 8 >= text.Length) - return false; + { + if (pos + 8 >= text.Length) + return false; - if (!uint.TryParse(text.Substring(pos + 1, 8), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) - return false; + if (!uint.TryParse(text.Substring(pos + 1, 8), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo, out uint result)) + return false; - if (result > 0xffff) - return false; + if (result > 0xffff) + return false; - if (IsOverlap(span, startPos, 10)) - return false; + if (IsOverlap(span, startPos, 10)) + return false; - pos += 8; + pos += 8; - break; - } + break; + } case 'x': - { - pos++; + { + pos++; - if (pos >= text.Length) - return false; + if (pos >= text.Length) + return false; - if (!IsHexadecimalDigit(text[pos])) - return false; + if (!IsHexadecimalDigit(text[pos])) + return false; + pos++; + if (pos < text.Length + && IsHexadecimalDigit(text[pos])) + { pos++; if (pos < text.Length && IsHexadecimalDigit(text[pos])) @@ -404,24 +408,20 @@ private static bool CanExtractSpanFromRegular( && IsHexadecimalDigit(text[pos])) { pos++; - if (pos < text.Length - && IsHexadecimalDigit(text[pos])) - { - pos++; - } } } + } - if (IsOverlap(span, startPos, pos - startPos)) - return false; + if (IsOverlap(span, startPos, pos - startPos)) + return false; - pos--; - break; - } + pos--; + break; + } default: - { - return false; - } + { + return false; + } } } else if (isInterpolatedText) diff --git a/src/CSharp/CSharp/StringLiteralTextBuilder.cs b/src/CSharp/CSharp/StringLiteralTextBuilder.cs index 6617374b9d..3a814e748c 100644 --- a/src/CSharp/CSharp/StringLiteralTextBuilder.cs +++ b/src/CSharp/CSharp/StringLiteralTextBuilder.cs @@ -43,25 +43,25 @@ public void Append(InterpolatedStringExpressionSyntax interpolatedString) switch (content.Kind()) { case SyntaxKind.Interpolation: + { + StringBuilder.Append(content.ToFullString()); + break; + } + case SyntaxKind.InterpolatedStringText: + { + var interpolatedText = (InterpolatedStringTextSyntax)content; + + if (IsVerbatim == isVerbatim) { - StringBuilder.Append(content.ToFullString()); - break; + StringBuilder.Append(interpolatedText.TextToken.Text); } - case SyntaxKind.InterpolatedStringText: + else { - var interpolatedText = (InterpolatedStringTextSyntax)content; - - if (IsVerbatim == isVerbatim) - { - StringBuilder.Append(interpolatedText.TextToken.Text); - } - else - { - Append(interpolatedText.TextToken.ValueText); - } - - break; + Append(interpolatedText.TextToken.ValueText); } + + break; + } } } } @@ -154,27 +154,27 @@ bool IsSpecialChar(char ch) switch (ch) { case '\"': - { - return true; - } + { + return true; + } case '\\': - { - return !IsVerbatim; - } + { + return !IsVerbatim; + } case '{': case '}': - { - return IsInterpolated; - } + { + return IsInterpolated; + } case '\r': case '\n': - { - return !IsVerbatim; - } + { + return !IsVerbatim; + } default: - { - return false; - } + { + return false; + } } } @@ -183,50 +183,50 @@ void AppendSpecialChar(char ch) switch (ch) { case '\"': + { + if (IsVerbatim) { - if (IsVerbatim) - { - StringBuilder.Append("\"\""); - } - else - { - StringBuilder.Append("\\\""); - } - - break; + StringBuilder.Append("\"\""); } - case '\\': + else { - Debug.Assert(!IsVerbatim); - - StringBuilder.Append(@"\\"); - break; + StringBuilder.Append("\\\""); } + + break; + } + case '\\': + { + Debug.Assert(!IsVerbatim); + + StringBuilder.Append(@"\\"); + break; + } case '{': - { - StringBuilder.Append("{{"); - break; - } + { + StringBuilder.Append("{{"); + break; + } case '}': - { - StringBuilder.Append("}}"); - break; - } + { + StringBuilder.Append("}}"); + break; + } case '\r': - { - StringBuilder.Append(@"\r"); - break; - } + { + StringBuilder.Append(@"\r"); + break; + } case '\n': - { - StringBuilder.Append(@"\n"); - break; - } + { + StringBuilder.Append(@"\n"); + break; + } default: - { - Debug.Fail(ch.ToString()); - break; - } + { + Debug.Fail(ch.ToString()); + break; + } } } } diff --git a/src/CSharp/CSharp/Syntax/GenericInfo.cs b/src/CSharp/CSharp/Syntax/GenericInfo.cs index f363ada17a..6425fce269 100644 --- a/src/CSharp/CSharp/Syntax/GenericInfo.cs +++ b/src/CSharp/CSharp/Syntax/GenericInfo.cs @@ -136,33 +136,33 @@ internal static GenericInfo Create(SyntaxNode? node) #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - return new GenericInfo((TypeDeclarationSyntax)node); - } + { + return new GenericInfo((TypeDeclarationSyntax)node); + } case SyntaxKind.DelegateDeclaration: - { - return new GenericInfo((DelegateDeclarationSyntax)node); - } + { + return new GenericInfo((DelegateDeclarationSyntax)node); + } case SyntaxKind.LocalFunctionStatement: - { - return new GenericInfo((LocalFunctionStatementSyntax)node); - } + { + return new GenericInfo((LocalFunctionStatementSyntax)node); + } case SyntaxKind.MethodDeclaration: - { - return new GenericInfo((MethodDeclarationSyntax)node); - } + { + return new GenericInfo((MethodDeclarationSyntax)node); + } case SyntaxKind.TypeParameterList: - { - return Create((TypeParameterListSyntax)node); - } + { + return Create((TypeParameterListSyntax)node); + } case SyntaxKind.TypeParameter: - { - return Create((TypeParameterSyntax)node); - } + { + return Create((TypeParameterSyntax)node); + } case SyntaxKind.TypeParameterConstraintClause: - { - return Create((TypeParameterConstraintClauseSyntax)node); - } + { + return Create((TypeParameterConstraintClauseSyntax)node); + } } if (node is TypeParameterConstraintSyntax typeParameterConstraint) diff --git a/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs b/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs index b74a048884..56bd4bae2f 100644 --- a/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs +++ b/src/CSharp/CSharp/Syntax/MemberDeclarationListInfo.cs @@ -178,21 +178,21 @@ internal static MemberDeclarationListInfo Create(SyntaxNode node) switch (node?.Kind()) { case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)node; - return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); - } + { + var compilationUnit = (CompilationUnitSyntax)node; + return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); + } case SyntaxKind.NamespaceDeclaration: - { - var namespaceDeclaration = (NamespaceDeclarationSyntax)node; - return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); - } + { + var namespaceDeclaration = (NamespaceDeclarationSyntax)node; + return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)node; - return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); - } + { + var namespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)node; + return new MemberDeclarationListInfo(namespaceDeclaration, namespaceDeclaration.Members); + } #endif case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: @@ -201,10 +201,10 @@ internal static MemberDeclarationListInfo Create(SyntaxNode node) case SyntaxKind.RecordStructDeclaration: #endif case SyntaxKind.InterfaceDeclaration: - { - var typeDeclaration = (TypeDeclarationSyntax)node; - return new MemberDeclarationListInfo(typeDeclaration, typeDeclaration.Members); - } + { + var typeDeclaration = (TypeDeclarationSyntax)node; + return new MemberDeclarationListInfo(typeDeclaration, typeDeclaration.Members); + } } return default; @@ -233,52 +233,52 @@ public MemberDeclarationListInfo WithMembers(SyntaxList switch (Parent.Kind()) { case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)Parent; - compilationUnit = compilationUnit.WithMembers(members); - return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); - } + { + var compilationUnit = (CompilationUnitSyntax)Parent; + compilationUnit = compilationUnit.WithMembers(members); + return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); + } case SyntaxKind.NamespaceDeclaration: - { - var declaration = (NamespaceDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (NamespaceDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #endif case SyntaxKind.ClassDeclaration: - { - var declaration = (ClassDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (ClassDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var declaration = (RecordDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (RecordDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.StructDeclaration: - { - var declaration = (StructDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (StructDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.InterfaceDeclaration: - { - var declaration = (InterfaceDeclarationSyntax)Parent; - declaration = declaration.WithMembers(members); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (InterfaceDeclarationSyntax)Parent; + declaration = declaration.WithMembers(members); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } } throw new InvalidOperationException(); @@ -294,52 +294,52 @@ public MemberDeclarationListInfo RemoveNode(SyntaxNode node, SyntaxRemoveOptions switch (Parent.Kind()) { case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)Parent; - compilationUnit = compilationUnit.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); - } + { + var compilationUnit = (CompilationUnitSyntax)Parent; + compilationUnit = compilationUnit.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); + } case SyntaxKind.NamespaceDeclaration: - { - var declaration = (NamespaceDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (NamespaceDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #endif case SyntaxKind.ClassDeclaration: - { - var declaration = (ClassDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (ClassDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var declaration = (RecordDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (RecordDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.StructDeclaration: - { - var declaration = (StructDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (StructDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.InterfaceDeclaration: - { - var declaration = (InterfaceDeclarationSyntax)Parent; - declaration = declaration.RemoveNode(node, options)!; - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (InterfaceDeclarationSyntax)Parent; + declaration = declaration.RemoveNode(node, options)!; + return new MemberDeclarationListInfo(declaration, declaration.Members); + } } throw new InvalidOperationException(); @@ -355,52 +355,52 @@ public MemberDeclarationListInfo ReplaceNode(SyntaxNode oldNode, SyntaxNode newN switch (Parent.Kind()) { case SyntaxKind.CompilationUnit: - { - var compilationUnit = (CompilationUnitSyntax)Parent; - compilationUnit = compilationUnit.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); - } + { + var compilationUnit = (CompilationUnitSyntax)Parent; + compilationUnit = compilationUnit.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(compilationUnit, compilationUnit.Members); + } case SyntaxKind.NamespaceDeclaration: - { - var declaration = (NamespaceDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (NamespaceDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (FileScopedNamespaceDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } #endif case SyntaxKind.ClassDeclaration: - { - var declaration = (ClassDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (ClassDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var declaration = (RecordDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (RecordDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.StructDeclaration: - { - var declaration = (StructDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (StructDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } case SyntaxKind.InterfaceDeclaration: - { - var declaration = (InterfaceDeclarationSyntax)Parent; - declaration = declaration.ReplaceNode(oldNode, newNode); - return new MemberDeclarationListInfo(declaration, declaration.Members); - } + { + var declaration = (InterfaceDeclarationSyntax)Parent; + declaration = declaration.ReplaceNode(oldNode, newNode); + return new MemberDeclarationListInfo(declaration, declaration.Members); + } } throw new InvalidOperationException(); diff --git a/src/CSharp/CSharp/Syntax/ModifierListInfo.cs b/src/CSharp/CSharp/Syntax/ModifierListInfo.cs index b076353e70..d340daf5ec 100644 --- a/src/CSharp/CSharp/Syntax/ModifierListInfo.cs +++ b/src/CSharp/CSharp/Syntax/ModifierListInfo.cs @@ -452,30 +452,30 @@ SyntaxKind GetTokenKind() switch (Modifiers[i].Kind()) { case SyntaxKind.PublicKeyword: - { - return (i, -1); - } + { + return (i, -1); + } case SyntaxKind.PrivateKeyword: case SyntaxKind.InternalKeyword: + { + for (int j = i + 1; j < count; j++) { - for (int j = i + 1; j < count; j++) - { - if (Modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) - return (i, j); - } - - return (i, -1); + if (Modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) + return (i, j); } + + return (i, -1); + } case SyntaxKind.ProtectedKeyword: + { + for (int j = i + 1; j < count; j++) { - for (int j = i + 1; j < count; j++) - { - if (Modifiers[j].IsKind(SyntaxKind.InternalKeyword, SyntaxKind.PrivateKeyword)) - return (i, j); - } - - return (i, -1); + if (Modifiers[j].IsKind(SyntaxKind.InternalKeyword, SyntaxKind.PrivateKeyword)) + return (i, j); } + + return (i, -1); + } } } @@ -494,9 +494,9 @@ private int GetFirstTokenIndex() case SyntaxKind.PrivateKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: - { - return i; - } + { + return i; + } } } @@ -513,138 +513,138 @@ public ModifierListInfo WithModifiers(SyntaxTokenList modifiers) switch (Parent.Kind()) { case SyntaxKind.ClassDeclaration: - { - var classDeclaration = (ClassDeclarationSyntax)Parent; - ClassDeclarationSyntax newNode = classDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var classDeclaration = (ClassDeclarationSyntax)Parent; + ClassDeclarationSyntax newNode = classDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.ConstructorDeclaration: - { - var constructorDeclaration = (ConstructorDeclarationSyntax)Parent; - ConstructorDeclarationSyntax newNode = constructorDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var constructorDeclaration = (ConstructorDeclarationSyntax)Parent; + ConstructorDeclarationSyntax newNode = constructorDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)Parent; - OperatorDeclarationSyntax newNode = operatorDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var operatorDeclaration = (OperatorDeclarationSyntax)Parent; + OperatorDeclarationSyntax newNode = operatorDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.ConversionOperatorDeclaration: - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)Parent; - ConversionOperatorDeclarationSyntax newNode = conversionOperatorDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)Parent; + ConversionOperatorDeclarationSyntax newNode = conversionOperatorDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.DelegateDeclaration: - { - var delegateDeclaration = (DelegateDeclarationSyntax)Parent; - DelegateDeclarationSyntax newNode = delegateDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var delegateDeclaration = (DelegateDeclarationSyntax)Parent; + DelegateDeclarationSyntax newNode = delegateDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.DestructorDeclaration: - { - var destructorDeclaration = (DestructorDeclarationSyntax)Parent; - DestructorDeclarationSyntax newNode = destructorDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var destructorDeclaration = (DestructorDeclarationSyntax)Parent; + DestructorDeclarationSyntax newNode = destructorDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.EnumDeclaration: - { - var enumDeclaration = (EnumDeclarationSyntax)Parent; - EnumDeclarationSyntax newNode = enumDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var enumDeclaration = (EnumDeclarationSyntax)Parent; + EnumDeclarationSyntax newNode = enumDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)Parent; - EventDeclarationSyntax newNode = eventDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var eventDeclaration = (EventDeclarationSyntax)Parent; + EventDeclarationSyntax newNode = eventDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.EventFieldDeclaration: - { - var eventFieldDeclaration = (EventFieldDeclarationSyntax)Parent; - EventFieldDeclarationSyntax newNode = eventFieldDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var eventFieldDeclaration = (EventFieldDeclarationSyntax)Parent; + EventFieldDeclarationSyntax newNode = eventFieldDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.FieldDeclaration: - { - var fieldDeclaration = (FieldDeclarationSyntax)Parent; - FieldDeclarationSyntax newNode = fieldDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var fieldDeclaration = (FieldDeclarationSyntax)Parent; + FieldDeclarationSyntax newNode = fieldDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)Parent; - IndexerDeclarationSyntax newNode = indexerDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var indexerDeclaration = (IndexerDeclarationSyntax)Parent; + IndexerDeclarationSyntax newNode = indexerDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.InterfaceDeclaration: - { - var interfaceDeclaration = (InterfaceDeclarationSyntax)Parent; - InterfaceDeclarationSyntax newNode = interfaceDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var interfaceDeclaration = (InterfaceDeclarationSyntax)Parent; + InterfaceDeclarationSyntax newNode = interfaceDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)Parent; - MethodDeclarationSyntax newNode = methodDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var methodDeclaration = (MethodDeclarationSyntax)Parent; + MethodDeclarationSyntax newNode = methodDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)Parent; - PropertyDeclarationSyntax newNode = propertyDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var propertyDeclaration = (PropertyDeclarationSyntax)Parent; + PropertyDeclarationSyntax newNode = propertyDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var recordDeclaration = (RecordDeclarationSyntax)Parent; - RecordDeclarationSyntax newNode = recordDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var recordDeclaration = (RecordDeclarationSyntax)Parent; + RecordDeclarationSyntax newNode = recordDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.StructDeclaration: - { - var structDeclaration = (StructDeclarationSyntax)Parent; - StructDeclarationSyntax newNode = structDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var structDeclaration = (StructDeclarationSyntax)Parent; + StructDeclarationSyntax newNode = structDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.IncompleteMember: - { - var incompleteMember = (IncompleteMemberSyntax)Parent; - IncompleteMemberSyntax newNode = incompleteMember.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var incompleteMember = (IncompleteMemberSyntax)Parent; + IncompleteMemberSyntax newNode = incompleteMember.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: - { - var accessorDeclaration = (AccessorDeclarationSyntax)Parent; - AccessorDeclarationSyntax newNode = accessorDeclaration.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var accessorDeclaration = (AccessorDeclarationSyntax)Parent; + AccessorDeclarationSyntax newNode = accessorDeclaration.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.LocalDeclarationStatement: - { - var localDeclarationStatement = (LocalDeclarationStatementSyntax)Parent; - LocalDeclarationStatementSyntax newNode = localDeclarationStatement.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var localDeclarationStatement = (LocalDeclarationStatementSyntax)Parent; + LocalDeclarationStatementSyntax newNode = localDeclarationStatement.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.LocalFunctionStatement: - { - var localFunctionStatement = (LocalFunctionStatementSyntax)Parent; - LocalFunctionStatementSyntax newNode = localFunctionStatement.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var localFunctionStatement = (LocalFunctionStatementSyntax)Parent; + LocalFunctionStatementSyntax newNode = localFunctionStatement.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } case SyntaxKind.Parameter: - { - var parameter = (ParameterSyntax)Parent; - ParameterSyntax newNode = parameter.WithModifiers(modifiers); - return new ModifierListInfo(newNode, newNode.Modifiers); - } + { + var parameter = (ParameterSyntax)Parent; + ParameterSyntax newNode = parameter.WithModifiers(modifiers); + return new ModifierListInfo(newNode, newNode.Modifiers); + } } throw new InvalidOperationException(); @@ -662,115 +662,115 @@ public ModifierFilter GetFilter() switch (Modifiers[i].Kind()) { case SyntaxKind.PublicKeyword: - { - filter |= ModifierFilter.Public; - break; - } + { + filter |= ModifierFilter.Public; + break; + } case SyntaxKind.PrivateKeyword: - { - filter |= ModifierFilter.Private; - break; - } + { + filter |= ModifierFilter.Private; + break; + } case SyntaxKind.InternalKeyword: - { - filter |= ModifierFilter.Internal; - break; - } + { + filter |= ModifierFilter.Internal; + break; + } case SyntaxKind.ProtectedKeyword: - { - filter |= ModifierFilter.Protected; - break; - } + { + filter |= ModifierFilter.Protected; + break; + } case SyntaxKind.StaticKeyword: - { - filter |= ModifierFilter.Static; - break; - } + { + filter |= ModifierFilter.Static; + break; + } case SyntaxKind.ReadOnlyKeyword: - { - filter |= ModifierFilter.ReadOnly; - break; - } + { + filter |= ModifierFilter.ReadOnly; + break; + } case SyntaxKind.SealedKeyword: - { - filter |= ModifierFilter.Sealed; - break; - } + { + filter |= ModifierFilter.Sealed; + break; + } case SyntaxKind.ConstKeyword: - { - filter |= ModifierFilter.Const; - break; - } + { + filter |= ModifierFilter.Const; + break; + } case SyntaxKind.VolatileKeyword: - { - filter |= ModifierFilter.Volatile; - break; - } + { + filter |= ModifierFilter.Volatile; + break; + } case SyntaxKind.NewKeyword: - { - filter |= ModifierFilter.New; - break; - } + { + filter |= ModifierFilter.New; + break; + } case SyntaxKind.OverrideKeyword: - { - filter |= ModifierFilter.Override; - break; - } + { + filter |= ModifierFilter.Override; + break; + } case SyntaxKind.AbstractKeyword: - { - filter |= ModifierFilter.Abstract; - break; - } + { + filter |= ModifierFilter.Abstract; + break; + } case SyntaxKind.VirtualKeyword: - { - filter |= ModifierFilter.Virtual; - break; - } + { + filter |= ModifierFilter.Virtual; + break; + } case SyntaxKind.RefKeyword: - { - filter |= ModifierFilter.Ref; - break; - } + { + filter |= ModifierFilter.Ref; + break; + } case SyntaxKind.OutKeyword: - { - filter |= ModifierFilter.Out; - break; - } + { + filter |= ModifierFilter.Out; + break; + } case SyntaxKind.InKeyword: - { - filter |= ModifierFilter.In; - break; - } + { + filter |= ModifierFilter.In; + break; + } case SyntaxKind.ParamsKeyword: - { - filter |= ModifierFilter.Params; - break; - } + { + filter |= ModifierFilter.Params; + break; + } case SyntaxKind.UnsafeKeyword: - { - filter |= ModifierFilter.Unsafe; - break; - } + { + filter |= ModifierFilter.Unsafe; + break; + } case SyntaxKind.PartialKeyword: - { - filter |= ModifierFilter.Partial; - break; - } + { + filter |= ModifierFilter.Partial; + break; + } case SyntaxKind.AsyncKeyword: - { - filter |= ModifierFilter.Async; - break; - } + { + filter |= ModifierFilter.Async; + break; + } case SyntaxKind.ExternKeyword: - { - filter |= ModifierFilter.Extern; - break; - } + { + filter |= ModifierFilter.Extern; + break; + } default: - { - Debug.Fail(Modifiers[i].Kind().ToString()); - break; - } + { + Debug.Fail(Modifiers[i].Kind().ToString()); + break; + } } } diff --git a/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs b/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs index 4d771e7ec5..3c3ae80b52 100644 --- a/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/NullCheckExpressionInfo.cs @@ -124,140 +124,140 @@ private static NullCheckExpressionInfo CreateImpl( { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - var binaryExpression = (BinaryExpressionSyntax)expression; + { + var binaryExpression = (BinaryExpressionSyntax)expression; - ExpressionSyntax? left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); + ExpressionSyntax? left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); - if (left is null) - break; + if (left is null) + break; - ExpressionSyntax? right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); + ExpressionSyntax? right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); - if (right is null) - break; + if (right is null) + break; - NullCheckExpressionInfo info = Create(binaryExpression, kind, left, right, allowedStyles, allowMissing, semanticModel, cancellationToken); + NullCheckExpressionInfo info = Create(binaryExpression, kind, left, right, allowedStyles, allowMissing, semanticModel, cancellationToken); - if (info.Success) - { - return info; - } - else - { - return Create(binaryExpression, kind, right, left, allowedStyles, allowMissing, semanticModel, cancellationToken); - } + if (info.Success) + { + return info; } - case SyntaxKind.SimpleMemberAccessExpression: + else { - if ((allowedStyles & NullCheckStyles.HasValue) == 0) - break; + return Create(binaryExpression, kind, right, left, allowedStyles, allowMissing, semanticModel, cancellationToken); + } + } + case SyntaxKind.SimpleMemberAccessExpression: + { + if ((allowedStyles & NullCheckStyles.HasValue) == 0) + break; - if (semanticModel is null) - break; + if (semanticModel is null) + break; - var memberAccessExpression = (MemberAccessExpressionSyntax)expression; + var memberAccessExpression = (MemberAccessExpressionSyntax)expression; - if (!IsPropertyOfNullableOfT(memberAccessExpression.Name, "HasValue", semanticModel, cancellationToken)) - break; + if (!IsPropertyOfNullableOfT(memberAccessExpression.Name, "HasValue", semanticModel, cancellationToken)) + break; - return new NullCheckExpressionInfo(expression, memberAccessExpression.Expression, NullCheckStyles.HasValue); - } + return new NullCheckExpressionInfo(expression, memberAccessExpression.Expression, NullCheckStyles.HasValue); + } case SyntaxKind.IsPatternExpression: - { - if ((allowedStyles & (NullCheckStyles.IsNull | NullCheckStyles.IsNotNull)) == 0) - break; - - var isPatternExpression = (IsPatternExpressionSyntax)expression; + { + if ((allowedStyles & (NullCheckStyles.IsNull | NullCheckStyles.IsNotNull)) == 0) + break; - PatternSyntax pattern = isPatternExpression.Pattern; + var isPatternExpression = (IsPatternExpressionSyntax)expression; - bool isNotPattern = pattern.IsKind(SyntaxKind.NotPattern); + PatternSyntax pattern = isPatternExpression.Pattern; - if (isNotPattern) - { - if ((allowedStyles & NullCheckStyles.IsNotNull) == 0) - break; + bool isNotPattern = pattern.IsKind(SyntaxKind.NotPattern); - pattern = ((UnaryPatternSyntax)pattern).Pattern; - } - else if ((allowedStyles & NullCheckStyles.IsNull) == 0) - { + if (isNotPattern) + { + if ((allowedStyles & NullCheckStyles.IsNotNull) == 0) break; - } - if (pattern is not ConstantPatternSyntax constantPattern) - break; + pattern = ((UnaryPatternSyntax)pattern).Pattern; + } + else if ((allowedStyles & NullCheckStyles.IsNull) == 0) + { + break; + } - if (!constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) - break; + if (pattern is not ConstantPatternSyntax constantPattern) + break; - ExpressionSyntax? e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); + if (!constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) + break; - if (e is null) - break; + ExpressionSyntax? e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); - return new NullCheckExpressionInfo( - expression, - e, - (isNotPattern) ? NullCheckStyles.IsNotNull : NullCheckStyles.IsNull); - } + if (e is null) + break; + + return new NullCheckExpressionInfo( + expression, + e, + (isNotPattern) ? NullCheckStyles.IsNotNull : NullCheckStyles.IsNull); + } case SyntaxKind.LogicalNotExpression: - { - bool isNotHasValueAllowed = (allowedStyles & (NullCheckStyles.NotHasValue)) != 0; - bool isNotIsNullAllowed = (allowedStyles & (NullCheckStyles.NotIsNull)) != 0; + { + bool isNotHasValueAllowed = (allowedStyles & (NullCheckStyles.NotHasValue)) != 0; + bool isNotIsNullAllowed = (allowedStyles & (NullCheckStyles.NotIsNull)) != 0; - if (!isNotHasValueAllowed && !isNotIsNullAllowed) - break; + if (!isNotHasValueAllowed && !isNotIsNullAllowed) + break; - var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression; + var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression; - ExpressionSyntax? operand = WalkAndCheck(logicalNotExpression.Operand, walkDownParentheses, allowMissing); + ExpressionSyntax? operand = WalkAndCheck(logicalNotExpression.Operand, walkDownParentheses, allowMissing); - if (operand is null) - break; + if (operand is null) + break; - switch (operand.Kind()) + switch (operand.Kind()) + { + case SyntaxKind.SimpleMemberAccessExpression: { - case SyntaxKind.SimpleMemberAccessExpression: - { - if (!isNotHasValueAllowed) - break; + if (!isNotHasValueAllowed) + break; - if (semanticModel is null) - break; + if (semanticModel is null) + break; - var memberAccessExpression = (MemberAccessExpressionSyntax)operand; + var memberAccessExpression = (MemberAccessExpressionSyntax)operand; - if (!IsPropertyOfNullableOfT(memberAccessExpression.Name, "HasValue", semanticModel, cancellationToken)) - break; + if (!IsPropertyOfNullableOfT(memberAccessExpression.Name, "HasValue", semanticModel, cancellationToken)) + break; - return new NullCheckExpressionInfo(expression, memberAccessExpression.Expression, NullCheckStyles.NotHasValue); - } - case SyntaxKind.IsPatternExpression: - { - if (!isNotIsNullAllowed) - break; + return new NullCheckExpressionInfo(expression, memberAccessExpression.Expression, NullCheckStyles.NotHasValue); + } + case SyntaxKind.IsPatternExpression: + { + if (!isNotIsNullAllowed) + break; - var isPatternExpression = (IsPatternExpressionSyntax)operand; + var isPatternExpression = (IsPatternExpressionSyntax)operand; - if (isPatternExpression.Pattern is not ConstantPatternSyntax constantPattern) - break; + if (isPatternExpression.Pattern is not ConstantPatternSyntax constantPattern) + break; - if (!constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) - break; + if (!constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression)) + break; - ExpressionSyntax? e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); + ExpressionSyntax? e = WalkAndCheck(isPatternExpression.Expression, walkDownParentheses, allowMissing); - if (e is null) - break; + if (e is null) + break; - return new NullCheckExpressionInfo(expression, e, NullCheckStyles.NotIsNull); - } + return new NullCheckExpressionInfo(expression, e, NullCheckStyles.NotIsNull); } - - break; } + + break; + } } return default; @@ -278,46 +278,46 @@ private static NullCheckExpressionInfo Create( case SyntaxKind.NullLiteralExpression: case SyntaxKind.DefaultLiteralExpression: case SyntaxKind.DefaultExpression: - { - NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.EqualsToNull : NullCheckStyles.NotEqualsToNull; + { + NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.EqualsToNull : NullCheckStyles.NotEqualsToNull; - if ((allowedStyles & style) == 0) - break; + if ((allowedStyles & style) == 0) + break; - if (!IsNullOrDefault(expression2, expression1, semanticModel, cancellationToken)) - break; + if (!IsNullOrDefault(expression2, expression1, semanticModel, cancellationToken)) + break; - return new NullCheckExpressionInfo( - binaryExpression, - expression2, - style); - } + return new NullCheckExpressionInfo( + binaryExpression, + expression2, + style); + } case SyntaxKind.TrueLiteralExpression: - { - NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.HasValue : NullCheckStyles.NotHasValue; - - return Create( - binaryExpression, - expression2, - style, - allowedStyles, - allowMissing, - semanticModel, - cancellationToken); - } + { + NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.HasValue : NullCheckStyles.NotHasValue; + + return Create( + binaryExpression, + expression2, + style, + allowedStyles, + allowMissing, + semanticModel, + cancellationToken); + } case SyntaxKind.FalseLiteralExpression: - { - NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.NotHasValue : NullCheckStyles.HasValue; - - return Create( - binaryExpression, - expression2, - style, - allowedStyles, - allowMissing, - semanticModel, - cancellationToken); - } + { + NullCheckStyles style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? NullCheckStyles.NotHasValue : NullCheckStyles.HasValue; + + return Create( + binaryExpression, + expression2, + style, + allowedStyles, + allowMissing, + semanticModel, + cancellationToken); + } } return default; @@ -378,33 +378,33 @@ private static bool IsNullOrDefault( switch (right?.Kind()) { case SyntaxKind.NullLiteralExpression: - { - return true; - } + { + return true; + } case SyntaxKind.DefaultExpression: - { - if (semanticModel is null) - return false; + { + if (semanticModel is null) + return false; - ITypeSymbol? typeSymbol = semanticModel.GetTypeSymbol(left, cancellationToken); + ITypeSymbol? typeSymbol = semanticModel.GetTypeSymbol(left, cancellationToken); - if (typeSymbol?.IsReferenceType != true) - return false; + if (typeSymbol?.IsReferenceType != true) + return false; - ITypeSymbol? typeSymbol2 = semanticModel.GetTypeSymbol(right, cancellationToken); + ITypeSymbol? typeSymbol2 = semanticModel.GetTypeSymbol(right, cancellationToken); - return SymbolEqualityComparer.Default.Equals(typeSymbol, typeSymbol2); - } + return SymbolEqualityComparer.Default.Equals(typeSymbol, typeSymbol2); + } case SyntaxKind.DefaultLiteralExpression: - { - return semanticModel? - .GetTypeSymbol(left, cancellationToken)? - .IsReferenceType == true; - } + { + return semanticModel? + .GetTypeSymbol(left, cancellationToken)? + .IsReferenceType == true; + } default: - { - return false; - } + { + return false; + } } } } diff --git a/src/CSharp/CSharp/Syntax/RegionInfo.cs b/src/CSharp/CSharp/Syntax/RegionInfo.cs index 7cef739118..9c8e033b17 100644 --- a/src/CSharp/CSharp/Syntax/RegionInfo.cs +++ b/src/CSharp/CSharp/Syntax/RegionInfo.cs @@ -98,20 +98,20 @@ private string DebuggerDisplay { case SyntaxKind.WhitespaceTrivia: case SyntaxKind.EndOfLineTrivia: - { - continue; - } + { + continue; + } case SyntaxKind.EndRegionDirectiveTrivia: - { - if (trivia.HasStructure) - return (EndRegionDirectiveTriviaSyntax)trivia.GetStructure()!; + { + if (trivia.HasStructure) + return (EndRegionDirectiveTriviaSyntax)trivia.GetStructure()!; - return null; - } + return null; + } default: - { - return null; - } + { + return null; + } } } diff --git a/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs b/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs index c0788f3174..ebf4c45bf4 100644 --- a/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/SingleParameterLambdaExpressionInfo.cs @@ -99,40 +99,40 @@ private static SingleParameterLambdaExpressionInfo CreateImpl( switch (lambdaExpression?.Kind()) { case SyntaxKind.SimpleLambdaExpression: - { - var simpleLambda = (SimpleLambdaExpressionSyntax)lambdaExpression; + { + var simpleLambda = (SimpleLambdaExpressionSyntax)lambdaExpression; - ParameterSyntax parameter = simpleLambda.Parameter; + ParameterSyntax parameter = simpleLambda.Parameter; - if (!Check(parameter, allowMissing)) - break; + if (!Check(parameter, allowMissing)) + break; - CSharpSyntaxNode body = simpleLambda.Body; + CSharpSyntaxNode body = simpleLambda.Body; - if (!Check(body, allowMissing)) - break; + if (!Check(body, allowMissing)) + break; - return new SingleParameterLambdaExpressionInfo(simpleLambda, parameter, body); - } + return new SingleParameterLambdaExpressionInfo(simpleLambda, parameter, body); + } case SyntaxKind.ParenthesizedLambdaExpression: - { - var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)lambdaExpression; + { + var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)lambdaExpression; - ParameterSyntax? parameter = parenthesizedLambda - .ParameterList? - .Parameters - .SingleOrDefault(shouldThrow: false); + ParameterSyntax? parameter = parenthesizedLambda + .ParameterList? + .Parameters + .SingleOrDefault(shouldThrow: false); - if (!Check(parameter, allowMissing)) - break; + if (!Check(parameter, allowMissing)) + break; - CSharpSyntaxNode body = parenthesizedLambda.Body; + CSharpSyntaxNode body = parenthesizedLambda.Body; - if (!Check(body, allowMissing)) - break; + if (!Check(body, allowMissing)) + break; - return new SingleParameterLambdaExpressionInfo(parenthesizedLambda, parameter!, body); - } + return new SingleParameterLambdaExpressionInfo(parenthesizedLambda, parameter!, body); + } } return default; diff --git a/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs b/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs index 0c92911d3d..e0da79f71b 100644 --- a/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs +++ b/src/CSharp/CSharp/Syntax/StringConcatenationExpressionInfo.cs @@ -121,22 +121,22 @@ internal InterpolatedStringExpressionSyntax ToInterpolatedStringExpression() switch (expression.Kind()) { case SyntaxKind.StringLiteralExpression: - { - builder.Append((LiteralExpressionSyntax)expression); - break; - } + { + builder.Append((LiteralExpressionSyntax)expression); + break; + } case SyntaxKind.InterpolatedStringExpression: - { - builder.Append((InterpolatedStringExpressionSyntax)expression); - break; - } + { + builder.Append((InterpolatedStringExpressionSyntax)expression); + break; + } default: - { - sb.Append('{'); - sb.Append(expression.ToString()); - sb.Append('}'); - break; - } + { + sb.Append('{'); + sb.Append(expression.ToString()); + sb.Append('}'); + break; + } } } diff --git a/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs b/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs index 1e700bb983..896113091d 100644 --- a/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs +++ b/src/CSharp/CSharp/Syntax/TypeParameterConstraintInfo.cs @@ -82,15 +82,15 @@ internal bool IsDuplicateConstraint { case SyntaxKind.ClassConstraint: case SyntaxKind.StructConstraint: + { + for (int i = 0; i < index; i++) { - for (int i = 0; i < index; i++) - { - if (constraints[i].Kind() == kind) - return true; - } - - break; + if (constraints[i].Kind() == kind) + return true; } + + break; + } } return false; @@ -120,85 +120,85 @@ internal static TypeParameterConstraintInfo Create( switch (parent?.Kind()) { case SyntaxKind.ClassDeclaration: - { - var classDeclaration = (ClassDeclarationSyntax)parent; + { + var classDeclaration = (ClassDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = classDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = classDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.DelegateDeclaration: - { - var delegateDeclaration = (DelegateDeclarationSyntax)parent; + { + var delegateDeclaration = (DelegateDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = delegateDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = delegateDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.InterfaceDeclaration: - { - var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; + { + var interfaceDeclaration = (InterfaceDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = interfaceDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = interfaceDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.LocalFunctionStatement: - { - var localFunctionStatement = (LocalFunctionStatementSyntax)parent; + { + var localFunctionStatement = (LocalFunctionStatementSyntax)parent; - TypeParameterListSyntax? typeParameterList = localFunctionStatement.TypeParameterList; + TypeParameterListSyntax? typeParameterList = localFunctionStatement.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)parent; + { + var methodDeclaration = (MethodDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = methodDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = methodDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var recordDeclaration = (RecordDeclarationSyntax)parent; + { + var recordDeclaration = (RecordDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = recordDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = recordDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } case SyntaxKind.StructDeclaration: - { - var structDeclaration = (StructDeclarationSyntax)parent; + { + var structDeclaration = (StructDeclarationSyntax)parent; - TypeParameterListSyntax? typeParameterList = structDeclaration.TypeParameterList; + TypeParameterListSyntax? typeParameterList = structDeclaration.TypeParameterList; - if (!Check(typeParameterList, allowMissing)) - return default; + if (!Check(typeParameterList, allowMissing)) + return default; - return new TypeParameterConstraintInfo(constraint, constraintClause); - } + return new TypeParameterConstraintInfo(constraint, constraintClause); + } } return default; diff --git a/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs b/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs index e608c1fe92..c8300480c8 100644 --- a/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs +++ b/src/CSharp/CSharp/Syntax/UsingDirectiveListInfo.cs @@ -114,21 +114,21 @@ internal static UsingDirectiveListInfo Create(SyntaxNode declaration) switch (declaration?.Kind()) { case SyntaxKind.CompilationUnit: - { - var typeDeclaration = (CompilationUnitSyntax)declaration; - return new UsingDirectiveListInfo(typeDeclaration, typeDeclaration.Usings); - } + { + var typeDeclaration = (CompilationUnitSyntax)declaration; + return new UsingDirectiveListInfo(typeDeclaration, typeDeclaration.Usings); + } case SyntaxKind.NamespaceDeclaration: - { - var namespaceDeclaration = (NamespaceDeclarationSyntax)declaration; - return new UsingDirectiveListInfo(namespaceDeclaration, namespaceDeclaration.Usings); - } + { + var namespaceDeclaration = (NamespaceDeclarationSyntax)declaration; + return new UsingDirectiveListInfo(namespaceDeclaration, namespaceDeclaration.Usings); + } #if ROSLYN_4_0 case SyntaxKind.FileScopedNamespaceDeclaration: - { - var fileScopedNamespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)declaration; - return new UsingDirectiveListInfo(fileScopedNamespaceDeclaration, fileScopedNamespaceDeclaration.Usings); - } + { + var fileScopedNamespaceDeclaration = (FileScopedNamespaceDeclarationSyntax)declaration; + return new UsingDirectiveListInfo(fileScopedNamespaceDeclaration, fileScopedNamespaceDeclaration.Usings); + } #endif } @@ -153,15 +153,15 @@ public UsingDirectiveListInfo WithUsings(SyntaxList usings switch (Parent) { case CompilationUnitSyntax compilationUnit: - { - compilationUnit = compilationUnit.WithUsings(usings); - return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); - } + { + compilationUnit = compilationUnit.WithUsings(usings); + return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); + } case NamespaceDeclarationSyntax declaration: - { - declaration = declaration.WithUsings(usings); - return new UsingDirectiveListInfo(declaration, declaration.Usings); - } + { + declaration = declaration.WithUsings(usings); + return new UsingDirectiveListInfo(declaration, declaration.Usings); + } } throw new InvalidOperationException(); @@ -177,15 +177,15 @@ public UsingDirectiveListInfo RemoveNode(SyntaxNode node, SyntaxRemoveOptions op switch (Parent) { case CompilationUnitSyntax compilationUnit: - { - compilationUnit = compilationUnit.RemoveNode(node, options)!; - return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); - } + { + compilationUnit = compilationUnit.RemoveNode(node, options)!; + return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); + } case NamespaceDeclarationSyntax declaration: - { - declaration = declaration.RemoveNode(node, options)!; - return new UsingDirectiveListInfo(declaration, declaration.Usings); - } + { + declaration = declaration.RemoveNode(node, options)!; + return new UsingDirectiveListInfo(declaration, declaration.Usings); + } } throw new InvalidOperationException(); @@ -201,15 +201,15 @@ public UsingDirectiveListInfo ReplaceNode(SyntaxNode oldNode, SyntaxNode newNode switch (Parent) { case CompilationUnitSyntax compilationUnit: - { - compilationUnit = compilationUnit.ReplaceNode(oldNode, newNode); - return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); - } + { + compilationUnit = compilationUnit.ReplaceNode(oldNode, newNode); + return new UsingDirectiveListInfo(compilationUnit, compilationUnit.Usings); + } case NamespaceDeclarationSyntax declaration: - { - declaration = declaration.ReplaceNode(oldNode, newNode); - return new UsingDirectiveListInfo(declaration, declaration.Usings); - } + { + declaration = declaration.ReplaceNode(oldNode, newNode); + return new UsingDirectiveListInfo(declaration, declaration.Usings); + } } throw new InvalidOperationException(); diff --git a/src/CSharp/CSharp/Syntax/XmlElementInfo.cs b/src/CSharp/CSharp/Syntax/XmlElementInfo.cs index 31d39a6ca3..16f7811e58 100644 --- a/src/CSharp/CSharp/Syntax/XmlElementInfo.cs +++ b/src/CSharp/CSharp/Syntax/XmlElementInfo.cs @@ -130,23 +130,23 @@ internal static XmlElementInfo Create(XmlNodeSyntax node) switch (node) { case XmlElementSyntax element: - { - string? localName = element.StartTag?.Name?.LocalName.ValueText; + { + string? localName = element.StartTag?.Name?.LocalName.ValueText; - if (localName is null) - return default; + if (localName is null) + return default; - return new XmlElementInfo(element, localName); - } + return new XmlElementInfo(element, localName); + } case XmlEmptyElementSyntax element: - { - string? localName = element.Name?.LocalName.ValueText; + { + string? localName = element.Name?.LocalName.ValueText; - if (localName is null) - return default; + if (localName is null) + return default; - return new XmlElementInfo(element, localName); - } + return new XmlElementInfo(element, localName); + } } return default; diff --git a/src/CSharp/CSharp/SyntaxAccessibility.cs b/src/CSharp/CSharp/SyntaxAccessibility.cs index 3e91eab963..8388a8f15e 100644 --- a/src/CSharp/CSharp/SyntaxAccessibility.cs +++ b/src/CSharp/CSharp/SyntaxAccessibility.cs @@ -298,44 +298,44 @@ public static Accessibility GetExplicitAccessibility(SyntaxTokenList modifiers) switch (modifiers[i].Kind()) { case SyntaxKind.PublicKeyword: - { - return Accessibility.Public; - } + { + return Accessibility.Public; + } case SyntaxKind.PrivateKeyword: + { + for (int j = i + 1; j < count; j++) { - for (int j = i + 1; j < count; j++) - { - if (modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) - return Accessibility.ProtectedAndInternal; - } - - return Accessibility.Private; + if (modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) + return Accessibility.ProtectedAndInternal; } + + return Accessibility.Private; + } case SyntaxKind.InternalKeyword: + { + for (int j = i + 1; j < count; j++) { - for (int j = i + 1; j < count; j++) - { - if (modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) - return Accessibility.ProtectedOrInternal; - } - - return Accessibility.Internal; + if (modifiers[j].IsKind(SyntaxKind.ProtectedKeyword)) + return Accessibility.ProtectedOrInternal; } + + return Accessibility.Internal; + } case SyntaxKind.ProtectedKeyword: + { + for (int j = i + 1; j < count; j++) { - for (int j = i + 1; j < count; j++) + switch (modifiers[j].Kind()) { - switch (modifiers[j].Kind()) - { - case SyntaxKind.InternalKeyword: - return Accessibility.ProtectedOrInternal; - case SyntaxKind.PrivateKeyword: - return Accessibility.ProtectedAndInternal; - } + case SyntaxKind.InternalKeyword: + return Accessibility.ProtectedOrInternal; + case SyntaxKind.PrivateKeyword: + return Accessibility.ProtectedAndInternal; } - - return Accessibility.Protected; } + + return Accessibility.Protected; + } } } @@ -430,19 +430,19 @@ public static bool IsValidAccessibility(SyntaxNode node, Accessibility accessibi case SyntaxKind.FileScopedNamespaceDeclaration: #endif case SyntaxKind.CompilationUnit: - { - return accessibility.Is(Accessibility.Public, Accessibility.Internal); - } + { + return accessibility.Is(Accessibility.Public, Accessibility.Internal); + } case SyntaxKind.StructDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - if (accessibility.ContainsProtected()) - return false; + { + if (accessibility.ContainsProtected()) + return false; - break; - } + break; + } } switch (node.Kind()) @@ -455,104 +455,104 @@ public static bool IsValidAccessibility(SyntaxNode node, Accessibility accessibi case SyntaxKind.RecordStructDeclaration: #endif case SyntaxKind.EnumDeclaration: - { - return true; - } + { + return true; + } case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)node; + { + var eventDeclaration = (EventDeclarationSyntax)node; - ModifierFilter filter = SyntaxInfo.ModifierListInfo(eventDeclaration).GetFilter(); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(eventDeclaration).GetFilter(); - return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) - && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - && CheckProtectedInStaticOrSealedClass(node) - && CheckAccessorAccessibility(eventDeclaration.AccessorList); - } + return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) + && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) + && CheckProtectedInStaticOrSealedClass(node) + && CheckAccessorAccessibility(eventDeclaration.AccessorList); + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - ModifierFilter filter = SyntaxInfo.ModifierListInfo(indexerDeclaration).GetFilter(); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(indexerDeclaration).GetFilter(); - return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) - && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - && CheckProtectedInStaticOrSealedClass(node) - && CheckAccessorAccessibility(indexerDeclaration.AccessorList); - } + return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) + && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) + && CheckProtectedInStaticOrSealedClass(node) + && CheckAccessorAccessibility(indexerDeclaration.AccessorList); + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; - ModifierFilter filter = SyntaxInfo.ModifierListInfo(propertyDeclaration).GetFilter(); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(propertyDeclaration).GetFilter(); - return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) - && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - && CheckProtectedInStaticOrSealedClass(node) - && CheckAccessorAccessibility(propertyDeclaration.AccessorList); - } + return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) + && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) + && CheckProtectedInStaticOrSealedClass(node) + && CheckAccessorAccessibility(propertyDeclaration.AccessorList); + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; + { + var methodDeclaration = (MethodDeclarationSyntax)node; - ModifierFilter filter = SyntaxInfo.ModifierListInfo(methodDeclaration).GetFilter(); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(methodDeclaration).GetFilter(); - return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) - && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - && CheckProtectedInStaticOrSealedClass(node); - } + return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) + && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) + && CheckProtectedInStaticOrSealedClass(node); + } case SyntaxKind.EventFieldDeclaration: - { - var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; + { + var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; - ModifierFilter filter = SyntaxInfo.ModifierListInfo(eventFieldDeclaration).GetFilter(); + ModifierFilter filter = SyntaxInfo.ModifierListInfo(eventFieldDeclaration).GetFilter(); - return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) - && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) - && CheckProtectedInStaticOrSealedClass(node); - } + return (ignoreOverride || !filter.HasAnyFlag(ModifierFilter.Override)) + && (accessibility != Accessibility.Private || !filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride)) + && CheckProtectedInStaticOrSealedClass(node); + } case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.IncompleteMember: - { - return CheckProtectedInStaticOrSealedClass(node); - } + { + return CheckProtectedInStaticOrSealedClass(node); + } case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: - { - return accessibility == Accessibility.Public; - } + { + return accessibility == Accessibility.Public; + } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: - { - var memberDeclaration = node.Parent?.Parent as MemberDeclarationSyntax; - - SyntaxDebug.Assert(memberDeclaration is not null, node); + { + var memberDeclaration = node.Parent?.Parent as MemberDeclarationSyntax; - if (memberDeclaration is not null) - { - if (!CheckProtectedInStaticOrSealedClass(memberDeclaration)) - return false; + SyntaxDebug.Assert(memberDeclaration is not null, node); - return accessibility.IsMoreRestrictiveThan(GetAccessibility(memberDeclaration)); - } + if (memberDeclaration is not null) + { + if (!CheckProtectedInStaticOrSealedClass(memberDeclaration)) + return false; - return false; + return accessibility.IsMoreRestrictiveThan(GetAccessibility(memberDeclaration)); } + + return false; + } case SyntaxKind.LocalFunctionStatement: - { - return false; - } + { + return false; + } default: - { - SyntaxDebug.Fail(node); - return false; - } + { + SyntaxDebug.Fail(node); + return false; + } } bool CheckProtectedInStaticOrSealedClass(SyntaxNode declaration) diff --git a/src/CSharp/CSharp/SyntaxRefactorings.cs b/src/CSharp/CSharp/SyntaxRefactorings.cs index dad16001dd..c7908362cf 100644 --- a/src/CSharp/CSharp/SyntaxRefactorings.cs +++ b/src/CSharp/CSharp/SyntaxRefactorings.cs @@ -239,69 +239,69 @@ public static TNode RemoveComments(TNode node, TextSpan span, CommentFilt switch (trivia.Kind()) { case SyntaxKind.SingleLineCommentTrivia: - { - if ((comments & CommentFilter.SingleLine) == 0) - break; - - AddTrivia(trivia); + { + if ((comments & CommentFilter.SingleLine) == 0) + break; - SyntaxTriviaList triviaList = trivia.GetContainingList(); + AddTrivia(trivia); - int index = triviaList.IndexOf(trivia); + SyntaxTriviaList triviaList = trivia.GetContainingList(); - if (index > 0) - { - SyntaxTrivia previousTrivia = triviaList[index - 1]; + int index = triviaList.IndexOf(trivia); - if (previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia)) - AddTrivia(previousTrivia); - } + if (index > 0) + { + SyntaxTrivia previousTrivia = triviaList[index - 1]; - if (index < triviaList.Count - 1) - { - SyntaxTrivia nextTrivia = triviaList[index + 1]; + if (previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia)) + AddTrivia(previousTrivia); + } - if (nextTrivia.IsKind(SyntaxKind.EndOfLineTrivia)) - AddTrivia(nextTrivia); - } + if (index < triviaList.Count - 1) + { + SyntaxTrivia nextTrivia = triviaList[index + 1]; - break; + if (nextTrivia.IsKind(SyntaxKind.EndOfLineTrivia)) + AddTrivia(nextTrivia); } - case SyntaxKind.SingleLineDocumentationCommentTrivia: - { - if ((comments & CommentFilter.SingleLineDocumentation) == 0) - break; - AddTrivia(trivia); + break; + } + case SyntaxKind.SingleLineDocumentationCommentTrivia: + { + if ((comments & CommentFilter.SingleLineDocumentation) == 0) + break; - SyntaxTriviaList triviaList = trivia.GetContainingList(); + AddTrivia(trivia); - int index = triviaList.IndexOf(trivia); + SyntaxTriviaList triviaList = trivia.GetContainingList(); - if (index > 0) - { - SyntaxTrivia previousTrivia = triviaList[index - 1]; + int index = triviaList.IndexOf(trivia); - if (previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia)) - AddTrivia(previousTrivia); - } + if (index > 0) + { + SyntaxTrivia previousTrivia = triviaList[index - 1]; - break; + if (previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia)) + AddTrivia(previousTrivia); } + + break; + } case SyntaxKind.MultiLineCommentTrivia: - { - if ((comments & CommentFilter.MultiLine) != 0) - RemoveMultiline(trivia); + { + if ((comments & CommentFilter.MultiLine) != 0) + RemoveMultiline(trivia); - break; - } + break; + } case SyntaxKind.MultiLineDocumentationCommentTrivia: - { - if ((comments & CommentFilter.MultiLineDocumentation) != 0) - RemoveMultiline(trivia); + { + if ((comments & CommentFilter.MultiLineDocumentation) != 0) + RemoveMultiline(trivia); - break; - } + break; + } } } } diff --git a/src/CSharp/CSharp/SyntaxWalkers/AssignedExpressionWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/AssignedExpressionWalker.cs index f3ecabe461..ef2e4bdbfb 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/AssignedExpressionWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/AssignedExpressionWalker.cs @@ -73,19 +73,19 @@ public override void VisitArgument(ArgumentSyntax node) switch (node.RefOrOutKeyword.Kind()) { case SyntaxKind.RefKeyword: - { - VisitAssignedExpression(node.Expression); - break; - } + { + VisitAssignedExpression(node.Expression); + break; + } case SyntaxKind.OutKeyword: - { - ExpressionSyntax expression = node.Expression; + { + ExpressionSyntax expression = node.Expression; - if (expression?.IsKind(SyntaxKind.DeclarationExpression) == false) - VisitAssignedExpression(expression); + if (expression?.IsKind(SyntaxKind.DeclarationExpression) == false) + VisitAssignedExpression(expression); - break; - } + break; + } } base.VisitArgument(node); diff --git a/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs index 70f074d9b6..d74d8776f6 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/MethodReferencedAsMethodGroupWalker.cs @@ -42,17 +42,17 @@ static bool IsInvoked(IdentifierNameSyntax identifierName) switch (parent.Kind()) { case SyntaxKind.InvocationExpression: - { - return true; - } + { + return true; + } case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.MemberBindingExpression: - { - if (parent.IsParentKind(SyntaxKind.InvocationExpression)) - return true; + { + if (parent.IsParentKind(SyntaxKind.InvocationExpression)) + return true; - break; - } + break; + } } return false; diff --git a/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs b/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs index a6f52e21f2..80aeb4835d 100644 --- a/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs +++ b/src/CSharp/CSharp/SyntaxWalkers/StatementWalker.cs @@ -184,140 +184,140 @@ public virtual void VisitStatement(StatementSyntax node) switch (node.Kind()) { case SyntaxKind.Block: - { - VisitBlock((BlockSyntax)node); - break; - } + { + VisitBlock((BlockSyntax)node); + break; + } case SyntaxKind.BreakStatement: - { - VisitBreakStatement((BreakStatementSyntax)node); - break; - } + { + VisitBreakStatement((BreakStatementSyntax)node); + break; + } case SyntaxKind.ContinueStatement: - { - VisitContinueStatement((ContinueStatementSyntax)node); - break; - } + { + VisitContinueStatement((ContinueStatementSyntax)node); + break; + } case SyntaxKind.DoStatement: - { - VisitDoStatement((DoStatementSyntax)node); - break; - } + { + VisitDoStatement((DoStatementSyntax)node); + break; + } case SyntaxKind.EmptyStatement: - { - VisitEmptyStatement((EmptyStatementSyntax)node); - break; - } + { + VisitEmptyStatement((EmptyStatementSyntax)node); + break; + } case SyntaxKind.ExpressionStatement: - { - VisitExpressionStatement((ExpressionStatementSyntax)node); - break; - } + { + VisitExpressionStatement((ExpressionStatementSyntax)node); + break; + } case SyntaxKind.FixedStatement: - { - VisitFixedStatement((FixedStatementSyntax)node); - break; - } + { + VisitFixedStatement((FixedStatementSyntax)node); + break; + } case SyntaxKind.ForEachStatement: - { - VisitForEachStatement((ForEachStatementSyntax)node); - break; - } + { + VisitForEachStatement((ForEachStatementSyntax)node); + break; + } case SyntaxKind.ForEachVariableStatement: - { - VisitForEachVariableStatement((ForEachVariableStatementSyntax)node); - break; - } + { + VisitForEachVariableStatement((ForEachVariableStatementSyntax)node); + break; + } case SyntaxKind.ForStatement: - { - VisitForStatement((ForStatementSyntax)node); - break; - } + { + VisitForStatement((ForStatementSyntax)node); + break; + } case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: - { - VisitGotoStatement((GotoStatementSyntax)node); - break; - } + { + VisitGotoStatement((GotoStatementSyntax)node); + break; + } case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: - { - VisitCheckedStatement((CheckedStatementSyntax)node); - break; - } + { + VisitCheckedStatement((CheckedStatementSyntax)node); + break; + } case SyntaxKind.IfStatement: - { - VisitIfStatement((IfStatementSyntax)node); - break; - } + { + VisitIfStatement((IfStatementSyntax)node); + break; + } case SyntaxKind.LabeledStatement: - { - VisitLabeledStatement((LabeledStatementSyntax)node); - break; - } + { + VisitLabeledStatement((LabeledStatementSyntax)node); + break; + } case SyntaxKind.LocalDeclarationStatement: - { - VisitLocalDeclarationStatement((LocalDeclarationStatementSyntax)node); - break; - } + { + VisitLocalDeclarationStatement((LocalDeclarationStatementSyntax)node); + break; + } case SyntaxKind.LocalFunctionStatement: - { - VisitLocalFunctionStatement((LocalFunctionStatementSyntax)node); - break; - } + { + VisitLocalFunctionStatement((LocalFunctionStatementSyntax)node); + break; + } case SyntaxKind.LockStatement: - { - VisitLockStatement((LockStatementSyntax)node); - break; - } + { + VisitLockStatement((LockStatementSyntax)node); + break; + } case SyntaxKind.ReturnStatement: - { - VisitReturnStatement((ReturnStatementSyntax)node); - break; - } + { + VisitReturnStatement((ReturnStatementSyntax)node); + break; + } case SyntaxKind.SwitchStatement: - { - VisitSwitchStatement((SwitchStatementSyntax)node); - break; - } + { + VisitSwitchStatement((SwitchStatementSyntax)node); + break; + } case SyntaxKind.ThrowStatement: - { - VisitThrowStatement((ThrowStatementSyntax)node); - break; - } + { + VisitThrowStatement((ThrowStatementSyntax)node); + break; + } case SyntaxKind.TryStatement: - { - VisitTryStatement((TryStatementSyntax)node); - break; - } + { + VisitTryStatement((TryStatementSyntax)node); + break; + } case SyntaxKind.UnsafeStatement: - { - VisitUnsafeStatement((UnsafeStatementSyntax)node); - break; - } + { + VisitUnsafeStatement((UnsafeStatementSyntax)node); + break; + } case SyntaxKind.UsingStatement: - { - VisitUsingStatement((UsingStatementSyntax)node); - break; - } + { + VisitUsingStatement((UsingStatementSyntax)node); + break; + } case SyntaxKind.WhileStatement: - { - VisitWhileStatement((WhileStatementSyntax)node); - break; - } + { + VisitWhileStatement((WhileStatementSyntax)node); + break; + } case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: - { - VisitYieldStatement((YieldStatementSyntax)node); - break; - } + { + VisitYieldStatement((YieldStatementSyntax)node); + break; + } default: - { - SyntaxDebug.Fail(node); - Visit(node); - break; - } + { + SyntaxDebug.Fail(node); + Visit(node); + break; + } } } } diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs index 7d75e2a435..fbbdf989ce 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeArgumentCodeFixProvider.cs @@ -40,19 +40,19 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UnknownLanguageName: + { + foreach (string languageName in RoslynUtility.WellKnownLanguageNames) { - foreach (string languageName in RoslynUtility.WellKnownLanguageNames) - { - CodeAction codeAction = CodeAction.Create( - $"Change language name to '{languageName}'", - ct => ChangeLanguageNameAsync(document, attributeArgument, languageName, ct), - GetEquivalenceKey(diagnostic, languageName)); + CodeAction codeAction = CodeAction.Create( + $"Change language name to '{languageName}'", + ct => ChangeLanguageNameAsync(document, attributeArgument, languageName, ct), + GetEquivalenceKey(diagnostic, languageName)); - context.RegisterCodeFix(codeAction, diagnostic); - } - - break; + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } } } diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeCodeFixProvider.cs index 1a2167ee55..6e0309d7b4 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/AttributeCodeFixProvider.cs @@ -42,15 +42,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case DiagnosticIdentifiers.SpecifyExportCodeFixProviderAttributeName: case DiagnosticIdentifiers.SpecifyExportCodeRefactoringProviderAttributeName: - { - CodeAction codeAction = CodeAction.Create( - "Specify name", - ct => SpecifyNameAsync(document, attribute, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + "Specify name", + ct => SpecifyNameAsync(document, attribute, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/BinaryExpressionCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/BinaryExpressionCodeFixProvider.cs index c94f822261..40db5a9ac9 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/BinaryExpressionCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/BinaryExpressionCodeFixProvider.cs @@ -43,30 +43,30 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount: - { - CodeAction codeAction = CodeAction.Create( - "Call 'Any' instead of accessing 'Count'", - ct => CallAnyInsteadOfUsingCountAsync(document, binaryExpression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Call 'Any' instead of accessing 'Count'", + ct => CallAnyInsteadOfUsingCountAsync(document, binaryExpression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UnnecessaryNullCheck: - { - CodeAction codeAction = CodeAction.Create( - "Remove unnecessary null check", - ct => - { - ExpressionSyntax newExpression = binaryExpression.Right.WithLeadingTrivia(binaryExpression.GetLeadingTrivia()); - - return document.ReplaceNodeAsync(binaryExpression, newExpression, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Remove unnecessary null check", + ct => + { + ExpressionSyntax newExpression = binaryExpression.Right.WithLeadingTrivia(binaryExpression.GetLeadingTrivia()); + + return document.ReplaceNodeAsync(binaryExpression, newExpression, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/InvocationExpressionCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/InvocationExpressionCodeFixProvider.cs index 7d14af68d9..01cdc60adf 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/InvocationExpressionCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/InvocationExpressionCodeFixProvider.cs @@ -43,26 +43,26 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UseElementAccess: - { - CodeAction codeAction = CodeAction.Create( - "Use [] instead of calling 'First'", - ct => UseElementAccessInsteadOfCallingFirstAsync(document, invocationExpression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use [] instead of calling 'First'", + ct => UseElementAccessInsteadOfCallingFirstAsync(document, invocationExpression, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseReturnValue: - { - CodeAction codeAction = CodeAction.Create( - $"Introduce local for '{invocationExpression}'", - ct => IntroduceLocalForExpressionAsync(document, invocationExpression, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + $"Introduce local for '{invocationExpression}'", + ct => IntroduceLocalForExpressionAsync(document, invocationExpression, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); + context.RegisterCodeFix(codeAction, diagnostic); - break; - } + break; + } } } diff --git a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs index 2b94b74086..eaa28637bc 100644 --- a/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs +++ b/src/CodeAnalysis.Analyzers.CodeFixes/CSharp/UsePatternMatchingCodeFixProvider.cs @@ -42,25 +42,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (node) { case SwitchStatementSyntax switchStatement: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => UsePatternMatchingAsync(document, switchStatement, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => UsePatternMatchingAsync(document, switchStatement, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case IfStatementSyntax ifStatement: - { - CodeAction codeAction = CodeAction.Create( - Title, - ct => UsePatternMatchingAsync(document, ifStatement, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + Title, + ct => UsePatternMatchingAsync(document, ifStatement, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } @@ -159,50 +159,50 @@ private static async Task UsePatternMatchingAsync( case IsKindExpressionStyle.IsKindConditional: case IsKindExpressionStyle.Kind: case IsKindExpressionStyle.KindConditional: - { - var block = (BlockSyntax)ifStatement.Statement; + { + var block = (BlockSyntax)ifStatement.Statement; - IsPatternExpressionSyntax isPatternExpression = CreateIsPatternExpression(block.Statements[0]); + IsPatternExpressionSyntax isPatternExpression = CreateIsPatternExpression(block.Statements[0]); - BlockSyntax newBlock = block.WithStatements(block.Statements.RemoveAt(0)); + BlockSyntax newBlock = block.WithStatements(block.Statements.RemoveAt(0)); - IfStatementSyntax newIfStatement = ifStatement.Update( - ifStatement.IfKeyword, - ifStatement.OpenParenToken, - isPatternExpression, - ifStatement.CloseParenToken, - newBlock, - ifStatement.Else); + IfStatementSyntax newIfStatement = ifStatement.Update( + ifStatement.IfKeyword, + ifStatement.OpenParenToken, + isPatternExpression, + ifStatement.CloseParenToken, + newBlock, + ifStatement.Else); - newIfStatement = newIfStatement.WithFormatterAnnotation(); + newIfStatement = newIfStatement.WithFormatterAnnotation(); - return await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false); + } case IsKindExpressionStyle.NotIsKind: case IsKindExpressionStyle.NotIsKindConditional: case IsKindExpressionStyle.NotKind: case IsKindExpressionStyle.NotKindConditional: - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); + { + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(ifStatement); - SyntaxList statements = statementsInfo.Statements; + SyntaxList statements = statementsInfo.Statements; - int index = statements.IndexOf(ifStatement); + int index = statements.IndexOf(ifStatement); - IsPatternExpressionSyntax isPatternExpression = CreateIsPatternExpression(statements[index + 1]); + IsPatternExpressionSyntax isPatternExpression = CreateIsPatternExpression(statements[index + 1]); - IfStatementSyntax newIfStatement = ifStatement.WithCondition(LogicalNotExpression(isPatternExpression.Parenthesize()).WithTriviaFrom(ifStatement.Condition)); + IfStatementSyntax newIfStatement = ifStatement.WithCondition(LogicalNotExpression(isPatternExpression.Parenthesize()).WithTriviaFrom(ifStatement.Condition)); - SyntaxList newStatements = statements - .ReplaceAt(index, newIfStatement) - .RemoveAt(index + 1); + SyntaxList newStatements = statements + .ReplaceAt(index, newIfStatement) + .RemoveAt(index + 1); - return await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false); - } + return await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } IsPatternExpressionSyntax CreateIsPatternExpression(StatementSyntax statement) diff --git a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs index 75d8f9c9b9..25ef0bf2e8 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/InvocationExpressionAnalyzer.cs @@ -59,42 +59,42 @@ private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext contex switch (invocationInfo.Arguments.Count) { case 0: + { + switch (methodName) { - switch (methodName) + case "First": { - case "First": - { - if (DiagnosticRules.UseElementAccess.IsEffective(context)) - UseElementAccessInsteadOfCallingFirst(); + if (DiagnosticRules.UseElementAccess.IsEffective(context)) + UseElementAccessInsteadOfCallingFirst(); - break; - } + break; } - - break; } + + break; + } case 1: + { + switch (methodName) { - switch (methodName) + case "ElementAt": { - case "ElementAt": - { - if (DiagnosticRules.UseElementAccess.IsEffective(context)) - UseElementAccessInsteadOfCallingElementAt(); - - break; - } - case "IsKind": - { - if (DiagnosticRules.UnnecessaryNullCheck.IsEffective(context)) - AnalyzeUnnecessaryNullCheck(); - - break; - } + if (DiagnosticRules.UseElementAccess.IsEffective(context)) + UseElementAccessInsteadOfCallingElementAt(); + + break; } + case "IsKind": + { + if (DiagnosticRules.UnnecessaryNullCheck.IsEffective(context)) + AnalyzeUnnecessaryNullCheck(); - break; + break; + } } + + break; + } } if (DiagnosticRules.UseReturnValue.IsEffective(context) diff --git a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs index 15a8f8387a..500d6a3603 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/NamedTypeSymbolAnalyzer.cs @@ -52,35 +52,35 @@ private static void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context) switch (baseType.Name) { case "DiagnosticAnalyzer": + { + if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_Diagnostics)) { - if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_Diagnostics)) - { - AnalyzeDiagnosticAnalyzer(context, symbol); - return; - } - - break; + AnalyzeDiagnosticAnalyzer(context, symbol); + return; } + + break; + } case "CodeFixProvider": + { + if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeFixes)) { - if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeFixes)) - { - AnalyzeCodeFixProvider(context, symbol); - return; - } - - break; + AnalyzeCodeFixProvider(context, symbol); + return; } + + break; + } case "CodeRefactoringProvider": + { + if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeRefactorings)) { - if (baseType.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_CodeRefactorings)) - { - AnalyzeCodeRefactoringProvider(context, symbol); - return; - } - - break; + AnalyzeCodeRefactoringProvider(context, symbol); + return; } + + break; + } } baseType = baseType.BaseType; @@ -141,36 +141,36 @@ private static void AnalyzeLanguageName(SymbolAnalysisContext context, Attribute switch (constructorArgument.Kind) { case TypedConstantKind.Primitive: + { + if (constructorArgument.Type.SpecialType == SpecialType.System_String + && !RoslynUtility.WellKnownLanguageNames.Contains((string)constructorArgument.Value)) { - if (constructorArgument.Type.SpecialType == SpecialType.System_String - && !RoslynUtility.WellKnownLanguageNames.Contains((string)constructorArgument.Value)) - { - ReportUnknownLanguageName(context, attribute, argumentIndex); - } - - argumentIndex++; - break; + ReportUnknownLanguageName(context, attribute, argumentIndex); } + + argumentIndex++; + break; + } case TypedConstantKind.Array: + { + foreach (TypedConstant typedConstant in constructorArgument.Values) { - foreach (TypedConstant typedConstant in constructorArgument.Values) + if (typedConstant.Kind == TypedConstantKind.Primitive + && typedConstant.Type.SpecialType == SpecialType.System_String + && !RoslynUtility.WellKnownLanguageNames.Contains((string)typedConstant.Value)) { - if (typedConstant.Kind == TypedConstantKind.Primitive - && typedConstant.Type.SpecialType == SpecialType.System_String - && !RoslynUtility.WellKnownLanguageNames.Contains((string)typedConstant.Value)) - { - ReportUnknownLanguageName(context, attribute, argumentIndex); - } - - argumentIndex++; + ReportUnknownLanguageName(context, attribute, argumentIndex); } - break; + argumentIndex++; } + + break; + } default: - { - return; - } + { + return; + } } } } diff --git a/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs index 7851016c70..0324c9fc18 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/SimpleMemberAccessExpressionAnalyzer.cs @@ -49,54 +49,54 @@ private static void AnalyzeSimpleMemberAccessExpression(SyntaxNodeAnalysisContex switch (name) { case IdentifierNameSyntax identifierName: + { + switch (identifierName.Identifier.ValueText) { - switch (identifierName.Identifier.ValueText) + case "Start": { - case "Start": - { - ExpressionSyntax expression = memberAccessExpression.Expression; + ExpressionSyntax expression = memberAccessExpression.Expression; - if (!expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) - break; + if (!expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) + break; - ISymbol symbol = context.SemanticModel.GetSymbol(memberAccessExpression, context.CancellationToken); + ISymbol symbol = context.SemanticModel.GetSymbol(memberAccessExpression, context.CancellationToken); - if (symbol is null) - break; + if (symbol is null) + break; - if (!symbol.ContainingType.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_Text_TextSpan)) - break; + if (!symbol.ContainingType.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis_Text_TextSpan)) + break; - var memberAccess2 = (MemberAccessExpressionSyntax)expression; + var memberAccess2 = (MemberAccessExpressionSyntax)expression; - SimpleNameSyntax name2 = memberAccess2.Name; + SimpleNameSyntax name2 = memberAccess2.Name; - if (name2 is not IdentifierNameSyntax identifierName2) - break; + if (name2 is not IdentifierNameSyntax identifierName2) + break; - if (!string.Equals(identifierName2.Identifier.ValueText, "Span", StringComparison.Ordinal)) - break; + if (!string.Equals(identifierName2.Identifier.ValueText, "Span", StringComparison.Ordinal)) + break; - ISymbol symbol2 = context.SemanticModel.GetSymbol(expression, context.CancellationToken); + ISymbol symbol2 = context.SemanticModel.GetSymbol(expression, context.CancellationToken); - if (symbol2 is null) - break; + if (symbol2 is null) + break; - if (!symbol2.ContainingType.HasMetadataName(MetadataNames.Microsoft_CodeAnalysis_SyntaxNode)) - break; + if (!symbol2.ContainingType.HasMetadataName(MetadataNames.Microsoft_CodeAnalysis_SyntaxNode)) + break; - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePropertySyntaxNodeSpanStart, memberAccessExpression); - break; - } - case "Count": - { - CallAnyInsteadOfUsingCount(); - break; - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UsePropertySyntaxNodeSpanStart, memberAccessExpression); + break; + } + case "Count": + { + CallAnyInsteadOfUsingCount(); + break; } - - break; } + + break; + } } void CallAnyInsteadOfUsingCount() diff --git a/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs b/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs index 6dac75dbc3..5a329f21fa 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/Syntax/IsKindExpressionInfo.cs @@ -64,42 +64,42 @@ internal static IsKindExpressionInfo Create( { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - var binaryExpression = (BinaryExpressionSyntax)expression; + { + var binaryExpression = (BinaryExpressionSyntax)expression; - ExpressionSyntax left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); + ExpressionSyntax left = WalkAndCheck(binaryExpression.Left, walkDownParentheses, allowMissing); - if (left is null) - break; + if (left is null) + break; - ExpressionSyntax right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); + ExpressionSyntax right = WalkAndCheck(binaryExpression.Right, walkDownParentheses, allowMissing); - if (right is null) - break; + if (right is null) + break; - IsKindExpressionInfo info = Create(binaryExpression, kind, left, right, semanticModel, cancellationToken); + IsKindExpressionInfo info = Create(binaryExpression, kind, left, right, semanticModel, cancellationToken); - if (info.Success) - { - return info; - } - else - { - return Create(binaryExpression, kind, right, left, semanticModel, cancellationToken); - } + if (info.Success) + { + return info; } - case SyntaxKind.InvocationExpression: + else { - return Create((InvocationExpressionSyntax)expression, semanticModel, IsKindExpressionStyle.IsKind, cancellationToken); + return Create(binaryExpression, kind, right, left, semanticModel, cancellationToken); } + } + case SyntaxKind.InvocationExpression: + { + return Create((InvocationExpressionSyntax)expression, semanticModel, IsKindExpressionStyle.IsKind, cancellationToken); + } case SyntaxKind.LogicalNotExpression: - { - var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression; + { + var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression; - ExpressionSyntax operand = WalkAndCheck(logicalNotExpression.Operand, walkDownParentheses, allowMissing); + ExpressionSyntax operand = WalkAndCheck(logicalNotExpression.Operand, walkDownParentheses, allowMissing); - return Create(operand as InvocationExpressionSyntax, semanticModel, IsKindExpressionStyle.NotIsKind, cancellationToken); - } + return Create(operand as InvocationExpressionSyntax, semanticModel, IsKindExpressionStyle.NotIsKind, cancellationToken); + } } return default; @@ -133,44 +133,44 @@ private static IsKindExpressionInfo Create( switch (expression1) { case InvocationExpressionSyntax invocationExpression: - { - SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); + { + SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression); - if (!invocationInfo.Success) - break; + if (!invocationInfo.Success) + break; - if (!IsKindMethod(invocationInfo.Name, semanticModel, cancellationToken)) - break; + if (!IsKindMethod(invocationInfo.Name, semanticModel, cancellationToken)) + break; - return new IsKindExpressionInfo(binaryExpression, invocationInfo.Expression, expression2, (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.Kind : IsKindExpressionStyle.NotKind); - } + return new IsKindExpressionInfo(binaryExpression, invocationInfo.Expression, expression2, (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.Kind : IsKindExpressionStyle.NotKind); + } case ConditionalAccessExpressionSyntax conditionalAccess: - { - if (conditionalAccess.WhenNotNull is not InvocationExpressionSyntax invocationExpression) - break; + { + if (conditionalAccess.WhenNotNull is not InvocationExpressionSyntax invocationExpression) + break; - if (invocationExpression.Expression is not MemberBindingExpressionSyntax memberBindingExpression) - break; + if (invocationExpression.Expression is not MemberBindingExpressionSyntax memberBindingExpression) + break; - if (expression2.IsKind(SyntaxKind.TrueLiteralExpression)) - { - if (!IsIsKindMethod(memberBindingExpression.Name, semanticModel, cancellationToken)) - break; + if (expression2.IsKind(SyntaxKind.TrueLiteralExpression)) + { + if (!IsIsKindMethod(memberBindingExpression.Name, semanticModel, cancellationToken)) + break; - IsKindExpressionStyle style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.IsKindConditional : IsKindExpressionStyle.NotIsKindConditional; + IsKindExpressionStyle style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.IsKindConditional : IsKindExpressionStyle.NotIsKindConditional; - return new IsKindExpressionInfo(binaryExpression, conditionalAccess.Expression, invocationExpression.ArgumentList.Arguments[0].Expression, style); - } - else - { - if (!IsKindMethod(memberBindingExpression.Name, semanticModel, cancellationToken)) - break; + return new IsKindExpressionInfo(binaryExpression, conditionalAccess.Expression, invocationExpression.ArgumentList.Arguments[0].Expression, style); + } + else + { + if (!IsKindMethod(memberBindingExpression.Name, semanticModel, cancellationToken)) + break; - IsKindExpressionStyle style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.KindConditional : IsKindExpressionStyle.NotKindConditional; + IsKindExpressionStyle style = (binaryExpressionKind == SyntaxKind.EqualsExpression) ? IsKindExpressionStyle.KindConditional : IsKindExpressionStyle.NotKindConditional; - return new IsKindExpressionInfo(binaryExpression, conditionalAccess.Expression, expression2, style); - } + return new IsKindExpressionInfo(binaryExpression, conditionalAccess.Expression, expression2, style); } + } } return default; diff --git a/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs b/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs index 87a037869b..52fc97520e 100644 --- a/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs +++ b/src/CodeAnalysis.Analyzers/CSharp/UsePatternMatchingAnalyzer.cs @@ -194,33 +194,33 @@ string GetName() switch (switchExpression.Kind()) { case SyntaxKind.IdentifierName: - { - StatementSyntax previousStatement = switchStatement.PreviousStatement(); + { + StatementSyntax previousStatement = switchStatement.PreviousStatement(); - if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement)) - return null; + if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement)) + return null; - localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)previousStatement); + localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)previousStatement); - if (!localInfo.Success) - return null; + if (!localInfo.Success) + return null; - if (localInfo.IdentifierText != ((IdentifierNameSyntax)switchExpression).Identifier.ValueText) - return null; + if (localInfo.IdentifierText != ((IdentifierNameSyntax)switchExpression).Identifier.ValueText) + return null; - if (!localInfo.Value.IsKind(SyntaxKind.InvocationExpression)) - return null; + if (!localInfo.Value.IsKind(SyntaxKind.InvocationExpression)) + return null; - return GetName2((InvocationExpressionSyntax)localInfo.Value); - } + return GetName2((InvocationExpressionSyntax)localInfo.Value); + } case SyntaxKind.InvocationExpression: - { - return GetName2((InvocationExpressionSyntax)switchExpression); - } + { + return GetName2((InvocationExpressionSyntax)switchExpression); + } default: - { - return null; - } + { + return null; + } } } @@ -276,32 +276,32 @@ private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) case IsKindExpressionStyle.IsKindConditional: case IsKindExpressionStyle.Kind: case IsKindExpressionStyle.KindConditional: - { - if (ifStatement.Statement is not BlockSyntax block) - return; + { + if (ifStatement.Statement is not BlockSyntax block) + return; - Analyze(block.Statements.FirstOrDefault()); - break; - } + Analyze(block.Statements.FirstOrDefault()); + break; + } case IsKindExpressionStyle.NotIsKind: case IsKindExpressionStyle.NotIsKindConditional: case IsKindExpressionStyle.NotKind: case IsKindExpressionStyle.NotKindConditional: - { - if (ifStatement.Else is not null) - return; + { + if (ifStatement.Else is not null) + return; - StatementSyntax statement = ifStatement.Statement.SingleNonBlockStatementOrDefault(); + StatementSyntax statement = ifStatement.Statement.SingleNonBlockStatementOrDefault(); - if (statement is null) - return; + if (statement is null) + return; - if (!CSharpFacts.IsJumpStatement(statement.Kind())) - return; + if (!CSharpFacts.IsJumpStatement(statement.Kind())) + return; - Analyze(ifStatement.NextStatement()); - break; - } + Analyze(ifStatement.NextStatement()); + break; + } } void Analyze(StatementSyntax statement) diff --git a/src/CodeAnalysis.Analyzers/RoslynSymbolUtility.cs b/src/CodeAnalysis.Analyzers/RoslynSymbolUtility.cs index d30165618a..2a042fefec 100644 --- a/src/CodeAnalysis.Analyzers/RoslynSymbolUtility.cs +++ b/src/CodeAnalysis.Analyzers/RoslynSymbolUtility.cs @@ -16,9 +16,9 @@ public static bool IsList(INamedTypeSymbol typeSymbol) case "SyntaxNodeOrTokenList": case "SyntaxTokenList": case "SyntaxTriviaList": - { - return typeSymbol.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis); - } + { + return typeSymbol.ContainingNamespace.HasMetadataName(RoslynMetadataNames.Microsoft_CodeAnalysis); + } } return false; diff --git a/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs index 70f51d9d6c..94b21dc8e9 100644 --- a/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/AddBodyCodeFixProvider.cs @@ -66,182 +66,182 @@ private static Func> GetCreateChangedDocument( switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; - - SyntaxToken semicolonToken = methodDeclaration.SemicolonToken; + { + var methodDeclaration = (MethodDeclarationSyntax)node; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + SyntaxToken semicolonToken = methodDeclaration.SemicolonToken; - ParameterListSyntax parameterList = methodDeclaration.ParameterList; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - if (parameterList is null) - break; + ParameterListSyntax parameterList = methodDeclaration.ParameterList; - return ct => - { - MethodDeclarationSyntax newNode = methodDeclaration - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); + if (parameterList is null) + break; - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } - case SyntaxKind.ConstructorDeclaration: + return ct => { - var constructorDeclaration = (ConstructorDeclarationSyntax)node; - - SyntaxToken semicolonToken = constructorDeclaration.SemicolonToken; + MethodDeclarationSyntax newNode = methodDeclaration + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } + case SyntaxKind.ConstructorDeclaration: + { + var constructorDeclaration = (ConstructorDeclarationSyntax)node; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + SyntaxToken semicolonToken = constructorDeclaration.SemicolonToken; - ParameterListSyntax parameterList = constructorDeclaration.ParameterList; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - if (parameterList is null) - break; + ParameterListSyntax parameterList = constructorDeclaration.ParameterList; - return ct => - { - ConstructorDeclarationSyntax newNode = constructorDeclaration - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); + if (parameterList is null) + break; - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } - case SyntaxKind.DestructorDeclaration: + return ct => { - var destructorDeclaration = (DestructorDeclarationSyntax)node; - - SyntaxToken semicolonToken = destructorDeclaration.SemicolonToken; + ConstructorDeclarationSyntax newNode = constructorDeclaration + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } + case SyntaxKind.DestructorDeclaration: + { + var destructorDeclaration = (DestructorDeclarationSyntax)node; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + SyntaxToken semicolonToken = destructorDeclaration.SemicolonToken; - ParameterListSyntax parameterList = destructorDeclaration.ParameterList; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - if (parameterList is null) - break; + ParameterListSyntax parameterList = destructorDeclaration.ParameterList; - return ct => - { - DestructorDeclarationSyntax newNode = destructorDeclaration - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); + if (parameterList is null) + break; - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } - case SyntaxKind.OperatorDeclaration: + return ct => { - var operatorDeclaration = (OperatorDeclarationSyntax)node; - - SyntaxToken semicolonToken = operatorDeclaration.SemicolonToken; + DestructorDeclarationSyntax newNode = destructorDeclaration + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } + case SyntaxKind.OperatorDeclaration: + { + var operatorDeclaration = (OperatorDeclarationSyntax)node; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + SyntaxToken semicolonToken = operatorDeclaration.SemicolonToken; - ParameterListSyntax parameterList = operatorDeclaration.ParameterList; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - if (parameterList is null) - break; + ParameterListSyntax parameterList = operatorDeclaration.ParameterList; - return ct => - { - OperatorDeclarationSyntax newNode = operatorDeclaration - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); + if (parameterList is null) + break; - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } - case SyntaxKind.ConversionOperatorDeclaration: + return ct => { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; - - SyntaxToken semicolonToken = conversionOperatorDeclaration.SemicolonToken; + OperatorDeclarationSyntax newNode = operatorDeclaration + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } + case SyntaxKind.ConversionOperatorDeclaration: + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + SyntaxToken semicolonToken = conversionOperatorDeclaration.SemicolonToken; - ParameterListSyntax parameterList = conversionOperatorDeclaration.ParameterList; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - if (parameterList is null) - break; + ParameterListSyntax parameterList = conversionOperatorDeclaration.ParameterList; - return ct => - { - ConversionOperatorDeclarationSyntax newNode = conversionOperatorDeclaration - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); + if (parameterList is null) + break; - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } + return ct => + { + ConversionOperatorDeclarationSyntax newNode = conversionOperatorDeclaration + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: - { - var accessorDeclaration = (AccessorDeclarationSyntax)node; + { + var accessorDeclaration = (AccessorDeclarationSyntax)node; - SyntaxToken semicolonToken = accessorDeclaration.SemicolonToken; + SyntaxToken semicolonToken = accessorDeclaration.SemicolonToken; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - return ct => - { - AccessorDeclarationSyntax newNode = accessorDeclaration - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block( - Token(default(SyntaxTriviaList), SyntaxKind.OpenBraceToken, TriviaList(ElasticSpace)), - default(SyntaxList), - Token(default(SyntaxTriviaList), SyntaxKind.CloseBraceToken, semicolonToken.LeadingAndTrailingTrivia()))); + return ct => + { + AccessorDeclarationSyntax newNode = accessorDeclaration + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block( + Token(default(SyntaxTriviaList), SyntaxKind.OpenBraceToken, TriviaList(ElasticSpace)), + default(SyntaxList), + Token(default(SyntaxTriviaList), SyntaxKind.CloseBraceToken, semicolonToken.LeadingAndTrailingTrivia()))); - SyntaxToken keyword = newNode.Keyword; + SyntaxToken keyword = newNode.Keyword; - if (!keyword.HasTrailingTrivia) - newNode = newNode.WithKeyword(keyword.WithTrailingTrivia(ElasticSpace)); + if (!keyword.HasTrailingTrivia) + newNode = newNode.WithKeyword(keyword.WithTrailingTrivia(ElasticSpace)); - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)node; + { + var localFunction = (LocalFunctionStatementSyntax)node; - SyntaxToken semicolonToken = localFunction.SemicolonToken; + SyntaxToken semicolonToken = localFunction.SemicolonToken; - if (semicolonToken.IsKind(SyntaxKind.None)) - break; + if (semicolonToken.IsKind(SyntaxKind.None)) + break; - ParameterListSyntax parameterList = localFunction.ParameterList; + ParameterListSyntax parameterList = localFunction.ParameterList; - if (parameterList is null) - break; + if (parameterList is null) + break; - return ct => - { - LocalFunctionStatementSyntax newNode = localFunction - .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) - .WithSemicolonToken(default(SyntaxToken)) - .WithBody(Block()) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(node, newNode, ct); - }; - } + return ct => + { + LocalFunctionStatementSyntax newNode = localFunction + .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) + .WithSemicolonToken(default(SyntaxToken)) + .WithBody(Block()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(node, newNode, ct); + }; + } } SyntaxDebug.Fail(node); diff --git a/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs index fdb5caddbb..5b3f296c71 100644 --- a/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/AddReturnStatementCodeFixProvider.cs @@ -45,77 +45,77 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (ancestor.Kind()) { case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)ancestor; + { + var methodDeclaration = (MethodDeclarationSyntax)ancestor; - if (!methodDeclaration.Modifiers.Contains(SyntaxKind.PartialKeyword)) - ComputeCodeFix(context, diagnostic, methodDeclaration.ReturnType, methodDeclaration.Body, semanticModel); + if (!methodDeclaration.Modifiers.Contains(SyntaxKind.PartialKeyword)) + ComputeCodeFix(context, diagnostic, methodDeclaration.ReturnType, methodDeclaration.Body, semanticModel); - return; - } + return; + } case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)ancestor; + { + var operatorDeclaration = (OperatorDeclarationSyntax)ancestor; - ComputeCodeFix(context, diagnostic, operatorDeclaration.ReturnType, operatorDeclaration.Body, semanticModel); - return; - } + ComputeCodeFix(context, diagnostic, operatorDeclaration.ReturnType, operatorDeclaration.Body, semanticModel); + return; + } case SyntaxKind.ConversionOperatorDeclaration: - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)ancestor; + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)ancestor; - ComputeCodeFix(context, diagnostic, conversionOperatorDeclaration.Type, conversionOperatorDeclaration.Body, semanticModel); - return; - } + ComputeCodeFix(context, diagnostic, conversionOperatorDeclaration.Type, conversionOperatorDeclaration.Body, semanticModel); + return; + } case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)ancestor; + { + var localFunction = (LocalFunctionStatementSyntax)ancestor; - ComputeCodeFix(context, diagnostic, localFunction.ReturnType, localFunction.Body, semanticModel); - return; - } + ComputeCodeFix(context, diagnostic, localFunction.ReturnType, localFunction.Body, semanticModel); + return; + } case SyntaxKind.GetAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)ancestor; + { + var accessor = (AccessorDeclarationSyntax)ancestor; - switch (accessor.Parent.Parent.Kind()) + switch (accessor.Parent.Parent.Kind()) + { + case SyntaxKind.PropertyDeclaration: { - case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)accessor.Parent.Parent; - - ComputeCodeFix(context, diagnostic, propertyDeclaration.Type, accessor.Body, semanticModel); - break; - } - case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)accessor.Parent.Parent; - - ComputeCodeFix(context, diagnostic, indexerDeclaration.Type, accessor.Body, semanticModel); - break; - } + var propertyDeclaration = (PropertyDeclarationSyntax)accessor.Parent.Parent; + + ComputeCodeFix(context, diagnostic, propertyDeclaration.Type, accessor.Body, semanticModel); + break; } + case SyntaxKind.IndexerDeclaration: + { + var indexerDeclaration = (IndexerDeclarationSyntax)accessor.Parent.Parent; - return; + ComputeCodeFix(context, diagnostic, indexerDeclaration.Type, accessor.Body, semanticModel); + break; + } } + + return; + } case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: - { - var anonymousFunction = (AnonymousFunctionExpressionSyntax)ancestor; + { + var anonymousFunction = (AnonymousFunctionExpressionSyntax)ancestor; - var body = anonymousFunction.Body as BlockSyntax; + var body = anonymousFunction.Body as BlockSyntax; - if (body?.Statements.Count > 0) - { - var methodSymbol = semanticModel.GetSymbol(anonymousFunction, context.CancellationToken) as IMethodSymbol; - - if (methodSymbol?.IsErrorType() == false) - ComputeCodeFix(context, diagnostic, methodSymbol.ReturnType, body); - } + if (body?.Statements.Count > 0) + { + var methodSymbol = semanticModel.GetSymbol(anonymousFunction, context.CancellationToken) as IMethodSymbol; - return; + if (methodSymbol?.IsErrorType() == false) + ComputeCodeFix(context, diagnostic, methodSymbol.ReturnType, body); } + + return; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs index 250cd709cb..4c4136bc04 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ArgumentCodeFixProvider.cs @@ -41,104 +41,104 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1620_ArgumentMustBePassedWithRefOrOutKeyword: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddOutModifierToArgument, context.Document, root.SyntaxTree)) - return; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddOutModifierToArgument, context.Document, root.SyntaxTree)) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - IParameterSymbol parameter = semanticModel.DetermineParameter(argument, allowCandidate: true, cancellationToken: context.CancellationToken); + IParameterSymbol parameter = semanticModel.DetermineParameter(argument, allowCandidate: true, cancellationToken: context.CancellationToken); - if (parameter is null) - return; + if (parameter is null) + return; - SyntaxToken refOrOutKeyword = default; + SyntaxToken refOrOutKeyword = default; - if (parameter.RefKind == RefKind.Out) - { - refOrOutKeyword = Token(SyntaxKind.OutKeyword); - } - else if (parameter.RefKind == RefKind.Ref) - { - refOrOutKeyword = Token(SyntaxKind.RefKeyword); - } - else - { - return; - } - - CodeAction codeAction = CodeAction.Create( - $"Add '{SyntaxFacts.GetText(refOrOutKeyword.Kind())}' modifier", - ct => - { - ArgumentSyntax newArgument = argument - .WithRefOrOutKeyword(refOrOutKeyword) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(argument, newArgument, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; + if (parameter.RefKind == RefKind.Out) + { + refOrOutKeyword = Token(SyntaxKind.OutKeyword); } - case CompilerDiagnosticIdentifiers.CS1615_ArgumentShouldNotBePassedWithRefOrOutKeyword: + else if (parameter.RefKind == RefKind.Ref) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveRefModifier, context.Document, root.SyntaxTree)) - return; - - CodeAction codeAction = CodeAction.Create( - "Remove 'ref' modifier", - ct => - { - ArgumentSyntax newArgument = argument - .WithRefOrOutKeyword(default(SyntaxToken)) - .PrependToLeadingTrivia(argument.RefOrOutKeyword.GetAllTrivia()) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(argument, newArgument, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; + refOrOutKeyword = Token(SyntaxKind.RefKeyword); } - case CompilerDiagnosticIdentifiers.CS0192_ReadOnlyFieldCannotBePassedAsRefOrOutValue: + else { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeFieldWritable, context.Document, root.SyntaxTree)) - return; + return; + } - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + CodeAction codeAction = CodeAction.Create( + $"Add '{SyntaxFacts.GetText(refOrOutKeyword.Kind())}' modifier", + ct => + { + ArgumentSyntax newArgument = argument + .WithRefOrOutKeyword(refOrOutKeyword) + .WithFormatterAnnotation(); - SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(argument.Expression, context.CancellationToken); + return context.Document.ReplaceNodeAsync(argument, newArgument, ct); + }, + GetEquivalenceKey(diagnostic)); - if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) - return; + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS1615_ArgumentShouldNotBePassedWithRefOrOutKeyword: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveRefModifier, context.Document, root.SyntaxTree)) + return; - if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not IFieldSymbol fieldSymbol) - return; + CodeAction codeAction = CodeAction.Create( + "Remove 'ref' modifier", + ct => + { + ArgumentSyntax newArgument = argument + .WithRefOrOutKeyword(default(SyntaxToken)) + .PrependToLeadingTrivia(argument.RefOrOutKeyword.GetAllTrivia()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(argument, newArgument, ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS0192_ReadOnlyFieldCannotBePassedAsRefOrOutValue: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeFieldWritable, context.Document, root.SyntaxTree)) + return; - if (fieldSymbol.DeclaredAccessibility != Accessibility.Private) - return; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (fieldSymbol.GetSyntax().Parent.Parent is not FieldDeclarationSyntax fieldDeclaration) - return; + SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(argument.Expression, context.CancellationToken); - TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor(); + if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) + return; - if (!argument.Ancestors().Any(f => f == containingTypeDeclaration)) - return; + if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not IFieldSymbol fieldSymbol) + return; - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - fieldDeclaration, - SyntaxKind.ReadOnlyKeyword, - title: $"Make '{fieldSymbol.Name}' writable", - additionalKey: CodeFixIdentifiers.MakeFieldWritable); + if (fieldSymbol.DeclaredAccessibility != Accessibility.Private) + return; - break; - } + if (fieldSymbol.GetSyntax().Parent.Parent is not FieldDeclarationSyntax fieldDeclaration) + return; + + TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor(); + + if (!argument.Ancestors().Any(f => f == containingTypeDeclaration)) + return; + + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + fieldDeclaration, + SyntaxKind.ReadOnlyKeyword, + title: $"Make '{fieldSymbol.Name}' writable", + additionalKey: CodeFixIdentifiers.MakeFieldWritable); + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/BaseListCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/BaseListCodeFixProvider.cs index 2dccc2bfc2..fb2a517ba3 100644 --- a/src/CodeFixes/CSharp/CodeFixes/BaseListCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/BaseListCodeFixProvider.cs @@ -43,79 +43,79 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1722_BaseClassMustComeBeforeAnyInterface: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface, context.Document, root.SyntaxTree)) - return; - - SeparatedSyntaxList types = baseList.Types; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveBaseClassBeforeAnyInterface, context.Document, root.SyntaxTree)) + return; - if (types.Count > 1) - { - BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span)); + SeparatedSyntaxList types = baseList.Types; - CodeAction codeAction = CodeAction.Create( - $"Move '{baseType.Type}' before any interface", - ct => - { - BaseTypeSyntax firstType = types[0]; + if (types.Count > 1) + { + BaseTypeSyntax baseType = types.First(f => context.Span.Contains(f.Span)); - SeparatedSyntaxList newTypes = types - .Replace(baseType, firstType.WithTriviaFrom(baseType)) - .ReplaceAt(0, baseType.WithTriviaFrom(firstType)); + CodeAction codeAction = CodeAction.Create( + $"Move '{baseType.Type}' before any interface", + ct => + { + BaseTypeSyntax firstType = types[0]; - BaseListSyntax newBaseList = baseList.WithTypes(newTypes); + SeparatedSyntaxList newTypes = types + .Replace(baseType, firstType.WithTriviaFrom(baseType)) + .ReplaceAt(0, baseType.WithTriviaFrom(firstType)); - return context.Document.ReplaceNodeAsync(baseList, newBaseList, ct); - }, - GetEquivalenceKey(diagnostic)); + BaseListSyntax newBaseList = baseList.WithTypes(newTypes); - context.RegisterCodeFix(codeAction, diagnostic); - } + return context.Document.ReplaceNodeAsync(baseList, newBaseList, ct); + }, + GetEquivalenceKey(diagnostic)); - break; + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } case CompilerDiagnosticIdentifiers.CS0713_StaticClassCannotDeriveFromType: case CompilerDiagnosticIdentifiers.CS0714_StaticClassCannotImplementInterfaces: + { + if (baseList.Parent is not ClassDeclarationSyntax classDeclaration) + break; + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeClassNonStatic, context.Document, root.SyntaxTree)) { - if (baseList.Parent is not ClassDeclarationSyntax classDeclaration) - break; - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeClassNonStatic, context.Document, root.SyntaxTree)) - { - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - classDeclaration, - SyntaxKind.StaticKeyword, - title: "Make class non-static", - additionalKey: CodeFixIdentifiers.MakeClassNonStatic); - } - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveBaseList, context.Document, root.SyntaxTree)) - { - CodeAction codeAction = CodeAction.Create( - "Remove base list", - ct => - { - SyntaxToken token = baseList.GetFirstToken().GetPreviousToken(); - - SyntaxTriviaList trivia = token.TrailingTrivia.EmptyIfWhitespace() - .AddRange(baseList.GetLeadingTrivia().EmptyIfWhitespace()) - .AddRange(baseList.GetTrailingTrivia()); - - ClassDeclarationSyntax newNode = classDeclaration - .ReplaceToken(token, token.WithTrailingTrivia(trivia)) - .WithBaseList(null); - - return context.Document.ReplaceNodeAsync(classDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveBaseList)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + classDeclaration, + SyntaxKind.StaticKeyword, + title: "Make class non-static", + additionalKey: CodeFixIdentifiers.MakeClassNonStatic); + } - break; + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveBaseList, context.Document, root.SyntaxTree)) + { + CodeAction codeAction = CodeAction.Create( + "Remove base list", + ct => + { + SyntaxToken token = baseList.GetFirstToken().GetPreviousToken(); + + SyntaxTriviaList trivia = token.TrailingTrivia.EmptyIfWhitespace() + .AddRange(baseList.GetLeadingTrivia().EmptyIfWhitespace()) + .AddRange(baseList.GetTrailingTrivia()); + + ClassDeclarationSyntax newNode = classDeclaration + .ReplaceToken(token, token.WithTrailingTrivia(trivia)) + .WithBaseList(null); + + return context.Document.ReplaceNodeAsync(classDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveBaseList)); + + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs index 721d1f9332..9bfa8711dd 100644 --- a/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/CannotConvertArgumentTypeCodeFixProvider.cs @@ -44,93 +44,93 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1503_CannotConvertArgumentType: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, document, root.SyntaxTree) + && expression.Kind() == SyntaxKind.NullLiteralExpression + && argument.Parent is ArgumentListSyntax argumentList) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, document, root.SyntaxTree) - && expression.Kind() == SyntaxKind.NullLiteralExpression - && argument.Parent is ArgumentListSyntax argumentList) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ImmutableArray parameterSymbols = FindParameters(argumentList, semanticModel, context.CancellationToken); + ImmutableArray parameterSymbols = FindParameters(argumentList, semanticModel, context.CancellationToken); - if (!parameterSymbols.IsDefault) - { - int index = argumentList.Arguments.IndexOf(argument); + if (!parameterSymbols.IsDefault) + { + int index = argumentList.Arguments.IndexOf(argument); - IParameterSymbol parameterSymbol = parameterSymbols[index]; + IParameterSymbol parameterSymbol = parameterSymbols[index]; - ITypeSymbol typeSymbol = parameterSymbol.Type; + ITypeSymbol typeSymbol = parameterSymbol.Type; - if (typeSymbol.IsValueType) - { - CodeFixRegistrator.ReplaceNullWithDefaultValue( - context, - diagnostic, - expression, - typeSymbol, - CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue); - } + if (typeSymbol.IsValueType) + { + CodeFixRegistrator.ReplaceNullWithDefaultValue( + context, + diagnostic, + expression, + typeSymbol, + CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue); } } + } + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, document, root.SyntaxTree) + && expression.IsKind( + SyntaxKind.IdentifierName, + SyntaxKind.GenericName, + SyntaxKind.SimpleMemberAccessExpression)) + { + InvocationExpressionSyntax invocationExpression = InvocationExpression( + expression.WithoutTrailingTrivia(), + ArgumentList().WithTrailingTrivia(expression.GetTrailingTrivia())); + + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, document, root.SyntaxTree) - && expression.IsKind( - SyntaxKind.IdentifierName, - SyntaxKind.GenericName, - SyntaxKind.SimpleMemberAccessExpression)) + if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) { - InvocationExpressionSyntax invocationExpression = InvocationExpression( - expression.WithoutTrailingTrivia(), - ArgumentList().WithTrailingTrivia(expression.GetTrailingTrivia())); + CodeAction codeAction = CodeAction.Create( + "Add argument list", + ct => + { + ArgumentSyntax newNode = argument.WithExpression(invocationExpression); - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + return document.ReplaceNodeAsync(argument, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.AddArgumentList)); - if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) - { - CodeAction codeAction = CodeAction.Create( - "Add argument list", - ct => - { - ArgumentSyntax newNode = argument.WithExpression(invocationExpression); - - return document.ReplaceNodeAsync(argument, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.AddArgumentList)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; } + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.CreateSingletonArray, document, root.SyntaxTree) - && expression?.IsMissing == false) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.CreateSingletonArray, document, root.SyntaxTree) + && expression?.IsMissing == false) + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression); - if (typeSymbol?.IsErrorType() == false) + if (typeSymbol?.IsErrorType() == false) + { + foreach (ITypeSymbol typeSymbol2 in DetermineParameterTypeHelper.DetermineParameterTypes(argument, semanticModel, context.CancellationToken)) { - foreach (ITypeSymbol typeSymbol2 in DetermineParameterTypeHelper.DetermineParameterTypes(argument, semanticModel, context.CancellationToken)) + if (!SymbolEqualityComparer.Default.Equals(typeSymbol, typeSymbol2) + && typeSymbol2 is IArrayTypeSymbol arrayType + && semanticModel.IsImplicitConversion(expression, arrayType.ElementType)) { - if (!SymbolEqualityComparer.Default.Equals(typeSymbol, typeSymbol2) - && typeSymbol2 is IArrayTypeSymbol arrayType - && semanticModel.IsImplicitConversion(expression, arrayType.ElementType)) - { - CodeAction codeAction = CodeAction.Create( - "Create singleton array", - ct => CreateSingletonArrayRefactoring.RefactorAsync(document, expression, arrayType.ElementType, semanticModel, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.CreateSingletonArray)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + CodeAction codeAction = CodeAction.Create( + "Create singleton array", + ct => CreateSingletonArrayRefactoring.RefactorAsync(document, expression, arrayType.ElementType, semanticModel, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.CreateSingletonArray)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; } } } - - break; } + + break; + } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/CannotImplicitlyConvertTypeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/CannotImplicitlyConvertTypeCodeFixProvider.cs index fc6e92164c..c4e5e3f620 100644 --- a/src/CodeFixes/CSharp/CodeFixes/CannotImplicitlyConvertTypeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/CannotImplicitlyConvertTypeCodeFixProvider.cs @@ -33,51 +33,51 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0029_CannotImplicitlyConvertType: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral, context.Document, root.SyntaxTree) + && node.IsKind(SyntaxKind.StringLiteralExpression)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral, context.Document, root.SyntaxTree) - && node.IsKind(SyntaxKind.StringLiteralExpression)) - { - var literalExpression = (LiteralExpressionSyntax)node; - - if (literalExpression.Token.ValueText.Length == 1) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + var literalExpression = (LiteralExpressionSyntax)node; - if (semanticModel.GetTypeInfo(node, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Char) - { - CodeAction codeAction = CodeAction.Create( - "Replace string literal with character literal", - ct => ReplaceStringLiteralWithCharacterLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - } - } - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree) - && node.IsParentKind(SyntaxKind.ReturnStatement)) + if (literalExpression.Token.ValueText.Length == 1) { - var returnStatement = (ReturnStatementSyntax)node.Parent; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); - - if (containingSymbol?.Kind == SymbolKind.Method - && ((IMethodSymbol)containingSymbol).ReturnType.OriginalDefinition.IsIEnumerableOrIEnumerableOfT()) + if (semanticModel.GetTypeInfo(node, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Char) { CodeAction codeAction = CodeAction.Create( - "Use yield return instead of return", - ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, SyntaxKind.YieldReturnStatement, semanticModel, ct), + "Replace string literal with character literal", + ct => ReplaceStringLiteralWithCharacterLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } } + } + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree) + && node.IsParentKind(SyntaxKind.ReturnStatement)) + { + var returnStatement = (ReturnStatementSyntax)node.Parent; + + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + + ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); - break; + if (containingSymbol?.Kind == SymbolKind.Method + && ((IMethodSymbol)containingSymbol).ReturnType.OriginalDefinition.IsIEnumerableOrIEnumerableOfT()) + { + CodeAction codeAction = CodeAction.Create( + "Use yield return instead of return", + ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, SyntaxKind.YieldReturnStatement, semanticModel, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + } } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs index f14a37d920..0cb83ef030 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ExpressionCodeFixProvider.cs @@ -51,502 +51,502 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0266_CannotImplicitlyConvertTypeExplicitConversionExists: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, context.CancellationToken); + TypeInfo typeInfo = semanticModel.GetTypeInfo(expression, context.CancellationToken); - ITypeSymbol type = typeInfo.Type; - ITypeSymbol convertedType = typeInfo.ConvertedType; + ITypeSymbol type = typeInfo.Type; + ITypeSymbol convertedType = typeInfo.ConvertedType; - if ((type is INamedTypeSymbol namedType) - && namedType.IsNullableType()) + if ((type is INamedTypeSymbol namedType) + && namedType.IsNullableType()) + { + if (convertedType?.SpecialType == SpecialType.System_Boolean + || AddComparisonWithBooleanLiteralRefactoring.IsCondition(expression)) { - if (convertedType?.SpecialType == SpecialType.System_Boolean - || AddComparisonWithBooleanLiteralRefactoring.IsCondition(expression)) + if (!IsRightExpressionOfAssignment(expression) + && IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddComparisonWithBooleanLiteral, context.Document, root.SyntaxTree)) { - if (!IsRightExpressionOfAssignment(expression) - && IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddComparisonWithBooleanLiteral, context.Document, root.SyntaxTree)) - { - CodeAction codeAction = CodeAction.Create( - AddComparisonWithBooleanLiteralRefactoring.GetTitle(expression), - ct => AddComparisonWithBooleanLiteralRefactoring.RefactorAsync(context.Document, expression, ct), - GetEquivalenceKey( - diagnostic, - CodeFixIdentifiers.AddComparisonWithBooleanLiteral)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + CodeAction codeAction = CodeAction.Create( + AddComparisonWithBooleanLiteralRefactoring.GetTitle(expression), + ct => AddComparisonWithBooleanLiteralRefactoring.RefactorAsync(context.Document, expression, ct), + GetEquivalenceKey( + diagnostic, + CodeFixIdentifiers.AddComparisonWithBooleanLiteral)); - static bool IsRightExpressionOfAssignment(ExpressionSyntax expression) - { - return expression.IsParentKind(SyntaxKind.SimpleAssignmentExpression) - && ((AssignmentExpressionSyntax)expression.Parent).Right == expression; - } + context.RegisterCodeFix(codeAction, diagnostic); } - else if (SymbolEqualityComparer.Default.Equals(namedType.TypeArguments[0], convertedType)) + + static bool IsRightExpressionOfAssignment(ExpressionSyntax expression) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseCoalesceExpression, context.Document, root.SyntaxTree)) - { - CodeAction codeAction = CodeAction.Create( - "Use coalesce expression", - ct => - { - ExpressionSyntax defaultValue = convertedType.GetDefaultValueSyntax(context.Document.GetDefaultSyntaxOptions()); - - ExpressionSyntax newNode = CoalesceExpression(expression.WithoutTrivia(), defaultValue) - .WithTriviaFrom(expression) - .Parenthesize() - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(expression, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseCoalesceExpression)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + return expression.IsParentKind(SyntaxKind.SimpleAssignmentExpression) + && ((AssignmentExpressionSyntax)expression.Parent).Right == expression; } } - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree) - && expression.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement)) + else if (SymbolEqualityComparer.Default.Equals(namedType.TypeArguments[0], convertedType)) { - ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); - } - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddExplicitCast, context.Document, root.SyntaxTree)) - CodeFixRegistrator.AddExplicitCast(context, diagnostic, expression, convertedType, semanticModel); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseCoalesceExpression, context.Document, root.SyntaxTree)) + { + CodeAction codeAction = CodeAction.Create( + "Use coalesce expression", + ct => + { + ExpressionSyntax defaultValue = convertedType.GetDefaultValueSyntax(context.Document.GetDefaultSyntaxOptions()); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeAccordingToInitializer, context.Document, root.SyntaxTree)) - ChangeTypeAccordingToInitializerRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + ExpressionSyntax newNode = CoalesceExpression(expression.WithoutTrivia(), defaultValue) + .WithTriviaFrom(expression) + .Parenthesize() + .WithFormatterAnnotation(); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.CreateSingletonArray, context.Document, root.SyntaxTree) - && type?.IsErrorType() == false - && !SymbolEqualityComparer.Default.Equals(type, convertedType) - && (convertedType is IArrayTypeSymbol arrayType) - && semanticModel.IsImplicitConversion(expression, arrayType.ElementType)) - { - CodeAction codeAction = CodeAction.Create( - "Create singleton array", - ct => CreateSingletonArrayRefactoring.RefactorAsync(context.Document, expression, arrayType.ElementType, semanticModel, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.CreateSingletonArray)); + return context.Document.ReplaceNodeAsync(expression, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseCoalesceExpression)); - context.RegisterCodeFix(codeAction, diagnostic); + context.RegisterCodeFix(codeAction, diagnostic); + } } - - break; } - case CompilerDiagnosticIdentifiers.CS0221_ConstantValueCannotBeConverted: + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree) + && expression.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement)) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseUncheckedExpression, context.Document, root.SyntaxTree)) - break; + ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + } - CodeAction codeAction = CodeAction.Create( - "Use 'unchecked'", - ct => - { - CheckedExpressionSyntax newNode = CSharpFactory.UncheckedExpression(expression.WithoutTrivia()); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddExplicitCast, context.Document, root.SyntaxTree)) + CodeFixRegistrator.AddExplicitCast(context, diagnostic, expression, convertedType, semanticModel); - newNode = newNode.WithTriviaFrom(expression); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeAccordingToInitializer, context.Document, root.SyntaxTree)) + ChangeTypeAccordingToInitializerRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); - return context.Document.ReplaceNodeAsync(expression, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.CreateSingletonArray, context.Document, root.SyntaxTree) + && type?.IsErrorType() == false + && !SymbolEqualityComparer.Default.Equals(type, convertedType) + && (convertedType is IArrayTypeSymbol arrayType) + && semanticModel.IsImplicitConversion(expression, arrayType.ElementType)) + { + CodeAction codeAction = CodeAction.Create( + "Create singleton array", + ct => CreateSingletonArrayRefactoring.RefactorAsync(context.Document, expression, arrayType.ElementType, semanticModel, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.CreateSingletonArray)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case CompilerDiagnosticIdentifiers.CS0133_ExpressionBeingAssignedMustBeConstant: - { - SyntaxNode parent = expression.Parent; - if (parent?.IsKind(SyntaxKind.EqualsValueClause) != true) - break; + break; + } + case CompilerDiagnosticIdentifiers.CS0221_ConstantValueCannotBeConverted: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseUncheckedExpression, context.Document, root.SyntaxTree)) + break; - parent = parent.Parent; + CodeAction codeAction = CodeAction.Create( + "Use 'unchecked'", + ct => + { + CheckedExpressionSyntax newNode = CSharpFactory.UncheckedExpression(expression.WithoutTrivia()); - if (parent?.IsKind(SyntaxKind.VariableDeclarator) != true) - break; + newNode = newNode.WithTriviaFrom(expression); - parent = parent.Parent; + return context.Document.ReplaceNodeAsync(expression, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - if (parent is not VariableDeclarationSyntax variableDeclaration) - break; + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS0133_ExpressionBeingAssignedMustBeConstant: + { + SyntaxNode parent = expression.Parent; - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstModifier, context.Document, root.SyntaxTree) - && variableDeclaration.Parent is LocalDeclarationStatementSyntax localDeclarationStatement) - { - SyntaxTokenList modifiers = localDeclarationStatement.Modifiers; + if (parent?.IsKind(SyntaxKind.EqualsValueClause) != true) + break; - if (!modifiers.Contains(SyntaxKind.ConstKeyword)) - break; + parent = parent.Parent; - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, localDeclarationStatement, SyntaxKind.ConstKeyword); - } - else if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceConstantWithField, context.Document, root.SyntaxTree) - && variableDeclaration.Variables.Count == 1 - && (variableDeclaration.Parent is FieldDeclarationSyntax fieldDeclaration) - && fieldDeclaration.Modifiers.Contains(SyntaxKind.ConstKeyword)) - { - CodeAction codeAction = CodeAction.Create( - UseReadOnlyFieldInsteadOfConstantRefactoring.Title, - ct => UseReadOnlyFieldInsteadOfConstantRefactoring.RefactorAsync(context.Document, fieldDeclaration, ct), - GetEquivalenceKey(diagnostic)); + if (parent?.IsKind(SyntaxKind.VariableDeclarator) != true) + break; - context.RegisterCodeFix(codeAction, diagnostic); + parent = parent.Parent; + + if (parent is not VariableDeclarationSyntax variableDeclaration) + break; + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstModifier, context.Document, root.SyntaxTree) + && variableDeclaration.Parent is LocalDeclarationStatementSyntax localDeclarationStatement) + { + SyntaxTokenList modifiers = localDeclarationStatement.Modifiers; + + if (!modifiers.Contains(SyntaxKind.ConstKeyword)) break; - } + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, localDeclarationStatement, SyntaxKind.ConstKeyword); + } + else if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceConstantWithField, context.Document, root.SyntaxTree) + && variableDeclaration.Variables.Count == 1 + && (variableDeclaration.Parent is FieldDeclarationSyntax fieldDeclaration) + && fieldDeclaration.Modifiers.Contains(SyntaxKind.ConstKeyword)) + { + CodeAction codeAction = CodeAction.Create( + UseReadOnlyFieldInsteadOfConstantRefactoring.Title, + ct => UseReadOnlyFieldInsteadOfConstantRefactoring.RefactorAsync(context.Document, fieldDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); break; } + + break; + } case CompilerDiagnosticIdentifiers.CS0037_CannotConvertNullToTypeBecauseItIsNonNullableValueType: case CompilerDiagnosticIdentifiers.CS0403_CannotConvertNullToTypeParameterBecauseItCouldBeNonNullableValueType: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, context.Document, root.SyntaxTree)) + break; + + if (expression.IsKind(SyntaxKind.NullLiteralExpression) + && expression.WalkUpParentheses().IsParentKind(SyntaxKind.SuppressNullableWarningExpression)) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, context.Document, root.SyntaxTree)) - break; + break; + } - if (expression.IsKind(SyntaxKind.NullLiteralExpression) - && expression.WalkUpParentheses().IsParentKind(SyntaxKind.SuppressNullableWarningExpression)) - { - break; - } + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + CodeFixRegistrator.ReplaceNullWithDefaultValue(context, diagnostic, expression, semanticModel); + break; + } + case CompilerDiagnosticIdentifiers.CS0472_ResultOfExpressionIsAlwaysConstantSinceValueIsNeverEqualToNull: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConditionThatIsAlwaysEqualToTrueOrFalse, context.Document, root.SyntaxTree)) + break; - CodeFixRegistrator.ReplaceNullWithDefaultValue(context, diagnostic, expression, semanticModel); + NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(expression, allowedStyles: NullCheckStyles.ComparisonToNull); + + if (!nullCheck.Success) break; - } - case CompilerDiagnosticIdentifiers.CS0472_ResultOfExpressionIsAlwaysConstantSinceValueIsNeverEqualToNull: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConditionThatIsAlwaysEqualToTrueOrFalse, context.Document, root.SyntaxTree)) - break; - NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(expression, allowedStyles: NullCheckStyles.ComparisonToNull); + CodeAction codeAction = CodeAction.Create( + "Remove condition", + ct => + { + ct.ThrowIfCancellationRequested(); - if (!nullCheck.Success) - break; + SyntaxNode newRoot = RemoveCondition(root, expression, nullCheck.Style == NullCheckStyles.NotEqualsToNull); - CodeAction codeAction = CodeAction.Create( - "Remove condition", - ct => - { - ct.ThrowIfCancellationRequested(); + ct.ThrowIfCancellationRequested(); - SyntaxNode newRoot = RemoveCondition(root, expression, nullCheck.Style == NullCheckStyles.NotEqualsToNull); + return Task.FromResult(context.Document.WithSyntaxRoot(newRoot)); + }, + GetEquivalenceKey(diagnostic)); - ct.ThrowIfCancellationRequested(); + context.RegisterCodeFix(codeAction, diagnostic); - return Task.FromResult(context.Document.WithSyntaxRoot(newRoot)); - }, - GetEquivalenceKey(diagnostic)); + break; + } + case CompilerDiagnosticIdentifiers.CS0201_OnlyAssignmentCallIncrementDecrementAndNewObjectExpressionsCanBeUsedAsStatement: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveParentheses, context.Document, root.SyntaxTree) + && expression is ParenthesizedExpressionSyntax parenthesizedExpression + && parenthesizedExpression?.IsMissing == false) + { + CodeAction codeAction = CodeActionFactory.RemoveParentheses(context.Document, parenthesizedExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case CompilerDiagnosticIdentifiers.CS0201_OnlyAssignmentCallIncrementDecrementAndNewObjectExpressionsCanBeUsedAsStatement: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveParentheses, context.Document, root.SyntaxTree) - && expression is ParenthesizedExpressionSyntax parenthesizedExpression - && parenthesizedExpression?.IsMissing == false) - { - CodeAction codeAction = CodeActionFactory.RemoveParentheses(context.Document, parenthesizedExpression, equivalenceKey: GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (expression.IsParentKind(SyntaxKind.ArrowExpressionClause)) + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree)) + break; - if (expression.IsParentKind(SyntaxKind.ArrowExpressionClause)) + ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + } + else if (expression.Parent is ExpressionStatementSyntax expressionStatement) + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, context.Document, root.SyntaxTree) + && expression.IsKind( + SyntaxKind.IdentifierName, + SyntaxKind.SimpleMemberAccessExpression)) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree)) - break; + SyntaxNode invocationExpression = InvocationExpression(expression); - ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) + { + CodeAction codeAction = CodeAction.Create( + "Add argument list", + ct => context.Document.ReplaceNodeAsync(expression, invocationExpression, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.AddArgumentList)); + + context.RegisterCodeFix(codeAction, diagnostic); + } } - else if (expression.Parent is ExpressionStatementSyntax expressionStatement) + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceComparisonWithAssignment, context.Document, root.SyntaxTree) + && expression.IsKind(SyntaxKind.EqualsExpression)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, context.Document, root.SyntaxTree) - && expression.IsKind( - SyntaxKind.IdentifierName, - SyntaxKind.SimpleMemberAccessExpression)) - { - SyntaxNode invocationExpression = InvocationExpression(expression); + BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo(expression); - if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) is not null) - { - CodeAction codeAction = CodeAction.Create( - "Add argument list", - ct => context.Document.ReplaceNodeAsync(expression, invocationExpression, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.AddArgumentList)); + if (!info.Success) + break; - context.RegisterCodeFix(codeAction, diagnostic); - } - } + ITypeSymbol leftTypeSymbol = semanticModel.GetTypeSymbol(info.Left, context.CancellationToken); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceComparisonWithAssignment, context.Document, root.SyntaxTree) - && expression.IsKind(SyntaxKind.EqualsExpression)) - { - BinaryExpressionInfo info = SyntaxInfo.BinaryExpressionInfo(expression); + if (leftTypeSymbol?.IsErrorType() != false) + break; - if (!info.Success) - break; + if (!semanticModel.IsImplicitConversion(info.Right, leftTypeSymbol)) + break; - ITypeSymbol leftTypeSymbol = semanticModel.GetTypeSymbol(info.Left, context.CancellationToken); + CodeAction codeAction = CodeAction.Create( + "Replace comparison with assignment", + ct => + { + AssignmentExpressionSyntax simpleAssignment = SimpleAssignmentExpression(info.Left, info.Right).WithTriviaFrom(expression); + return context.Document.ReplaceNodeAsync(expression, simpleAssignment, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceComparisonWithAssignment)); - if (leftTypeSymbol?.IsErrorType() != false) - break; + context.RegisterCodeFix(codeAction, diagnostic); + } - if (!semanticModel.IsImplicitConversion(info.Right, leftTypeSymbol)) - break; + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceConditionalExpressionWithIfElse, context.Document, root.SyntaxTree) + && (expression is ConditionalExpressionSyntax conditionalExpression) + && conditionalExpression.Condition is not null) + { + ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; + ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; + if (whenTrue is not null + && whenFalse is not null + && semanticModel.GetTypeSymbol(whenTrue, context.CancellationToken)?.SpecialType == SpecialType.System_Void + && semanticModel.GetTypeSymbol(whenFalse, context.CancellationToken)?.SpecialType == SpecialType.System_Void) + { CodeAction codeAction = CodeAction.Create( - "Replace comparison with assignment", + "Replace ?: with if-else", ct => { - AssignmentExpressionSyntax simpleAssignment = SimpleAssignmentExpression(info.Left, info.Right).WithTriviaFrom(expression); - return context.Document.ReplaceNodeAsync(expression, simpleAssignment, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceComparisonWithAssignment)); + IfStatementSyntax newNode = IfStatement( + conditionalExpression.Condition.WalkDownParentheses(), + Block(ExpressionStatement(whenTrue)), + ElseClause(Block(ExpressionStatement(whenFalse)))); - context.RegisterCodeFix(codeAction, diagnostic); - } + newNode = newNode + .WithTriviaFrom(expressionStatement) + .WithFormatterAnnotation(); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceConditionalExpressionWithIfElse, context.Document, root.SyntaxTree) - && (expression is ConditionalExpressionSyntax conditionalExpression) - && conditionalExpression.Condition is not null) - { - ExpressionSyntax whenTrue = conditionalExpression.WhenTrue; - ExpressionSyntax whenFalse = conditionalExpression.WhenFalse; + return context.Document.ReplaceNodeAsync(expressionStatement, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceConditionalExpressionWithIfElse)); - if (whenTrue is not null - && whenFalse is not null - && semanticModel.GetTypeSymbol(whenTrue, context.CancellationToken)?.SpecialType == SpecialType.System_Void - && semanticModel.GetTypeSymbol(whenFalse, context.CancellationToken)?.SpecialType == SpecialType.System_Void) - { - CodeAction codeAction = CodeAction.Create( - "Replace ?: with if-else", - ct => - { - IfStatementSyntax newNode = IfStatement( - conditionalExpression.Condition.WalkDownParentheses(), - Block(ExpressionStatement(whenTrue)), - ElseClause(Block(ExpressionStatement(whenFalse)))); - - newNode = newNode - .WithTriviaFrom(expressionStatement) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(expressionStatement, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceConditionalExpressionWithIfElse)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } + } - if (semanticModel.GetSymbol(expression, context.CancellationToken)?.IsErrorType() != false) - break; + if (semanticModel.GetSymbol(expression, context.CancellationToken)?.IsErrorType() != false) + break; - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken); - if (typeSymbol?.IsErrorType() != false) - break; + if (typeSymbol?.IsErrorType() != false) + break; - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.IntroduceLocalVariable, context.Document, root.SyntaxTree) - && !expressionStatement.IsEmbedded()) - { - bool addAwait = typeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT() - && semanticModel.GetEnclosingSymbol(expressionStatement.SpanStart, context.CancellationToken).IsAsyncMethod(); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.IntroduceLocalVariable, context.Document, root.SyntaxTree) + && !expressionStatement.IsEmbedded()) + { + bool addAwait = typeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT() + && semanticModel.GetEnclosingSymbol(expressionStatement.SpanStart, context.CancellationToken).IsAsyncMethod(); - CodeAction codeAction = CodeAction.Create( - IntroduceLocalVariableRefactoring.GetTitle(expression), - ct => IntroduceLocalVariableRefactoring.RefactorAsync(context.Document, expressionStatement, typeSymbol, addAwait, semanticModel, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.IntroduceLocalVariable)); + CodeAction codeAction = CodeAction.Create( + IntroduceLocalVariableRefactoring.GetTitle(expression), + ct => IntroduceLocalVariableRefactoring.RefactorAsync(context.Document, expressionStatement, typeSymbol, addAwait, semanticModel, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.IntroduceLocalVariable)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.IntroduceField, context.Document, root.SyntaxTree)) - { - CodeAction codeAction = CodeAction.Create( - $"Introduce field for '{expression}'", - ct => IntroduceFieldRefactoring.RefactorAsync(context.Document, expressionStatement, typeSymbol, semanticModel, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.IntroduceField)); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.IntroduceField, context.Document, root.SyntaxTree)) + { + CodeAction codeAction = CodeAction.Create( + $"Introduce field for '{expression}'", + ct => IntroduceFieldRefactoring.RefactorAsync(context.Document, expressionStatement, typeSymbol, semanticModel, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.IntroduceField)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } + } + break; + } + case CompilerDiagnosticIdentifiers.CS0029_CannotImplicitlyConvertType: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceYieldReturnWithForEach, context.Document, root.SyntaxTree) + && expression.IsParentKind(SyntaxKind.YieldReturnStatement)) + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + ReplaceYieldReturnWithForEachRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); break; } - case CompilerDiagnosticIdentifiers.CS0029_CannotImplicitlyConvertType: + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree) + && expression.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement, SyntaxKind.ArrowExpressionClause)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceYieldReturnWithForEach, context.Document, root.SyntaxTree) - && expression.IsParentKind(SyntaxKind.YieldReturnStatement)) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ReplaceYieldReturnWithForEachRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); - break; - } + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree) - && expression.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement, SyntaxKind.ArrowExpressionClause)) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + break; + } - ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); - break; - } + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeAccordingToInitializer, context.Document, root.SyntaxTree)) + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeAccordingToInitializer, context.Document, root.SyntaxTree)) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + CodeFixRegistrationResult result = ChangeTypeAccordingToInitializerRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); - CodeFixRegistrationResult result = ChangeTypeAccordingToInitializerRefactoring.ComputeCodeFix(context, diagnostic, expression, semanticModel); + if (!result.Success) + RemoveAssignmentOfVoidExpression(context, diagnostic, expression, semanticModel); - if (!result.Success) - RemoveAssignmentOfVoidExpression(context, diagnostic, expression, semanticModel); + break; + } - break; - } + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral, context.Document, root.SyntaxTree) + && expression?.Kind() == SyntaxKind.StringLiteralExpression) + { + var literalExpression = (LiteralExpressionSyntax)expression; - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral, context.Document, root.SyntaxTree) - && expression?.Kind() == SyntaxKind.StringLiteralExpression) + if (literalExpression.Token.ValueText.Length == 1) { - var literalExpression = (LiteralExpressionSyntax)expression; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (literalExpression.Token.ValueText.Length == 1) + if (semanticModel.GetTypeInfo(expression, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Char) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - if (semanticModel.GetTypeInfo(expression, context.CancellationToken).ConvertedType?.SpecialType == SpecialType.System_Char) - { - CodeAction codeAction = CodeAction.Create( - "Replace string literal with character literal", - ct => ReplaceStringLiteralWithCharacterLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral)); + CodeAction codeAction = CodeAction.Create( + "Replace string literal with character literal", + ct => ReplaceStringLiteralWithCharacterLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceStringLiteralWithCharacterLiteral)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } } + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree) - && expression.IsParentKind(SyntaxKind.ReturnStatement)) - { - var returnStatement = (ReturnStatementSyntax)expression.Parent; + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree) + && expression.IsParentKind(SyntaxKind.ReturnStatement)) + { + var returnStatement = (ReturnStatementSyntax)expression.Parent; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); + ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); - if (containingSymbol?.Kind == SymbolKind.Method - && ((IMethodSymbol)containingSymbol).ReturnType.OriginalDefinition.IsIEnumerableOrIEnumerableOfT()) - { - CodeAction codeAction = CodeAction.Create( - "Use yield return instead of return", - ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, SyntaxKind.YieldReturnStatement, semanticModel, ct), - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn)); + if (containingSymbol?.Kind == SymbolKind.Method + && ((IMethodSymbol)containingSymbol).ReturnType.OriginalDefinition.IsIEnumerableOrIEnumerableOfT()) + { + CodeAction codeAction = CodeAction.Create( + "Use yield return instead of return", + ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, SyntaxKind.YieldReturnStatement, semanticModel, ct), + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } - - break; } + + break; + } case CompilerDiagnosticIdentifiers.CS0131_LeftHandSideOfAssignmentMustBeVariablePropertyOrIndexer: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstModifier, context.Document, root.SyntaxTree)) - return; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstModifier, context.Document, root.SyntaxTree)) + return; - if (!expression.IsKind(SyntaxKind.IdentifierName)) - return; + if (!expression.IsKind(SyntaxKind.IdentifierName)) + return; - if (!expression.IsParentKind(SyntaxKind.SimpleAssignmentExpression)) - return; + if (!expression.IsParentKind(SyntaxKind.SimpleAssignmentExpression)) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(expression, context.CancellationToken); + SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(expression, context.CancellationToken); - if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) - return; + if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) + return; - if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not ILocalSymbol localSymbol) - return; + if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not ILocalSymbol localSymbol) + return; - if (!localSymbol.IsConst) - return; + if (!localSymbol.IsConst) + return; - SyntaxNode node = localSymbol.GetSyntaxOrDefault(context.CancellationToken); + SyntaxNode node = localSymbol.GetSyntaxOrDefault(context.CancellationToken); - if (!node.IsKind(SyntaxKind.VariableDeclarator)) - return; + if (!node.IsKind(SyntaxKind.VariableDeclarator)) + return; - node = node.Parent; + node = node.Parent; - if (!node.IsKind(SyntaxKind.VariableDeclaration)) - return; + if (!node.IsKind(SyntaxKind.VariableDeclaration)) + return; - node = node.Parent; + node = node.Parent; - if (node is not LocalDeclarationStatementSyntax localDeclaration) - return; + if (node is not LocalDeclarationStatementSyntax localDeclaration) + return; - SyntaxToken constModifier = localDeclaration.Modifiers.Find(SyntaxKind.ConstKeyword); + SyntaxToken constModifier = localDeclaration.Modifiers.Find(SyntaxKind.ConstKeyword); - if (!constModifier.IsKind(SyntaxKind.ConstKeyword)) - return; + if (!constModifier.IsKind(SyntaxKind.ConstKeyword)) + return; - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, localDeclaration, constModifier); + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, localDeclaration, constModifier); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0191_ReadOnlyFieldCannotBeAssignedTo: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeFieldWritable, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeFieldWritable, context.Document, root.SyntaxTree)) + break; - SimpleAssignmentExpressionInfo simpleAssignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression.Parent); + SimpleAssignmentExpressionInfo simpleAssignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression.Parent); - if (!simpleAssignment.Success) - return; + if (!simpleAssignment.Success) + return; - if (simpleAssignment.Left != expression) - return; + if (simpleAssignment.Left != expression) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(expression, context.CancellationToken); + SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(expression, context.CancellationToken); - if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) - return; + if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) + return; - if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not IFieldSymbol fieldSymbol) - return; + if (symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is not IFieldSymbol fieldSymbol) + return; - if (fieldSymbol.DeclaredAccessibility != Accessibility.Private) - return; + if (fieldSymbol.DeclaredAccessibility != Accessibility.Private) + return; - if (fieldSymbol.GetSyntax().Parent.Parent is not FieldDeclarationSyntax fieldDeclaration) - return; + if (fieldSymbol.GetSyntax().Parent.Parent is not FieldDeclarationSyntax fieldDeclaration) + return; - TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor(); + TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor(); - if (!expression.Ancestors().Any(f => f == containingTypeDeclaration)) - return; + if (!expression.Ancestors().Any(f => f == containingTypeDeclaration)) + return; - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - fieldDeclaration, - SyntaxKind.ReadOnlyKeyword, - title: $"Make '{fieldSymbol.Name}' writable"); + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + fieldDeclaration, + SyntaxKind.ReadOnlyKeyword, + title: $"Make '{fieldSymbol.Name}' writable"); - break; - } + break; + } } } } @@ -563,119 +563,119 @@ private static TNode RemoveCondition( switch (parent?.Kind()) { case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)parent; - - if (ifStatement.Condition == expression) - { - if (isTrue) - { - return RemoveOrReplaceNode(node, ifStatement, ifStatement.Statement); - } - else - { - return RemoveOrReplaceNode(node, ifStatement, ifStatement.Else?.Statement); - } - } + { + var ifStatement = (IfStatementSyntax)parent; - break; - } - case SyntaxKind.DoStatement: + if (ifStatement.Condition == expression) { - var doStatement = (DoStatementSyntax)parent; - - if (doStatement.Condition == expression - && !isTrue) + if (isTrue) { - return RemoveOrReplaceNode(node, doStatement, doStatement.Statement); + return RemoveOrReplaceNode(node, ifStatement, ifStatement.Statement); } - - break; - } - case SyntaxKind.WhileStatement: - { - var whileStatement = (WhileStatementSyntax)parent; - - if (whileStatement.Condition == expression - && !isTrue) + else { - return node.RemoveStatement(whileStatement); + return RemoveOrReplaceNode(node, ifStatement, ifStatement.Else?.Statement); } - - break; } - case SyntaxKind.ForStatement: - { - var forStatement = (ForStatementSyntax)parent; - if (forStatement.Condition == expression) - { - if (isTrue) - { - return node.RemoveNode(expression); - } - else - { - return node.RemoveStatement(forStatement); - } - } + break; + } + case SyntaxKind.DoStatement: + { + var doStatement = (DoStatementSyntax)parent; - break; - } - case SyntaxKind.ConditionalExpression: + if (doStatement.Condition == expression + && !isTrue) { - var conditionalExpression = (ConditionalExpressionSyntax)parent; + return RemoveOrReplaceNode(node, doStatement, doStatement.Statement); + } - if (conditionalExpression.Condition == expression) - { - if (isTrue) - { - return RemoveOrReplaceNode(node, conditionalExpression, conditionalExpression.WhenTrue); - } - else - { - return RemoveOrReplaceNode(node, conditionalExpression, conditionalExpression.WhenFalse); - } - } + break; + } + case SyntaxKind.WhileStatement: + { + var whileStatement = (WhileStatementSyntax)parent; - break; - } - case SyntaxKind.LogicalAndExpression: + if (whileStatement.Condition == expression + && !isTrue) { - var logicalAnd = (BinaryExpressionSyntax)parent; - - ExpressionSyntax left = logicalAnd.Left; - ExpressionSyntax right = logicalAnd.Right; + return node.RemoveStatement(whileStatement); + } - ExpressionSyntax other = (left == expression) ? right : left; + break; + } + case SyntaxKind.ForStatement: + { + var forStatement = (ForStatementSyntax)parent; + if (forStatement.Condition == expression) + { if (isTrue) { - return RemoveOrReplaceNode(node, logicalAnd, other); + return node.RemoveNode(expression); } else { - return RemoveCondition(node, logicalAnd, isTrue); + return node.RemoveStatement(forStatement); } } - case SyntaxKind.LogicalOrExpression: - { - var logicalOr = (BinaryExpressionSyntax)parent; - - ExpressionSyntax left = logicalOr.Left; - ExpressionSyntax right = logicalOr.Right; - ExpressionSyntax other = (left == expression) ? right : left; + break; + } + case SyntaxKind.ConditionalExpression: + { + var conditionalExpression = (ConditionalExpressionSyntax)parent; + if (conditionalExpression.Condition == expression) + { if (isTrue) { - return RemoveCondition(node, logicalOr, isTrue); + return RemoveOrReplaceNode(node, conditionalExpression, conditionalExpression.WhenTrue); } else { - return RemoveOrReplaceNode(node, logicalOr, other); + return RemoveOrReplaceNode(node, conditionalExpression, conditionalExpression.WhenFalse); } } + + break; + } + case SyntaxKind.LogicalAndExpression: + { + var logicalAnd = (BinaryExpressionSyntax)parent; + + ExpressionSyntax left = logicalAnd.Left; + ExpressionSyntax right = logicalAnd.Right; + + ExpressionSyntax other = (left == expression) ? right : left; + + if (isTrue) + { + return RemoveOrReplaceNode(node, logicalAnd, other); + } + else + { + return RemoveCondition(node, logicalAnd, isTrue); + } + } + case SyntaxKind.LogicalOrExpression: + { + var logicalOr = (BinaryExpressionSyntax)parent; + + ExpressionSyntax left = logicalOr.Left; + ExpressionSyntax right = logicalOr.Right; + + ExpressionSyntax other = (left == expression) ? right : left; + + if (isTrue) + { + return RemoveCondition(node, logicalOr, isTrue); + } + else + { + return RemoveOrReplaceNode(node, logicalOr, other); + } + } } return node.ReplaceNode(expression, BooleanLiteralExpression(isTrue)); diff --git a/src/CodeFixes/CSharp/CodeFixes/IdentifierNameCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/IdentifierNameCodeFixProvider.cs index ad6c3c7a89..682dab9be6 100644 --- a/src/CodeFixes/CSharp/CodeFixes/IdentifierNameCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/IdentifierNameCodeFixProvider.cs @@ -46,96 +46,96 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0165_UseOfUnassignedLocalVariable: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.InitializeLocalVariableWithDefaultValue, context.Document, root.SyntaxTree)) - return; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.InitializeLocalVariableWithDefaultValue, context.Document, root.SyntaxTree)) + return; - SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - if (semanticModel.GetSymbol(identifierName, cancellationToken) is not ILocalSymbol localSymbol) - break; + if (semanticModel.GetSymbol(identifierName, cancellationToken) is not ILocalSymbol localSymbol) + break; - ITypeSymbol typeSymbol = localSymbol.Type; + ITypeSymbol typeSymbol = localSymbol.Type; - if (typeSymbol.Kind == SymbolKind.ErrorType) - break; + if (typeSymbol.Kind == SymbolKind.ErrorType) + break; - if (localSymbol.GetSyntax(cancellationToken) is not VariableDeclaratorSyntax variableDeclarator) - break; + if (localSymbol.GetSyntax(cancellationToken) is not VariableDeclaratorSyntax variableDeclarator) + break; - CodeAction codeAction = CodeAction.Create( - $"Initialize '{identifierName.Identifier.ValueText}' with default value", - ct => - { - SyntaxToken identifier = variableDeclarator.Identifier; + CodeAction codeAction = CodeAction.Create( + $"Initialize '{identifierName.Identifier.ValueText}' with default value", + ct => + { + SyntaxToken identifier = variableDeclarator.Identifier; - var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; + var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; - ExpressionSyntax value = typeSymbol.GetDefaultValueSyntax(variableDeclaration.Type.WithoutTrivia(), document.GetDefaultSyntaxOptions()); + ExpressionSyntax value = typeSymbol.GetDefaultValueSyntax(variableDeclaration.Type.WithoutTrivia(), document.GetDefaultSyntaxOptions()); - if (value.IsKind(SyntaxKind.DefaultExpression) - && document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) - { - value = CSharpFactory.DefaultLiteralExpression().WithTriviaFrom(value); - } + if (value.IsKind(SyntaxKind.DefaultExpression) + && document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) + { + value = CSharpFactory.DefaultLiteralExpression().WithTriviaFrom(value); + } - EqualsValueClauseSyntax newEqualsValue = EqualsValueClause(value) - .WithLeadingTrivia(TriviaList(Space)) - .WithTrailingTrivia(identifier.TrailingTrivia); + EqualsValueClauseSyntax newEqualsValue = EqualsValueClause(value) + .WithLeadingTrivia(TriviaList(Space)) + .WithTrailingTrivia(identifier.TrailingTrivia); - VariableDeclaratorSyntax newNode = variableDeclarator - .WithInitializer(newEqualsValue) - .WithIdentifier(identifier.WithoutTrailingTrivia()); + VariableDeclaratorSyntax newNode = variableDeclarator + .WithInitializer(newEqualsValue) + .WithIdentifier(identifier.WithoutTrailingTrivia()); - return document.ReplaceNodeAsync(variableDeclarator, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(variableDeclarator, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0103_NameDoesNotExistInCurrentContext: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddVariableType, context.Document, root.SyntaxTree)) - return; - - if (identifierName.Parent is not ArgumentSyntax argument) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddVariableType, context.Document, root.SyntaxTree)) + return; - if (!argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) - break; + if (identifierName.Parent is not ArgumentSyntax argument) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (!argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) + break; - foreach (ITypeSymbol typeSymbol in DetermineParameterTypeHelper.DetermineParameterTypes(argument, semanticModel, cancellationToken)) - { - if (typeSymbol.Kind == SymbolKind.TypeParameter) - continue; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - string typeName = SymbolDisplay.ToMinimalDisplayString(typeSymbol, semanticModel, identifierName.SpanStart, SymbolDisplayFormats.DisplayName); + foreach (ITypeSymbol typeSymbol in DetermineParameterTypeHelper.DetermineParameterTypes(argument, semanticModel, cancellationToken)) + { + if (typeSymbol.Kind == SymbolKind.TypeParameter) + continue; - CodeAction codeAction = CodeAction.Create( - $"Add variable type '{typeName}'", - ct => - { - DeclarationExpressionSyntax newNode = DeclarationExpression( - typeSymbol.ToTypeSyntax(), - SingleVariableDesignation(identifierName.Identifier.WithoutTrivia()).WithLeadingTrivia(Space)); + string typeName = SymbolDisplay.ToMinimalDisplayString(typeSymbol, semanticModel, identifierName.SpanStart, SymbolDisplayFormats.DisplayName); - newNode = newNode - .WithTriviaFrom(identifierName) - .WithFormatterAnnotation(); + CodeAction codeAction = CodeAction.Create( + $"Add variable type '{typeName}'", + ct => + { + DeclarationExpressionSyntax newNode = DeclarationExpression( + typeSymbol.ToTypeSyntax(), + SingleVariableDesignation(identifierName.Identifier.WithoutTrivia()).WithLeadingTrivia(Space)); - return document.ReplaceNodeAsync(identifierName, newNode, ct); - }, - GetEquivalenceKey(diagnostic, typeName)); + newNode = newNode + .WithTriviaFrom(identifierName) + .WithFormatterAnnotation(); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + return document.ReplaceNodeAsync(identifierName, newNode, ct); + }, + GetEquivalenceKey(diagnostic, typeName)); + context.RegisterCodeFix(codeAction, diagnostic); break; } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs index b4f6e6f62a..8f60a94aa4 100644 --- a/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/MemberDeclarationCodeFixProvider.cs @@ -70,335 +70,335 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1591_MissingXmlCommentForPubliclyVisibleTypeOrMember: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddDocumentationComment, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddDocumentationComment, context.Document, root.SyntaxTree)) + break; - CodeAction codeAction = CodeAction.Create( - "Add documentation comment", - ct => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, false, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + "Add documentation comment", + ct => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, false, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); + context.RegisterCodeFix(codeAction, diagnostic); - CodeAction codeAction2 = CodeAction.Create( - "Add documentation comment (copy from base if available)", - ct => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, true, ct), - GetEquivalenceKey(diagnostic, "CopyFromBaseIfAvailable")); + CodeAction codeAction2 = CodeAction.Create( + "Add documentation comment (copy from base if available)", + ct => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, true, ct), + GetEquivalenceKey(diagnostic, "CopyFromBaseIfAvailable")); - context.RegisterCodeFix(codeAction2, diagnostic); - break; - } + context.RegisterCodeFix(codeAction2, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0508_MethodReturnTypeMustMatchOverriddenMethodReturnType: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMethodReturnType, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMethodReturnType, context.Document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); + var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - ITypeSymbol typeSymbol = methodSymbol.OverriddenMethod.ReturnType; + ITypeSymbol typeSymbol = methodSymbol.OverriddenMethod.ReturnType; - CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); + CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0766_PartialMethodsMustHaveVoidReturnType: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMethodReturnType, context.Document, root.SyntaxTree)) - break; - - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMethodReturnType, context.Document, root.SyntaxTree)) + break; - var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken); + var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; - if (otherPart is null) - break; + MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken); - CodeAction codeAction = CodeAction.Create( - "Change return type to 'void'", - ct => - { - return context.Document.Solution().ReplaceNodesAsync( - new MethodDeclarationSyntax[] { methodDeclaration, otherPart }, - (node, _) => node.WithReturnType(CSharpFactory.VoidType().WithTriviaFrom(node.ReturnType)), - ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); + if (otherPart is null) break; - } + + CodeAction codeAction = CodeAction.Create( + "Change return type to 'void'", + ct => + { + return context.Document.Solution().ReplaceNodesAsync( + new MethodDeclarationSyntax[] { methodDeclaration, otherPart }, + (node, _) => node.WithReturnType(CSharpFactory.VoidType().WithTriviaFrom(node.ReturnType)), + ct); + }, + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS1715_MemberTypeMustMatchOverriddenMemberType: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType, context.Document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = null; + ITypeSymbol typeSymbol = null; + + switch (memberDeclaration.Kind()) + { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.IndexerDeclaration: + { + var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - switch (memberDeclaration.Kind()) + typeSymbol = propertySymbol.OverriddenProperty.Type; + break; + } + case SyntaxKind.EventDeclaration: { - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.IndexerDeclaration: - { - var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - - typeSymbol = propertySymbol.OverriddenProperty.Type; - break; - } - case SyntaxKind.EventDeclaration: - { - var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - - typeSymbol = eventSymbol.OverriddenEvent.Type; - break; - } - case SyntaxKind.EventFieldDeclaration: - { - VariableDeclaratorSyntax declarator = ((EventFieldDeclarationSyntax)memberDeclaration).Declaration.Variables[0]; - - var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, context.CancellationToken); - - typeSymbol = eventSymbol.OverriddenEvent.Type; - break; - } + var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); + + typeSymbol = eventSymbol.OverriddenEvent.Type; + break; } + case SyntaxKind.EventFieldDeclaration: + { + VariableDeclaratorSyntax declarator = ((EventFieldDeclarationSyntax)memberDeclaration).Declaration.Variables[0]; - CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); + var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, context.CancellationToken); - break; + typeSymbol = eventSymbol.OverriddenEvent.Type; + break; + } } + + CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); + + break; + } case CompilerDiagnosticIdentifiers.CS0260_MissingPartialModifier: case CompilerDiagnosticIdentifiers.CS0751_PartialMethodMustBeDeclaredInPartialClassOrPartialStruct: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddPartialModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddPartialModifier, context.Document, root.SyntaxTree)) + break; - SyntaxNode node = null; + SyntaxNode node = null; - switch (memberDeclaration.Kind()) + switch (memberDeclaration.Kind()) + { + case SyntaxKind.MethodDeclaration: { - case SyntaxKind.MethodDeclaration: - { - if (memberDeclaration.IsParentKind( - SyntaxKind.ClassDeclaration, - SyntaxKind.StructDeclaration, + if (memberDeclaration.IsParentKind( + SyntaxKind.ClassDeclaration, + SyntaxKind.StructDeclaration, #if ROSLYN_4_0 - SyntaxKind.RecordStructDeclaration, + SyntaxKind.RecordStructDeclaration, #endif - SyntaxKind.RecordDeclaration)) - { - node = memberDeclaration.Parent; - } - - break; - } - case SyntaxKind.ClassDeclaration: - case SyntaxKind.StructDeclaration: + SyntaxKind.RecordDeclaration)) + { + node = memberDeclaration.Parent; + } + + break; + } + case SyntaxKind.ClassDeclaration: + case SyntaxKind.StructDeclaration: #if ROSLYN_4_0 - case SyntaxKind.RecordStructDeclaration: + case SyntaxKind.RecordStructDeclaration: #endif - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.RecordDeclaration: - { - node = memberDeclaration; - break; - } + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.RecordDeclaration: + { + node = memberDeclaration; + break; } + } - SyntaxDebug.Assert(node is not null, memberDeclaration); - - if (node is null) - break; + SyntaxDebug.Assert(node is not null, memberDeclaration); - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword, title: $"Make {CSharpFacts.GetTitle(node)} partial"); + if (node is null) break; - } + + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword, title: $"Make {CSharpFacts.GetTitle(node)} partial"); + break; + } case CompilerDiagnosticIdentifiers.CS0513_MemberIsAbstractButItIsContainedInNonAbstractClass: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassAbstract, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassAbstract, context.Document, root.SyntaxTree)) + break; - if (!memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)) - break; + if (!memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)) + break; - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - memberDeclaration.Parent, - SyntaxKind.AbstractKeyword, - title: "Make containing class abstract"); + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + memberDeclaration.Parent, + SyntaxKind.AbstractKeyword, + title: "Make containing class abstract"); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0132_StaticConstructorMustBeParameterless: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveParametersFromStaticConstructor, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveParametersFromStaticConstructor, context.Document, root.SyntaxTree)) + break; - var constructorDeclaration = (ConstructorDeclarationSyntax)memberDeclaration; + var constructorDeclaration = (ConstructorDeclarationSyntax)memberDeclaration; - CodeAction codeAction = CodeAction.Create( - "Remove parameters", - ct => - { - ParameterListSyntax parameterList = constructorDeclaration.ParameterList; + CodeAction codeAction = CodeAction.Create( + "Remove parameters", + ct => + { + ParameterListSyntax parameterList = constructorDeclaration.ParameterList; - ParameterListSyntax newParameterList = parameterList - .WithParameters(default(SeparatedSyntaxList)) - .WithOpenParenToken(parameterList.OpenParenToken.WithoutTrailingTrivia()) - .WithCloseParenToken(parameterList.CloseParenToken.WithoutLeadingTrivia()); + ParameterListSyntax newParameterList = parameterList + .WithParameters(default(SeparatedSyntaxList)) + .WithOpenParenToken(parameterList.OpenParenToken.WithoutTrailingTrivia()) + .WithCloseParenToken(parameterList.CloseParenToken.WithoutLeadingTrivia()); - ConstructorDeclarationSyntax newNode = constructorDeclaration.WithParameterList(newParameterList); + ConstructorDeclarationSyntax newNode = constructorDeclaration.WithParameterList(newParameterList); - return context.Document.ReplaceNodeAsync(constructorDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(constructorDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0541_ExplicitInterfaceDeclarationCanOnlyBeDeclaredInClassOrStruct: case CompilerDiagnosticIdentifiers.CS0525_InterfacesCannotContainFields: case CompilerDiagnosticIdentifiers.CS0567_InterfacesCannotContainOperators: case CompilerDiagnosticIdentifiers.CS0524_InterfacesCannotDeclareTypes: case CompilerDiagnosticIdentifiers.CS0575_OnlyClassTypesCanContainDestructors: case CompilerDiagnosticIdentifiers.CS0568_StructsCannotContainExplicitParameterlessConstructors: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) - break; - - CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) break; - } + + CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); + break; + } case CompilerDiagnosticIdentifiers.CS0574_NameOfDestructorMustMatchNameOfClass: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RenameDestructorToMatchClassName, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RenameDestructorToMatchClassName, context.Document, root.SyntaxTree)) + break; - if (memberDeclaration is not DestructorDeclarationSyntax destructorDeclaration) - break; + if (memberDeclaration is not DestructorDeclarationSyntax destructorDeclaration) + break; - if (memberDeclaration.Parent is not ClassDeclarationSyntax classDeclaration) - break; + if (memberDeclaration.Parent is not ClassDeclarationSyntax classDeclaration) + break; - if (classDeclaration.Identifier.ValueText.Length == 0) - break; + if (classDeclaration.Identifier.ValueText.Length == 0) + break; - CodeAction codeAction = CodeAction.Create( - "Rename destructor to match class name", - ct => - { - DestructorDeclarationSyntax newNode = destructorDeclaration.WithIdentifier(classDeclaration.Identifier.WithTriviaFrom(destructorDeclaration.Identifier)); + CodeAction codeAction = CodeAction.Create( + "Rename destructor to match class name", + ct => + { + DestructorDeclarationSyntax newNode = destructorDeclaration.WithIdentifier(classDeclaration.Identifier.WithTriviaFrom(destructorDeclaration.Identifier)); - return context.Document.ReplaceNodeAsync(destructorDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(destructorDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS8139_CannotChangeTupleElementNameWhenOverridingInheritedMember: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RenameTupleElement, context.Document, root.SyntaxTree)) - break; - - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) - { - IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RenameTupleElement, context.Document, root.SyntaxTree)) + break; - if (methodSymbol.ReturnType is not INamedTypeSymbol tupleType) - break; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!tupleType.IsTupleType) - break; + if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) + { + IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); - if (methodSymbol.OverriddenMethod?.ReturnType is not INamedTypeSymbol baseTupleType) - break; + if (methodSymbol.ReturnType is not INamedTypeSymbol tupleType) + break; - if (!baseTupleType.IsTupleType) - break; + if (!tupleType.IsTupleType) + break; - ImmutableArray elements = tupleType.TupleElements; - ImmutableArray baseElements = baseTupleType.TupleElements; + if (methodSymbol.OverriddenMethod?.ReturnType is not INamedTypeSymbol baseTupleType) + break; - if (elements.Length != baseElements.Length) - break; + if (!baseTupleType.IsTupleType) + break; - int i = 0; - while (i < elements.Length) - { - if (elements[i].Name != baseElements[i].Name) - break; + ImmutableArray elements = tupleType.TupleElements; + ImmutableArray baseElements = baseTupleType.TupleElements; - i++; - } + if (elements.Length != baseElements.Length) + break; - if (i == elements.Length) + int i = 0; + while (i < elements.Length) + { + if (elements[i].Name != baseElements[i].Name) break; - TupleElementSyntax tupleElement = ((TupleTypeSyntax)methodDeclaration.ReturnType).Elements[i]; + i++; + } - CodeAction codeAction = CodeAction.Create( - $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", - ct => RenameTupleElementAsync(context.Document, methodDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), - GetEquivalenceKey(diagnostic)); + if (i == elements.Length) + break; - context.RegisterCodeFix(codeAction, diagnostic); - } - else if (memberDeclaration is PropertyDeclarationSyntax propertyDeclaration) - { - IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); + TupleElementSyntax tupleElement = ((TupleTypeSyntax)methodDeclaration.ReturnType).Elements[i]; - if (propertySymbol.Type is not INamedTypeSymbol tupleType) - break; + CodeAction codeAction = CodeAction.Create( + $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", + ct => RenameTupleElementAsync(context.Document, methodDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), + GetEquivalenceKey(diagnostic)); - if (!tupleType.IsTupleType) - break; + context.RegisterCodeFix(codeAction, diagnostic); + } + else if (memberDeclaration is PropertyDeclarationSyntax propertyDeclaration) + { + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); - if (propertySymbol.OverriddenProperty?.Type is not INamedTypeSymbol baseTupleType) - break; + if (propertySymbol.Type is not INamedTypeSymbol tupleType) + break; - if (!baseTupleType.IsTupleType) - break; + if (!tupleType.IsTupleType) + break; - ImmutableArray elements = tupleType.TupleElements; - ImmutableArray baseElements = baseTupleType.TupleElements; + if (propertySymbol.OverriddenProperty?.Type is not INamedTypeSymbol baseTupleType) + break; - if (elements.Length != baseElements.Length) - break; + if (!baseTupleType.IsTupleType) + break; - int i = 0; - while (i < elements.Length) - { - if (elements[i].Name != baseElements[i].Name) - break; + ImmutableArray elements = tupleType.TupleElements; + ImmutableArray baseElements = baseTupleType.TupleElements; - i++; - } + if (elements.Length != baseElements.Length) + break; - if (i == elements.Length) + int i = 0; + while (i < elements.Length) + { + if (elements[i].Name != baseElements[i].Name) break; - TupleElementSyntax tupleElement = ((TupleTypeSyntax)propertyDeclaration.Type).Elements[i]; + i++; + } - CodeAction codeAction = CodeAction.Create( - $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", - ct => RenameTupleElementAsync(context.Document, propertyDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), - GetEquivalenceKey(diagnostic)); + if (i == elements.Length) + break; - context.RegisterCodeFix(codeAction, diagnostic); - } + TupleElementSyntax tupleElement = ((TupleTypeSyntax)propertyDeclaration.Type).Elements[i]; - break; + CodeAction codeAction = CodeAction.Create( + $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", + ct => RenameTupleElementAsync(context.Document, propertyDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } case CompilerDiagnosticIdentifiers.CS3000_MethodsWithVariableArgumentsAreNotCLSCompliant: case CompilerDiagnosticIdentifiers.CS3001_ArgumentTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.CS3002_ReturnTypeIsNotCLSCompliant: @@ -411,36 +411,36 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) case CompilerDiagnosticIdentifiers.CS3016_ArraysAsAttributeArgumentsIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.CS3024_ConstraintTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.CS3027_TypeIsNotCLSCompliantBecauseBaseInterfaceIsNotCLSCompliant: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MarkDeclarationAsNonCLSCompliant, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MarkDeclarationAsNonCLSCompliant, context.Document, root.SyntaxTree)) + break; - CodeAction codeAction = CodeAction.Create( - $"Mark {CSharpFacts.GetTitle(memberDeclaration)} as non-CLS-compliant", - ct => MarkDeclarationAsNonCLSCompliantAsync(context.Document, memberDeclaration, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Mark {CSharpFacts.GetTitle(memberDeclaration)} as non-CLS-compliant", + ct => MarkDeclarationAsNonCLSCompliantAsync(context.Document, memberDeclaration, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0539_ExplicitInterfaceDeclarationIsNotMemberOfInterface: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddParameterToExplicitlyImplementedInterfaceMember, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddParameterToExplicitlyImplementedInterfaceMember, context.Document, root.SyntaxTree)) + break; - var context2 = new CommonFixContext( - context.Document, - GetEquivalenceKey(diagnostic), - await context.GetSemanticModelAsync().ConfigureAwait(false), - context.CancellationToken); + var context2 = new CommonFixContext( + context.Document, + GetEquivalenceKey(diagnostic), + await context.GetSemanticModelAsync().ConfigureAwait(false), + context.CancellationToken); - CodeAction codeAction = AddParameterToInterfaceMemberRefactoring.ComputeRefactoringForExplicitImplementation(context2, memberDeclaration); + CodeAction codeAction = AddParameterToInterfaceMemberRefactoring.ComputeRefactoringForExplicitImplementation(context2, memberDeclaration); - if (codeAction is not null) - context.RegisterCodeFix(codeAction, diagnostic); + if (codeAction is not null) + context.RegisterCodeFix(codeAction, diagnostic); - break; - } + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/MemberHidesInheritedMemberCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/MemberHidesInheritedMemberCodeFixProvider.cs index db4b7789e4..bbb6b31d33 100644 --- a/src/CodeFixes/CSharp/CodeFixes/MemberHidesInheritedMemberCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/MemberHidesInheritedMemberCodeFixProvider.cs @@ -37,31 +37,31 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0108_MemberHidesInheritedMemberUseNewKeywordIfHidingWasIntended: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNewModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.NewKeyword, additionalKey: nameof(SyntaxKind.NewKeyword)); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNewModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.NewKeyword, additionalKey: nameof(SyntaxKind.NewKeyword)); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) - CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) + CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0114_MemberHidesInheritedMemberToMakeCurrentMethodOverrideThatImplementationAddOverrideKeyword: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddOverrideModifier, context.Document, root.SyntaxTree) + && !SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddOverrideModifier, context.Document, root.SyntaxTree) - && !SyntaxInfo.ModifierListInfo(memberDeclaration).IsStatic) - { - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.OverrideKeyword, additionalKey: nameof(SyntaxKind.OverrideKeyword)); - } + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.OverrideKeyword, additionalKey: nameof(SyntaxKind.OverrideKeyword)); + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNewModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.NewKeyword, additionalKey: nameof(SyntaxKind.NewKeyword)); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNewModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, memberDeclaration, SyntaxKind.NewKeyword, additionalKey: nameof(SyntaxKind.NewKeyword)); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) - CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveMemberDeclaration, context.Document, root.SyntaxTree)) + CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); - break; - } + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs index a8e8950b6c..bd2548ab49 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ModifiersCodeFixProvider.cs @@ -99,426 +99,426 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0106_ModifierIsNotValidForThisItem: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + break; - SyntaxTokenList modifiers = SyntaxInfo.ModifierListInfo(node).Modifiers; + SyntaxTokenList modifiers = SyntaxInfo.ModifierListInfo(node).Modifiers; - if (modifiers.Contains(token)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, token); - break; - } - else if (IsInterfaceMemberOrExplicitInterfaceImplementation(node)) - { - ModifiersCodeFixRegistrator.RemoveModifiers( - context, - diagnostic, - node, - modifiers, - f => + if (modifiers.Contains(token)) + { + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, token); + break; + } + else if (IsInterfaceMemberOrExplicitInterfaceImplementation(node)) + { + ModifiersCodeFixRegistrator.RemoveModifiers( + context, + diagnostic, + node, + modifiers, + f => + { + switch (f.Kind()) { - switch (f.Kind()) + case SyntaxKind.PublicKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.StaticKeyword: + case SyntaxKind.VirtualKeyword: + case SyntaxKind.OverrideKeyword: + case SyntaxKind.AbstractKeyword: { - case SyntaxKind.PublicKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.InternalKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.StaticKeyword: - case SyntaxKind.VirtualKeyword: - case SyntaxKind.OverrideKeyword: - case SyntaxKind.AbstractKeyword: - { - return true; - } + return true; } + } - return false; - }); - } - else if (node.IsKind(SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.EventFieldDeclaration) - && node.IsParentKind( + return false; + }); + } + else if (node.IsKind(SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.EventFieldDeclaration) + && node.IsParentKind( #if ROSLYN_4_0 - SyntaxKind.RecordStructDeclaration, + SyntaxKind.RecordStructDeclaration, #endif - SyntaxKind.StructDeclaration) - && modifiers.Contains(SyntaxKind.VirtualKeyword)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword); - } - else if (node.IsKind(SyntaxKind.IndexerDeclaration) - && modifiers.Contains(SyntaxKind.StaticKeyword)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword); - } - else if (node.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.EventFieldDeclaration) - && modifiers.Contains(SyntaxKind.AsyncKeyword)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AsyncKeyword); - } - - break; + SyntaxKind.StructDeclaration) + && modifiers.Contains(SyntaxKind.VirtualKeyword)) + { + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword); } - case CompilerDiagnosticIdentifiers.CS0107_MoreThanOneProtectionModifier: + else if (node.IsKind(SyntaxKind.IndexerDeclaration) + && modifiers.Contains(SyntaxKind.StaticKeyword)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, token); - - break; + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword); } + else if (node.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.EventFieldDeclaration) + && modifiers.Contains(SyntaxKind.AsyncKeyword)) + { + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AsyncKeyword); + } + + break; + } + case CompilerDiagnosticIdentifiers.CS0107_MoreThanOneProtectionModifier: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, token); + + break; + } case CompilerDiagnosticIdentifiers.CS0275_AccessibilityModifiersMayNotBeUsedOnAccessorsInInterface: case CompilerDiagnosticIdentifiers.CS0515_AccessModifiersAreNotAllowedOnStaticConstructors: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveAccessibility(context, diagnostic, node); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveAccessibility(context, diagnostic, node); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS1609_ModifiersCannotBePlacedOnEventAccessorDeclarations: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifiers(context, diagnostic, node); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifiers(context, diagnostic, node); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0753_OnlyMethodsClassesStructsOrInterfacesMayBePartial: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0441_ClassCannotBeBothStaticAndSealed: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - break; - - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword, additionalKey: nameof(SyntaxKind.StaticKeyword)); - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.SealedKeyword, additionalKey: nameof(SyntaxKind.SealedKeyword)); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) break; - } + + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword, additionalKey: nameof(SyntaxKind.StaticKeyword)); + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.SealedKeyword, additionalKey: nameof(SyntaxKind.SealedKeyword)); + break; + } case CompilerDiagnosticIdentifiers.CS0678_FieldCanNotBeBothVolatileAndReadOnly: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + break; - var fieldDeclaration = (FieldDeclarationSyntax)node; + var fieldDeclaration = (FieldDeclarationSyntax)node; - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, fieldDeclaration, SyntaxKind.VolatileKeyword, additionalKey: nameof(SyntaxKind.VolatileKeyword)); - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, fieldDeclaration, SyntaxKind.ReadOnlyKeyword, additionalKey: nameof(SyntaxKind.ReadOnlyKeyword)); - break; - } + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, fieldDeclaration, SyntaxKind.VolatileKeyword, additionalKey: nameof(SyntaxKind.VolatileKeyword)); + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, fieldDeclaration, SyntaxKind.ReadOnlyKeyword, additionalKey: nameof(SyntaxKind.ReadOnlyKeyword)); + break; + } case CompilerDiagnosticIdentifiers.CS0628_NewProtectedMemberDeclaredInSealedClass: case CompilerDiagnosticIdentifiers.CS1057_StaticClassesCannotContainProtectedMembers: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrPrivate); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrPrivate); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0621_VirtualOrAbstractMembersCannotBePrivate: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveVirtualModifier, context.Document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveVirtualModifier, context.Document, root.SyntaxTree)) - { - ModifierListInfo modifierInfo = SyntaxInfo.ModifierListInfo(node); + ModifierListInfo modifierInfo = SyntaxInfo.ModifierListInfo(node); - if (modifierInfo.IsVirtual) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword, additionalKey: nameof(SyntaxKind.VirtualKeyword)); - } + if (modifierInfo.IsVirtual) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword, additionalKey: nameof(SyntaxKind.VirtualKeyword)); + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrProtected); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrProtected); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0442_AbstractPropertiesCannotHavePrivateAccessors: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveAccessibility(context, diagnostic, node, additionalKey: CodeFixIdentifiers.RemoveInvalidModifier); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveAccessibility(context, diagnostic, node, additionalKey: CodeFixIdentifiers.RemoveInvalidModifier); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrProtected); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternalOrProtected); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0112_StaticMemberCannotBeMarkedOverrideVirtualOrAbstract: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - break; - - if (!node.IsParentKind(SyntaxKind.ClassDeclaration) - || !((ClassDeclarationSyntax)node.Parent).Modifiers.Contains(SyntaxKind.StaticKeyword)) - { - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword, additionalKey: nameof(SyntaxKind.StaticKeyword)); - } - - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OverrideKeyword, additionalKey: nameof(SyntaxKind.OverrideKeyword)); - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword, additionalKey: nameof(SyntaxKind.VirtualKeyword)); - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AbstractKeyword, additionalKey: nameof(SyntaxKind.AbstractKeyword)); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) break; + + if (!node.IsParentKind(SyntaxKind.ClassDeclaration) + || !((ClassDeclarationSyntax)node.Parent).Modifiers.Contains(SyntaxKind.StaticKeyword)) + { + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.StaticKeyword, additionalKey: nameof(SyntaxKind.StaticKeyword)); } + + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OverrideKeyword, additionalKey: nameof(SyntaxKind.OverrideKeyword)); + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.VirtualKeyword, additionalKey: nameof(SyntaxKind.VirtualKeyword)); + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AbstractKeyword, additionalKey: nameof(SyntaxKind.AbstractKeyword)); + break; + } case CompilerDiagnosticIdentifiers.CS1994_AsyncModifierCanOnlyBeUsedInMethodsThatHaveBody: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AsyncKeyword); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.AsyncKeyword); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0750_PartialMethodCannotHaveAccessModifiersOrVirtualAbstractOverrideNewSealedOrExternModifiers: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + break; - ModifiersCodeFixRegistrator.RemoveModifiers( - context, - diagnostic, - node, - f => + ModifiersCodeFixRegistrator.RemoveModifiers( + context, + diagnostic, + node, + f => + { + switch (f.Kind()) { - switch (f.Kind()) + case SyntaxKind.PublicKeyword: + case SyntaxKind.ProtectedKeyword: + case SyntaxKind.InternalKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.VirtualKeyword: + case SyntaxKind.AbstractKeyword: + case SyntaxKind.OverrideKeyword: + case SyntaxKind.NewKeyword: + case SyntaxKind.SealedKeyword: + case SyntaxKind.ExternKeyword: { - case SyntaxKind.PublicKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.InternalKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.VirtualKeyword: - case SyntaxKind.AbstractKeyword: - case SyntaxKind.OverrideKeyword: - case SyntaxKind.NewKeyword: - case SyntaxKind.SealedKeyword: - case SyntaxKind.ExternKeyword: - { - return true; - } + return true; } + } - return false; - }); + return false; + }); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS1105_ExtensionMethodMustBeStatic: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) - AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); - - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) - { - var methodDeclaration = (MethodDeclarationSyntax)node; + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) + AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); - ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0]; + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) + { + var methodDeclaration = (MethodDeclarationSyntax)node; - SyntaxToken modifier = parameter.Modifiers.Find(SyntaxKind.ThisKeyword); + ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0]; - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, modifier, additionalKey: CodeFixIdentifiers.RemoveThisModifier); - } + SyntaxToken modifier = parameter.Modifiers.Find(SyntaxKind.ThisKeyword); - break; + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, parameter, modifier, additionalKey: CodeFixIdentifiers.RemoveThisModifier); } + + break; + } case CompilerDiagnosticIdentifiers.CS1106_ExtensionMethodMustBeDefinedInNonGenericStaticClass: - { - if (node is not ClassDeclarationSyntax classDeclaration) - return; + { + if (node is not ClassDeclarationSyntax classDeclaration) + return; - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree) - && !classDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword)) - { - AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); - } + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree) + && !classDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword)) + { + AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) - { - IEnumerable thisParameters = classDeclaration.Members - .Where(f => f.IsKind(SyntaxKind.MethodDeclaration)) - .Cast() - .Select(f => f.ParameterList?.Parameters.FirstOrDefault()) - .Where(f => f?.Modifiers.Contains(SyntaxKind.ThisKeyword) == true); - - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - thisParameters, - SyntaxKind.ThisKeyword, - title: "Remove 'this' modifier from extension methods", - additionalKey: CodeFixIdentifiers.RemoveThisModifier); - } + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) + { + IEnumerable thisParameters = classDeclaration.Members + .Where(f => f.IsKind(SyntaxKind.MethodDeclaration)) + .Cast() + .Select(f => f.ParameterList?.Parameters.FirstOrDefault()) + .Where(f => f?.Modifiers.Contains(SyntaxKind.ThisKeyword) == true); - break; + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + thisParameters, + SyntaxKind.ThisKeyword, + title: "Remove 'this' modifier from extension methods", + additionalKey: CodeFixIdentifiers.RemoveThisModifier); } + + break; + } case CompilerDiagnosticIdentifiers.CS0759_NoDefiningDeclarationFoundForImplementingDeclarationOfPartialMethod: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS1100_MethodHasParameterModifierThisWhichIsNotOnFirstParameter: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, token.Parent, token); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveThisModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, token.Parent, token); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0708_CannotDeclareInstanceMembersInStaticClass: case CompilerDiagnosticIdentifiers.CS0710_StaticClassesCannotHaveInstanceConstructors: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) - AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) + AddStaticModifier(context, diagnostic, node, CodeFixIdentifiers.AddStaticModifier); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassNonStatic, context.Document, root.SyntaxTree)) - { - var classDeclaration = (ClassDeclarationSyntax)node.Parent; - - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - classDeclaration, - classDeclaration.Modifiers.Find(SyntaxKind.StaticKeyword), - title: "Make containing class non-static", - additionalKey: CodeFixIdentifiers.MakeContainingClassNonStatic); - } + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassNonStatic, context.Document, root.SyntaxTree)) + { + var classDeclaration = (ClassDeclarationSyntax)node.Parent; - break; + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + classDeclaration, + classDeclaration.Modifiers.Find(SyntaxKind.StaticKeyword), + title: "Make containing class non-static", + additionalKey: CodeFixIdentifiers.MakeContainingClassNonStatic); } + + break; + } case CompilerDiagnosticIdentifiers.CS1527_ElementsDefinedInNamespaceCannotBeExplicitlyDeclaredAsPrivateProtectedOrProtectedInternal: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternal); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeAccessibility, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.ChangeAccessibility(context, diagnostic, node, _publicOrInternal); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0101_NamespaceAlreadyContainsDefinition: case CompilerDiagnosticIdentifiers.CS0102_TypeAlreadyContainsDefinition: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddPartialModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddPartialModifier, context.Document, root.SyntaxTree)) + break; - if (!node.IsKind( - SyntaxKind.ClassDeclaration, - SyntaxKind.StructDeclaration, + if (!node.IsKind( + SyntaxKind.ClassDeclaration, + SyntaxKind.StructDeclaration, #if ROSLYN_4_0 - SyntaxKind.RecordStructDeclaration, + SyntaxKind.RecordStructDeclaration, #endif - SyntaxKind.InterfaceDeclaration, - SyntaxKind.MethodDeclaration)) - { - return; - } + SyntaxKind.InterfaceDeclaration, + SyntaxKind.MethodDeclaration)) + { + return; + } - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ISymbol symbol = semanticModel.GetDeclaredSymbol(node, context.CancellationToken); + ISymbol symbol = semanticModel.GetDeclaredSymbol(node, context.CancellationToken); - ImmutableArray syntaxReferences = symbol.DeclaringSyntaxReferences; + ImmutableArray syntaxReferences = symbol.DeclaringSyntaxReferences; - if (syntaxReferences.Length <= 1) - break; + if (syntaxReferences.Length <= 1) + break; - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - ImmutableArray.CreateRange(syntaxReferences, f => f.GetSyntax(context.CancellationToken)), - SyntaxKind.PartialKeyword, - title: $"Make {CSharpFacts.GetTitle(node)} partial"); + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + ImmutableArray.CreateRange(syntaxReferences, f => f.GetSyntax(context.CancellationToken)), + SyntaxKind.PartialKeyword, + title: $"Make {CSharpFacts.GetTitle(node)} partial"); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0115_NoSuitableMethodFoundToOverride: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OverrideKeyword); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveInvalidModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OverrideKeyword); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS1988_AsyncMethodsCannotHaveRefOrOutParameters: case CompilerDiagnosticIdentifiers.CS1623_IteratorsCannotHaveRefOrOutParameters: case CompilerDiagnosticIdentifiers.CS0192_ReadOnlyFieldCannotBePassedAsRefOrOutValue: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveRefModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.RefKeyword, additionalKey: nameof(SyntaxKind.RefKeyword)); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveRefModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.RefKeyword, additionalKey: nameof(SyntaxKind.RefKeyword)); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveOutModifier, context.Document, root.SyntaxTree)) - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OutKeyword, additionalKey: nameof(SyntaxKind.OutKeyword)); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveOutModifier, context.Document, root.SyntaxTree)) + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.OutKeyword, additionalKey: nameof(SyntaxKind.OutKeyword)); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0573_CannotHaveInstancePropertyOrFieldInitializersInStruct: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) - AddStaticModifier(context, diagnostic, node); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddStaticModifier, context.Document, root.SyntaxTree)) + AddStaticModifier(context, diagnostic, node); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0501_MemberMustDeclareBodyBecauseItIsNotMarkedAbstractExternOrPartial: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddModifierAbstract, context.Document, root.SyntaxTree) + && node.IsKind(SyntaxKind.MethodDeclaration) + && (node.Parent as ClassDeclarationSyntax)?.Modifiers.Contains(SyntaxKind.AbstractKeyword) == true) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddModifierAbstract, context.Document, root.SyntaxTree) - && node.IsKind(SyntaxKind.MethodDeclaration) - && (node.Parent as ClassDeclarationSyntax)?.Modifiers.Contains(SyntaxKind.AbstractKeyword) == true) - { - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.AbstractKeyword); - } - - break; + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.AbstractKeyword); } + + break; + } case CompilerDiagnosticIdentifiers.CS0549_NewVirtualMemberInSealedClass: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveVirtualModifier, context.Document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveVirtualModifier, context.Document, root.SyntaxTree)) + if (node is AccessorDeclarationSyntax + && SyntaxInfo.ModifierListInfo(node.Parent.Parent).IsVirtual) { - if (node is AccessorDeclarationSyntax - && SyntaxInfo.ModifierListInfo(node.Parent.Parent).IsVirtual) - { - node = node.Parent.Parent; - } - - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - node, - SyntaxKind.VirtualKeyword, - additionalKey: CodeFixIdentifiers.RemoveVirtualModifier); + node = node.Parent.Parent; } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassUnsealed, context.Document, root.SyntaxTree) - && node.Parent is ClassDeclarationSyntax classDeclaration) - { - ModifiersCodeFixRegistrator.RemoveModifier( - context, - diagnostic, - classDeclaration, - SyntaxKind.SealedKeyword, - title: "Make containing class unsealed", - additionalKey: CodeFixIdentifiers.MakeContainingClassUnsealed); - } - - break; + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + node, + SyntaxKind.VirtualKeyword, + additionalKey: CodeFixIdentifiers.RemoveVirtualModifier); } - case CompilerDiagnosticIdentifiers.CS8340_InstanceFieldsOfReadOnlyStructsMustBeReadOnly: + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingClassUnsealed, context.Document, root.SyntaxTree) + && node.Parent is ClassDeclarationSyntax classDeclaration) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeMemberReadOnly, context.Document, root.SyntaxTree)) - break; + ModifiersCodeFixRegistrator.RemoveModifier( + context, + diagnostic, + classDeclaration, + SyntaxKind.SealedKeyword, + title: "Make containing class unsealed", + additionalKey: CodeFixIdentifiers.MakeContainingClassUnsealed); + } - ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.ReadOnlyKeyword); + break; + } + case CompilerDiagnosticIdentifiers.CS8340_InstanceFieldsOfReadOnlyStructsMustBeReadOnly: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeMemberReadOnly, context.Document, root.SyntaxTree)) break; - } + + ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.ReadOnlyKeyword); + break; + } case CompilerDiagnosticIdentifiers.CS0238_MemberCannotBeSealedBecauseItIsNotOverride: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveSealedModifier, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveSealedModifier, context.Document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (semanticModel.GetDiagnostic( - CompilerDiagnosticIdentifiers.CS0114_MemberHidesInheritedMemberToMakeCurrentMethodOverrideThatImplementationAddOverrideKeyword, - CSharpUtility.GetIdentifier(node).Span, - context.CancellationToken) is not null) - { - break; - } - - ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.SealedKeyword); + if (semanticModel.GetDiagnostic( + CompilerDiagnosticIdentifiers.CS0114_MemberHidesInheritedMemberToMakeCurrentMethodOverrideThatImplementationAddOverrideKeyword, + CSharpUtility.GetIdentifier(node).Span, + context.CancellationToken) is not null) + { break; } + + ModifiersCodeFixRegistrator.RemoveModifier(context, diagnostic, node, SyntaxKind.SealedKeyword); + break; + } } } } @@ -539,28 +539,28 @@ private static bool IsInterfaceMemberOrExplicitInterfaceImplementation(SyntaxNod switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; - } + { + return node.IsParentKind(SyntaxKind.InterfaceDeclaration) + || ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; + } case SyntaxKind.PropertyDeclaration: - { - return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; - } + { + return node.IsParentKind(SyntaxKind.InterfaceDeclaration) + || ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; + } case SyntaxKind.IndexerDeclaration: - { - return node.IsParentKind(SyntaxKind.InterfaceDeclaration) - || ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; - } + { + return node.IsParentKind(SyntaxKind.InterfaceDeclaration) + || ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; + } case SyntaxKind.EventFieldDeclaration: - { - return node.IsParentKind(SyntaxKind.InterfaceDeclaration); - } + { + return node.IsParentKind(SyntaxKind.InterfaceDeclaration); + } case SyntaxKind.EventDeclaration: - { - return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; - } + { + return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier is not null; + } } return false; diff --git a/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs index 45a9528c08..5c091d1d90 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ObjectCreationExpressionCodeFixProvider.cs @@ -44,105 +44,105 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS7036_ThereIsNoArgumentGivenThatCorrespondsToRequiredFormalParameter: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveInitializerExpressionsToConstructor, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveInitializerExpressionsToConstructor, context.Document, root.SyntaxTree)) + break; - if (!objectCreationExpression.Type.Span.Contains(diagnostic.Location.SourceSpan)) - return; + if (!objectCreationExpression.Type.Span.Contains(diagnostic.Location.SourceSpan)) + return; - ArgumentListSyntax argumentList = objectCreationExpression.ArgumentList; + ArgumentListSyntax argumentList = objectCreationExpression.ArgumentList; - if (argumentList?.Arguments.Any() == true) - return; + if (argumentList?.Arguments.Any() == true) + return; - InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; + InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; - if (initializer is null) - return; + if (initializer is null) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - List expressions = null; + List expressions = null; - foreach (ExpressionSyntax expression in initializer.Expressions) + foreach (ExpressionSyntax expression in initializer.Expressions) + { + if (expression is AssignmentExpressionSyntax assignment + && semanticModel.GetDiagnostic( + CompilerDiagnosticIdentifiers.CS0272_PropertyOrIndexerCannotBeUsedInThisContextBecauseSetAccessorIsAccessible, + assignment.Left.Span, + context.CancellationToken) is not null) { - if (expression is AssignmentExpressionSyntax assignment - && semanticModel.GetDiagnostic( - CompilerDiagnosticIdentifiers.CS0272_PropertyOrIndexerCannotBeUsedInThisContextBecauseSetAccessorIsAccessible, - assignment.Left.Span, - context.CancellationToken) is not null) - { - (expressions ??= new List()).Add(expression); - } + (expressions ??= new List()).Add(expression); } + } - if (expressions is null) - return; - - TypeSyntax type = objectCreationExpression.Type; + if (expressions is null) + return; - if (argumentList is null) - { - argumentList = ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()); - type = type.WithoutTrailingTrivia(); - } + TypeSyntax type = objectCreationExpression.Type; - SeparatedSyntaxList arguments = expressions - .Select(f => Argument(((AssignmentExpressionSyntax)f).Right)) - .ToSeparatedSyntaxList(); + if (argumentList is null) + { + argumentList = ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()); + type = type.WithoutTrailingTrivia(); + } - argumentList = argumentList.WithArguments(arguments); + SeparatedSyntaxList arguments = expressions + .Select(f => Argument(((AssignmentExpressionSyntax)f).Right)) + .ToSeparatedSyntaxList(); - ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.Update( - objectCreationExpression.NewKeyword, - type, - argumentList, - initializer); + argumentList = argumentList.WithArguments(arguments); - SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo( - objectCreationExpression.SpanStart, - newObjectCreationExpression, - SpeculativeBindingOption.BindAsExpression); + ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.Update( + objectCreationExpression.NewKeyword, + type, + argumentList, + initializer); - if (symbolInfo.Symbol is IMethodSymbol methodSymbol - && methodSymbol.MethodKind == MethodKind.Constructor) - { - CodeAction codeAction = CodeAction.Create( - "Move initializer expressions to constructor", - ct => - { - InitializerExpressionSyntax newInitializer = initializer.RemoveNodes(expressions, SyntaxRefactorings.DefaultRemoveOptions); + SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo( + objectCreationExpression.SpanStart, + newObjectCreationExpression, + SpeculativeBindingOption.BindAsExpression); - if (!newInitializer.Expressions.Any() - && newInitializer - .DescendantTrivia(TextSpan.FromBounds(newInitializer.OpenBraceToken.SpanStart, newInitializer.CloseBraceToken.SpanStart)) - .All(f => f.IsWhitespaceOrEndOfLineTrivia())) - { - newInitializer = null; + if (symbolInfo.Symbol is IMethodSymbol methodSymbol + && methodSymbol.MethodKind == MethodKind.Constructor) + { + CodeAction codeAction = CodeAction.Create( + "Move initializer expressions to constructor", + ct => + { + InitializerExpressionSyntax newInitializer = initializer.RemoveNodes(expressions, SyntaxRefactorings.DefaultRemoveOptions); - ArgumentListSyntax newArgumentList = newObjectCreationExpression - .ArgumentList - .TrimTrailingTrivia() - .AppendToTrailingTrivia(initializer.GetTrailingTrivia()); + if (!newInitializer.Expressions.Any() + && newInitializer + .DescendantTrivia(TextSpan.FromBounds(newInitializer.OpenBraceToken.SpanStart, newInitializer.CloseBraceToken.SpanStart)) + .All(f => f.IsWhitespaceOrEndOfLineTrivia())) + { + newInitializer = null; - newObjectCreationExpression = newObjectCreationExpression - .WithArgumentList(newArgumentList); - } + ArgumentListSyntax newArgumentList = newObjectCreationExpression + .ArgumentList + .TrimTrailingTrivia() + .AppendToTrailingTrivia(initializer.GetTrailingTrivia()); newObjectCreationExpression = newObjectCreationExpression - .WithInitializer(newInitializer) - .WithFormatterAnnotation(); + .WithArgumentList(newArgumentList); + } - return context.Document.ReplaceNodeAsync(objectCreationExpression, newObjectCreationExpression, ct); - }, - GetEquivalenceKey(diagnostic)); + newObjectCreationExpression = newObjectCreationExpression + .WithInitializer(newInitializer) + .WithFormatterAnnotation(); - context.RegisterCodeFix(codeAction, diagnostic); - } + return context.Document.ReplaceNodeAsync(objectCreationExpression, newObjectCreationExpression, ct); + }, + GetEquivalenceKey(diagnostic)); - break; + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs index 31554c835c..c3e10bebbd 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ParameterCodeFixProvider.cs @@ -40,60 +40,60 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0225_ParamsParameterMustBeSingleDimensionalArray: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeOfParamsParameter, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeTypeOfParamsParameter, context.Document, root.SyntaxTree)) + break; - TypeSyntax type = parameter.Type; + TypeSyntax type = parameter.Type; - if (type?.IsMissing == false) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (type?.IsMissing == false) + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); - if (typeSymbol?.Kind == SymbolKind.NamedType - && typeSymbol.SupportsExplicitDeclaration()) - { - ArrayTypeSyntax newType = ArrayType( - typeSymbol.ToMinimalTypeSyntax(semanticModel, parameter.SpanStart), - SingletonList(ArrayRankSpecifier())); + if (typeSymbol?.Kind == SymbolKind.NamedType + && typeSymbol.SupportsExplicitDeclaration()) + { + ArrayTypeSyntax newType = ArrayType( + typeSymbol.ToMinimalTypeSyntax(semanticModel, parameter.SpanStart), + SingletonList(ArrayRankSpecifier())); - CodeAction codeAction = CodeAction.Create( - $"Change parameter type to '{newType}'", - ct => context.Document.ReplaceNodeAsync(type, newType.WithTriviaFrom(type), ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + $"Change parameter type to '{newType}'", + ct => context.Document.ReplaceNodeAsync(type, newType.WithTriviaFrom(type), ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } - - break; } + + break; + } case CompilerDiagnosticIdentifiers.CS1751_CannotSpecifyDefaultValueForParameterArray: case CompilerDiagnosticIdentifiers.CS1741_RefOrOutParameterCannotHaveDefaultValue: case CompilerDiagnosticIdentifiers.CS1743_CannotSpecifyDefaultValueForThisParameter: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveDefaultValueFromParameter, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveDefaultValueFromParameter, context.Document, root.SyntaxTree)) + break; - EqualsValueClauseSyntax defaultValue = parameter.Default; + EqualsValueClauseSyntax defaultValue = parameter.Default; - CodeAction codeAction = CodeAction.Create( - "Remove default value from parameter", - ct => - { - ParameterSyntax newParameter = parameter - .RemoveNode(defaultValue) - .WithFormatterAnnotation(); + CodeAction codeAction = CodeAction.Create( + "Remove default value from parameter", + ct => + { + ParameterSyntax newParameter = parameter + .RemoveNode(defaultValue) + .WithFormatterAnnotation(); - return context.Document.ReplaceNodeAsync(parameter, newParameter, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(parameter, newParameter, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/RemoveImplementationFromAbstractMemberCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/RemoveImplementationFromAbstractMemberCodeFixProvider.cs index 7bc2adc535..aac80026bf 100644 --- a/src/CodeFixes/CSharp/CodeFixes/RemoveImplementationFromAbstractMemberCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/RemoveImplementationFromAbstractMemberCodeFixProvider.cs @@ -63,76 +63,76 @@ private static Task RefactorAsync( switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; + { + var methodDeclaration = (MethodDeclarationSyntax)node; - MethodDeclarationSyntax newNode = methodDeclaration - .WithBody(null) - .WithExpressionBody(null) - .WithSemicolonToken(SemicolonToken()) - .WithFormatterAnnotation(); + MethodDeclarationSyntax newNode = methodDeclaration + .WithBody(null) + .WithExpressionBody(null) + .WithSemicolonToken(SemicolonToken()) + .WithFormatterAnnotation(); - return document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken); + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; - ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - - PropertyDeclarationSyntax newNode = propertyDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default(SyntaxToken)) - .WithAccessorList(AccessorList(AutoGetAccessorDeclaration()).WithTriviaFrom(expressionBody)) - .WithFormatterAnnotation(); - - return document.ReplaceNodeAsync(propertyDeclaration, newNode, cancellationToken); - } + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; + ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; + + PropertyDeclarationSyntax newNode = propertyDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default(SyntaxToken)) + .WithAccessorList(AccessorList(AutoGetAccessorDeclaration()).WithTriviaFrom(expressionBody)) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(propertyDeclaration, newNode, cancellationToken); + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; - ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; - - IndexerDeclarationSyntax newNode = indexerDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default(SyntaxToken)) - .WithAccessorList(AccessorList(AutoGetAccessorDeclaration()).WithTriviaFrom(expressionBody)) - .WithFormatterAnnotation(); - - return document.ReplaceNodeAsync(indexerDeclaration, newNode, cancellationToken); - } + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; + ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; + + IndexerDeclarationSyntax newNode = indexerDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default(SyntaxToken)) + .WithAccessorList(AccessorList(AutoGetAccessorDeclaration()).WithTriviaFrom(expressionBody)) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(indexerDeclaration, newNode, cancellationToken); + } case SyntaxKind.EventDeclaration: - { - var eventDeclaration = (EventDeclarationSyntax)node; + { + var eventDeclaration = (EventDeclarationSyntax)node; - EventFieldDeclarationSyntax eventFieldDeclaration = EventFieldDeclaration( - eventDeclaration.AttributeLists, - eventDeclaration.Modifiers, - eventDeclaration.EventKeyword, - VariableDeclaration(eventDeclaration.Type, VariableDeclarator(eventDeclaration.Identifier)), - SemicolonToken()); + EventFieldDeclarationSyntax eventFieldDeclaration = EventFieldDeclaration( + eventDeclaration.AttributeLists, + eventDeclaration.Modifiers, + eventDeclaration.EventKeyword, + VariableDeclaration(eventDeclaration.Type, VariableDeclarator(eventDeclaration.Identifier)), + SemicolonToken()); - eventFieldDeclaration = eventFieldDeclaration.WithFormatterAnnotation(); + eventFieldDeclaration = eventFieldDeclaration.WithFormatterAnnotation(); - return document.ReplaceNodeAsync(eventDeclaration, eventFieldDeclaration, cancellationToken); - } + return document.ReplaceNodeAsync(eventDeclaration, eventFieldDeclaration, cancellationToken); + } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; - - AccessorDeclarationSyntax newAccessor = accessor - .WithBody(null) - .WithExpressionBody(null) - .WithSemicolonToken(SemicolonToken()) - .WithTrailingTrivia( - accessor.DescendantTrivia( - TextSpan.FromBounds( - accessor.BodyOrExpressionBody().SpanStart, - accessor.Span.End))) - .WithFormatterAnnotation(); - - return document.ReplaceNodeAsync(accessor, newAccessor, cancellationToken); - } + { + var accessor = (AccessorDeclarationSyntax)node; + + AccessorDeclarationSyntax newAccessor = accessor + .WithBody(null) + .WithExpressionBody(null) + .WithSemicolonToken(SemicolonToken()) + .WithTrailingTrivia( + accessor.DescendantTrivia( + TextSpan.FromBounds( + accessor.BodyOrExpressionBody().SpanStart, + accessor.Span.End))) + .WithFormatterAnnotation(); + + return document.ReplaceNodeAsync(accessor, newAccessor, cancellationToken); + } } Debug.Fail(""); diff --git a/src/CodeFixes/CSharp/CodeFixes/RemovePropertyOrFieldInitializerCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/RemovePropertyOrFieldInitializerCodeFixProvider.cs index b84191b313..10daa1ffdc 100644 --- a/src/CodeFixes/CSharp/CodeFixes/RemovePropertyOrFieldInitializerCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/RemovePropertyOrFieldInitializerCodeFixProvider.cs @@ -46,45 +46,45 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (GetNode(token)) { case PropertyDeclarationSyntax propertyDeclaration: - { - EqualsValueClauseSyntax initializer = propertyDeclaration.Initializer; - - CodeAction codeAction = CodeAction.Create( - Title, - ct => - { - PropertyDeclarationSyntax newNode = propertyDeclaration - .RemoveNode(initializer) - .WithSemicolonToken(default(SyntaxToken)) - .AppendToTrailingTrivia(propertyDeclaration.SemicolonToken.GetAllTrivia()) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemovePropertyOrFieldInitializer)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + EqualsValueClauseSyntax initializer = propertyDeclaration.Initializer; + + CodeAction codeAction = CodeAction.Create( + Title, + ct => + { + PropertyDeclarationSyntax newNode = propertyDeclaration + .RemoveNode(initializer) + .WithSemicolonToken(default(SyntaxToken)) + .AppendToTrailingTrivia(propertyDeclaration.SemicolonToken.GetAllTrivia()) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemovePropertyOrFieldInitializer)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case VariableDeclaratorSyntax variableDeclarator: - { - EqualsValueClauseSyntax initializer = variableDeclarator.Initializer; - - CodeAction codeAction = CodeAction.Create( - Title, - ct => - { - VariableDeclaratorSyntax newNode = variableDeclarator - .RemoveNode(initializer) - .WithFormatterAnnotation(); - - return context.Document.ReplaceNodeAsync(variableDeclarator, newNode, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemovePropertyOrFieldInitializer)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + EqualsValueClauseSyntax initializer = variableDeclarator.Initializer; + + CodeAction codeAction = CodeAction.Create( + Title, + ct => + { + VariableDeclaratorSyntax newNode = variableDeclarator + .RemoveNode(initializer) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(variableDeclarator, newNode, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemovePropertyOrFieldInitializer)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } static SyntaxNode GetNode(SyntaxToken token) diff --git a/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs index 5c65f57725..01b407cc31 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ReturnStatementCodeFixProvider.cs @@ -40,84 +40,84 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1622_CannotReturnValueFromIterator: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree)) + break; + + ExpressionSyntax expression = returnStatement.Expression; + + if (expression is not null) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, context.Document, root.SyntaxTree)) - break; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ExpressionSyntax expression = returnStatement.Expression; + ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); - if (expression is not null) + if (containingSymbol?.Kind == SymbolKind.Method) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); + var methodSymbol = (IMethodSymbol)containingSymbol; - if (containingSymbol?.Kind == SymbolKind.Method) - { - var methodSymbol = (IMethodSymbol)containingSymbol; + ITypeSymbol returnType = methodSymbol.ReturnType; - ITypeSymbol returnType = methodSymbol.ReturnType; + var replacementKind = SyntaxKind.None; - var replacementKind = SyntaxKind.None; + if (returnType.SpecialType == SpecialType.System_Collections_IEnumerable) + { + if (semanticModel + .GetTypeSymbol(expression, context.CancellationToken) + .OriginalDefinition + .IsIEnumerableOrIEnumerableOfT()) + { + replacementKind = SyntaxKind.ForEachStatement; + } + else + { + replacementKind = SyntaxKind.YieldReturnStatement; + } + } + else if (returnType.Kind == SymbolKind.NamedType) + { + var namedTypeSymbol = (INamedTypeSymbol)returnType; - if (returnType.SpecialType == SpecialType.System_Collections_IEnumerable) + if (namedTypeSymbol.OriginalDefinition.IsIEnumerableOfT()) { - if (semanticModel - .GetTypeSymbol(expression, context.CancellationToken) - .OriginalDefinition - .IsIEnumerableOrIEnumerableOfT()) - { - replacementKind = SyntaxKind.ForEachStatement; - } - else + if (semanticModel.IsImplicitConversion(expression, namedTypeSymbol.TypeArguments[0])) { replacementKind = SyntaxKind.YieldReturnStatement; } - } - else if (returnType.Kind == SymbolKind.NamedType) - { - var namedTypeSymbol = (INamedTypeSymbol)returnType; - - if (namedTypeSymbol.OriginalDefinition.IsIEnumerableOfT()) + else { - if (semanticModel.IsImplicitConversion(expression, namedTypeSymbol.TypeArguments[0])) - { - replacementKind = SyntaxKind.YieldReturnStatement; - } - else - { - replacementKind = SyntaxKind.ForEachStatement; - } + replacementKind = SyntaxKind.ForEachStatement; } } + } - if (replacementKind == SyntaxKind.YieldReturnStatement - || (replacementKind == SyntaxKind.ForEachStatement && !returnStatement.SpanContainsDirectives())) - { - CodeAction codeAction = CodeAction.Create( - "Use yield return instead of return", - ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, replacementKind, semanticModel, ct), - GetEquivalenceKey(diagnostic)); + if (replacementKind == SyntaxKind.YieldReturnStatement + || (replacementKind == SyntaxKind.ForEachStatement && !returnStatement.SpanContainsDirectives())) + { + CodeAction codeAction = CodeAction.Create( + "Use yield return instead of return", + ct => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, replacementKind, semanticModel, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - } + context.RegisterCodeFix(codeAction, diagnostic); } } - - break; } + + break; + } case CompilerDiagnosticIdentifiers.CS0127_SinceMethodReturnsVoidReturnKeywordMustNotBeFollowedByObjectExpression: case CompilerDiagnosticIdentifiers.CS1997_SinceMethodIsAsyncMethodThatReturnsTaskReturnKeywordMustNotBeFollowedByObjectExpression: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree)) - { - ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, returnStatement.Expression, semanticModel); - } - - break; + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression, context.Document, root.SyntaxTree)) + { + ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, returnStatement.Expression, semanticModel); } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs index edf639ebdd..c8ac220299 100644 --- a/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/ReturnTypeOfAsyncMethodMustBeVoidOrTaskOrTaskOfTCodeFixProvider.cs @@ -96,19 +96,19 @@ private static (bool containsReturnAwait, bool containsAwaitStatement) AnalyzeAw switch (descendant) { case ReturnStatementSyntax returnStatement: - { - if (returnStatement.Expression?.WalkDownParentheses().Kind() == SyntaxKind.AwaitExpression) - containsReturnAwait = true; + { + if (returnStatement.Expression?.WalkDownParentheses().Kind() == SyntaxKind.AwaitExpression) + containsReturnAwait = true; - break; - } + break; + } case ExpressionStatementSyntax expressionStatement: - { - if (expressionStatement.Expression?.Kind() == SyntaxKind.AwaitExpression) - containsAwaitStatement = true; + { + if (expressionStatement.Expression?.Kind() == SyntaxKind.AwaitExpression) + containsAwaitStatement = true; - break; - } + break; + } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs index b68125c7e0..595555bc21 100644 --- a/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/SimpleNameCodeFixProvider.cs @@ -119,51 +119,51 @@ private static ExpressionSyntax GetReturnExpression(SyntaxNode node) switch (node.Parent) { case MethodDeclarationSyntax methodDeclaration: + { + if (object.ReferenceEquals(node, methodDeclaration.ReturnType)) { - if (object.ReferenceEquals(node, methodDeclaration.ReturnType)) - { - ExpressionSyntax expression = methodDeclaration.ExpressionBody?.Expression; + ExpressionSyntax expression = methodDeclaration.ExpressionBody?.Expression; - if (expression is not null) - return expression; + if (expression is not null) + return expression; - StatementSyntax statement = methodDeclaration.Body?.SingleNonBlockStatementOrDefault(); + StatementSyntax statement = methodDeclaration.Body?.SingleNonBlockStatementOrDefault(); - return (statement as ReturnStatementSyntax)?.Expression; - } - - break; + return (statement as ReturnStatementSyntax)?.Expression; } + + break; + } case LocalFunctionStatementSyntax localFunction: + { + if (object.ReferenceEquals(node, localFunction.ReturnType)) { - if (object.ReferenceEquals(node, localFunction.ReturnType)) - { - ExpressionSyntax expression = localFunction.ExpressionBody?.Expression; - - if (expression is not null) - return expression; + ExpressionSyntax expression = localFunction.ExpressionBody?.Expression; - StatementSyntax statement = localFunction.Body?.SingleNonBlockStatementOrDefault(); + if (expression is not null) + return expression; - return (statement as ReturnStatementSyntax)?.Expression; - } + StatementSyntax statement = localFunction.Body?.SingleNonBlockStatementOrDefault(); - break; + return (statement as ReturnStatementSyntax)?.Expression; } + + break; + } case VariableDeclarationSyntax variableDeclaration: + { + if (object.ReferenceEquals(node, variableDeclaration.Type) + && node.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) { - if (object.ReferenceEquals(node, variableDeclaration.Type) - && node.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) - { - return variableDeclaration - .Variables - .SingleOrDefault(shouldThrow: false)? - .Initializer? - .Value; - } - - break; + return variableDeclaration + .Variables + .SingleOrDefault(shouldThrow: false)? + .Initializer? + .Value; } + + break; + } } return null; diff --git a/src/CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs index 243439831c..bb2215331c 100644 --- a/src/CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/StatementCodeFixProvider.cs @@ -38,87 +38,87 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS1522_EmptySwitchBlock: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveEmptySwitchStatement, context.Document, root.SyntaxTree)) - break; - - if (statement is not SwitchStatementSyntax switchStatement) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveEmptySwitchStatement, context.Document, root.SyntaxTree)) + break; - CodeFixRegistrator.RemoveStatement(context, diagnostic, switchStatement); + if (statement is not SwitchStatementSyntax switchStatement) break; - } + + CodeFixRegistrator.RemoveStatement(context, diagnostic, switchStatement); + break; + } case CompilerDiagnosticIdentifiers.CS0139_NoEnclosingLoopOutOfWhichToBreakOrContinue: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveJumpStatement, context.Document, root.SyntaxTree)) + CodeFixRegistrator.RemoveStatement(context, diagnostic, statement); + + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceBreakWithContinue, context.Document, root.SyntaxTree) + && statement.Kind() == SyntaxKind.BreakStatement) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveJumpStatement, context.Document, root.SyntaxTree)) - CodeFixRegistrator.RemoveStatement(context, diagnostic, statement); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceBreakWithContinue, context.Document, root.SyntaxTree) - && statement.Kind() == SyntaxKind.BreakStatement) + if (semanticModel.GetEnclosingSymbol(statement.SpanStart, context.CancellationToken) is IMethodSymbol methodSymbol) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - if (semanticModel.GetEnclosingSymbol(statement.SpanStart, context.CancellationToken) is IMethodSymbol methodSymbol) + if (methodSymbol.ReturnsVoid + || (methodSymbol.IsAsync && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task))) { - if (methodSymbol.ReturnsVoid - || (methodSymbol.IsAsync && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task))) - { - CodeAction codeAction = CodeAction.Create( - "Replace 'break' with 'return'", - ct => - { - var breakStatement = (BreakStatementSyntax)statement; - SyntaxToken breakKeyword = breakStatement.BreakKeyword; - - ReturnStatementSyntax newStatement = SyntaxFactory.ReturnStatement( - SyntaxFactory.Token(breakKeyword.LeadingTrivia, SyntaxKind.ReturnKeyword, breakKeyword.TrailingTrivia), - null, - breakStatement.SemicolonToken); - - return context.Document.ReplaceNodeAsync(statement, newStatement, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceBreakWithContinue)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + CodeAction codeAction = CodeAction.Create( + "Replace 'break' with 'return'", + ct => + { + var breakStatement = (BreakStatementSyntax)statement; + SyntaxToken breakKeyword = breakStatement.BreakKeyword; + + ReturnStatementSyntax newStatement = SyntaxFactory.ReturnStatement( + SyntaxFactory.Token(breakKeyword.LeadingTrivia, SyntaxKind.ReturnKeyword, breakKeyword.TrailingTrivia), + null, + breakStatement.SemicolonToken); + + return context.Document.ReplaceNodeAsync(statement, newStatement, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceBreakWithContinue)); + + context.RegisterCodeFix(codeAction, diagnostic); } } + } - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveJumpStatement, context.Document, root.SyntaxTree)) - CodeFixRegistrator.RemoveStatement(context, diagnostic, statement); + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveJumpStatement, context.Document, root.SyntaxTree)) + CodeFixRegistrator.RemoveStatement(context, diagnostic, statement); - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceBreakWithContinue, context.Document, root.SyntaxTree) - && statement.Kind() == SyntaxKind.BreakStatement) + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceBreakWithContinue, context.Document, root.SyntaxTree) + && statement.Kind() == SyntaxKind.BreakStatement) + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (semanticModel.GetEnclosingSymbol(statement.SpanStart, context.CancellationToken) is IMethodSymbol methodSymbol) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (semanticModel.GetEnclosingSymbol(statement.SpanStart, context.CancellationToken) is IMethodSymbol methodSymbol) + if (methodSymbol.ReturnsVoid + || (methodSymbol.IsAsync && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task))) { - if (methodSymbol.ReturnsVoid - || (methodSymbol.IsAsync && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task))) - { - CodeAction codeAction = CodeAction.Create( - "Replace 'break' with 'return'", - ct => - { - var breakStatement = (BreakStatementSyntax)statement; - SyntaxToken breakKeyword = breakStatement.BreakKeyword; - - ReturnStatementSyntax newStatement = SyntaxFactory.ReturnStatement( - SyntaxFactory.Token(breakKeyword.LeadingTrivia, SyntaxKind.ReturnKeyword, breakKeyword.TrailingTrivia), - null, - breakStatement.SemicolonToken); - - return context.Document.ReplaceNodeAsync(statement, newStatement, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceBreakWithContinue)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + CodeAction codeAction = CodeAction.Create( + "Replace 'break' with 'return'", + ct => + { + var breakStatement = (BreakStatementSyntax)statement; + SyntaxToken breakKeyword = breakStatement.BreakKeyword; + + ReturnStatementSyntax newStatement = SyntaxFactory.ReturnStatement( + SyntaxFactory.Token(breakKeyword.LeadingTrivia, SyntaxKind.ReturnKeyword, breakKeyword.TrailingTrivia), + null, + breakStatement.SemicolonToken); + + return context.Document.ReplaceNodeAsync(statement, newStatement, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.ReplaceBreakWithContinue)); + + context.RegisterCodeFix(codeAction, diagnostic); } } - - break; } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs index eef8a91ca4..ef3df5a461 100644 --- a/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/SyntaxErrorCharExpectedCodeFixProvider.cs @@ -42,27 +42,27 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (expression.Parent.Kind()) { case SyntaxKind.ArrayInitializerExpression: - { - var initializer = (InitializerExpressionSyntax)expression.Parent; + { + var initializer = (InitializerExpressionSyntax)expression.Parent; - SeparatedSyntaxList expressions = initializer.Expressions; + SeparatedSyntaxList expressions = initializer.Expressions; - position = FindMissingCommaPosition(expressions, expression); - break; - } + position = FindMissingCommaPosition(expressions, expression); + break; + } case SyntaxKind.EqualsValueClause: - { - var equalsValueClause = (EqualsValueClauseSyntax)expression.Parent; - - if (equalsValueClause.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration) - { - var enumDeclaration = (EnumDeclarationSyntax)enumMemberDeclaration.Parent; + { + var equalsValueClause = (EqualsValueClauseSyntax)expression.Parent; - position = FindMissingCommaPosition(enumDeclaration.Members, enumMemberDeclaration); - } + if (equalsValueClause.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration) + { + var enumDeclaration = (EnumDeclarationSyntax)enumMemberDeclaration.Parent; - break; + position = FindMissingCommaPosition(enumDeclaration.Members, enumMemberDeclaration); } + + break; + } } if (position == -1) diff --git a/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs index d16bcc1cb9..7cbe1389af 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TokenCodeFixProvider.cs @@ -61,637 +61,637 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0023_OperatorCannotBeAppliedToOperand: + { + if (kind == SyntaxKind.QuestionToken + && token.Parent is ConditionalAccessExpressionSyntax conditionalAccess) { - if (kind == SyntaxKind.QuestionToken - && token.Parent is ConditionalAccessExpressionSyntax conditionalAccess) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(conditionalAccess.Expression, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(conditionalAccess.Expression, context.CancellationToken); - if (typeSymbol?.IsErrorType() == false - && !typeSymbol.IsNullableType()) + if (typeSymbol?.IsErrorType() == false + && !typeSymbol.IsNullableType()) + { + if (typeSymbol.IsValueType) { - if (typeSymbol.IsValueType) + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConditionalAccess, document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConditionalAccess, document, root.SyntaxTree)) - { - CodeAction codeAction = CodeAction.Create( - "Remove '?' operator", - ct => document.WithTextChangeAsync(token.Span, "", ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + CodeAction codeAction = CodeAction.Create( + "Remove '?' operator", + ct => document.WithTextChangeAsync(token.Span, "", ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } - else if (typeSymbol.IsReferenceType) + } + else if (typeSymbol.IsReferenceType) + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, document, root.SyntaxTree) + && conditionalAccess.WhenNotNull is MemberBindingExpressionSyntax memberBindingExpression) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList, document, root.SyntaxTree) - && conditionalAccess.WhenNotNull is MemberBindingExpressionSyntax memberBindingExpression) - { - ConditionalAccessExpressionSyntax newNode = conditionalAccess.WithWhenNotNull( - InvocationExpression( - memberBindingExpression.WithoutTrailingTrivia(), - ArgumentList().WithTrailingTrivia(memberBindingExpression.GetTrailingTrivia()))); - - CodeAction codeAction = CodeAction.Create( - "Add argument list", - ct => document.ReplaceNodeAsync(conditionalAccess, newNode, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } + ConditionalAccessExpressionSyntax newNode = conditionalAccess.WithWhenNotNull( + InvocationExpression( + memberBindingExpression.WithoutTrailingTrivia(), + ArgumentList().WithTrailingTrivia(memberBindingExpression.GetTrailingTrivia()))); + + CodeAction codeAction = CodeAction.Create( + "Add argument list", + ct => document.ReplaceNodeAsync(conditionalAccess, newNode, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); } } } - - break; } - case CompilerDiagnosticIdentifiers.CS0267_PartialModifierCanOnlyAppearImmediatelyBeforeClassStructInterfaceOrVoid: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.OrderModifiers, document, root.SyntaxTree)) - break; - ModifiersCodeFixRegistrator.MoveModifier(context, diagnostic, token.Parent, token); + break; + } + case CompilerDiagnosticIdentifiers.CS0267_PartialModifierCanOnlyAppearImmediatelyBeforeClassStructInterfaceOrVoid: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.OrderModifiers, document, root.SyntaxTree)) break; - } + + ModifiersCodeFixRegistrator.MoveModifier(context, diagnostic, token.Parent, token); + break; + } case CompilerDiagnosticIdentifiers.CS1750_ValueCannotBeUsedAsDefaultParameter: - { - if (token.Parent is not ParameterSyntax parameter) - break; + { + if (token.Parent is not ParameterSyntax parameter) + break; - ExpressionSyntax value = parameter.Default?.Value; + ExpressionSyntax value = parameter.Default?.Value; - if (value is null) - break; + if (value is null) + break; - if (value.IsKind(SyntaxKind.NullLiteralExpression)) + if (value.IsKind(SyntaxKind.NullLiteralExpression)) + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue, document, root.SyntaxTree)) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - CodeFixRegistrator.ReplaceNullWithDefaultValue(context, diagnostic, value, semanticModel); - } + CodeFixRegistrator.ReplaceNullWithDefaultValue(context, diagnostic, value, semanticModel); } - else if (!value.IsKind(SyntaxKind.DefaultExpression, SyntaxKind.DefaultLiteralExpression)) + } + else if (!value.IsKind(SyntaxKind.DefaultExpression, SyntaxKind.DefaultLiteralExpression)) + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeParameterType, document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeParameterType, document, root.SyntaxTree)) - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(value, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(value, context.CancellationToken); - if (!typeSymbol.IsKind(SymbolKind.ErrorType)) - { - CodeFixRegistrator.ChangeType(context, diagnostic, parameter.Type, typeSymbol, semanticModel); - } + if (!typeSymbol.IsKind(SymbolKind.ErrorType)) + { + CodeFixRegistrator.ChangeType(context, diagnostic, parameter.Type, typeSymbol, semanticModel); } } - - break; } - case CompilerDiagnosticIdentifiers.CS0126_ObjectOfTypeConvertibleToTypeIsRequired: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReturnDefaultValue, document, root.SyntaxTree)) - break; - if (!token.IsKind(SyntaxKind.ReturnKeyword)) - break; + break; + } + case CompilerDiagnosticIdentifiers.CS0126_ObjectOfTypeConvertibleToTypeIsRequired: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReturnDefaultValue, document, root.SyntaxTree)) + break; - if (!token.IsParentKind(SyntaxKind.ReturnStatement)) - break; + if (!token.IsKind(SyntaxKind.ReturnKeyword)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (!token.IsParentKind(SyntaxKind.ReturnStatement)) + break; - ISymbol symbol = semanticModel.GetEnclosingSymbol(token.SpanStart, context.CancellationToken); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (symbol is null) - break; + ISymbol symbol = semanticModel.GetEnclosingSymbol(token.SpanStart, context.CancellationToken); - SymbolKind symbolKind = symbol.Kind; + if (symbol is null) + break; - ITypeSymbol typeSymbol = null; + SymbolKind symbolKind = symbol.Kind; - if (symbolKind == SymbolKind.Method) - { - var methodSymbol = (IMethodSymbol)symbol; + ITypeSymbol typeSymbol = null; - typeSymbol = methodSymbol.ReturnType; + if (symbolKind == SymbolKind.Method) + { + var methodSymbol = (IMethodSymbol)symbol; - if (methodSymbol.IsAsync - && (typeSymbol is INamedTypeSymbol namedTypeSymbol)) - { - ImmutableArray typeArguments = namedTypeSymbol.TypeArguments; + typeSymbol = methodSymbol.ReturnType; - if (typeArguments.Any()) - typeSymbol = typeArguments[0]; - } - } - else if (symbolKind == SymbolKind.Property) + if (methodSymbol.IsAsync + && (typeSymbol is INamedTypeSymbol namedTypeSymbol)) { - typeSymbol = ((IPropertySymbol)symbol).Type; - } - else - { - Debug.Fail(symbolKind.ToString()); + ImmutableArray typeArguments = namedTypeSymbol.TypeArguments; + + if (typeArguments.Any()) + typeSymbol = typeArguments[0]; } + } + else if (symbolKind == SymbolKind.Property) + { + typeSymbol = ((IPropertySymbol)symbol).Type; + } + else + { + Debug.Fail(symbolKind.ToString()); + } - if (typeSymbol is null) - break; + if (typeSymbol is null) + break; - if (typeSymbol.Kind == SymbolKind.ErrorType) - break; + if (typeSymbol.Kind == SymbolKind.ErrorType) + break; - if (!typeSymbol.SupportsExplicitDeclaration()) - break; + if (!typeSymbol.SupportsExplicitDeclaration()) + break; - var returnStatement = (ReturnStatementSyntax)token.Parent; + var returnStatement = (ReturnStatementSyntax)token.Parent; - CodeAction codeAction = CodeAction.Create( - "Return default value", - ct => + CodeAction codeAction = CodeAction.Create( + "Return default value", + ct => + { + ExpressionSyntax expression = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); + + if (expression.IsKind(SyntaxKind.DefaultExpression) + && document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) { - ExpressionSyntax expression = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); + expression = CSharpFactory.DefaultLiteralExpression().WithTriviaFrom(expression); + } - if (expression.IsKind(SyntaxKind.DefaultExpression) - && document.SupportsLanguageFeature(CSharpLanguageFeature.DefaultLiteral)) - { - expression = CSharpFactory.DefaultLiteralExpression().WithTriviaFrom(expression); - } + ReturnStatementSyntax newNode = returnStatement.WithExpression(expression); - ReturnStatementSyntax newNode = returnStatement.WithExpression(expression); + return document.ReplaceNodeAsync(returnStatement, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - return document.ReplaceNodeAsync(returnStatement, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS1031_TypeExpected: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddMissingType, document, root.SyntaxTree)) + break; - context.RegisterCodeFix(codeAction, diagnostic); + if (!token.IsKind(SyntaxKind.CloseParenToken)) break; - } - case CompilerDiagnosticIdentifiers.CS1031_TypeExpected: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddMissingType, document, root.SyntaxTree)) - break; - if (!token.IsKind(SyntaxKind.CloseParenToken)) - break; + if (token.Parent is not DefaultExpressionSyntax defaultExpression) + break; - if (token.Parent is not DefaultExpressionSyntax defaultExpression) - break; + if (defaultExpression.Type is not IdentifierNameSyntax identifierName) + break; - if (defaultExpression.Type is not IdentifierNameSyntax identifierName) - break; + if (!identifierName.IsMissing) + break; - if (!identifierName.IsMissing) - break; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + TypeInfo typeInfo = semanticModel.GetTypeInfo(defaultExpression, context.CancellationToken); - TypeInfo typeInfo = semanticModel.GetTypeInfo(defaultExpression, context.CancellationToken); + ITypeSymbol convertedType = typeInfo.ConvertedType; - ITypeSymbol convertedType = typeInfo.ConvertedType; + if (convertedType?.SupportsExplicitDeclaration() != true) + break; - if (convertedType?.SupportsExplicitDeclaration() != true) - break; + CodeAction codeAction = CodeAction.Create( + $"Add type '{SymbolDisplay.ToMinimalDisplayString(convertedType, semanticModel, defaultExpression.SpanStart, SymbolDisplayFormats.DisplayName)}'", + ct => + { + TypeSyntax newType = convertedType.ToTypeSyntax() + .WithTriviaFrom(identifierName) + .WithFormatterAndSimplifierAnnotation(); - CodeAction codeAction = CodeAction.Create( - $"Add type '{SymbolDisplay.ToMinimalDisplayString(convertedType, semanticModel, defaultExpression.SpanStart, SymbolDisplayFormats.DisplayName)}'", - ct => - { - TypeSyntax newType = convertedType.ToTypeSyntax() - .WithTriviaFrom(identifierName) - .WithFormatterAndSimplifierAnnotation(); + return document.ReplaceNodeAsync(identifierName, newType, ct); + }, + GetEquivalenceKey(diagnostic)); - return document.ReplaceNodeAsync(identifierName, newType, ct); - }, - GetEquivalenceKey(diagnostic)); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS1597_SemicolonAfterMethodOrAccessorBlockIsNotValid: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveSemicolon, document, root.SyntaxTree)) + break; - context.RegisterCodeFix(codeAction, diagnostic); + if (!token.IsKind(SyntaxKind.SemicolonToken)) break; - } - case CompilerDiagnosticIdentifiers.CS1597_SemicolonAfterMethodOrAccessorBlockIsNotValid: + + switch (token.Parent) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveSemicolon, document, root.SyntaxTree)) - break; + case MethodDeclarationSyntax methodDeclaration: + { + BlockSyntax body = methodDeclaration.Body; - if (!token.IsKind(SyntaxKind.SemicolonToken)) - break; + if (body is null) + break; - switch (token.Parent) - { - case MethodDeclarationSyntax methodDeclaration: + CodeAction codeAction = CodeAction.Create( + "Remove semicolon", + ct => { - BlockSyntax body = methodDeclaration.Body; + SyntaxTriviaList trivia = body + .GetTrailingTrivia() + .EmptyIfWhitespace() + .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) + .AddRange(token.TrailingTrivia); - if (body is null) - break; + MethodDeclarationSyntax newNode = methodDeclaration + .WithBody(body.WithTrailingTrivia(trivia)) + .WithSemicolonToken(default(SyntaxToken)); - CodeAction codeAction = CodeAction.Create( - "Remove semicolon", - ct => - { - SyntaxTriviaList trivia = body - .GetTrailingTrivia() - .EmptyIfWhitespace() - .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) - .AddRange(token.TrailingTrivia); - - MethodDeclarationSyntax newNode = methodDeclaration - .WithBody(body.WithTrailingTrivia(trivia)) - .WithSemicolonToken(default(SyntaxToken)); - - return document.ReplaceNodeAsync(methodDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(methodDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case PropertyDeclarationSyntax propertyDeclaration: + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case PropertyDeclarationSyntax propertyDeclaration: + { + AccessorListSyntax accessorList = propertyDeclaration.AccessorList; + + if (accessorList is null) + break; + + CodeAction codeAction = CodeAction.Create( + "Remove semicolon", + ct => { - AccessorListSyntax accessorList = propertyDeclaration.AccessorList; + SyntaxTriviaList trivia = accessorList + .GetTrailingTrivia() + .EmptyIfWhitespace() + .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) + .AddRange(token.TrailingTrivia); - if (accessorList is null) - break; + PropertyDeclarationSyntax newNode = propertyDeclaration + .WithAccessorList(accessorList.WithTrailingTrivia(trivia)) + .WithSemicolonToken(default(SyntaxToken)); - CodeAction codeAction = CodeAction.Create( - "Remove semicolon", - ct => - { - SyntaxTriviaList trivia = accessorList - .GetTrailingTrivia() - .EmptyIfWhitespace() - .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) - .AddRange(token.TrailingTrivia); - - PropertyDeclarationSyntax newNode = propertyDeclaration - .WithAccessorList(accessorList.WithTrailingTrivia(trivia)) - .WithSemicolonToken(default(SyntaxToken)); - - return document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(propertyDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } - case AccessorDeclarationSyntax accessorDeclaration: + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case AccessorDeclarationSyntax accessorDeclaration: + { + BlockSyntax body = accessorDeclaration.Body; + + if (body is null) + break; + + CodeAction codeAction = CodeAction.Create( + "Remove semicolon", + ct => { - BlockSyntax body = accessorDeclaration.Body; + SyntaxTriviaList trivia = body + .GetTrailingTrivia() + .EmptyIfWhitespace() + .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) + .AddRange(token.TrailingTrivia); - if (body is null) - break; + AccessorDeclarationSyntax newNode = accessorDeclaration + .WithBody(body.WithTrailingTrivia(trivia)) + .WithSemicolonToken(default(SyntaxToken)); - CodeAction codeAction = CodeAction.Create( - "Remove semicolon", - ct => - { - SyntaxTriviaList trivia = body - .GetTrailingTrivia() - .EmptyIfWhitespace() - .AddRange(token.LeadingTrivia.EmptyIfWhitespace()) - .AddRange(token.TrailingTrivia); - - AccessorDeclarationSyntax newNode = accessorDeclaration - .WithBody(body.WithTrailingTrivia(trivia)) - .WithSemicolonToken(default(SyntaxToken)); - - return document.ReplaceNodeAsync(accessorDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(accessorDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; } - - break; } + + break; + } case CompilerDiagnosticIdentifiers.CS0030_CannotConvertType: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeForEachType, document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ChangeForEachType, document, root.SyntaxTree)) + break; - if (!token.IsKind(SyntaxKind.ForEachKeyword)) - break; + if (!token.IsKind(SyntaxKind.ForEachKeyword)) + break; - if (token.Parent is not ForEachStatementSyntax forEachStatement) - break; + if (token.Parent is not ForEachStatementSyntax forEachStatement) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); + ForEachStatementInfo info = semanticModel.GetForEachStatementInfo(forEachStatement); - ITypeSymbol typeSymbol = info.ElementType; + ITypeSymbol typeSymbol = info.ElementType; - if (typeSymbol.SupportsExplicitDeclaration()) - CodeFixRegistrator.ChangeType(context, diagnostic, forEachStatement.Type, typeSymbol, semanticModel, CodeFixIdentifiers.ChangeForEachType); + if (typeSymbol.SupportsExplicitDeclaration()) + CodeFixRegistrator.ChangeType(context, diagnostic, forEachStatement.Type, typeSymbol, semanticModel, CodeFixIdentifiers.ChangeForEachType); - CodeFixRegistrator.ChangeTypeToVar(context, diagnostic, forEachStatement.Type, CodeFixIdentifiers.ChangeTypeToVar); - break; - } + CodeFixRegistrator.ChangeTypeToVar(context, diagnostic, forEachStatement.Type, CodeFixIdentifiers.ChangeTypeToVar); + break; + } case CompilerDiagnosticIdentifiers.CS1737_OptionalParametersMustAppearAfterAllRequiredParameters: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddDefaultValueToParameter, document, root.SyntaxTree)) + break; + + if (token.Parent is not BaseParameterListSyntax parameterList) + break; + + SeparatedSyntaxList parameters = parameterList.Parameters; + + ParameterSyntax parameter = null; + + for (int i = 0; i < parameters.Count; i++) { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddDefaultValueToParameter, document, root.SyntaxTree)) - break; + ParameterSyntax p = parameters[i]; - if (token.Parent is not BaseParameterListSyntax parameterList) + if (p.FullSpan.End <= token.SpanStart) + { + parameter = p; + } + else + { break; + } + } - SeparatedSyntaxList parameters = parameterList.Parameters; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ParameterSyntax parameter = null; + IParameterSymbol parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, context.CancellationToken); - for (int i = 0; i < parameters.Count; i++) - { - ParameterSyntax p = parameters[i]; + ITypeSymbol typeSymbol = parameterSymbol.Type; - if (p.FullSpan.End <= token.SpanStart) - { - parameter = p; - } - else - { - break; - } - } + if (typeSymbol.Kind == SymbolKind.ErrorType) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + CodeAction codeAction = CodeAction.Create( + "Add default value", + ct => + { + ExpressionSyntax defaultValue = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); - IParameterSymbol parameterSymbol = semanticModel.GetDeclaredSymbol(parameter, context.CancellationToken); + ParameterSyntax newParameter = parameter + .WithDefault(EqualsValueClause(defaultValue).WithTrailingTrivia(parameter.GetTrailingTrivia())) + .WithoutTrailingTrivia() + .WithFormatterAnnotation(); - ITypeSymbol typeSymbol = parameterSymbol.Type; + return document.ReplaceNodeAsync(parameter, newParameter, ct); + }, + GetEquivalenceKey(diagnostic)); - if (typeSymbol.Kind == SymbolKind.ErrorType) - break; + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS8632_AnnotationForNullableReferenceTypesShouldOnlyBeUsedWithinNullableAnnotationsContext: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveAnnotationForNullableReferenceTypes, document, root.SyntaxTree)) + break; - CodeAction codeAction = CodeAction.Create( - "Add default value", - ct => - { - ExpressionSyntax defaultValue = typeSymbol.GetDefaultValueSyntax(document.GetDefaultSyntaxOptions()); + if (!token.IsKind(SyntaxKind.QuestionToken)) + return; - ParameterSyntax newParameter = parameter - .WithDefault(EqualsValueClause(defaultValue).WithTrailingTrivia(parameter.GetTrailingTrivia())) - .WithoutTrailingTrivia() - .WithFormatterAnnotation(); + CodeAction codeAction = CodeAction.Create( + "Remove 'nullable' annotation", + ct => + { + var textChange = new TextChange(token.Span, ""); - return document.ReplaceNodeAsync(parameter, newParameter, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.WithTextChangeAsync(textChange, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); + context.RegisterCodeFix(codeAction, diagnostic); + break; + } + case CompilerDiagnosticIdentifiers.CS8602_DereferenceOfPossiblyNullReference: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) break; - } - case CompilerDiagnosticIdentifiers.CS8632_AnnotationForNullableReferenceTypesShouldOnlyBeUsedWithinNullableAnnotationsContext: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveAnnotationForNullableReferenceTypes, document, root.SyntaxTree)) - break; - if (!token.IsKind(SyntaxKind.QuestionToken)) - return; + Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); + + if (!token.IsKind(SyntaxKind.IdentifierToken)) + return; + + if (!token.IsParentKind(SyntaxKind.IdentifierName)) + return; + SyntaxNode node = token.Parent + .WalkUp(f => f.IsKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression)) + .Parent; + + if (node.IsKind(SyntaxKind.ExpressionStatement) + && token.SpanStart == node.SpanStart) + { CodeAction codeAction = CodeAction.Create( - "Remove 'nullable' annotation", + "Use null propagation operator", ct => { - var textChange = new TextChange(token.Span, ""); + var textChange = new TextChange(new TextSpan(token.Span.End, 0), "?"); return document.WithTextChangeAsync(textChange, ct); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - break; } - case CompilerDiagnosticIdentifiers.CS8602_DereferenceOfPossiblyNullReference: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) - break; - Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); + return; + } + case CompilerDiagnosticIdentifiers.CS8604_PossibleNullReferenceArgumentForParameter: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) + break; - if (!token.IsKind(SyntaxKind.IdentifierToken)) - return; + Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); - if (!token.IsParentKind(SyntaxKind.IdentifierName)) - return; + if (!token.IsKind(SyntaxKind.IdentifierToken)) + return; - SyntaxNode node = token.Parent - .WalkUp(f => f.IsKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression)) - .Parent; + if (!token.IsParentKind(SyntaxKind.IdentifierName)) + return; - if (node.IsKind(SyntaxKind.ExpressionStatement) - && token.SpanStart == node.SpanStart) + CodeAction codeAction = CodeAction.Create( + "Use null-forgiving operator", + ct => { - CodeAction codeAction = CodeAction.Create( - "Use null propagation operator", - ct => - { - var textChange = new TextChange(new TextSpan(token.Span.End, 0), "?"); + var identifierName = (IdentifierNameSyntax)token.Parent; - return document.WithTextChangeAsync(textChange, ct); - }, - GetEquivalenceKey(diagnostic)); + PostfixUnaryExpressionSyntax newExpression = SuppressNullableWarningExpression(identifierName.WithoutTrivia()) + .WithTriviaFrom(identifierName); - context.RegisterCodeFix(codeAction, diagnostic); - } + return document.ReplaceNodeAsync(identifierName, newExpression, ct); + }, + GetEquivalenceKey(diagnostic)); - return; - } - case CompilerDiagnosticIdentifiers.CS8604_PossibleNullReferenceArgumentForParameter: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) - break; + context.RegisterCodeFix(codeAction, diagnostic); + return; + } + case CompilerDiagnosticIdentifiers.CS8618_NonNullableMemberIsUninitialized: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) + break; - Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); + Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); - if (!token.IsKind(SyntaxKind.IdentifierToken)) - return; - - if (!token.IsParentKind(SyntaxKind.IdentifierName)) - return; + if (!token.IsKind(SyntaxKind.IdentifierToken)) + return; + if (token.IsParentKind(SyntaxKind.PropertyDeclaration)) + { CodeAction codeAction = CodeAction.Create( "Use null-forgiving operator", ct => { - var identifierName = (IdentifierNameSyntax)token.Parent; + var property = (PropertyDeclarationSyntax)token.Parent; - PostfixUnaryExpressionSyntax newExpression = SuppressNullableWarningExpression(identifierName.WithoutTrivia()) - .WithTriviaFrom(identifierName); + PropertyDeclarationSyntax newProperty = property + .WithoutTrailingTrivia() + .WithInitializer(EqualsValueClause(SuppressNullableWarningExpression(NullLiteralExpression()))) + .WithSemicolonToken(SemicolonToken().WithTrailingTrivia(property.GetTrailingTrivia())); - return document.ReplaceNodeAsync(identifierName, newExpression, ct); + return document.ReplaceNodeAsync(property, newProperty, ct); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); - return; } - case CompilerDiagnosticIdentifiers.CS8618_NonNullableMemberIsUninitialized: + else { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, document, root.SyntaxTree)) - break; - - Debug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token.Kind().ToString()); - - if (!token.IsKind(SyntaxKind.IdentifierToken)) - return; + SyntaxDebug.Assert( + (token.IsParentKind(SyntaxKind.VariableDeclarator) + && token.Parent.IsParentKind(SyntaxKind.VariableDeclaration) + && token.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) + || token.IsParentKind(SyntaxKind.ConstructorDeclaration), + token); - if (token.IsParentKind(SyntaxKind.PropertyDeclaration)) + if (token.IsParentKind(SyntaxKind.VariableDeclarator) + && token.Parent.IsParentKind(SyntaxKind.VariableDeclaration) + && token.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) { CodeAction codeAction = CodeAction.Create( "Use null-forgiving operator", ct => { - var property = (PropertyDeclarationSyntax)token.Parent; + var declarator = (VariableDeclaratorSyntax)token.Parent; - PropertyDeclarationSyntax newProperty = property + VariableDeclaratorSyntax newDeclarator = declarator .WithoutTrailingTrivia() - .WithInitializer(EqualsValueClause(SuppressNullableWarningExpression(NullLiteralExpression()))) - .WithSemicolonToken(SemicolonToken().WithTrailingTrivia(property.GetTrailingTrivia())); + .WithInitializer( + EqualsValueClause(SuppressNullableWarningExpression(NullLiteralExpression())) + .WithTrailingTrivia(declarator.GetTrailingTrivia())); - return document.ReplaceNodeAsync(property, newProperty, ct); + return document.ReplaceNodeAsync(declarator, newDeclarator, ct); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } - else - { - SyntaxDebug.Assert( - (token.IsParentKind(SyntaxKind.VariableDeclarator) - && token.Parent.IsParentKind(SyntaxKind.VariableDeclaration) - && token.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration, SyntaxKind.EventFieldDeclaration)) - || token.IsParentKind(SyntaxKind.ConstructorDeclaration), - token); - - if (token.IsParentKind(SyntaxKind.VariableDeclarator) - && token.Parent.IsParentKind(SyntaxKind.VariableDeclaration) - && token.Parent.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) - { - CodeAction codeAction = CodeAction.Create( - "Use null-forgiving operator", - ct => - { - var declarator = (VariableDeclaratorSyntax)token.Parent; - - VariableDeclaratorSyntax newDeclarator = declarator - .WithoutTrailingTrivia() - .WithInitializer( - EqualsValueClause(SuppressNullableWarningExpression(NullLiteralExpression())) - .WithTrailingTrivia(declarator.GetTrailingTrivia())); - - return document.ReplaceNodeAsync(declarator, newDeclarator, ct); - }, - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - } - } - - break; } + + break; + } case CompilerDiagnosticIdentifiers.CS8403_MethodWithIteratorBlockMustBeAsyncToReturnIAsyncEnumerableOfT: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddAsyncModifier, document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddAsyncModifier, document, root.SyntaxTree)) + break; - SyntaxDebug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token); - SyntaxDebug.Assert(token.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement), token.Parent); + SyntaxDebug.Assert(token.IsKind(SyntaxKind.IdentifierToken), token); + SyntaxDebug.Assert(token.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement), token.Parent); - if (token.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) - { - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - token.Parent, - SyntaxKind.AsyncKeyword, - additionalKey: CodeFixIdentifiers.AddAsyncModifier); - } - - break; + if (token.IsParentKind(SyntaxKind.MethodDeclaration, SyntaxKind.LocalFunctionStatement)) + { + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + token.Parent, + SyntaxKind.AsyncKeyword, + additionalKey: CodeFixIdentifiers.AddAsyncModifier); } + + break; + } case CompilerDiagnosticIdentifiers.CS8610_NullabilityOfReferenceTypesInTypeOfParameterDoesNotMatchOverriddenMember: case CompilerDiagnosticIdentifiers.CS8765_NullabilityOfTypeOfParameterDoesNotMatchOverriddenMember: case CompilerDiagnosticIdentifiers.CS8767_NullabilityDoesNotMatchImplementedMember: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNullableAnnotation, document, root.SyntaxTree)) - break; - - if (token.Parent is not MemberDeclarationSyntax memberDeclaration) - return; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNullableAnnotation, document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (token.Parent is not MemberDeclarationSyntax memberDeclaration) + return; - ISymbol symbol = semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (symbol is null) - return; + ISymbol symbol = semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); - ISymbol baseSymbol = null; - if (diagnostic.Id == CompilerDiagnosticIdentifiers.CS8767_NullabilityDoesNotMatchImplementedMember) - { - using IEnumerator en = symbol.FindImplementedInterfaceMembers().GetEnumerator(); + if (symbol is null) + return; - if (en.MoveNext()) - { - baseSymbol = en.Current; + ISymbol baseSymbol = null; + if (diagnostic.Id == CompilerDiagnosticIdentifiers.CS8767_NullabilityDoesNotMatchImplementedMember) + { + using IEnumerator en = symbol.FindImplementedInterfaceMembers().GetEnumerator(); - if (en.MoveNext()) - return; - } - } - else + if (en.MoveNext()) { - baseSymbol = symbol.OverriddenSymbol(); + baseSymbol = en.Current; - if (baseSymbol is null) + if (en.MoveNext()) return; } + } + else + { + baseSymbol = symbol.OverriddenSymbol(); - SeparatedSyntaxList parameters = CSharpUtility.GetParameters(memberDeclaration); + if (baseSymbol is null) + return; + } - ImmutableArray parameterSymbols = symbol.GetParameters(); + SeparatedSyntaxList parameters = CSharpUtility.GetParameters(memberDeclaration); - if (parameters.Count != parameterSymbols.Length) - return; + ImmutableArray parameterSymbols = symbol.GetParameters(); + + if (parameters.Count != parameterSymbols.Length) + return; - ImmutableArray parametersSymbols2 = baseSymbol.GetParameters(); + ImmutableArray parametersSymbols2 = baseSymbol.GetParameters(); - if (parameters.Count != parametersSymbols2.Length) - return; + if (parameters.Count != parametersSymbols2.Length) + return; - MemberDeclarationSyntax newNode = memberDeclaration; - int offset = 0; + MemberDeclarationSyntax newNode = memberDeclaration; + int offset = 0; - for (int i = parameters.Count - 1; i >= 0; i--) + for (int i = parameters.Count - 1; i >= 0; i--) + { + if (!SymbolEqualityComparer.IncludeNullability.Equals(parameterSymbols[i].Type, parametersSymbols2[i].Type)) { - if (!SymbolEqualityComparer.IncludeNullability.Equals(parameterSymbols[i].Type, parametersSymbols2[i].Type)) - { - var parameter = (BaseParameterSyntax)newNode.FindNode(parameters[i].Span.Offset(-offset)); + var parameter = (BaseParameterSyntax)newNode.FindNode(parameters[i].Span.Offset(-offset)); - TypeSyntax newType = parametersSymbols2[i].Type.ToTypeSyntax() - .WithTriviaFrom(parameter.Type) - .WithSimplifierAnnotation(); + TypeSyntax newType = parametersSymbols2[i].Type.ToTypeSyntax() + .WithTriviaFrom(parameter.Type) + .WithSimplifierAnnotation(); - if (newNode == memberDeclaration) - offset = newNode.FullSpan.Start; + if (newNode == memberDeclaration) + offset = newNode.FullSpan.Start; - newNode = newNode.ReplaceNode(parameter, parameter.WithType(newType)); - } + newNode = newNode.ReplaceNode(parameter, parameter.WithType(newType)); } + } - context.RegisterCodeFix( - CodeAction.Create( - "Declare as nullable", - ct => document.ReplaceNodeAsync(memberDeclaration, newNode, ct), - GetEquivalenceKey(diagnostic)), - diagnostic); + context.RegisterCodeFix( + CodeAction.Create( + "Declare as nullable", + ct => document.ReplaceNodeAsync(memberDeclaration, newNode, ct), + GetEquivalenceKey(diagnostic)), + diagnostic); - break; - } + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeDeclarationCodeFixProvider.cs index cdbc64af12..573a99ca72 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeDeclarationCodeFixProvider.cs @@ -42,57 +42,57 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0660_TypeDefinesEqualityOperatorButDoesNotOverrideObjectEquals: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.DefineObjectEquals, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.DefineObjectEquals, context.Document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - var typeSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken) as ITypeSymbol; + var typeSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken) as ITypeSymbol; - if (typeSymbol?.IsErrorType() != false) - break; + if (typeSymbol?.IsErrorType() != false) + break; - CodeAction codeAction = CodeAction.Create( - "Override object.Equals", - ct => - { - TypeSyntax type = typeSymbol.ToMinimalTypeSyntax(semanticModel, typeDeclaration.Identifier.SpanStart); + CodeAction codeAction = CodeAction.Create( + "Override object.Equals", + ct => + { + TypeSyntax type = typeSymbol.ToMinimalTypeSyntax(semanticModel, typeDeclaration.Identifier.SpanStart); - MethodDeclarationSyntax methodDeclaration = ObjectEqualsMethodDeclaration(type); + MethodDeclarationSyntax methodDeclaration = ObjectEqualsMethodDeclaration(type); - TypeDeclarationSyntax newNode = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); + TypeDeclarationSyntax newNode = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); - return context.Document.ReplaceNodeAsync(typeDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(typeDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0661_TypeDefinesEqualityOperatorButDoesNotOverrideObjectGetHashCode: case CompilerDiagnosticIdentifiers.CS0659_TypeOverridesObjectEqualsButDoesNotOverrideObjectGetHashCode: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.DefineObjectGetHashCode, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.DefineObjectGetHashCode, context.Document, root.SyntaxTree)) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - MethodDeclarationSyntax methodDeclaration = ObjectGetHashCodeMethodDeclaration(); + MethodDeclarationSyntax methodDeclaration = ObjectGetHashCodeMethodDeclaration(); - CodeAction codeAction = CodeAction.Create( - "Override object.GetHashCode", - ct => - { - TypeDeclarationSyntax newNode = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); + CodeAction codeAction = CodeAction.Create( + "Override object.GetHashCode", + ct => + { + TypeDeclarationSyntax newNode = MemberDeclarationInserter.Default.Insert(typeDeclaration, methodDeclaration); - return context.Document.ReplaceNodeAsync(typeDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(typeDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs index 7c867074b7..3ffed88962 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeDoesNotContainDefinitionCodeFixProvider.cs @@ -36,87 +36,87 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (expression) { case SimpleNameSyntax simpleName: - { - SyntaxDebug.Assert(expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.GenericName), expression); + { + SyntaxDebug.Assert(expression.IsKind(SyntaxKind.IdentifierName, SyntaxKind.GenericName), expression); - if (simpleName.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) - { - var memberAccessExpression = (MemberAccessExpressionSyntax)simpleName.Parent; + if (simpleName.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) + { + var memberAccessExpression = (MemberAccessExpressionSyntax)simpleName.Parent; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression)) + if (memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression)) + { + if (!memberAccessExpression.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression) + && IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceInvocationWithMemberAccessOrViceVersa, context.Document, root.SyntaxTree)) { - if (!memberAccessExpression.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression) - && IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceInvocationWithMemberAccessOrViceVersa, context.Document, root.SyntaxTree)) - { - var invocationExpression = (InvocationExpressionSyntax)memberAccessExpression.Parent; + var invocationExpression = (InvocationExpressionSyntax)memberAccessExpression.Parent; - if (!invocationExpression.ArgumentList.Arguments.Any()) - { - ReplaceInvocationWithMemberAccess(context, diagnostic, memberAccessExpression, invocationExpression, semanticModel); - } + if (!invocationExpression.ArgumentList.Arguments.Any()) + { + ReplaceInvocationWithMemberAccess(context, diagnostic, memberAccessExpression, invocationExpression, semanticModel); } } - else + } + else + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.FixMemberAccessName, context.Document, root.SyntaxTree)) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.FixMemberAccessName, context.Document, root.SyntaxTree)) - { - CodeFixRegistrationResult result = ReplaceCountWithLengthOrViceVersa(context, diagnostic, memberAccessExpression.Expression, simpleName, semanticModel); + CodeFixRegistrationResult result = ReplaceCountWithLengthOrViceVersa(context, diagnostic, memberAccessExpression.Expression, simpleName, semanticModel); - if (result.Success) - break; - } + if (result.Success) + break; + } - if (!memberAccessExpression.IsParentKind(SyntaxKind.ConditionalAccessExpression) - && IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceInvocationWithMemberAccessOrViceVersa, context.Document, root.SyntaxTree)) - { - ReplaceMemberAccessWithInvocation(context, diagnostic, memberAccessExpression, semanticModel); - } + if (!memberAccessExpression.IsParentKind(SyntaxKind.ConditionalAccessExpression) + && IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceInvocationWithMemberAccessOrViceVersa, context.Document, root.SyntaxTree)) + { + ReplaceMemberAccessWithInvocation(context, diagnostic, memberAccessExpression, semanticModel); } } - - break; } + + break; + } case MemberBindingExpressionSyntax memberBindingExpression: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.FixMemberAccessName, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.FixMemberAccessName, context.Document, root.SyntaxTree)) + break; - if (memberBindingExpression.Parent is not ConditionalAccessExpressionSyntax conditionalAccessExpression) - break; + if (memberBindingExpression.Parent is not ConditionalAccessExpressionSyntax conditionalAccessExpression) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - CodeFixRegistrationResult result = ReplaceCountWithLengthOrViceVersa(context, diagnostic, conditionalAccessExpression.Expression, memberBindingExpression.Name, semanticModel); + CodeFixRegistrationResult result = ReplaceCountWithLengthOrViceVersa(context, diagnostic, conditionalAccessExpression.Expression, memberBindingExpression.Name, semanticModel); - break; - } + break; + } case AwaitExpressionSyntax awaitExpression: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveAwaitKeyword, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveAwaitKeyword, context.Document, root.SyntaxTree)) + break; - CodeAction codeAction = CodeAction.Create( - "Remove 'await'", - ct => - { - ExpressionSyntax expression2 = awaitExpression.Expression; + CodeAction codeAction = CodeAction.Create( + "Remove 'await'", + ct => + { + ExpressionSyntax expression2 = awaitExpression.Expression; - SyntaxTriviaList leadingTrivia = awaitExpression - .GetLeadingTrivia() - .AddRange(awaitExpression.AwaitKeyword.TrailingTrivia.EmptyIfWhitespace()) - .AddRange(expression2.GetLeadingTrivia().EmptyIfWhitespace()); + SyntaxTriviaList leadingTrivia = awaitExpression + .GetLeadingTrivia() + .AddRange(awaitExpression.AwaitKeyword.TrailingTrivia.EmptyIfWhitespace()) + .AddRange(expression2.GetLeadingTrivia().EmptyIfWhitespace()); - ExpressionSyntax newNode = expression2.WithLeadingTrivia(leadingTrivia); + ExpressionSyntax newNode = expression2.WithLeadingTrivia(leadingTrivia); - return document.ReplaceNodeAsync(awaitExpression, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(awaitExpression, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs index da0e900dd3..2958af5519 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintClauseCodeFixProvider.cs @@ -38,63 +38,63 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0080_ConstraintsAreNotAllowedOnNonGenericDeclarations: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraintClauses, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraintClauses, context.Document, root.SyntaxTree)) + break; - GenericInfo genericInfo = SyntaxInfo.GenericInfo(constraintClause); + GenericInfo genericInfo = SyntaxInfo.GenericInfo(constraintClause); - if (!genericInfo.Success) - break; + if (!genericInfo.Success) + break; - CodeAction codeAction = CodeAction.Create( - "Remove constraints", - ct => - { - GenericInfo newGenericInfo = genericInfo.RemoveAllConstraintClauses(); + CodeAction codeAction = CodeAction.Create( + "Remove constraints", + ct => + { + GenericInfo newGenericInfo = genericInfo.RemoveAllConstraintClauses(); - return context.Document.ReplaceNodeAsync(genericInfo.Node, newGenericInfo.Node, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(genericInfo.Node, newGenericInfo.Node, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case CompilerDiagnosticIdentifiers.CS0409_ConstraintClauseHasAlreadyBeenSpecified: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.CombineConstraintClauses, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.CombineConstraintClauses, context.Document, root.SyntaxTree)) + break; - GenericInfo genericInfo = SyntaxInfo.GenericInfo(constraintClause); + GenericInfo genericInfo = SyntaxInfo.GenericInfo(constraintClause); - int index = genericInfo.ConstraintClauses.IndexOf(constraintClause); + int index = genericInfo.ConstraintClauses.IndexOf(constraintClause); - string name = constraintClause.Name.Identifier.ValueText; + string name = constraintClause.Name.Identifier.ValueText; - TypeParameterConstraintClauseSyntax constraintClause2 = genericInfo.FindConstraintClause(name); + TypeParameterConstraintClauseSyntax constraintClause2 = genericInfo.FindConstraintClause(name); - if (constraintClause2 is null) - break; + if (constraintClause2 is null) + break; - CodeAction codeAction = CodeAction.Create( - $"Combine constraints for '{name}'", - ct => - { - TypeParameterConstraintClauseSyntax newConstraintClause = constraintClause2.WithConstraints(constraintClause2.Constraints.AddRange(constraintClause.Constraints)); + CodeAction codeAction = CodeAction.Create( + $"Combine constraints for '{name}'", + ct => + { + TypeParameterConstraintClauseSyntax newConstraintClause = constraintClause2.WithConstraints(constraintClause2.Constraints.AddRange(constraintClause.Constraints)); - SyntaxList newConstraintClauses = genericInfo.ConstraintClauses - .Replace(constraintClause2, newConstraintClause) - .RemoveAt(index); + SyntaxList newConstraintClauses = genericInfo.ConstraintClauses + .Replace(constraintClause2, newConstraintClause) + .RemoveAt(index); - GenericInfo newGenericInfo = genericInfo.WithConstraintClauses(newConstraintClauses); + GenericInfo newGenericInfo = genericInfo.WithConstraintClauses(newConstraintClauses); - return context.Document.ReplaceNodeAsync(genericInfo.Node, newGenericInfo.Node, ct); - }, - GetEquivalenceKey(diagnostic)); + return context.Document.ReplaceNodeAsync(genericInfo.Node, newGenericInfo.Node, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs index 1edcc82175..4f8303791d 100644 --- a/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/TypeParameterConstraintCodeFixProvider.cs @@ -42,88 +42,88 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0401_NewConstraintMustBeLastConstraintSpecified: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveConstraint, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveConstraint, context.Document, root.SyntaxTree)) + break; - TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); + TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); - if (!constraintInfo.Success) - break; + if (!constraintInfo.Success) + break; - MoveConstraint(context, diagnostic, constraintInfo, constraintInfo.Constraints.Count - 1); + MoveConstraint(context, diagnostic, constraintInfo, constraintInfo.Constraints.Count - 1); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0405_DuplicateConstraintForTypeParameter: - { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) - RemoveConstraint(context, diagnostic, constraint); + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) + RemoveConstraint(context, diagnostic, constraint); - break; - } + break; + } case CompilerDiagnosticIdentifiers.CS0449_ClassOrStructConstraintMustComeBeforeAnyOtherConstraints: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveConstraint, context.Document, root.SyntaxTree)) - break; - - TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); - - if (!constraintInfo.Success) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveConstraint, context.Document, root.SyntaxTree)) + break; - if (constraintInfo.IsDuplicateConstraint) - { - RemoveConstraint(context, diagnostic, constraint); - } - else - { - MoveConstraint(context, diagnostic, constraintInfo, 0); - } + TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); + if (!constraintInfo.Success) break; + + if (constraintInfo.IsDuplicateConstraint) + { + RemoveConstraint(context, diagnostic, constraint); } - case CompilerDiagnosticIdentifiers.CS0450_CannotSpecifyBothConstraintClassAndClassOrStructConstraint: + else { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) - break; + MoveConstraint(context, diagnostic, constraintInfo, 0); + } - TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); + break; + } + case CompilerDiagnosticIdentifiers.CS0450_CannotSpecifyBothConstraintClassAndClassOrStructConstraint: + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) + break; - if (!constraintInfo.Success) - break; + TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); - RemoveConstraint(context, diagnostic, constraint); + if (!constraintInfo.Success) + break; - TypeParameterConstraintSyntax classConstraint = constraintInfo.Constraints.Find(SyntaxKind.ClassConstraint); + RemoveConstraint(context, diagnostic, constraint); - if (classConstraint is not null) - RemoveConstraint(context, diagnostic, classConstraint); + TypeParameterConstraintSyntax classConstraint = constraintInfo.Constraints.Find(SyntaxKind.ClassConstraint); - TypeParameterConstraintSyntax structConstraint = constraintInfo.Constraints.Find(SyntaxKind.StructConstraint); + if (classConstraint is not null) + RemoveConstraint(context, diagnostic, classConstraint); - if (structConstraint is not null) - RemoveConstraint(context, diagnostic, structConstraint); + TypeParameterConstraintSyntax structConstraint = constraintInfo.Constraints.Find(SyntaxKind.StructConstraint); - break; - } + if (structConstraint is not null) + RemoveConstraint(context, diagnostic, structConstraint); + + break; + } case CompilerDiagnosticIdentifiers.CS0451_NewConstraintCannotBeUsedWithStructConstraint: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveConstraint, context.Document, root.SyntaxTree)) + break; - RemoveConstraint(context, diagnostic, constraint); + RemoveConstraint(context, diagnostic, constraint); - TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); + TypeParameterConstraintInfo constraintInfo = SyntaxInfo.TypeParameterConstraintInfo(constraint); - if (!constraintInfo.Success) - break; + if (!constraintInfo.Success) + break; - TypeParameterConstraintSyntax structConstraint = constraintInfo.Constraints.Find(SyntaxKind.StructConstraint); + TypeParameterConstraintSyntax structConstraint = constraintInfo.Constraints.Find(SyntaxKind.StructConstraint); - RemoveConstraint(context, diagnostic, structConstraint); - break; - } + RemoveConstraint(context, diagnostic, structConstraint); + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs index a69c6e4aac..57393fa52a 100644 --- a/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/UnreachableCodeCodeFixProvider.cs @@ -89,82 +89,82 @@ private static CodeAction CreateCodeActionForIfElse(Document document, Diagnosti switch (node?.Kind()) { case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)node; + { + var ifStatement = (IfStatementSyntax)node; - ElseClauseSyntax elseClause = ifStatement.Else; + ElseClauseSyntax elseClause = ifStatement.Else; - if (elseClause is not null - && ifStatement.IsParentKind(SyntaxKind.ElseClause)) - { - return CodeAction.Create( - Title, - cz => document.ReplaceNodeAsync(ifStatement.Parent, elseClause, cz), - GetEquivalenceKey(diagnostic)); - } + if (elseClause is not null + && ifStatement.IsParentKind(SyntaxKind.ElseClause)) + { + return CodeAction.Create( + Title, + cz => document.ReplaceNodeAsync(ifStatement.Parent, elseClause, cz), + GetEquivalenceKey(diagnostic)); + } - StatementSyntax statement = elseClause?.Statement; + StatementSyntax statement = elseClause?.Statement; - if (statement is not null) + if (statement is not null) + { + if (statement is BlockSyntax block) { - if (statement is BlockSyntax block) - { - SyntaxList statements = block.Statements; + SyntaxList statements = block.Statements; - if (statements.Any()) - { - return CreateCodeAction(document, diagnostic, ifStatement, statements); - } - } - else + if (statements.Any()) { - return CreateCodeAction(document, diagnostic, ifStatement, statement); + return CreateCodeAction(document, diagnostic, ifStatement, statements); } } - - return CodeAction.Create( - Title, - ct => document.RemoveStatementAsync(ifStatement, ct), - GetEquivalenceKey(diagnostic)); + else + { + return CreateCodeAction(document, diagnostic, ifStatement, statement); + } } + + return CodeAction.Create( + Title, + ct => document.RemoveStatementAsync(ifStatement, ct), + GetEquivalenceKey(diagnostic)); + } case SyntaxKind.ElseClause: + { + var elseClause = (ElseClauseSyntax)node; + + if (elseClause.IsParentKind(SyntaxKind.IfStatement)) { - var elseClause = (ElseClauseSyntax)node; + var ifStatement = (IfStatementSyntax)elseClause.Parent; - if (elseClause.IsParentKind(SyntaxKind.IfStatement)) + if (ifStatement.IsTopmostIf()) { - var ifStatement = (IfStatementSyntax)elseClause.Parent; + StatementSyntax statement = ifStatement.Statement; - if (ifStatement.IsTopmostIf()) + if (statement is not null) { - StatementSyntax statement = ifStatement.Statement; + if (statement is BlockSyntax block) + { + SyntaxList statements = block.Statements; - if (statement is not null) + if (statements.Any()) + return CreateCodeAction(document, diagnostic, ifStatement, statements); + } + else { - if (statement is BlockSyntax block) - { - SyntaxList statements = block.Statements; - - if (statements.Any()) - return CreateCodeAction(document, diagnostic, ifStatement, statements); - } - else - { - return CreateCodeAction(document, diagnostic, ifStatement, statement); - } + return CreateCodeAction(document, diagnostic, ifStatement, statement); } } } - - return CodeAction.Create( - Title, - ct => document.RemoveNodeAsync(elseClause, ct), - GetEquivalenceKey(diagnostic)); } + + return CodeAction.Create( + Title, + ct => document.RemoveNodeAsync(elseClause, ct), + GetEquivalenceKey(diagnostic)); + } case SyntaxKind.Block: - { - return CreateCodeActionForIfElse(document, diagnostic, node.Parent); - } + { + return CreateCodeActionForIfElse(document, diagnostic, node.Parent); + } } return null; diff --git a/src/CodeFixes/CSharp/CodeFixes/UnsafeCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/UnsafeCodeFixProvider.cs index a5e3304ed3..4ded98f88a 100644 --- a/src/CodeFixes/CSharp/CodeFixes/UnsafeCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/UnsafeCodeFixProvider.cs @@ -35,113 +35,113 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS0214_PointersAndFixedSizeBuffersMayOnlyBeUsedInUnsafeContext: + { + if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, document, root.SyntaxTree) + && node is StackAllocArrayCreationExpressionSyntax stackAllocArrayCreation + && node.IsParentKind(SyntaxKind.EqualsValueClause) + && node.Parent.IsParentKind(SyntaxKind.VariableDeclarator) + && node.Parent.Parent.Parent is VariableDeclarationSyntax variableDeclaration + && variableDeclaration.Type.IsVar) { - if (IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, document, root.SyntaxTree) - && node is StackAllocArrayCreationExpressionSyntax stackAllocArrayCreation - && node.IsParentKind(SyntaxKind.EqualsValueClause) - && node.Parent.IsParentKind(SyntaxKind.VariableDeclarator) - && node.Parent.Parent.Parent is VariableDeclarationSyntax variableDeclaration - && variableDeclaration.Type.IsVar) - { - TypeSyntax type = stackAllocArrayCreation.Type; + TypeSyntax type = stackAllocArrayCreation.Type; - if (type is ArrayTypeSyntax arrayType) - type = arrayType.ElementType; + if (type is ArrayTypeSyntax arrayType) + type = arrayType.ElementType; - CodeAction spanCodeAction = CodeAction.Create( - "Use Span", - ct => - { - TypeSyntax spanOfT = SyntaxFactory.ParseTypeName($"global::System.Span<{type}>") - .WithSimplifierAnnotation(); + CodeAction spanCodeAction = CodeAction.Create( + "Use Span", + ct => + { + TypeSyntax spanOfT = SyntaxFactory.ParseTypeName($"global::System.Span<{type}>") + .WithSimplifierAnnotation(); - return document.ReplaceNodeAsync(variableDeclaration.Type, spanOfT, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, "System_Span_T")); + return document.ReplaceNodeAsync(variableDeclaration.Type, spanOfT, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, "System_Span_T")); - context.RegisterCodeFix(spanCodeAction, diagnostic); + context.RegisterCodeFix(spanCodeAction, diagnostic); - CodeAction readOnlySpanCodeAction = CodeAction.Create( - "Use ReadOnlySpan", - ct => - { - TypeSyntax spanOfT = SyntaxFactory.ParseTypeName($"global::System.ReadOnlySpan<{type}>") - .WithSimplifierAnnotation(); + CodeAction readOnlySpanCodeAction = CodeAction.Create( + "Use ReadOnlySpan", + ct => + { + TypeSyntax spanOfT = SyntaxFactory.ParseTypeName($"global::System.ReadOnlySpan<{type}>") + .WithSimplifierAnnotation(); - return document.ReplaceNodeAsync(variableDeclaration.Type, spanOfT, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, "System_ReadOnlySpan_T")); + return document.ReplaceNodeAsync(variableDeclaration.Type, spanOfT, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, "System_ReadOnlySpan_T")); - context.RegisterCodeFix(readOnlySpanCodeAction, diagnostic); - } + context.RegisterCodeFix(readOnlySpanCodeAction, diagnostic); + } - var fStatement = false; - var fMemberDeclaration = false; + var fStatement = false; + var fMemberDeclaration = false; - foreach (SyntaxNode ancestor in node.AncestorsAndSelf()) + foreach (SyntaxNode ancestor in node.AncestorsAndSelf()) + { + if (fStatement + && fMemberDeclaration) { - if (fStatement - && fMemberDeclaration) - { - break; - } + break; + } - if (!fStatement - && ancestor is StatementSyntax statement) - { - fStatement = true; + if (!fStatement + && ancestor is StatementSyntax statement) + { + fStatement = true; - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.WrapInUnsafeStatement, document, root.SyntaxTree)) - continue; + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.WrapInUnsafeStatement, document, root.SyntaxTree)) + continue; - if (statement.IsKind(SyntaxKind.Block) - && statement.Parent is StatementSyntax statement2) - { - statement = statement2; - } + if (statement.IsKind(SyntaxKind.Block) + && statement.Parent is StatementSyntax statement2) + { + statement = statement2; + } - if (statement.IsKind(SyntaxKind.UnsafeStatement)) - break; + if (statement.IsKind(SyntaxKind.UnsafeStatement)) + break; - CodeAction codeAction = CodeAction.Create( - "Wrap in unsafe block", - ct => - { - BlockSyntax block = (statement.IsKind(SyntaxKind.Block)) - ? (BlockSyntax)statement - : SyntaxFactory.Block(statement); + CodeAction codeAction = CodeAction.Create( + "Wrap in unsafe block", + ct => + { + BlockSyntax block = (statement.IsKind(SyntaxKind.Block)) + ? (BlockSyntax)statement + : SyntaxFactory.Block(statement); - UnsafeStatementSyntax unsafeStatement = SyntaxFactory.UnsafeStatement(block).WithFormatterAnnotation(); + UnsafeStatementSyntax unsafeStatement = SyntaxFactory.UnsafeStatement(block).WithFormatterAnnotation(); - return document.ReplaceNodeAsync(statement, unsafeStatement, ct); - }, - GetEquivalenceKey(diagnostic, CodeFixIdentifiers.WrapInUnsafeStatement)); + return document.ReplaceNodeAsync(statement, unsafeStatement, ct); + }, + GetEquivalenceKey(diagnostic, CodeFixIdentifiers.WrapInUnsafeStatement)); - context.RegisterCodeFix(codeAction, diagnostic); - } - else if (!fMemberDeclaration - && ancestor is MemberDeclarationSyntax) - { - fMemberDeclaration = true; + context.RegisterCodeFix(codeAction, diagnostic); + } + else if (!fMemberDeclaration + && ancestor is MemberDeclarationSyntax) + { + fMemberDeclaration = true; - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingDeclarationUnsafe, document, root.SyntaxTree)) - continue; + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeContainingDeclarationUnsafe, document, root.SyntaxTree)) + continue; - if (!CSharpFacts.CanHaveModifiers(ancestor.Kind())) - continue; + if (!CSharpFacts.CanHaveModifiers(ancestor.Kind())) + continue; - ModifiersCodeFixRegistrator.AddModifier( - context, - diagnostic, - ancestor, - SyntaxKind.UnsafeKeyword, - title: "Make containing declaration unsafe", - additionalKey: CodeFixIdentifiers.MakeContainingDeclarationUnsafe); - } + ModifiersCodeFixRegistrator.AddModifier( + context, + diagnostic, + ancestor, + SyntaxKind.UnsafeKeyword, + title: "Make containing declaration unsafe", + additionalKey: CodeFixIdentifiers.MakeContainingDeclarationUnsafe); } - - break; } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/UseNullForgivingOperatorCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/UseNullForgivingOperatorCodeFixProvider.cs index 8a8ef8edae..a379bea4fc 100644 --- a/src/CodeFixes/CSharp/CodeFixes/UseNullForgivingOperatorCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/UseNullForgivingOperatorCodeFixProvider.cs @@ -52,25 +52,25 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CS8625_CannotConvertNullLiteralToNonNullableReferenceType: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, context.Document, root.SyntaxTree)) - break; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseNullForgivingOperator, context.Document, root.SyntaxTree)) + break; - CodeAction codeAction = CodeAction.Create( - "Use null-forgiving operator", - ct => - { - PostfixUnaryExpressionSyntax newExpression = SuppressNullableWarningExpression(expression.WithoutTrivia()) - .WithTriviaFrom(expression); + CodeAction codeAction = CodeAction.Create( + "Use null-forgiving operator", + ct => + { + PostfixUnaryExpressionSyntax newExpression = SuppressNullableWarningExpression(expression.WithoutTrivia()) + .WithTriviaFrom(expression); - return document.ReplaceNodeAsync(expression, newExpression, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceNodeAsync(expression, newExpression, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); + context.RegisterCodeFix(codeAction, diagnostic); - break; - } + break; + } } } } diff --git a/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs b/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs index 810c3f9388..43d033e802 100644 --- a/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs +++ b/src/CodeFixes/CSharp/CodeFixes/VariableDeclarationCodeFixProvider.cs @@ -59,72 +59,72 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case CompilerDiagnosticIdentifiers.CS0819_ImplicitlyTypedVariablesCannotHaveMultipleDeclarators: case CompilerDiagnosticIdentifiers.CS0822_ImplicitlyTypedVariablesCannotBeConstant: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, context.Document, root.SyntaxTree)) - return; - - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, context.Document, root.SyntaxTree)) + return; - TypeSyntax type = variableDeclaration.Type; + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); + TypeSyntax type = variableDeclaration.Type; - if (typeSymbol?.SupportsExplicitDeclaration() == true) - { - CodeAction codeAction = CodeActionFactory.ChangeType(context.Document, type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic)); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); - context.RegisterCodeFix(codeAction, diagnostic); - } + if (typeSymbol?.SupportsExplicitDeclaration() == true) + { + CodeAction codeAction = CodeActionFactory.ChangeType(context.Document, type, typeSymbol, semanticModel, equivalenceKey: GetEquivalenceKey(diagnostic)); - break; + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } case CompilerDiagnosticIdentifiers.CS0128_LocalVariableOrFunctionIsAlreadyDefinedInThisScope: case CompilerDiagnosticIdentifiers.CS0136_LocalOrParameterCannotBeDeclaredInThisScopeBecauseThatNameIsUsedInEnclosingScopeToDefineLocalOrParameter: - { - if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceVariableDeclarationWithAssignment, context.Document, root.SyntaxTree)) - return; - - if (variableDeclaration.Parent is not LocalDeclarationStatementSyntax localDeclaration) - return; + { + if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceVariableDeclarationWithAssignment, context.Document, root.SyntaxTree)) + return; - VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); + if (variableDeclaration.Parent is not LocalDeclarationStatementSyntax localDeclaration) + return; - if (variableDeclarator is null) - break; + VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); - ExpressionSyntax value = variableDeclarator.Initializer?.Value; - - if (value is null) - break; - - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (variableDeclarator is null) + break; - VariableDeclaratorSyntax variableDeclarator2 = FindVariableDeclarator( - variableDeclarator.Identifier.ValueText, - semanticModel.GetEnclosingSymbolSyntax(localDeclaration.SpanStart, context.CancellationToken)); + ExpressionSyntax value = variableDeclarator.Initializer?.Value; - if (variableDeclarator2?.SpanStart < localDeclaration.SpanStart) - { - CodeAction codeAction = CodeAction.Create( - "Replace variable declaration with assignment", - ct => - { - ExpressionStatementSyntax newNode = CSharpFactory.SimpleAssignmentStatement( - SyntaxFactory.IdentifierName(variableDeclarator.Identifier), - value); + if (value is null) + break; - newNode = newNode - .WithTriviaFrom(localDeclaration) - .WithFormatterAnnotation(); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return context.Document.ReplaceNodeAsync(localDeclaration, newNode, ct); - }, - GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - } + VariableDeclaratorSyntax variableDeclarator2 = FindVariableDeclarator( + variableDeclarator.Identifier.ValueText, + semanticModel.GetEnclosingSymbolSyntax(localDeclaration.SpanStart, context.CancellationToken)); - break; + if (variableDeclarator2?.SpanStart < localDeclaration.SpanStart) + { + CodeAction codeAction = CodeAction.Create( + "Replace variable declaration with assignment", + ct => + { + ExpressionStatementSyntax newNode = CSharpFactory.SimpleAssignmentStatement( + SyntaxFactory.IdentifierName(variableDeclarator.Identifier), + value); + + newNode = newNode + .WithTriviaFrom(localDeclaration) + .WithFormatterAnnotation(); + + return context.Document.ReplaceNodeAsync(localDeclaration, newNode, ct); + }, + GetEquivalenceKey(diagnostic)); + context.RegisterCodeFix(codeAction, diagnostic); } + + break; + } } } } diff --git a/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs b/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs index 7c884d1af7..735f8d641f 100644 --- a/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs +++ b/src/CodeFixes/CSharp/Refactorings/ChangeMemberTypeRefactoring.cs @@ -181,28 +181,28 @@ private static (ISymbol symbol, ITypeSymbol typeSymbol) GetContainingSymbolAndTy switch (semanticModel.GetEnclosingSymbol(expression.SpanStart, cancellationToken)) { case IMethodSymbol methodSymbol: - { - MethodKind methodKind = methodSymbol.MethodKind; - - if (methodKind == MethodKind.PropertyGet) - { - var propertySymbol = (IPropertySymbol)methodSymbol.AssociatedSymbol; - - return (propertySymbol, propertySymbol.Type); - } + { + MethodKind methodKind = methodSymbol.MethodKind; - if (methodKind == MethodKind.Ordinary - && methodSymbol.PartialImplementationPart is not null) - { - methodSymbol = methodSymbol.PartialImplementationPart; - } + if (methodKind == MethodKind.PropertyGet) + { + var propertySymbol = (IPropertySymbol)methodSymbol.AssociatedSymbol; - return (methodSymbol, methodSymbol.ReturnType); + return (propertySymbol, propertySymbol.Type); } - case IFieldSymbol fieldSymbol: + + if (methodKind == MethodKind.Ordinary + && methodSymbol.PartialImplementationPart is not null) { - return (fieldSymbol, fieldSymbol.Type); + methodSymbol = methodSymbol.PartialImplementationPart; } + + return (methodSymbol, methodSymbol.ReturnType); + } + case IFieldSymbol fieldSymbol: + { + return (fieldSymbol, fieldSymbol.Type); + } } SyntaxDebug.Fail(expression); diff --git a/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs b/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs index 898c0002f0..06704a08f8 100644 --- a/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs +++ b/src/CodeFixes/CSharp/Refactorings/ChangeTypeAccordingToInitializerRefactoring.cs @@ -26,18 +26,18 @@ public static CodeFixRegistrationResult ComputeCodeFix( switch (equalsValueClause.Parent) { case VariableDeclaratorSyntax variableDeclarator: - { - return ComputeCodeFix(context, diagnostic, expression, variableDeclarator, semanticModel); - } + { + return ComputeCodeFix(context, diagnostic, expression, variableDeclarator, semanticModel); + } case PropertyDeclarationSyntax propertyDeclaration: - { - return ComputeCodeFix(context, diagnostic, expression, propertyDeclaration, semanticModel); - } + { + return ComputeCodeFix(context, diagnostic, expression, propertyDeclaration, semanticModel); + } default: - { - SyntaxDebug.Fail(equalsValueClause.Parent); - break; - } + { + SyntaxDebug.Fail(equalsValueClause.Parent); + break; + } } return default; diff --git a/src/CodeFixes/CSharp/Refactorings/UseYieldReturnInsteadOfReturnRefactoring.cs b/src/CodeFixes/CSharp/Refactorings/UseYieldReturnInsteadOfReturnRefactoring.cs index e92de992fb..46be955a18 100644 --- a/src/CodeFixes/CSharp/Refactorings/UseYieldReturnInsteadOfReturnRefactoring.cs +++ b/src/CodeFixes/CSharp/Refactorings/UseYieldReturnInsteadOfReturnRefactoring.cs @@ -26,49 +26,49 @@ public static Task RefactorAsync( switch (replacementKind) { case SyntaxKind.YieldReturnStatement: - { - YieldStatementSyntax yieldReturnStatement = YieldStatement( - SyntaxKind.YieldReturnStatement, - Token(returnKeyword.LeadingTrivia, SyntaxKind.YieldKeyword, TriviaList(Space)), - returnKeyword.WithoutLeadingTrivia(), - expression, - returnStatement.SemicolonToken); + { + YieldStatementSyntax yieldReturnStatement = YieldStatement( + SyntaxKind.YieldReturnStatement, + Token(returnKeyword.LeadingTrivia, SyntaxKind.YieldKeyword, TriviaList(Space)), + returnKeyword.WithoutLeadingTrivia(), + expression, + returnStatement.SemicolonToken); - return document.ReplaceNodeAsync(returnStatement, yieldReturnStatement, cancellationToken); - } + return document.ReplaceNodeAsync(returnStatement, yieldReturnStatement, cancellationToken); + } case SyntaxKind.ForEachStatement: - { - string name = NameGenerator.Default.EnsureUniqueLocalName( - DefaultNames.ForEachVariable, - semanticModel, - returnStatement.SpanStart, - cancellationToken: cancellationToken); + { + string name = NameGenerator.Default.EnsureUniqueLocalName( + DefaultNames.ForEachVariable, + semanticModel, + returnStatement.SpanStart, + cancellationToken: cancellationToken); - YieldStatementSyntax yieldReturnStatement = YieldStatement( - SyntaxKind.YieldReturnStatement, - Token(default(SyntaxTriviaList), SyntaxKind.YieldKeyword, TriviaList(Space)), - returnKeyword.WithoutLeadingTrivia(), - IdentifierName(name), - returnStatement.SemicolonToken.WithoutTrailingTrivia()); + YieldStatementSyntax yieldReturnStatement = YieldStatement( + SyntaxKind.YieldReturnStatement, + Token(default(SyntaxTriviaList), SyntaxKind.YieldKeyword, TriviaList(Space)), + returnKeyword.WithoutLeadingTrivia(), + IdentifierName(name), + returnStatement.SemicolonToken.WithoutTrailingTrivia()); - StatementSyntax newNode = ForEachStatement( - VarType(), - name, - expression, - Block(yieldReturnStatement)); + StatementSyntax newNode = ForEachStatement( + VarType(), + name, + expression, + Block(yieldReturnStatement)); - if (returnStatement.IsEmbedded()) - newNode = Block(newNode); + if (returnStatement.IsEmbedded()) + newNode = Block(newNode); - newNode = newNode.WithTriviaFrom(returnStatement); + newNode = newNode.WithTriviaFrom(returnStatement); - return document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken); - } + return document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken); + } default: - { - Debug.Fail(""); - return Task.FromResult(document); - } + { + Debug.Fail(""); + return Task.FromResult(document); + } } } } diff --git a/src/CommandLine/FindSymbols/SymbolFinder.cs b/src/CommandLine/FindSymbols/SymbolFinder.cs index 2b5912dc37..e1149f379a 100644 --- a/src/CommandLine/FindSymbols/SymbolFinder.cs +++ b/src/CommandLine/FindSymbols/SymbolFinder.cs @@ -59,63 +59,63 @@ internal static async Task> FindSymbolsAsync( switch (reason) { case SymbolFilterReason.None: + { + if (options.IgnoreGeneratedCode + && GeneratedCodeUtility.IsGeneratedCode(symbol, generatedCodeAttribute, f => syntaxFactsService.IsComment(f), cancellationToken)) { - if (options.IgnoreGeneratedCode - && GeneratedCodeUtility.IsGeneratedCode(symbol, generatedCodeAttribute, f => syntaxFactsService.IsComment(f), cancellationToken)) - { - continue; - } + continue; + } - if (symbol.IsKind(SymbolKind.Method)) + if (symbol.IsKind(SymbolKind.Method)) + { + if (canContainUnityScriptMethods is null + && namespaceOrTypeSymbol is INamedTypeSymbol typeSymbol) { - if (canContainUnityScriptMethods is null - && namespaceOrTypeSymbol is INamedTypeSymbol typeSymbol) - { - canContainUnityScriptMethods = typeSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); - } - - if (canContainUnityScriptMethods == true - && UnityScriptMethods.MethodNames.Contains(symbol.Name)) - { - continue; - } + canContainUnityScriptMethods = typeSymbol.InheritsFrom(UnityScriptMethods.MonoBehaviourClassName); } - if (options.Unused) + if (canContainUnityScriptMethods == true + && UnityScriptMethods.MethodNames.Contains(symbol.Name)) { - bool isUnused = await UnusedSymbolUtility.IsUnusedSymbolAsync(symbol, project.Solution, cancellationToken); - - if (isUnused - && !UnusedSymbolUtility.CanBeUnreferenced(symbol)) - { - (symbols ??= ImmutableArray.CreateBuilder()).Add(symbol); - continue; - } + continue; } - else + } + + if (options.Unused) + { + bool isUnused = await UnusedSymbolUtility.IsUnusedSymbolAsync(symbol, project.Solution, cancellationToken); + + if (isUnused + && !UnusedSymbolUtility.CanBeUnreferenced(symbol)) { (symbols ??= ImmutableArray.CreateBuilder()).Add(symbol); + continue; } - - break; } - case SymbolFilterReason.WithoutAttribute: + else { - continue; + (symbols ??= ImmutableArray.CreateBuilder()).Add(symbol); } + + break; + } + case SymbolFilterReason.WithoutAttribute: + { + continue; + } case SymbolFilterReason.Visibility: case SymbolFilterReason.SymbolGroup: case SymbolFilterReason.Ignored: case SymbolFilterReason.WithAttribute: case SymbolFilterReason.Other: - { - break; - } + { + break; + } default: - { - Debug.Fail(reason.ToString()); - break; - } + { + Debug.Fail(reason.ToString()); + break; + } } } diff --git a/src/CommandLine/FindSymbols/UnusedSymbolUtility.cs b/src/CommandLine/FindSymbols/UnusedSymbolUtility.cs index f718d9c9de..b8da2ca026 100644 --- a/src/CommandLine/FindSymbols/UnusedSymbolUtility.cs +++ b/src/CommandLine/FindSymbols/UnusedSymbolUtility.cs @@ -33,68 +33,68 @@ public static bool CanBeUnusedSymbol(ISymbol symbol) switch (symbol.Kind) { case SymbolKind.Namespace: - { - return false; - } + { + return false; + } case SymbolKind.NamedType: - { - return true; - } + { + return true; + } case SymbolKind.Event: - { - if (symbol.IsOverride) - return false; + { + if (symbol.IsOverride) + return false; - var eventSymbol = (IEventSymbol)symbol; + var eventSymbol = (IEventSymbol)symbol; - return eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty - && !eventSymbol.ImplementsInterfaceMember(allInterfaces: true); - } + return eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty + && !eventSymbol.ImplementsInterfaceMember(allInterfaces: true); + } case SymbolKind.Field: - { - var fieldSymbol = (IFieldSymbol)symbol; + { + var fieldSymbol = (IFieldSymbol)symbol; - return !fieldSymbol.ImplementsInterfaceMember(allInterfaces: true); - } + return !fieldSymbol.ImplementsInterfaceMember(allInterfaces: true); + } case SymbolKind.Property: - { - if (symbol.IsOverride) - return false; + { + if (symbol.IsOverride) + return false; - var propertySymbol = (IPropertySymbol)symbol; + var propertySymbol = (IPropertySymbol)symbol; - return propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty - && !propertySymbol.ImplementsInterfaceMember(allInterfaces: true); - } + return propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty + && !propertySymbol.ImplementsInterfaceMember(allInterfaces: true); + } case SymbolKind.Method: - { - if (symbol.IsOverride) - return false; + { + if (symbol.IsOverride) + return false; - var methodSymbol = (IMethodSymbol)symbol; + var methodSymbol = (IMethodSymbol)symbol; - switch (methodSymbol.MethodKind) + switch (methodSymbol.MethodKind) + { + case MethodKind.Ordinary: { - case MethodKind.Ordinary: - { - return methodSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty - && !SymbolUtility.CanBeEntryPoint(methodSymbol) - && !methodSymbol.ImplementsInterfaceMember(allInterfaces: true); - } - case MethodKind.Constructor: - { - return methodSymbol.Parameters.Any() - || !methodSymbol.ContainingType.IsAbstract; - } + return methodSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty + && !SymbolUtility.CanBeEntryPoint(methodSymbol) + && !methodSymbol.ImplementsInterfaceMember(allInterfaces: true); + } + case MethodKind.Constructor: + { + return methodSymbol.Parameters.Any() + || !methodSymbol.ContainingType.IsAbstract; } - - return false; } + + return false; + } default: - { - Debug.Fail(symbol.Kind.ToString()); - return false; - } + { + Debug.Fail(symbol.Kind.ToString()); + return false; + } } } @@ -207,17 +207,17 @@ bool CanBeReferencedInDebuggerDisplayAttribute() switch (symbol.Kind) { case SymbolKind.Field: - { - return true; - } + { + return true; + } case SymbolKind.Method: - { - return !((IMethodSymbol)symbol).Parameters.Any(); - } + { + return !((IMethodSymbol)symbol).Parameters.Any(); + } case SymbolKind.Property: - { - return !((IPropertySymbol)symbol).IsIndexer; - } + { + return !((IPropertySymbol)symbol).IsIndexer; + } } return false; @@ -232,55 +232,55 @@ bool IsReferencedInDebuggerDisplayAttribute(string value) switch (value[i]) { case '{': - { - i++; + { + i++; - int startIndex = i; + int startIndex = i; - while (i < length) + while (i < length) + { + char ch = value[i]; + + if (ch == '}' + || ch == ',' + || ch == '(') { - char ch = value[i]; + int nameLength = i - startIndex; - if (ch == '}' - || ch == ',' - || ch == '(') + if (nameLength > 0 + && string.CompareOrdinal(symbol.Name, 0, value, startIndex, nameLength) == 0) { - int nameLength = i - startIndex; + return true; + } - if (nameLength > 0 - && string.CompareOrdinal(symbol.Name, 0, value, startIndex, nameLength) == 0) - { - return true; - } + if (ch != '}') + { + i++; - if (ch != '}') + while (i < length + && value[i] != '}') { i++; - - while (i < length - && value[i] != '}') - { - i++; - } } - - break; } - i++; + break; } - break; + i++; } + + break; + } case '}': - { - return false; - } + { + return false; + } case '\\': - { - i++; - break; - } + { + i++; + break; + } } } diff --git a/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs b/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs index 755a9e482a..d2ee39c4da 100644 --- a/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs +++ b/src/CommandLine/Html/SymbolDefinitionHtmlWriter.cs @@ -630,23 +630,23 @@ public override void WriteDocumentationComment(ISymbol symbol) case XmlTag.See: case XmlTag.ParamRef: case XmlTag.TypeParamRef: - { - int lineNumber = ((IXmlLineInfo)e).LineNumber; - - if (elementsByLine is null) - elementsByLine = new Dictionary>(); + { + int lineNumber = ((IXmlLineInfo)e).LineNumber; - if (elementsByLine.TryGetValue(lineNumber, out List elements)) - { - elements.Add(e); - } - else - { - elementsByLine.Add(lineNumber, new List() { e }); - } + if (elementsByLine is null) + elementsByLine = new Dictionary>(); - break; + if (elementsByLine.TryGetValue(lineNumber, out List elements)) + { + elements.Add(e); + } + else + { + elementsByLine.Add(lineNumber, new List() { e }); } + + break; + } } } @@ -673,63 +673,63 @@ public override void WriteDocumentationComment(ISymbol symbol) { case XmlTag.ParamRef: case XmlTag.TypeParamRef: - { - string name = e.Attribute("name")?.Value; - - if (name is not null) - { - Write(line.Substring(lastPos, linePos - lastPos)); - Write(name); - } + { + string name = e.Attribute("name")?.Value; - lastPos = linePos + e.ToString().Length; - break; + if (name is not null) + { + Write(line.Substring(lastPos, linePos - lastPos)); + Write(name); } + + lastPos = linePos + e.ToString().Length; + break; + } case XmlTag.See: - { - string commentId = e.Attribute("cref")?.Value; + { + string commentId = e.Attribute("cref")?.Value; - if (commentId is not null) - { - Write(line.Substring(lastPos, linePos - lastPos)); + if (commentId is not null) + { + Write(line.Substring(lastPos, linePos - lastPos)); - ISymbol s = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId)?.OriginalDefinition; + ISymbol s = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId)?.OriginalDefinition; - if (s is not null) + if (s is not null) + { + if (s.Kind == SymbolKind.Field + && s.ContainingType.TypeKind == TypeKind.Enum) { - if (s.Kind == SymbolKind.Field - && s.ContainingType.TypeKind == TypeKind.Enum) - { - WriteSymbol(s.ContainingType); - Write("."); - Write(s.Name); - } - else - { - WriteParts(s, s.ToDisplayParts(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_TypeParameters)); - WriteSymbol(s); - } + WriteSymbol(s.ContainingType); + Write("."); + Write(s.Name); } else { - Debug.Fail(commentId); - Write(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); + WriteParts(s, s.ToDisplayParts(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_TypeParameters)); + WriteSymbol(s); } } else { - string langword = e.Attribute("langword")?.Value; - - if (langword is not null) - { - Write(line.Substring(lastPos, linePos - lastPos)); - Write(langword); - } + Debug.Fail(commentId); + Write(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); } + } + else + { + string langword = e.Attribute("langword")?.Value; - lastPos = linePos + e.ToString().Length; - break; + if (langword is not null) + { + Write(line.Substring(lastPos, linePos - lastPos)); + Write(langword); + } } + + lastPos = linePos + e.ToString().Length; + break; + } } } @@ -842,59 +842,59 @@ private void WriteDocumentationCommentToolTip(XElement element) switch (XmlTagMapper.GetTagOrDefault(e.Name.LocalName)) { case XmlTag.C: - { - string value = e.Value; - value = TextUtility.ToSingleLine(value); - Write(value); - break; - } + { + string value = e.Value; + value = TextUtility.ToSingleLine(value); + Write(value); + break; + } case XmlTag.Para: - { - WriteLine(); - WriteLine(); - WriteDocumentationCommentToolTip(e); - WriteLine(); - WriteLine(); - break; - } + { + WriteLine(); + WriteLine(); + WriteDocumentationCommentToolTip(e); + WriteLine(); + WriteLine(); + break; + } case XmlTag.ParamRef: - { - string parameterName = e.Attribute("name")?.Value; + { + string parameterName = e.Attribute("name")?.Value; - if (parameterName is not null) - Write(parameterName); + if (parameterName is not null) + Write(parameterName); - break; - } + break; + } case XmlTag.See: + { + string commentId = e.Attribute("cref")?.Value; + + if (commentId is not null) { - string commentId = e.Attribute("cref")?.Value; + ISymbol symbol = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId); - if (commentId is not null) + if (symbol is not null) { - ISymbol symbol = DocumentationProvider.GetFirstSymbolForDeclarationId(commentId); - - if (symbol is not null) - { - Write(symbol.ToDisplayParts(Format.GetFormat())); - } - else - { - Write(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); - } + Write(symbol.ToDisplayParts(Format.GetFormat())); + } + else + { + Write(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); } - - break; } + + break; + } case XmlTag.TypeParamRef: - { - string typeParameterName = e.Attribute("name")?.Value; + { + string typeParameterName = e.Attribute("name")?.Value; - if (typeParameterName is not null) - Write(typeParameterName); + if (typeParameterName is not null) + Write(typeParameterName); - break; - } + break; + } } } else diff --git a/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs b/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs index 7c1af69ec6..e38a03b83a 100644 --- a/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs +++ b/src/CommandLine/Json/SymbolDefinitionJsonWriter.cs @@ -455,32 +455,32 @@ private bool HasContent(INamedTypeSymbol typeSymbol) case TypeKind.Class: case TypeKind.Interface: case TypeKind.Struct: + { + if (Filter.Includes(SymbolGroupFilter.Member) + && typeSymbol.GetMembers().Any(f => !f.IsKind(SymbolKind.NamedType) && Filter.IsMatch(f))) { - if (Filter.Includes(SymbolGroupFilter.Member) - && typeSymbol.GetMembers().Any(f => !f.IsKind(SymbolKind.NamedType) && Filter.IsMatch(f))) - { - return true; - } - - if (Layout != SymbolDefinitionListLayout.TypeHierarchy - && (Filter.Includes(SymbolGroupFilter.Type)) - && typeSymbol.GetTypeMembers().Any(f => Filter.IsMatch(f))) - { - return true; - } - - break; + return true; } - case TypeKind.Enum: + + if (Layout != SymbolDefinitionListLayout.TypeHierarchy + && (Filter.Includes(SymbolGroupFilter.Type)) + && typeSymbol.GetTypeMembers().Any(f => Filter.IsMatch(f))) { - if (Filter.Includes(SymbolGroupFilter.EnumField) - && typeSymbol.GetMembers().Any(m => m.Kind == SymbolKind.Field && Filter.IsMatch((IFieldSymbol)m))) - { - return true; - } + return true; + } - break; + break; + } + case TypeKind.Enum: + { + if (Filter.Includes(SymbolGroupFilter.EnumField) + && typeSymbol.GetMembers().Any(m => m.Kind == SymbolKind.Field && Filter.IsMatch((IFieldSymbol)m))) + { + return true; } + + break; + } } return false; diff --git a/src/CommandLine/ParseHelpers.cs b/src/CommandLine/ParseHelpers.cs index c0faa1800e..1e12f48a3d 100644 --- a/src/CommandLine/ParseHelpers.cs +++ b/src/CommandLine/ParseHelpers.cs @@ -207,30 +207,30 @@ public static bool TryParseVerbosity(string value, out Verbosity verbosity) switch (value) { case "q": - { - verbosity = Verbosity.Quiet; - return true; - } + { + verbosity = Verbosity.Quiet; + return true; + } case "m": - { - verbosity = Verbosity.Minimal; - return true; - } + { + verbosity = Verbosity.Minimal; + return true; + } case "n": - { - verbosity = Verbosity.Normal; - return true; - } + { + verbosity = Verbosity.Normal; + return true; + } case "d": - { - verbosity = Verbosity.Detailed; - return true; - } + { + verbosity = Verbosity.Detailed; + return true; + } case "diag": - { - verbosity = Verbosity.Diagnostic; - return true; - } + { + verbosity = Verbosity.Diagnostic; + return true; + } } if (Enum.TryParse(value, ignoreCase: true, out verbosity)) @@ -246,16 +246,16 @@ public static bool TryParseLanguage(string value, out string language) { case "cs": case "csharp": - { - language = LanguageNames.CSharp; - return true; - } + { + language = LanguageNames.CSharp; + return true; + } case "vb": case "visual-basic": - { - language = LanguageNames.VisualBasic; - return true; - } + { + language = LanguageNames.VisualBasic; + return true; + } } WriteLine($"Unknown language '{value}'.", Verbosity.Quiet); diff --git a/src/CommandLine/Rename/CliSymbolRenameState.cs b/src/CommandLine/Rename/CliSymbolRenameState.cs index e0bf646866..f925be6dd6 100644 --- a/src/CommandLine/Rename/CliSymbolRenameState.cs +++ b/src/CommandLine/Rename/CliSymbolRenameState.cs @@ -202,29 +202,29 @@ public override async Task RenameSymbolsAsync(Project project, CancellationToken { case DialogResult.None: case DialogResult.No: - { - ignoreIds?.Add(symbolId); - return default; - } + { + ignoreIds?.Add(symbolId); + return default; + } case DialogResult.NoToAll: - { - ErrorResolution = CliCompilationErrorResolution.Skip; - ignoreIds?.Add(symbolId); - return default; - } + { + ErrorResolution = CliCompilationErrorResolution.Skip; + ignoreIds?.Add(symbolId); + return default; + } case DialogResult.Yes: - { - break; - } + { + break; + } case DialogResult.YesToAll: - { - ErrorResolution = CliCompilationErrorResolution.None; - break; - } + { + ErrorResolution = CliCompilationErrorResolution.None; + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } else if (ErrorResolution == CliCompilationErrorResolution.Abort) @@ -248,29 +248,29 @@ public override async Task RenameSymbolsAsync(Project project, CancellationToken { case DialogResult.None: case DialogResult.No: - { - ignoreIds?.Add(symbolId); - return default; - } + { + ignoreIds?.Add(symbolId); + return default; + } case DialogResult.NoToAll: - { - DryRun = true; - ignoreIds?.Add(symbolId); - return default; - } + { + DryRun = true; + ignoreIds?.Add(symbolId); + return default; + } case DialogResult.Yes: - { - break; - } + { + break; + } case DialogResult.YesToAll: - { - Ask = false; - break; - } + { + Ask = false; + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs index bd47a47071..2ba48bc73a 100644 --- a/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs +++ b/src/Common/CSharp/Analysis/AddExceptionToDocumentationComment/AddExceptionToDocumentationCommentAnalysis.cs @@ -101,32 +101,32 @@ private static bool CanAddExceptionToComment( { case XmlTag.Include: case XmlTag.Exclude: - { - if (isFirst) - containsIncludeOrExclude = true; + { + if (isFirst) + containsIncludeOrExclude = true; - break; - } + break; + } case XmlTag.InheritDoc: - { - return false; - } + { + return false; + } case XmlTag.Exception: + { + if (!containsException) { - if (!containsException) + if (info.IsEmptyElement) { - if (info.IsEmptyElement) - { - containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); - } - else - { - containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); - } + containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); + } + else + { + containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); } - - break; } + + break; + } } if (isFirst) diff --git a/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs b/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs index 01844a77e7..91f0c1cc67 100644 --- a/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs +++ b/src/Common/CSharp/Analysis/BlockExpressionAnalysis.cs @@ -53,27 +53,27 @@ public static BlockExpressionAnalysis Create(BlockSyntax block, bool allowExpres switch (statement.Kind()) { case SyntaxKind.ReturnStatement: - { - var returnStatement = (ReturnStatementSyntax)statement; - return new BlockExpressionAnalysis(returnStatement, returnStatement.Expression, returnStatement.SemicolonToken, returnStatement.ReturnKeyword); - } + { + var returnStatement = (ReturnStatementSyntax)statement; + return new BlockExpressionAnalysis(returnStatement, returnStatement.Expression, returnStatement.SemicolonToken, returnStatement.ReturnKeyword); + } case SyntaxKind.ExpressionStatement: - { - if (!allowExpressionStatement) - return default; + { + if (!allowExpressionStatement) + return default; - var expressionStatement = (ExpressionStatementSyntax)statement; - return new BlockExpressionAnalysis(expressionStatement, expressionStatement.Expression, expressionStatement.SemicolonToken, default); - } + var expressionStatement = (ExpressionStatementSyntax)statement; + return new BlockExpressionAnalysis(expressionStatement, expressionStatement.Expression, expressionStatement.SemicolonToken, default); + } case SyntaxKind.ThrowStatement: - { - var throwStatement = (ThrowStatementSyntax)statement; - return new BlockExpressionAnalysis(throwStatement, throwStatement.Expression, throwStatement.SemicolonToken, throwStatement.ThrowKeyword); - } + { + var throwStatement = (ThrowStatementSyntax)statement; + return new BlockExpressionAnalysis(throwStatement, throwStatement.Expression, throwStatement.SemicolonToken, throwStatement.ThrowKeyword); + } default: - { - return default; - } + { + return default; + } } } } diff --git a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs index 3ba4f5fd4c..1fdf8e3f04 100644 --- a/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs +++ b/src/Common/CSharp/Analysis/CallExtensionMethodAsInstanceMethodAnalysis.cs @@ -108,22 +108,22 @@ MemberAccessExpressionSyntax CreateNewMemberAccessExpression() { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: - { - return SimpleMemberAccessExpression( - ParenthesizedExpression(argument.Expression), - (SimpleNameSyntax)expression); - } + { + return SimpleMemberAccessExpression( + ParenthesizedExpression(argument.Expression), + (SimpleNameSyntax)expression); + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - return memberAccess.WithExpression(ParenthesizedExpression(argument.Expression)); - } + return memberAccess.WithExpression(ParenthesizedExpression(argument.Expression)); + } default: - { - SyntaxDebug.Fail(expression); - return null; - } + { + SyntaxDebug.Fail(expression); + return null; + } } } } diff --git a/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs b/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs index 1e5bf33df0..fda0d90a7c 100644 --- a/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs +++ b/src/Common/CSharp/Analysis/ChangeAccessibilityAnalysis.cs @@ -68,15 +68,15 @@ public static AccessibilityFilter GetValidAccessibilityFilter( case Accessibility.ProtectedOrInternal: case Accessibility.Internal: case Accessibility.Public: - { - all |= accessibility.GetAccessibilityFilter(); - break; - } + { + all |= accessibility.GetAccessibilityFilter(); + break; + } default: - { - Debug.Fail(accessibility.ToString()); - return AccessibilityFilter.None; - } + { + Debug.Fail(accessibility.ToString()); + return AccessibilityFilter.None; + } } ModifierListInfo modifiersInfo = SyntaxInfo.ModifierListInfo(member); @@ -98,19 +98,19 @@ public static AccessibilityFilter GetValidAccessibilityFilter( case Accessibility.Protected: case Accessibility.Internal: case Accessibility.Public: - { - valid &= accessibility.GetAccessibilityFilter(); + { + valid &= accessibility.GetAccessibilityFilter(); - if (valid == AccessibilityFilter.None) - return AccessibilityFilter.None; + if (valid == AccessibilityFilter.None) + return AccessibilityFilter.None; - availableAccessibilities = _accessibilityArrayMap[accessibility]; - continue; - } + availableAccessibilities = _accessibilityArrayMap[accessibility]; + continue; + } default: - { - return AccessibilityFilter.None; - } + { + return AccessibilityFilter.None; + } } } @@ -135,10 +135,10 @@ public static AccessibilityFilter GetValidAccessibilityFilter( case AccessibilityFilter.Protected: case AccessibilityFilter.Internal: case AccessibilityFilter.Public: - { - valid &= ~all; - break; - } + { + valid &= ~all; + break; + } } } @@ -199,79 +199,79 @@ private static bool IsBaseDeclarationWithoutSource( switch (member) { case EventFieldDeclarationSyntax eventFieldDeclaration: + { + foreach (VariableDeclaratorSyntax declarator in eventFieldDeclaration.Declaration.Variables) { - foreach (VariableDeclaratorSyntax declarator in eventFieldDeclaration.Declaration.Variables) - { - var symbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken); - - if (symbol? - .BaseOverriddenEvent()? - .Locations - .FirstOrDefault()? - .Kind != LocationKind.SourceFile) - { - return true; - } - } + var symbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken); - break; - } - case MethodDeclarationSyntax methodDeclaration: - { - if (semanticModel - .GetDeclaredSymbol(methodDeclaration, cancellationToken)? - .BaseOverriddenMethod()? + if (symbol? + .BaseOverriddenEvent()? .Locations .FirstOrDefault()? .Kind != LocationKind.SourceFile) { return true; } + } - break; + break; + } + case MethodDeclarationSyntax methodDeclaration: + { + if (semanticModel + .GetDeclaredSymbol(methodDeclaration, cancellationToken)? + .BaseOverriddenMethod()? + .Locations + .FirstOrDefault()? + .Kind != LocationKind.SourceFile) + { + return true; } + + break; + } case PropertyDeclarationSyntax propertyDeclaration: + { + if (semanticModel + .GetDeclaredSymbol(propertyDeclaration, cancellationToken)? + .BaseOverriddenProperty()? + .Locations + .FirstOrDefault()? + .Kind != LocationKind.SourceFile) { - if (semanticModel - .GetDeclaredSymbol(propertyDeclaration, cancellationToken)? - .BaseOverriddenProperty()? - .Locations - .FirstOrDefault()? - .Kind != LocationKind.SourceFile) - { - return true; - } - - break; + return true; } + + break; + } case EventDeclarationSyntax eventDeclaration: + { + if (semanticModel + .GetDeclaredSymbol(eventDeclaration, cancellationToken)? + .BaseOverriddenEvent()? + .Locations + .FirstOrDefault()? + .Kind != LocationKind.SourceFile) { - if (semanticModel - .GetDeclaredSymbol(eventDeclaration, cancellationToken)? - .BaseOverriddenEvent()? - .Locations - .FirstOrDefault()? - .Kind != LocationKind.SourceFile) - { - return true; - } - - break; + return true; } + + break; + } case IndexerDeclarationSyntax indexerDeclaration: + { + if (semanticModel + .GetDeclaredSymbol(indexerDeclaration, cancellationToken)? + .BaseOverriddenProperty()? + .Locations + .FirstOrDefault()? + .Kind != LocationKind.SourceFile) { - if (semanticModel - .GetDeclaredSymbol(indexerDeclaration, cancellationToken)? - .BaseOverriddenProperty()? - .Locations - .FirstOrDefault()? - .Kind != LocationKind.SourceFile) - { - return true; - } - - break; + return true; } + + break; + } } return false; diff --git a/src/Common/CSharp/Analysis/If/IfAnalysis.cs b/src/Common/CSharp/Analysis/If/IfAnalysis.cs index 476be885cf..fe8bc12190 100644 --- a/src/Common/CSharp/Analysis/If/IfAnalysis.cs +++ b/src/Common/CSharp/Analysis/If/IfAnalysis.cs @@ -78,40 +78,40 @@ public static ImmutableArray Analyze( switch (kind1) { case SyntaxKind.ExpressionStatement: - { - return Analyze( - ifStatement, - condition, - (ExpressionStatementSyntax)statement1, - (ExpressionStatementSyntax)statement2, - options, - semanticModel, - cancellationToken); - } + { + return Analyze( + ifStatement, + condition, + (ExpressionStatementSyntax)statement1, + (ExpressionStatementSyntax)statement2, + options, + semanticModel, + cancellationToken); + } case SyntaxKind.ReturnStatement: - { - return Analyze( - ifStatement, - condition, - ((ReturnStatementSyntax)statement1).Expression?.WalkDownParentheses(), - ((ReturnStatementSyntax)statement2).Expression?.WalkDownParentheses(), - options, - isYield: false, - semanticModel: semanticModel, - cancellationToken: cancellationToken); - } + { + return Analyze( + ifStatement, + condition, + ((ReturnStatementSyntax)statement1).Expression?.WalkDownParentheses(), + ((ReturnStatementSyntax)statement2).Expression?.WalkDownParentheses(), + options, + isYield: false, + semanticModel: semanticModel, + cancellationToken: cancellationToken); + } case SyntaxKind.YieldReturnStatement: - { - return Analyze( - ifStatement, - condition, - ((YieldStatementSyntax)statement1).Expression?.WalkDownParentheses(), - ((YieldStatementSyntax)statement2).Expression?.WalkDownParentheses(), - options, - isYield: true, - semanticModel: semanticModel, - cancellationToken: cancellationToken); - } + { + return Analyze( + ifStatement, + condition, + ((YieldStatementSyntax)statement1).Expression?.WalkDownParentheses(), + ((YieldStatementSyntax)statement2).Expression?.WalkDownParentheses(), + options, + isYield: true, + semanticModel: semanticModel, + cancellationToken: cancellationToken); + } } } } diff --git a/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs b/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs index b05b7da339..1f4ffea924 100644 --- a/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs +++ b/src/Common/CSharp/Analysis/ReduceIfNesting/ReduceIfNestingAnalysis.cs @@ -123,159 +123,159 @@ private static ReduceIfNestingAnalysisResult AnalyzeCore( case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: + { + if (jumpKind == SyntaxKind.None) { - if (jumpKind == SyntaxKind.None) - { - jumpKind = SyntaxKind.ReturnStatement; - } - else if (jumpKind != SyntaxKind.ReturnStatement) - { - return Fail(parent); - } + jumpKind = SyntaxKind.ReturnStatement; + } + else if (jumpKind != SyntaxKind.ReturnStatement) + { + return Fail(parent); + } - if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) - return Fail(parent); + if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) + return Fail(parent); - return Success(jumpKind, parent); - } + return Success(jumpKind, parent); + } case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.GetAccessorDeclaration: - { - if (jumpKind == SyntaxKind.None) - return Fail(parent); + { + if (jumpKind == SyntaxKind.None) + return Fail(parent); - if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) - return Fail(parent); + if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) + return Fail(parent); - return Success(jumpKind, parent); - } + return Success(jumpKind, parent); + } case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)parent; - - if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) - return Fail(parent); + { + var methodDeclaration = (MethodDeclarationSyntax)parent; - if (jumpKind != SyntaxKind.None) - return Success(jumpKind, parent); + if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) + return Fail(parent); - if (methodDeclaration.ReturnsVoid()) - return Success(SyntaxKind.ReturnStatement, parent); + if (jumpKind != SyntaxKind.None) + return Success(jumpKind, parent); - if (methodDeclaration.Modifiers.Contains(SyntaxKind.AsyncKeyword) - && semanticModel - .GetDeclaredSymbol(methodDeclaration, cancellationToken)? - .ReturnType - .HasMetadataName(MetadataNames.System_Threading_Tasks_Task) == true) - { - return Success(SyntaxKind.ReturnStatement, parent); - } + if (methodDeclaration.ReturnsVoid()) + return Success(SyntaxKind.ReturnStatement, parent); - if (semanticModel + if (methodDeclaration.Modifiers.Contains(SyntaxKind.AsyncKeyword) + && semanticModel .GetDeclaredSymbol(methodDeclaration, cancellationToken)? .ReturnType - .OriginalDefinition - .IsIEnumerableOrIEnumerableOfT() == true - && methodDeclaration.ContainsYield()) - { - return Success(SyntaxKind.YieldBreakStatement, parent); - } - - break; + .HasMetadataName(MetadataNames.System_Threading_Tasks_Task) == true) + { + return Success(SyntaxKind.ReturnStatement, parent); } - case SyntaxKind.LocalFunctionStatement: + + if (semanticModel + .GetDeclaredSymbol(methodDeclaration, cancellationToken)? + .ReturnType + .OriginalDefinition + .IsIEnumerableOrIEnumerableOfT() == true + && methodDeclaration.ContainsYield()) { - var localFunction = (LocalFunctionStatementSyntax)parent; + return Success(SyntaxKind.YieldBreakStatement, parent); + } - if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) - return Fail(parent); + break; + } + case SyntaxKind.LocalFunctionStatement: + { + var localFunction = (LocalFunctionStatementSyntax)parent; - if (jumpKind != SyntaxKind.None) - return Success(jumpKind, parent); + if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) + return Fail(parent); - if (localFunction.ReturnsVoid()) - return Success(SyntaxKind.ReturnStatement, parent); + if (jumpKind != SyntaxKind.None) + return Success(jumpKind, parent); - if (localFunction.Modifiers.Contains(SyntaxKind.AsyncKeyword) - && semanticModel.GetDeclaredSymbol(localFunction, cancellationToken)? - .ReturnType - .HasMetadataName(MetadataNames.System_Threading_Tasks_Task) == true) - { - return Success(SyntaxKind.ReturnStatement, parent); - } + if (localFunction.ReturnsVoid()) + return Success(SyntaxKind.ReturnStatement, parent); - if (semanticModel.GetDeclaredSymbol(localFunction, cancellationToken)? + if (localFunction.Modifiers.Contains(SyntaxKind.AsyncKeyword) + && semanticModel.GetDeclaredSymbol(localFunction, cancellationToken)? .ReturnType - .OriginalDefinition - .IsIEnumerableOrIEnumerableOfT() == true - && localFunction.ContainsYield()) - { - return Success(SyntaxKind.YieldBreakStatement, parent); - } - - break; + .HasMetadataName(MetadataNames.System_Threading_Tasks_Task) == true) + { + return Success(SyntaxKind.ReturnStatement, parent); + } + + if (semanticModel.GetDeclaredSymbol(localFunction, cancellationToken)? + .ReturnType + .OriginalDefinition + .IsIEnumerableOrIEnumerableOfT() == true + && localFunction.ContainsYield()) + { + return Success(SyntaxKind.YieldBreakStatement, parent); } + + break; + } case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: - { - var anonymousFunction = (AnonymousFunctionExpressionSyntax)parent; - - if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) - return Fail(parent); + { + var anonymousFunction = (AnonymousFunctionExpressionSyntax)parent; - if (jumpKind != SyntaxKind.None) - return Success(jumpKind, parent); + if (IfStatementLocalVariableAnalysis.DoDeclaredVariablesOverlapWithOuterScope(ifStatement, semanticModel)) + return Fail(parent); - if (semanticModel.GetSymbol(anonymousFunction, cancellationToken) is not IMethodSymbol methodSymbol) - return Fail(parent); + if (jumpKind != SyntaxKind.None) + return Success(jumpKind, parent); - if (methodSymbol.ReturnsVoid) - return Success(SyntaxKind.ReturnStatement, parent); + if (semanticModel.GetSymbol(anonymousFunction, cancellationToken) is not IMethodSymbol methodSymbol) + return Fail(parent); - if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) - && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task)) - { - return Success(SyntaxKind.ReturnStatement, parent); - } + if (methodSymbol.ReturnsVoid) + return Success(SyntaxKind.ReturnStatement, parent); - break; - } - case SyntaxKind.IfStatement: + if (anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) + && methodSymbol.ReturnType.HasMetadataName(MetadataNames.System_Threading_Tasks_Task)) { - ifStatement = (IfStatementSyntax)parent; - - if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) - { - if (ifStatement.Else is not null) - return Fail(parent); + return Success(SyntaxKind.ReturnStatement, parent); + } - if (!options.AllowIfInsideIfElse()) - return Fail(parent); + break; + } + case SyntaxKind.IfStatement: + { + ifStatement = (IfStatementSyntax)parent; - return AnalyzeCore(ifStatement.GetTopmostIf(), semanticModel, jumpKind, options, cancellationToken); - } - else - { - if (!IsFixable(ifStatement)) - return Fail(parent); + if (ifStatement.IsParentKind(SyntaxKind.ElseClause)) + { + if (ifStatement.Else is not null) + return Fail(parent); - if (!options.AllowNestedFix()) - return Fail(parent); + if (!options.AllowIfInsideIfElse()) + return Fail(parent); - return AnalyzeCore(ifStatement, semanticModel, jumpKind, options, cancellationToken); - } + return AnalyzeCore(ifStatement.GetTopmostIf(), semanticModel, jumpKind, options, cancellationToken); } - case SyntaxKind.ElseClause: + else { - if (!options.AllowIfInsideIfElse()) + if (!IsFixable(ifStatement)) return Fail(parent); - var elseClause = (ElseClauseSyntax)parent; + if (!options.AllowNestedFix()) + return Fail(parent); - return AnalyzeCore(elseClause.GetTopmostIf(), semanticModel, jumpKind, options, cancellationToken); + return AnalyzeCore(ifStatement, semanticModel, jumpKind, options, cancellationToken); } + } + case SyntaxKind.ElseClause: + { + if (!options.AllowIfInsideIfElse()) + return Fail(parent); + + var elseClause = (ElseClauseSyntax)parent; + + return AnalyzeCore(elseClause.GetTopmostIf(), semanticModel, jumpKind, options, cancellationToken); + } } return Fail(parent); @@ -367,46 +367,46 @@ internal static SyntaxKind GetJumpKind(StatementSyntax statement) switch (statement) { case BreakStatementSyntax _: - { - return SyntaxKind.BreakStatement; - } + { + return SyntaxKind.BreakStatement; + } case ContinueStatementSyntax _: - { - return SyntaxKind.ContinueStatement; - } + { + return SyntaxKind.ContinueStatement; + } case ReturnStatementSyntax returnStatement: - { - ExpressionSyntax expression = returnStatement.Expression; - - if (expression is null) - return SyntaxKind.ReturnStatement; + { + ExpressionSyntax expression = returnStatement.Expression; - SyntaxKind kind = expression.Kind(); + if (expression is null) + return SyntaxKind.ReturnStatement; - if (kind.Is( - SyntaxKind.NullLiteralExpression, - SyntaxKind.DefaultLiteralExpression, - SyntaxKind.TrueLiteralExpression, - SyntaxKind.FalseLiteralExpression)) - { - return kind; - } + SyntaxKind kind = expression.Kind(); - return SyntaxKind.None; + if (kind.Is( + SyntaxKind.NullLiteralExpression, + SyntaxKind.DefaultLiteralExpression, + SyntaxKind.TrueLiteralExpression, + SyntaxKind.FalseLiteralExpression)) + { + return kind; } + + return SyntaxKind.None; + } case ThrowStatementSyntax throwStatement: - { - ExpressionSyntax expression = throwStatement.Expression; + { + ExpressionSyntax expression = throwStatement.Expression; - if (expression is null) - return SyntaxKind.ThrowStatement; + if (expression is null) + return SyntaxKind.ThrowStatement; - return SyntaxKind.None; - } + return SyntaxKind.None; + } default: - { - return SyntaxKind.None; - } + { + return SyntaxKind.None; + } } } diff --git a/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs b/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs index 84abb81616..c8132903bc 100644 --- a/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs +++ b/src/Common/CSharp/Analysis/RemoveAsyncAwaitAnalysis.cs @@ -125,21 +125,21 @@ public static RemoveAsyncAwaitAnalysis Create( switch (body.Kind()) { case SyntaxKind.Block: - { - return AnalyzeMethodBody(lambda, (BlockSyntax)body, semanticModel, cancellationToken); - } + { + return AnalyzeMethodBody(lambda, (BlockSyntax)body, semanticModel, cancellationToken); + } case SyntaxKind.AwaitExpression: - { - var awaitExpression = (AwaitExpressionSyntax)body; - - if (!AwaitExpressionWalker.ContainsAwaitExpression(awaitExpression.Expression) - && VerifyTypes(lambda, awaitExpression, semanticModel, cancellationToken)) - { - return new RemoveAsyncAwaitAnalysis(awaitExpression); - } + { + var awaitExpression = (AwaitExpressionSyntax)body; - break; + if (!AwaitExpressionWalker.ContainsAwaitExpression(awaitExpression.Expression) + && VerifyTypes(lambda, awaitExpression, semanticModel, cancellationToken)) + { + return new RemoveAsyncAwaitAnalysis(awaitExpression); } + + break; + } } return default; @@ -175,84 +175,84 @@ private static RemoveAsyncAwaitAnalysis AnalyzeMethodBody( switch (statement.Kind()) { case SyntaxKind.ReturnStatement: - { - var returnStatement = (ReturnStatementSyntax)statement; + { + var returnStatement = (ReturnStatementSyntax)statement; - AwaitExpressionSyntax awaitExpression = GetAwaitExpression(returnStatement); + AwaitExpressionSyntax awaitExpression = GetAwaitExpression(returnStatement); - if (awaitExpression is null) - return default; + if (awaitExpression is null) + return default; - AwaitExpressionWalker walker = VisitStatements(); + AwaitExpressionWalker walker = VisitStatements(); - HashSet awaitExpressions = walker.AwaitExpressions; + HashSet awaitExpressions = walker.AwaitExpressions; - if (awaitExpressions.Count == 1) - { - if (VerifyTypes(node, awaitExpression, semanticModel, cancellationToken)) - return new RemoveAsyncAwaitAnalysis(walker); - } - else if (awaitExpressions.Count > 1) + if (awaitExpressions.Count == 1) + { + if (VerifyTypes(node, awaitExpression, semanticModel, cancellationToken)) + return new RemoveAsyncAwaitAnalysis(walker); + } + else if (awaitExpressions.Count > 1) + { + StatementSyntax prevStatement = statements[statements.IndexOf(returnStatement) - 1]; + + switch (prevStatement.Kind()) { - StatementSyntax prevStatement = statements[statements.IndexOf(returnStatement) - 1]; + case SyntaxKind.IfStatement: + { + if (VerifyIfStatement((IfStatementSyntax)prevStatement, awaitExpressions.Count - 1, endsWithElse: false) + && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) + { + return new RemoveAsyncAwaitAnalysis(walker); + } - switch (prevStatement.Kind()) + break; + } + case SyntaxKind.SwitchStatement: { - case SyntaxKind.IfStatement: - { - if (VerifyIfStatement((IfStatementSyntax)prevStatement, awaitExpressions.Count - 1, endsWithElse: false) - && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) - { - return new RemoveAsyncAwaitAnalysis(walker); - } - - break; - } - case SyntaxKind.SwitchStatement: - { - if (VerifySwitchStatement((SwitchStatementSyntax)prevStatement, awaitExpressions.Count - 1, containsDefaultSection: false) - && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) - { - return new RemoveAsyncAwaitAnalysis(walker); - } - - break; - } + if (VerifySwitchStatement((SwitchStatementSyntax)prevStatement, awaitExpressions.Count - 1, containsDefaultSection: false) + && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) + { + return new RemoveAsyncAwaitAnalysis(walker); + } + + break; } } - - return default; } + + return default; + } case SyntaxKind.IfStatement: - { - AwaitExpressionWalker walker = VisitStatements(); + { + AwaitExpressionWalker walker = VisitStatements(); - HashSet awaitExpressions = walker.AwaitExpressions; + HashSet awaitExpressions = walker.AwaitExpressions; - if (awaitExpressions.Count > 0 - && VerifyIfStatement((IfStatementSyntax)statement, awaitExpressions.Count, endsWithElse: true) - && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) - { - return new RemoveAsyncAwaitAnalysis(walker); - } - - return default; - } - case SyntaxKind.SwitchStatement: + if (awaitExpressions.Count > 0 + && VerifyIfStatement((IfStatementSyntax)statement, awaitExpressions.Count, endsWithElse: true) + && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) { - AwaitExpressionWalker walker = VisitStatements(); + return new RemoveAsyncAwaitAnalysis(walker); + } - HashSet awaitExpressions = walker.AwaitExpressions; + return default; + } + case SyntaxKind.SwitchStatement: + { + AwaitExpressionWalker walker = VisitStatements(); - if (awaitExpressions.Count > 0 - && VerifySwitchStatement((SwitchStatementSyntax)statement, awaitExpressions.Count, containsDefaultSection: true) - && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) - { - return new RemoveAsyncAwaitAnalysis(walker); - } + HashSet awaitExpressions = walker.AwaitExpressions; - return default; + if (awaitExpressions.Count > 0 + && VerifySwitchStatement((SwitchStatementSyntax)statement, awaitExpressions.Count, containsDefaultSection: true) + && VerifyTypes(node, awaitExpressions, semanticModel, cancellationToken)) + { + return new RemoveAsyncAwaitAnalysis(walker); } + + return default; + } } return default; diff --git a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs index 026ab5b91a..9e2027a794 100644 --- a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs +++ b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantReturnStatementAnalysis.cs @@ -53,28 +53,28 @@ protected override bool IsFixable(StatementSyntax statement, StatementSyntax con case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.SetAccessorDeclaration: - { - return true; - } + { + return true; + } case SyntaxKind.MethodDeclaration: - { - return ((MethodDeclarationSyntax)block.Parent).ReturnType?.IsVoid() == true; - } + { + return ((MethodDeclarationSyntax)block.Parent).ReturnType?.IsVoid() == true; + } case SyntaxKind.LocalFunctionStatement: - { - return ((LocalFunctionStatementSyntax)block.Parent).ReturnType?.IsVoid() == true; - } + { + return ((LocalFunctionStatementSyntax)block.Parent).ReturnType?.IsVoid() == true; + } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.AnonymousMethodExpression: - { - return statement is ReturnStatementSyntax returnStatement - && returnStatement.Expression is null; - } + { + return statement is ReturnStatementSyntax returnStatement + && returnStatement.Expression is null; + } default: - { - return false; - } + { + return false; + } } } } diff --git a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs index 3ae60abc20..abf403e00a 100644 --- a/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs +++ b/src/Common/CSharp/Analysis/RemoveRedundantStatement/RemoveRedundantStatementAnalysis`1.cs @@ -30,49 +30,49 @@ public virtual bool IsFixable(TStatement statement) switch (kind) { case SyntaxKind.IfStatement: - { - containingStatement = (StatementSyntax)parent; + { + containingStatement = (StatementSyntax)parent; - block = containingStatement.Parent as BlockSyntax; + block = containingStatement.Parent as BlockSyntax; - if (block is null) - return false; + if (block is null) + return false; - if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) - return false; + if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) + return false; - parent = block.Parent; - break; - } + parent = block.Parent; + break; + } case SyntaxKind.ElseClause: - { - parent = ((ElseClauseSyntax)parent).GetTopmostIf(); - break; - } + { + parent = ((ElseClauseSyntax)parent).GetTopmostIf(); + break; + } case SyntaxKind.TryStatement: - { - containingStatement = (TryStatementSyntax)parent; + { + containingStatement = (TryStatementSyntax)parent; - block = containingStatement.Parent as BlockSyntax; + block = containingStatement.Parent as BlockSyntax; - if (block is null) - return false; + if (block is null) + return false; - if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) - return false; + if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) + return false; - parent = block.Parent; - break; - } + parent = block.Parent; + break; + } case SyntaxKind.CatchClause: - { - parent = parent.Parent as TryStatementSyntax; - break; - } + { + parent = parent.Parent as TryStatementSyntax; + break; + } default: - { - return IsFixable(statement, containingStatement, block, kind); - } + { + return IsFixable(statement, containingStatement, block, kind); + } } } } @@ -93,49 +93,49 @@ internal bool IsFixable(StatementSyntax statement, BlockSyntax block) switch (kind) { case SyntaxKind.IfStatement: - { - containingStatement = (StatementSyntax)parent; + { + containingStatement = (StatementSyntax)parent; - block = containingStatement.Parent as BlockSyntax; + block = containingStatement.Parent as BlockSyntax; - if (block is null) - return false; + if (block is null) + return false; - if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) - return false; + if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) + return false; - parent = block.Parent; - break; - } + parent = block.Parent; + break; + } case SyntaxKind.ElseClause: - { - parent = ((ElseClauseSyntax)parent).GetTopmostIf(); - break; - } + { + parent = ((ElseClauseSyntax)parent).GetTopmostIf(); + break; + } case SyntaxKind.TryStatement: - { - containingStatement = (TryStatementSyntax)parent; + { + containingStatement = (TryStatementSyntax)parent; - block = containingStatement.Parent as BlockSyntax; + block = containingStatement.Parent as BlockSyntax; - if (block is null) - return false; + if (block is null) + return false; - if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) - return false; + if (!block.Statements.IsLast(containingStatement, ignoreLocalFunctions: true)) + return false; - parent = block.Parent; - break; - } + parent = block.Parent; + break; + } case SyntaxKind.CatchClause: - { - parent = parent.Parent as TryStatementSyntax; - break; - } + { + parent = parent.Parent as TryStatementSyntax; + break; + } default: - { - return IsFixable(statement, containingStatement, block, kind); - } + { + return IsFixable(statement, containingStatement, block, kind); + } } } } diff --git a/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs b/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs index 63368508f0..2cab51d568 100644 --- a/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseConstantInsteadOfFieldAnalysis.cs @@ -27,28 +27,28 @@ public static bool IsFixable( { case SyntaxKind.ConstKeyword: case SyntaxKind.NewKeyword: - { - return false; - } + { + return false; + } case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: - { - if (onlyPrivate) - return false; + { + if (onlyPrivate) + return false; - break; - } + break; + } case SyntaxKind.StaticKeyword: - { - isStatic = true; - break; - } + { + isStatic = true; + break; + } case SyntaxKind.ReadOnlyKeyword: - { - isReadOnly = true; - break; - } + { + isReadOnly = true; + break; + } } } @@ -180,26 +180,26 @@ public override void VisitArgument(ArgumentSyntax node) switch (node.RefOrOutKeyword.Kind()) { case SyntaxKind.RefKeyword: - { - VisitAssignedExpression(node.Expression); - break; - } + { + VisitAssignedExpression(node.Expression); + break; + } case SyntaxKind.OutKeyword: - { - ExpressionSyntax expression = node.Expression; + { + ExpressionSyntax expression = node.Expression; - if (expression?.IsKind(SyntaxKind.DeclarationExpression) == false) - VisitAssignedExpression(expression); + if (expression?.IsKind(SyntaxKind.DeclarationExpression) == false) + VisitAssignedExpression(expression); - break; - } + break; + } case SyntaxKind.InKeyword: - { - if (IsFieldIdentifier(node.Expression)) - CanBeConvertedToConstant = false; + { + if (IsFieldIdentifier(node.Expression)) + CanBeConvertedToConstant = false; - break; - } + break; + } } base.VisitArgument(node); diff --git a/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs b/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs index 3ad42b9a12..b293e6cfdd 100644 --- a/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs +++ b/src/Common/CSharp/Analysis/UseMethodChaining/UseMethodChainingAnalysis.cs @@ -26,36 +26,36 @@ public static bool IsFixable( switch (parent?.Kind()) { case SyntaxKind.ExpressionStatement: - { - var expressionStatement = (ExpressionStatementSyntax)parent; + { + var expressionStatement = (ExpressionStatementSyntax)parent; - if (WalkDownMethodChain(invocationInfo).Expression is not IdentifierNameSyntax identifierName) - break; + if (WalkDownMethodChain(invocationInfo).Expression is not IdentifierNameSyntax identifierName) + break; - string name = identifierName.Identifier.ValueText; + string name = identifierName.Identifier.ValueText; - return WithoutAssignmentAnalysis.Analyze(invocationInfo, expressionStatement, name, semanticModel, cancellationToken); - } + return WithoutAssignmentAnalysis.Analyze(invocationInfo, expressionStatement, name, semanticModel, cancellationToken); + } case SyntaxKind.SimpleAssignmentExpression: - { - var assignmentExpression = (AssignmentExpressionSyntax)parent; + { + var assignmentExpression = (AssignmentExpressionSyntax)parent; - if (assignmentExpression.Left is not IdentifierNameSyntax identifierName) - break; + if (assignmentExpression.Left is not IdentifierNameSyntax identifierName) + break; - if (assignmentExpression.Right != invocationExpression) - break; + if (assignmentExpression.Right != invocationExpression) + break; - if (assignmentExpression.Parent is not ExpressionStatementSyntax expressionStatement) - break; + if (assignmentExpression.Parent is not ExpressionStatementSyntax expressionStatement) + break; - string name = identifierName.Identifier.ValueText; + string name = identifierName.Identifier.ValueText; - if (name != (WalkDownMethodChain(invocationInfo).Expression as IdentifierNameSyntax)?.Identifier.ValueText) - break; + if (name != (WalkDownMethodChain(invocationInfo).Expression as IdentifierNameSyntax)?.Identifier.ValueText) + break; - return WithAssignmentAnalysis.Analyze(invocationInfo, expressionStatement, name, semanticModel, cancellationToken); - } + return WithAssignmentAnalysis.Analyze(invocationInfo, expressionStatement, name, semanticModel, cancellationToken); + } } return false; diff --git a/src/Common/CSharp/IndentationAnalysis.cs b/src/Common/CSharp/IndentationAnalysis.cs index 3b2d31d5b4..68a93a01cf 100644 --- a/src/Common/CSharp/IndentationAnalysis.cs +++ b/src/Common/CSharp/IndentationAnalysis.cs @@ -149,122 +149,122 @@ private static (SyntaxTrivia, SyntaxTrivia, bool isFromCompilationUnit) Determin switch (node) { case MemberDeclarationSyntax member: + { + switch (node.Parent) { - switch (node.Parent) + case NamespaceDeclarationSyntax @namespace: { - case NamespaceDeclarationSyntax @namespace: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(member, @namespace.CloseBraceToken); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case BaseTypeDeclarationSyntax baseType: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(member, baseType.CloseBraceToken); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case CompilationUnitSyntax compilationUnit: - { - SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); - return (trivia, default, false); - } - default: - { - return default; - } + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(member, @namespace.CloseBraceToken); + + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; } + case BaseTypeDeclarationSyntax baseType: + { + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(member, baseType.CloseBraceToken); - break; + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + case CompilationUnitSyntax compilationUnit: + { + SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); + return (trivia, default, false); + } + default: + { + return default; + } } + + break; + } case AccessorDeclarationSyntax accessor: + { + switch (node.Parent) { - switch (node.Parent) + case AccessorListSyntax accessorList: { - case AccessorListSyntax accessorList: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(accessor, accessorList.CloseBraceToken); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - default: - { - return default; - } - } + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(accessor, accessorList.CloseBraceToken); - break; + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + default: + { + return default; + } } + + break; + } case BlockSyntax _: - { - break; - } + { + break; + } case StatementSyntax statement: + { + switch (node.Parent) { - switch (node.Parent) + case SwitchSectionSyntax switchSection: { - case SwitchSectionSyntax switchSection: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, switchSection); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case BlockSyntax block: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, block.CloseBraceToken); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case StatementSyntax statement2: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, statement2); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case ElseClauseSyntax elseClause: - { - (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, elseClause); - - if (trivia1.Span.Length > 0) - return (trivia1, trivia2, true); - - break; - } - case GlobalStatementSyntax: - { - break; - } - default: - { - return default; - } + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, switchSection); + + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; } + case BlockSyntax block: + { + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, block.CloseBraceToken); - break; + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + case StatementSyntax statement2: + { + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, statement2); + + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + case ElseClauseSyntax elseClause: + { + (SyntaxTrivia trivia1, SyntaxTrivia trivia2) = GetIndentationSize(statement, elseClause); + + if (trivia1.Span.Length > 0) + return (trivia1, trivia2, true); + + break; + } + case GlobalStatementSyntax: + { + break; + } + default: + { + return default; + } } + + break; + } case CompilationUnitSyntax compilationUnit: - { - SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); - return (trivia, default, false); - } + { + SyntaxTrivia trivia = DetermineIndentationSize(compilationUnit); + return (trivia, default, false); + } } node = node.Parent; diff --git a/src/Common/CSharp/TriviaBlock.cs b/src/Common/CSharp/TriviaBlock.cs index 4e73e3bbd1..097867c8f9 100644 --- a/src/Common/CSharp/TriviaBlock.cs +++ b/src/Common/CSharp/TriviaBlock.cs @@ -133,122 +133,122 @@ private static TriviaBlock Analyze(SyntaxNodeOrToken first, SyntaxNodeOrToken se switch (trivia.Kind()) { case SyntaxKind.MultiLineCommentTrivia: + { + return default; + } + case SyntaxKind.EndOfLineTrivia: + { + if (firstEolEnd == -1) { - return default; + position = reader.Current.Span.Start; + firstEolEnd = reader.Current.Span.End; } - case SyntaxKind.EndOfLineTrivia: + else if (firstEolEnd >= 0) { - if (firstEolEnd == -1) - { - position = reader.Current.Span.Start; - firstEolEnd = reader.Current.Span.End; - } - else if (firstEolEnd >= 0) - { - position = firstEolEnd; - firstEolEnd = -2; - } - - if (state == State.Start) - { - state = State.NewLine; - } - else if (state == State.NewLine) - { - state = State.Blank; - } - else if (state == State.Comment) - { - state = State.Blank; - - if (commentState == CommentState.Comment) - commentState = CommentState.AfterComment; - } + position = firstEolEnd; + firstEolEnd = -2; + } - break; + if (state == State.Start) + { + state = State.NewLine; } - case SyntaxKind.SingleLineCommentTrivia: + else if (state == State.NewLine) { - if (!reader.Read(SyntaxKind.EndOfLineTrivia)) - return default; + state = State.Blank; + } + else if (state == State.Comment) + { + state = State.Blank; - if (first.IsKind(SyntaxKind.None)) - { - position = reader.Current.Span.Start; - firstEolEnd = reader.Current.Span.End; - } - else if (firstEolEnd == -1) - { - position = reader.Current.Span.Start; - firstEolEnd = reader.Current.Span.End; - } - else if (firstEolEnd >= 0) - { - firstEolEnd = -2; - } + if (commentState == CommentState.Comment) + commentState = CommentState.AfterComment; + } - if (state == State.Start) - { - state = State.NewLine; - } - else if (state == State.NewLine) - { - stateBeforeComment = State.NewLine; - } - else if (state == State.Blank) - { - stateBeforeComment = State.Blank; + break; + } + case SyntaxKind.SingleLineCommentTrivia: + { + if (!reader.Read(SyntaxKind.EndOfLineTrivia)) + return default; - if (commentState == CommentState.AfterComment) - return default; - } + if (first.IsKind(SyntaxKind.None)) + { + position = reader.Current.Span.Start; + firstEolEnd = reader.Current.Span.End; + } + else if (firstEolEnd == -1) + { + position = reader.Current.Span.Start; + firstEolEnd = reader.Current.Span.End; + } + else if (firstEolEnd >= 0) + { + firstEolEnd = -2; + } - commentState = CommentState.Comment; - break; + if (state == State.Start) + { + state = State.NewLine; } + else if (state == State.NewLine) + { + stateBeforeComment = State.NewLine; + } + else if (state == State.Blank) + { + stateBeforeComment = State.Blank; + + if (commentState == CommentState.AfterComment) + return default; + } + + commentState = CommentState.Comment; + break; + } case SyntaxKind.None: case SyntaxKind.SingleLineDocumentationCommentTrivia: case SyntaxKind.MultiLineDocumentationCommentTrivia: + { + return new TriviaBlock( + first, + second, + GetKind(state, stateBeforeComment), + position, + singleLineComment: commentState == CommentState.Comment || commentState == CommentState.AfterComment, + documentationComment: SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind())); + + static TriviaBlockKind GetKind(State state, State triviaBeforeComment) { - return new TriviaBlock( - first, - second, - GetKind(state, stateBeforeComment), - position, - singleLineComment: commentState == CommentState.Comment || commentState == CommentState.AfterComment, - documentationComment: SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind())); - - static TriviaBlockKind GetKind(State state, State triviaBeforeComment) + switch (state) { - switch (state) - { - case State.Start: - return TriviaBlockKind.NoNewLine; - case State.NewLine: - return TriviaBlockKind.NewLine; - case State.Blank: - return TriviaBlockKind.BlankLine; - case State.Comment: - switch (triviaBeforeComment) - { - case State.Start: - case State.NewLine: - return TriviaBlockKind.NewLine; - case State.Blank: - return TriviaBlockKind.BlankLine; - default: - throw new InvalidOperationException(); - } - default: - throw new InvalidOperationException(); - } + case State.Start: + return TriviaBlockKind.NoNewLine; + case State.NewLine: + return TriviaBlockKind.NewLine; + case State.Blank: + return TriviaBlockKind.BlankLine; + case State.Comment: + switch (triviaBeforeComment) + { + case State.Start: + case State.NewLine: + return TriviaBlockKind.NewLine; + case State.Blank: + return TriviaBlockKind.BlankLine; + default: + throw new InvalidOperationException(); + } + default: + throw new InvalidOperationException(); } } + } default: - { - Debug.Fail(trivia.Kind().ToString()); - return default; - } + { + Debug.Fail(trivia.Kind().ToString()); + return default; + } } } } diff --git a/src/Common/Configuration/ConfigMigrator.cs b/src/Common/Configuration/ConfigMigrator.cs index c0ba0bf36e..20d3dec373 100644 --- a/src/Common/Configuration/ConfigMigrator.cs +++ b/src/Common/Configuration/ConfigMigrator.cs @@ -171,131 +171,131 @@ static void MarkFileAsMigrated(string path) switch (kvp.Key) { case "RCS0011i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.BlankLineBetweenSingleLineAccessors, "true") - : (ConfigOptionKeys.BlankLineBetweenSingleLineAccessors, "false"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.BlankLineBetweenSingleLineAccessors, "true") + : (ConfigOptionKeys.BlankLineBetweenSingleLineAccessors, "false"); + } case "RCS0015i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.BlankLineBetweenUsingDirectives, "never") - : (ConfigOptionKeys.BlankLineBetweenUsingDirectives, "separate_groups"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.BlankLineBetweenUsingDirectives, "never") + : (ConfigOptionKeys.BlankLineBetweenUsingDirectives, "separate_groups"); + } case "RCS0027i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.BinaryOperatorNewLine, "before") - : (ConfigOptionKeys.BinaryOperatorNewLine, "after"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.BinaryOperatorNewLine, "before") + : (ConfigOptionKeys.BinaryOperatorNewLine, "after"); + } case "RCS0028i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ConditionalOperatorNewLine, "before") - : (ConfigOptionKeys.ConditionalOperatorNewLine, "after"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ConditionalOperatorNewLine, "before") + : (ConfigOptionKeys.ConditionalOperatorNewLine, "after"); + } case "RCS0032i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ArrowTokenNewLine, "before") - : (ConfigOptionKeys.ArrowTokenNewLine, "after"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ArrowTokenNewLine, "before") + : (ConfigOptionKeys.ArrowTokenNewLine, "after"); + } case "RCS0051i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.NewLineBeforeWhileInDoStatement, "true") - : (ConfigOptionKeys.NewLineBeforeWhileInDoStatement, "false"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.NewLineBeforeWhileInDoStatement, "true") + : (ConfigOptionKeys.NewLineBeforeWhileInDoStatement, "false"); + } case "RCS0052i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.EqualsTokenNewLine, "before") - : (ConfigOptionKeys.EqualsTokenNewLine, "after"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.EqualsTokenNewLine, "before") + : (ConfigOptionKeys.EqualsTokenNewLine, "after"); + } case "RCS1014a": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Explicit) - : (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_ImplicitWhenTypeIsObvious); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Explicit) + : (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_ImplicitWhenTypeIsObvious); + } case "RCS1014i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Explicit) - : (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Implicit); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Explicit) + : (ConfigOptionKeys.ArrayCreationTypeStyle, ConfigOptionValues.ArrayCreationTypeStyle_Implicit); + } case "RCS1016a": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.UseBlockBodyWhenExpressionSpansOverMultipleLines, "false") - : (ConfigOptionKeys.UseBlockBodyWhenExpressionSpansOverMultipleLines, "true"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.UseBlockBodyWhenExpressionSpansOverMultipleLines, "false") + : (ConfigOptionKeys.UseBlockBodyWhenExpressionSpansOverMultipleLines, "true"); + } case "RCS1016b": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.UseBlockBodyWhenDeclarationSpansOverMultipleLines, "false") - : (ConfigOptionKeys.UseBlockBodyWhenDeclarationSpansOverMultipleLines, "true"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.UseBlockBodyWhenDeclarationSpansOverMultipleLines, "false") + : (ConfigOptionKeys.UseBlockBodyWhenDeclarationSpansOverMultipleLines, "true"); + } case "RCS1016i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.BodyStyle, ConfigOptionValues.BodyStyle_Expression) - : (ConfigOptionKeys.BodyStyle, ConfigOptionValues.BodyStyle_Block); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.BodyStyle, ConfigOptionValues.BodyStyle_Expression) + : (ConfigOptionKeys.BodyStyle, ConfigOptionValues.BodyStyle_Block); + } case "RCS1018i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.AccessibilityModifiers, ConfigOptionValues.AccessibilityModifiers_Explicit) - : (ConfigOptionKeys.AccessibilityModifiers, ConfigOptionValues.AccessibilityModifiers_Implicit); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.AccessibilityModifiers, ConfigOptionValues.AccessibilityModifiers_Explicit) + : (ConfigOptionKeys.AccessibilityModifiers, ConfigOptionValues.AccessibilityModifiers_Implicit); + } case "RCS1036a": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.BlankLineBetweenClosingBraceAndSwitchSection, "true") - : (ConfigOptionKeys.BlankLineBetweenClosingBraceAndSwitchSection, "false"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.BlankLineBetweenClosingBraceAndSwitchSection, "true") + : (ConfigOptionKeys.BlankLineBetweenClosingBraceAndSwitchSection, "false"); + } case "RCS1050i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ObjectCreationParenthesesStyle, ConfigOptionValues.ObjectCreationParenthesesStyle_Include) - : (ConfigOptionKeys.ObjectCreationParenthesesStyle, ConfigOptionValues.ObjectCreationParenthesesStyle_Omit); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ObjectCreationParenthesesStyle, ConfigOptionValues.ObjectCreationParenthesesStyle_Include) + : (ConfigOptionKeys.ObjectCreationParenthesesStyle, ConfigOptionValues.ObjectCreationParenthesesStyle_Omit); + } case "RCS1051a": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ConditionalOperatorConditionParenthesesStyle, ConfigOptionValues.ConditionalOperatorConditionParenthesesStyle_Include) - : (ConfigOptionKeys.ConditionalOperatorConditionParenthesesStyle, ConfigOptionValues.ConditionalOperatorConditionParenthesesStyle_OmitWhenConditionIsSingleToken); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ConditionalOperatorConditionParenthesesStyle, ConfigOptionValues.ConditionalOperatorConditionParenthesesStyle_Include) + : (ConfigOptionKeys.ConditionalOperatorConditionParenthesesStyle, ConfigOptionValues.ConditionalOperatorConditionParenthesesStyle_OmitWhenConditionIsSingleToken); + } case "RCS1078i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.EmptyStringStyle, ConfigOptionValues.EmptyStringStyle_Literal) - : (ConfigOptionKeys.EmptyStringStyle, ConfigOptionValues.EmptyStringStyle_Field); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.EmptyStringStyle, ConfigOptionValues.EmptyStringStyle_Literal) + : (ConfigOptionKeys.EmptyStringStyle, ConfigOptionValues.EmptyStringStyle_Field); + } case "RCS1090i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.ConfigureAwait, "true") - : (ConfigOptionKeys.ConfigureAwait, "false"); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.ConfigureAwait, "true") + : (ConfigOptionKeys.ConfigureAwait, "false"); + } case "RCS1096i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.EnumHasFlagStyle, ConfigOptionValues.EnumHasFlagStyle_Operator) - : (ConfigOptionKeys.EnumHasFlagStyle, ConfigOptionValues.EnumHasFlagStyle_Method); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.EnumHasFlagStyle, ConfigOptionValues.EnumHasFlagStyle_Operator) + : (ConfigOptionKeys.EnumHasFlagStyle, ConfigOptionValues.EnumHasFlagStyle_Method); + } case "RCS1207i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.UseAnonymousFunctionOrMethodGroup, ConfigOptionValues.UseAnonymousFunctionOrMethodGroup_MethodGroup) - : (ConfigOptionKeys.UseAnonymousFunctionOrMethodGroup, ConfigOptionValues.UseAnonymousFunctionOrMethodGroup_AnonymousFunction); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.UseAnonymousFunctionOrMethodGroup, ConfigOptionValues.UseAnonymousFunctionOrMethodGroup_MethodGroup) + : (ConfigOptionKeys.UseAnonymousFunctionOrMethodGroup, ConfigOptionValues.UseAnonymousFunctionOrMethodGroup_AnonymousFunction); + } case "RCS1248i": - { - return (kvp.Value == ReportDiagnostic.Suppress) - ? (ConfigOptionKeys.NullCheckStyle, ConfigOptionValues.NullCheckStyle_PatternMatching) - : (ConfigOptionKeys.NullCheckStyle, ConfigOptionValues.NullCheckStyle_EqualityOperator); - } + { + return (kvp.Value == ReportDiagnostic.Suppress) + ? (ConfigOptionKeys.NullCheckStyle, ConfigOptionValues.NullCheckStyle_PatternMatching) + : (ConfigOptionKeys.NullCheckStyle, ConfigOptionValues.NullCheckStyle_EqualityOperator); + } } Debug.Fail(kvp.Key); diff --git a/src/Common/RuleSetLoader.cs b/src/Common/RuleSetLoader.cs index 5b370a16d2..931d955e37 100644 --- a/src/Common/RuleSetLoader.cs +++ b/src/Common/RuleSetLoader.cs @@ -137,35 +137,35 @@ private static bool IsStricterThan(ReportDiagnostic action1, ReportDiagnostic ac switch (action2) { case ReportDiagnostic.Suppress: - { - return true; - } + { + return true; + } case ReportDiagnostic.Default: - { - return action1 == ReportDiagnostic.Warn - || action1 == ReportDiagnostic.Error - || action1 == ReportDiagnostic.Info - || action1 == ReportDiagnostic.Hidden; - } + { + return action1 == ReportDiagnostic.Warn + || action1 == ReportDiagnostic.Error + || action1 == ReportDiagnostic.Info + || action1 == ReportDiagnostic.Hidden; + } case ReportDiagnostic.Hidden: - { - return action1 == ReportDiagnostic.Warn - || action1 == ReportDiagnostic.Error - || action1 == ReportDiagnostic.Info; - } + { + return action1 == ReportDiagnostic.Warn + || action1 == ReportDiagnostic.Error + || action1 == ReportDiagnostic.Info; + } case ReportDiagnostic.Info: - { - return action1 == ReportDiagnostic.Warn - || action1 == ReportDiagnostic.Error; - } + { + return action1 == ReportDiagnostic.Warn + || action1 == ReportDiagnostic.Error; + } case ReportDiagnostic.Warn: - { - return action1 == ReportDiagnostic.Error; - } + { + return action1 == ReportDiagnostic.Error; + } case ReportDiagnostic.Error: - { - return false; - } + { + return false; + } } return false; diff --git a/src/Core/CreateNameFromTypeSymbolHelper.cs b/src/Core/CreateNameFromTypeSymbolHelper.cs index c2bf6f99a7..32886cb5bf 100644 --- a/src/Core/CreateNameFromTypeSymbolHelper.cs +++ b/src/Core/CreateNameFromTypeSymbolHelper.cs @@ -79,25 +79,25 @@ private static ITypeSymbol ExtractFromArrayOrGenericCollection(ITypeSymbol typeS switch (typeSymbol.Kind) { case SymbolKind.ArrayType: - { - return ((IArrayTypeSymbol)typeSymbol).ElementType; - } + { + return ((IArrayTypeSymbol)typeSymbol).ElementType; + } case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; - ImmutableArray typeArguments = namedTypeSymbol.TypeArguments; - - if (typeArguments.Length == 1 - && namedTypeSymbol.Implements(SpecialType.System_Collections_IEnumerable, allInterfaces: true)) - { - ITypeSymbol typeArgument = typeArguments[0]; + { + var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; + ImmutableArray typeArguments = namedTypeSymbol.TypeArguments; - if (ValidateTypeArgumentName(typeArgument.Name)) - return typeArgument; - } + if (typeArguments.Length == 1 + && namedTypeSymbol.Implements(SpecialType.System_Collections_IEnumerable, allInterfaces: true)) + { + ITypeSymbol typeArgument = typeArguments[0]; - break; + if (ValidateTypeArgumentName(typeArgument.Name)) + return typeArgument; } + + break; + } } return typeSymbol; @@ -122,24 +122,24 @@ private static bool UsePlural(ITypeSymbol typeSymbol) switch (typeSymbol.Kind) { case SymbolKind.ArrayType: - { - return true; - } + { + return true; + } case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; - - if (namedTypeSymbol.TypeArguments.Length <= 1 - && !namedTypeSymbol.HasMetadataName(MetadataNames.System_Dynamic_ExpandoObject)) - { - ImmutableArray allInterfaces = typeSymbol.AllInterfaces; + { + var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; - return allInterfaces.Any(f => f.SpecialType == SpecialType.System_Collections_IEnumerable) - && !allInterfaces.Any(f => f.HasMetadataName(MetadataNames.System_Collections_IDictionary)); - } + if (namedTypeSymbol.TypeArguments.Length <= 1 + && !namedTypeSymbol.HasMetadataName(MetadataNames.System_Dynamic_ExpandoObject)) + { + ImmutableArray allInterfaces = typeSymbol.AllInterfaces; - break; + return allInterfaces.Any(f => f.SpecialType == SpecialType.System_Collections_IEnumerable) + && !allInterfaces.Any(f => f.HasMetadataName(MetadataNames.System_Collections_IDictionary)); } + + break; + } } return false; diff --git a/src/Core/DiagnosticIdPrefix.cs b/src/Core/DiagnosticIdPrefix.cs index 5c950adf87..dd1b1c9411 100644 --- a/src/Core/DiagnosticIdPrefix.cs +++ b/src/Core/DiagnosticIdPrefix.cs @@ -21,143 +21,143 @@ public static string GetPrefix(string id) switch (id[0]) { case 'A': + { + if (HasPrefix(AD)) { - if (HasPrefix(AD)) - { - return AD; - } - else if (HasPrefix(Async)) - { - return Async; - } - - break; + return AD; } - case 'B': + else if (HasPrefix(Async)) { - if (HasPrefix(BC)) - { - return BC; - } - else if (HasPrefix(BL)) - { - return BL; - } + return Async; + } - break; + break; + } + case 'B': + { + if (HasPrefix(BC)) + { + return BC; } + else if (HasPrefix(BL)) + { + return BL; + } + + break; + } case 'C': + { + if (HasPrefix(CA)) { - if (HasPrefix(CA)) - { - return CA; - } - else if (HasPrefix(CC)) - { - return CC; - } - else if (HasPrefix(CS)) - { - return CS; - } - - break; + return CA; } - case 'E': + else if (HasPrefix(CC)) + { + return CC; + } + else if (HasPrefix(CS)) { - if (HasPrefix(ENC)) - { - return ENC; - } + return CS; + } - break; + break; + } + case 'E': + { + if (HasPrefix(ENC)) + { + return ENC; } + + break; + } case 'I': + { + if (HasPrefix(IDE)) { - if (HasPrefix(IDE)) - { - return IDE; - } - else if (HasPrefix(IL)) - { - return IL; - } - - break; + return IDE; } + else if (HasPrefix(IL)) + { + return IL; + } + + break; + } case 'R': + { + if (HasPrefix(RCS)) { - if (HasPrefix(RCS)) - { - return RCS; - } - else if (HasPrefix(ROS)) - { - return ROS; - } - else if (HasPrefix(RECS)) - { - return RECS; - } - else if (HasPrefix(REVB)) - { - return REVB; - } - else if (HasPrefix(RS)) - { - return RS; - } - - break; + return RCS; } - case 'S': + else if (HasPrefix(ROS)) { - if (HasPrefix(SA)) - { - return SA; - } - else if (HasPrefix(SX)) - { - return SX; - } + return ROS; + } + else if (HasPrefix(RECS)) + { + return RECS; + } + else if (HasPrefix(REVB)) + { + return REVB; + } + else if (HasPrefix(RS)) + { + return RS; + } - break; + break; + } + case 'S': + { + if (HasPrefix(SA)) + { + return SA; } - case 'U': + else if (HasPrefix(SX)) { - if (HasPrefix(U2U)) - { - return U2U; - } + return SX; + } - break; + break; + } + case 'U': + { + if (HasPrefix(U2U)) + { + return U2U; } + + break; + } case 'V': + { + if (HasPrefix(VB)) { - if (HasPrefix(VB)) - { - return VB; - } - else if (HasPrefix(VSSDK)) - { - return VSSDK; - } - else if (HasPrefix(VSTHRD)) - { - return VSTHRD; - } - - break; + return VB; } - case 'x': + else if (HasPrefix(VSSDK)) + { + return VSSDK; + } + else if (HasPrefix(VSTHRD)) { - if (HasPrefix(xUnit)) - { - return xUnit; - } + return VSTHRD; + } - break; + break; + } + case 'x': + { + if (HasPrefix(xUnit)) + { + return xUnit; } + + break; + } } int prefixLength = GetPrefixLength(id); diff --git a/src/Core/Extensions/EnumExtensions.cs b/src/Core/Extensions/EnumExtensions.cs index 15c57175a1..29fc651dfa 100644 --- a/src/Core/Extensions/EnumExtensions.cs +++ b/src/Core/Extensions/EnumExtensions.cs @@ -61,34 +61,34 @@ public static bool IsMoreRestrictiveThan(this Accessibility accessibility, Acces switch (other) { case Accessibility.Public: - { - return accessibility == Accessibility.Internal - || accessibility == Accessibility.ProtectedOrInternal - || accessibility == Accessibility.ProtectedAndInternal - || accessibility == Accessibility.Protected - || accessibility == Accessibility.Private; - } + { + return accessibility == Accessibility.Internal + || accessibility == Accessibility.ProtectedOrInternal + || accessibility == Accessibility.ProtectedAndInternal + || accessibility == Accessibility.Protected + || accessibility == Accessibility.Private; + } case Accessibility.Internal: - { - return accessibility == Accessibility.ProtectedAndInternal - || accessibility == Accessibility.Private; - } + { + return accessibility == Accessibility.ProtectedAndInternal + || accessibility == Accessibility.Private; + } case Accessibility.ProtectedOrInternal: - { - return accessibility == Accessibility.Internal - || accessibility == Accessibility.Protected - || accessibility == Accessibility.ProtectedAndInternal - || accessibility == Accessibility.Private; - } + { + return accessibility == Accessibility.Internal + || accessibility == Accessibility.Protected + || accessibility == Accessibility.ProtectedAndInternal + || accessibility == Accessibility.Private; + } case Accessibility.ProtectedAndInternal: case Accessibility.Protected: - { - return accessibility == Accessibility.Private; - } + { + return accessibility == Accessibility.Private; + } case Accessibility.Private: - { - return false; - } + { + return false; + } } return false; diff --git a/src/Core/Extensions/SymbolExtensions.cs b/src/Core/Extensions/SymbolExtensions.cs index f0aadf0bdb..a85030b525 100644 --- a/src/Core/Extensions/SymbolExtensions.cs +++ b/src/Core/Extensions/SymbolExtensions.cs @@ -518,58 +518,58 @@ internal static Visibility GetVisibility(this ISymbol symbol) case Accessibility.Public: case Accessibility.Protected: case Accessibility.ProtectedOrInternal: - { - symbol = symbol.ContainingType; - break; - } + { + symbol = symbol.ContainingType; + break; + } case Accessibility.Internal: case Accessibility.ProtectedAndInternal: - { - if (visibility == Visibility.Public) - visibility = Visibility.Internal; + { + if (visibility == Visibility.Public) + visibility = Visibility.Internal; - symbol = symbol.ContainingType; - break; - } + symbol = symbol.ContainingType; + break; + } case Accessibility.Private: - { - visibility = Visibility.Private; + { + visibility = Visibility.Private; - symbol = symbol.ContainingType; - break; - } + symbol = symbol.ContainingType; + break; + } case Accessibility.NotApplicable: + { + switch (symbol.Kind) { - switch (symbol.Kind) + case SymbolKind.Local: { - case SymbolKind.Local: - { - return Visibility.Private; - } - case SymbolKind.Parameter: - case SymbolKind.TypeParameter: - { - symbol = symbol.ContainingSymbol; - break; - } - case SymbolKind.Namespace: - case SymbolKind.Alias: - { - return Visibility.NotApplicable; - } - default: - { - Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); - return Visibility.NotApplicable; - } + return Visibility.Private; + } + case SymbolKind.Parameter: + case SymbolKind.TypeParameter: + { + symbol = symbol.ContainingSymbol; + break; + } + case SymbolKind.Namespace: + case SymbolKind.Alias: + { + return Visibility.NotApplicable; + } + default: + { + Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); + return Visibility.NotApplicable; } - - break; } + + break; + } default: - { - throw new InvalidOperationException($"Unknown accessibility '{symbol.DeclaredAccessibility}'."); - } + { + throw new InvalidOperationException($"Unknown accessibility '{symbol.DeclaredAccessibility}'."); + } } } while (symbol is not null); @@ -1532,30 +1532,30 @@ public static bool SupportsExplicitDeclaration(this ITypeSymbol typeSymbol) { case SymbolKind.TypeParameter: case SymbolKind.DynamicType: - { - return true; - } + { + return true; + } case SymbolKind.ArrayType: - { - return SupportsExplicitDeclaration(((IArrayTypeSymbol)typeSymbol).ElementType); - } + { + return SupportsExplicitDeclaration(((IArrayTypeSymbol)typeSymbol).ElementType); + } case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; + { + var namedTypeSymbol = (INamedTypeSymbol)typeSymbol; - if (typeSymbol.IsTupleType) + if (typeSymbol.IsTupleType) + { + foreach (IFieldSymbol tupleElement in namedTypeSymbol.TupleElements) { - foreach (IFieldSymbol tupleElement in namedTypeSymbol.TupleElements) - { - if (!SupportsExplicitDeclaration(tupleElement.Type)) - return false; - } - - return true; + if (!SupportsExplicitDeclaration(tupleElement.Type)) + return false; } - return SupportsExplicitDeclaration2(namedTypeSymbol.TypeArguments); + return true; } + + return SupportsExplicitDeclaration2(namedTypeSymbol.TypeArguments); + } } return false; @@ -1570,18 +1570,18 @@ static bool SupportsExplicitDeclaration2(ImmutableArray typeSymbols switch (symbol.Kind) { case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)symbol; + { + var namedTypeSymbol = (INamedTypeSymbol)symbol; - if (!SupportsExplicitDeclaration2(namedTypeSymbol.TypeArguments)) - return false; + if (!SupportsExplicitDeclaration2(namedTypeSymbol.TypeArguments)) + return false; - break; - } + break; + } case SymbolKind.ErrorType: - { - return false; - } + { + return false; + } } } diff --git a/src/Core/MetadataName.cs b/src/Core/MetadataName.cs index 4ba8a9056f..72d7760c67 100644 --- a/src/Core/MetadataName.cs +++ b/src/Core/MetadataName.cs @@ -118,38 +118,38 @@ internal string ToString(SymbolDisplayTypeQualificationStyle typeQualificationSt switch (typeQualificationStyle) { case SymbolDisplayTypeQualificationStyle.NameOnly: - { - return Name; - } + { + return Name; + } case SymbolDisplayTypeQualificationStyle.NameAndContainingTypes: - { - if (ContainingTypes.Any()) - return string.Join("+", ContainingTypes) + "+" + Name; + { + if (ContainingTypes.Any()) + return string.Join("+", ContainingTypes) + "+" + Name; - return Name; - } + return Name; + } case SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces: + { + if (ContainingNamespaces.Any()) { - if (ContainingNamespaces.Any()) + string @namespace = string.Join(".", ContainingNamespaces); + + if (ContainingTypes.Any()) { - string @namespace = string.Join(".", ContainingNamespaces); - - if (ContainingTypes.Any()) - { - return @namespace + "." + string.Join("+", ContainingTypes) + "+" + Name; - } - else - { - return @namespace + "." + Name; - } + return @namespace + "." + string.Join("+", ContainingTypes) + "+" + Name; } - else if (ContainingTypes.Any()) + else { - return string.Join("+", ContainingTypes) + "+" + Name; + return @namespace + "." + Name; } - - return Name; } + else if (ContainingTypes.Any()) + { + return string.Join("+", ContainingTypes) + "+" + Name; + } + + return Name; + } } throw new ArgumentException($"Unknown enum value '{typeQualificationStyle}'.", nameof(typeQualificationStyle)); diff --git a/src/Core/OneOrMany`1.cs b/src/Core/OneOrMany`1.cs index 9ca1ff914a..8871547dc8 100644 --- a/src/Core/OneOrMany`1.cs +++ b/src/Core/OneOrMany`1.cs @@ -37,16 +37,16 @@ public T this[int index] switch (_state) { case State.One: - { - if (index == 0) - return _value!; + { + if (index == 0) + return _value!; - break; - } + break; + } case State.Many: - { - return _values[index]; - } + { + return _values[index]; + } } throw new ArgumentOutOfRangeException(nameof(index), index, ""); @@ -102,19 +102,19 @@ public bool Equals(OneOrMany other) switch (_state) { case State.Default: - { - return other._state == State.Default; - } + { + return other._state == State.Default; + } case State.One: - { - return other._state == State.One - && EqualityComparer.Default.Equals(_value!, other._value!); - } + { + return other._state == State.One + && EqualityComparer.Default.Equals(_value!, other._value!); + } case State.Many: - { - return other._state == State.Many - && _values.Equals(other._values); - } + { + return other._state == State.Many + && _values.Equals(other._values); + } } throw new InvalidOperationException(); diff --git a/src/Documentation/DocumentationGenerator.cs b/src/Documentation/DocumentationGenerator.cs index 0827f87ee5..e213d9cf24 100644 --- a/src/Documentation/DocumentationGenerator.cs +++ b/src/Documentation/DocumentationGenerator.cs @@ -257,56 +257,56 @@ private void GenerateRoot(DocumentationWriter writer) switch (part) { case RootDocumentationParts.Content: - { - IEnumerable names = EnabledAndSortedRootParts - .Where(f => HasContent(f)) - .OrderBy(f => f, RootPartComparer) - .Select(f => Resources.GetHeading(f)); + { + IEnumerable names = EnabledAndSortedRootParts + .Where(f => HasContent(f)) + .OrderBy(f => f, RootPartComparer) + .Select(f => Resources.GetHeading(f)); - if ((Options.IgnoredRootParts & RootDocumentationParts.Content) == 0) - writer.WriteContent(names); + if ((Options.IgnoredRootParts & RootDocumentationParts.Content) == 0) + writer.WriteContent(names); - break; - } + break; + } case RootDocumentationParts.Types: case RootDocumentationParts.Namespaces: - { - IEnumerable namespaceSymbols = typeSymbols - .Select(f => f.ContainingNamespace) - .Distinct(MetadataNameEqualityComparer.Instance); + { + IEnumerable namespaceSymbols = typeSymbols + .Select(f => f.ContainingNamespace) + .Distinct(MetadataNameEqualityComparer.Instance); - bool includeTypes = (Options.IgnoredRootParts & RootDocumentationParts.Types) == 0; + bool includeTypes = (Options.IgnoredRootParts & RootDocumentationParts.Types) == 0; - writer.WriteTypesByNamespace( - typeSymbols, - (includeTypes) ? Resources.TypesTitle : Resources.NamespacesTitle, - 2, - includeTypes: includeTypes); + writer.WriteTypesByNamespace( + typeSymbols, + (includeTypes) ? Resources.TypesTitle : Resources.NamespacesTitle, + 2, + includeTypes: includeTypes); - break; - } + break; + } case RootDocumentationParts.ClassHierarchy: + { + if (typeSymbols.Any(f => !f.IsStatic && f.TypeKind == TypeKind.Class)) { - if (typeSymbols.Any(f => !f.IsStatic && f.TypeKind == TypeKind.Class)) - { - INamedTypeSymbol objectType = DocumentationModel.Compilations[0].ObjectType; + INamedTypeSymbol objectType = DocumentationModel.Compilations[0].ObjectType; - IEnumerable instanceClasses = typeSymbols.Where(f => !f.IsStatic && f.TypeKind == TypeKind.Class); + IEnumerable instanceClasses = typeSymbols.Where(f => !f.IsStatic && f.TypeKind == TypeKind.Class); - writer.WriteHeading2(Resources.ClassHierarchyTitle); + writer.WriteHeading2(Resources.ClassHierarchyTitle); - writer.WriteClassHierarchy(objectType, instanceClasses, includeContainingNamespace: Options.IncludeContainingNamespace(IncludeContainingNamespaceFilter.ClassHierarchy)); - - writer.WriteLine(); - } + writer.WriteClassHierarchy(objectType, instanceClasses, includeContainingNamespace: Options.IncludeContainingNamespace(IncludeContainingNamespaceFilter.ClassHierarchy)); - break; + writer.WriteLine(); } + + break; + } case RootDocumentationParts.Other: - { - GenerateExternalTypesExtensions(writer); - break; - } + { + GenerateExternalTypesExtensions(writer); + break; + } } } @@ -355,97 +355,97 @@ private DocumentationGeneratorResult GenerateNamespace(INamespaceSymbol namespac switch (part) { case NamespaceDocumentationParts.Content: - { - IEnumerable names = EnabledAndSortedNamespaceParts - .Where(f => HasContent(f)) - .OrderBy(f => f, NamespacePartComparer) - .Select(f => Resources.GetHeading(f)); + { + IEnumerable names = EnabledAndSortedNamespaceParts + .Where(f => HasContent(f)) + .OrderBy(f => f, NamespacePartComparer) + .Select(f => Resources.GetHeading(f)); - if ((Options.IgnoredNamespaceParts & NamespaceDocumentationParts.Content) == 0) - writer.WriteContent(names, includeLinkToRoot: true); + if ((Options.IgnoredNamespaceParts & NamespaceDocumentationParts.Content) == 0) + writer.WriteContent(names, includeLinkToRoot: true); - break; - } + break; + } case NamespaceDocumentationParts.ContainingNamespace: - { - INamespaceSymbol containingNamespace = namespaceSymbol.ContainingNamespace; + { + INamespaceSymbol containingNamespace = namespaceSymbol.ContainingNamespace; - if (containingNamespace?.IsGlobalNamespace == false) - writer.WriteContainingNamespace(containingNamespace, Resources.ContainingNamespaceTitle); + if (containingNamespace?.IsGlobalNamespace == false) + writer.WriteContainingNamespace(containingNamespace, Resources.ContainingNamespaceTitle); - break; - } + break; + } case NamespaceDocumentationParts.Summary: - { - xmlDocumentation?.GetElement(WellKnownXmlTags.Summary)?.WriteContentTo(writer); - break; - } + { + xmlDocumentation?.GetElement(WellKnownXmlTags.Summary)?.WriteContentTo(writer); + break; + } case NamespaceDocumentationParts.Examples: - { - if (xmlDocumentation is not null) - writer.WriteExamples(namespaceSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteExamples(namespaceSymbol, xmlDocumentation); - break; - } + break; + } case NamespaceDocumentationParts.Remarks: - { - if (xmlDocumentation is not null) - writer.WriteRemarks(namespaceSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteRemarks(namespaceSymbol, xmlDocumentation); - break; - } + break; + } case NamespaceDocumentationParts.Classes: - { - WriteTypes(typeSymbols, TypeKind.Class); - break; - } + { + WriteTypes(typeSymbols, TypeKind.Class); + break; + } case NamespaceDocumentationParts.Structs: - { - WriteTypes(typeSymbols, TypeKind.Struct); - break; - } + { + WriteTypes(typeSymbols, TypeKind.Struct); + break; + } case NamespaceDocumentationParts.Interfaces: - { - WriteTypes(typeSymbols, TypeKind.Interface); - break; - } + { + WriteTypes(typeSymbols, TypeKind.Interface); + break; + } case NamespaceDocumentationParts.Enums: - { - WriteTypes(typeSymbols, TypeKind.Enum); - break; - } + { + WriteTypes(typeSymbols, TypeKind.Enum); + break; + } case NamespaceDocumentationParts.Delegates: - { - WriteTypes(typeSymbols, TypeKind.Delegate); - break; - } + { + WriteTypes(typeSymbols, TypeKind.Delegate); + break; + } case NamespaceDocumentationParts.Namespaces: + { + if (HasContent(NamespaceDocumentationParts.Namespaces)) { - if (HasContent(NamespaceDocumentationParts.Namespaces)) - { - IEnumerable namespaces = DocumentationModel - .Types - .SelectMany(f => f.GetContainingNamespaces()) - .Where(f => MetadataNameEqualityComparer.Instance.Equals(f.ContainingNamespace, namespaceSymbol)) - .Distinct(MetadataNameEqualityComparer.Instance) - .OrderBy(f => f, SymbolDefinitionComparer.SystemFirst); - - WriteNamespaces(namespaces); - } + IEnumerable namespaces = DocumentationModel + .Types + .SelectMany(f => f.GetContainingNamespaces()) + .Where(f => MetadataNameEqualityComparer.Instance.Equals(f.ContainingNamespace, namespaceSymbol)) + .Distinct(MetadataNameEqualityComparer.Instance) + .OrderBy(f => f, SymbolDefinitionComparer.SystemFirst); - break; + WriteNamespaces(namespaces); } + + break; + } case NamespaceDocumentationParts.SeeAlso: - { - if (xmlDocumentation is not null) - writer.WriteSeeAlso(namespaceSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteSeeAlso(namespaceSymbol, xmlDocumentation); - break; - } + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } @@ -486,53 +486,53 @@ bool HasContent(NamespaceDocumentationParts part) case NamespaceDocumentationParts.Content: case NamespaceDocumentationParts.Summary: case NamespaceDocumentationParts.ContainingNamespace: - { - return false; - } + { + return false; + } case NamespaceDocumentationParts.Examples: - { - return xmlDocumentation?.HasElement(WellKnownXmlTags.Example) == true; - } + { + return xmlDocumentation?.HasElement(WellKnownXmlTags.Example) == true; + } case NamespaceDocumentationParts.Remarks: - { - return xmlDocumentation?.HasElement(WellKnownXmlTags.Remarks) == true; - } + { + return xmlDocumentation?.HasElement(WellKnownXmlTags.Remarks) == true; + } case NamespaceDocumentationParts.Classes: - { - return typeSymbols.Any(f => f.TypeKind == TypeKind.Class); - } + { + return typeSymbols.Any(f => f.TypeKind == TypeKind.Class); + } case NamespaceDocumentationParts.Structs: - { - return typeSymbols.Any(f => f.TypeKind == TypeKind.Struct); - } + { + return typeSymbols.Any(f => f.TypeKind == TypeKind.Struct); + } case NamespaceDocumentationParts.Interfaces: - { - return typeSymbols.Any(f => f.TypeKind == TypeKind.Interface); - } + { + return typeSymbols.Any(f => f.TypeKind == TypeKind.Interface); + } case NamespaceDocumentationParts.Enums: - { - return typeSymbols.Any(f => f.TypeKind == TypeKind.Enum); - } + { + return typeSymbols.Any(f => f.TypeKind == TypeKind.Enum); + } case NamespaceDocumentationParts.Delegates: - { - return typeSymbols.Any(f => f.TypeKind == TypeKind.Delegate); - } + { + return typeSymbols.Any(f => f.TypeKind == TypeKind.Delegate); + } case NamespaceDocumentationParts.Namespaces: - { - return !typeSymbols.Any() - && DocumentationModel - .Types - .SelectMany(f => f.GetContainingNamespaces()) - .Any(f => MetadataNameEqualityComparer.Instance.Equals(f.ContainingNamespace, namespaceSymbol)); - } + { + return !typeSymbols.Any() + && DocumentationModel + .Types + .SelectMany(f => f.GetContainingNamespaces()) + .Any(f => MetadataNameEqualityComparer.Instance.Equals(f.ContainingNamespace, namespaceSymbol)); + } case NamespaceDocumentationParts.SeeAlso: - { - return xmlDocumentation?.GetElements(WellKnownXmlTags.SeeAlso).Any() == true; - } + { + return xmlDocumentation?.GetElements(WellKnownXmlTags.SeeAlso).Any() == true; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } @@ -619,195 +619,195 @@ private DocumentationGeneratorResult GenerateType(TypeDocumentationModel typeMod switch (part) { case TypeDocumentationParts.Content: - { - IEnumerable names = EnabledAndSortedTypeParts - .Where(f => HasContent(f)) - .OrderBy(f => f, TypePartComparer) - .Select(f => Resources.GetHeading(f)); + { + IEnumerable names = EnabledAndSortedTypeParts + .Where(f => HasContent(f)) + .OrderBy(f => f, TypePartComparer) + .Select(f => Resources.GetHeading(f)); - if ((Options.IgnoredTypeParts & TypeDocumentationParts.Content) == 0) - writer.WriteContent(names, includeLinkToRoot: true); + if ((Options.IgnoredTypeParts & TypeDocumentationParts.Content) == 0) + writer.WriteContent(names, includeLinkToRoot: true); - break; - } + break; + } case TypeDocumentationParts.ContainingNamespace: - { - INamespaceSymbol containingNamespace = typeModel.ContainingNamespace; + { + INamespaceSymbol containingNamespace = typeModel.ContainingNamespace; - if (containingNamespace is not null) - writer.WriteContainingNamespace(containingNamespace, Resources.NamespaceTitle); + if (containingNamespace is not null) + writer.WriteContainingNamespace(containingNamespace, Resources.NamespaceTitle); - break; - } + break; + } case TypeDocumentationParts.ContainingAssembly: - { - writer.WriteContainingAssembly(typeModel.ContainingAssembly, Resources.AssemblyTitle); - break; - } + { + writer.WriteContainingAssembly(typeModel.ContainingAssembly, Resources.AssemblyTitle); + break; + } case TypeDocumentationParts.ObsoleteMessage: - { - if (typeModel.IsObsolete) - writer.WriteObsoleteMessage(typeSymbol); + { + if (typeModel.IsObsolete) + writer.WriteObsoleteMessage(typeSymbol); - break; - } + break; + } case TypeDocumentationParts.Summary: - { - if (xmlDocumentation is not null) - writer.WriteSummary(typeSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteSummary(typeSymbol, xmlDocumentation); - break; - } + break; + } case TypeDocumentationParts.Declaration: - { - writer.WriteDefinition(typeSymbol); - break; - } + { + writer.WriteDefinition(typeSymbol); + break; + } case TypeDocumentationParts.TypeParameters: - { - writer.WriteTypeParameters(typeModel.TypeParameters); - break; - } + { + writer.WriteTypeParameters(typeModel.TypeParameters); + break; + } case TypeDocumentationParts.Parameters: - { - writer.WriteParameters(typeModel.Parameters); - break; - } + { + writer.WriteParameters(typeModel.Parameters); + break; + } case TypeDocumentationParts.ReturnValue: - { - if (xmlDocumentation is not null) - writer.WriteReturnType(typeSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteReturnType(typeSymbol, xmlDocumentation); - break; - } + break; + } case TypeDocumentationParts.Inheritance: - { - writer.WriteInheritance(typeSymbol); - break; - } + { + writer.WriteInheritance(typeSymbol); + break; + } case TypeDocumentationParts.Attributes: - { - writer.WriteAttributes(typeSymbol); - break; - } + { + writer.WriteAttributes(typeSymbol); + break; + } case TypeDocumentationParts.Derived: - { - if (derivedTypes.Any()) - writer.WriteDerivedTypes(derivedTypes); + { + if (derivedTypes.Any()) + writer.WriteDerivedTypes(derivedTypes); - break; - } + break; + } case TypeDocumentationParts.Implements: - { - writer.WriteImplementedInterfaces(typeModel.GetImplementedInterfaces(Options.OmitIEnumerable)); - break; - } + { + writer.WriteImplementedInterfaces(typeModel.GetImplementedInterfaces(Options.OmitIEnumerable)); + break; + } case TypeDocumentationParts.Examples: - { - if (xmlDocumentation is not null) - writer.WriteExamples(typeSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteExamples(typeSymbol, xmlDocumentation); - break; - } + break; + } case TypeDocumentationParts.Remarks: - { - if (xmlDocumentation is not null) - writer.WriteRemarks(typeSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteRemarks(typeSymbol, xmlDocumentation); - break; - } + break; + } case TypeDocumentationParts.Constructors: + { + writer.WriteConstructors(typeModel.GetConstructors()); + break; + } + case TypeDocumentationParts.Fields: + { + if (typeModel.TypeKind == TypeKind.Enum) { - writer.WriteConstructors(typeModel.GetConstructors()); - break; + writer.WriteEnumFields(typeModel.GetFields(), typeSymbol); } - case TypeDocumentationParts.Fields: + else { - if (typeModel.TypeKind == TypeKind.Enum) - { - writer.WriteEnumFields(typeModel.GetFields(), typeSymbol); - } - else - { - writer.WriteFields(typeModel.GetFields(includeInherited: includeInherited), containingType: typeSymbol); - } - - break; + writer.WriteFields(typeModel.GetFields(includeInherited: includeInherited), containingType: typeSymbol); } + + break; + } case TypeDocumentationParts.Indexers: - { - writer.WriteIndexers(typeModel.GetIndexers(includeInherited: includeInherited), containingType: typeSymbol); - break; - } + { + writer.WriteIndexers(typeModel.GetIndexers(includeInherited: includeInherited), containingType: typeSymbol); + break; + } case TypeDocumentationParts.Properties: - { - writer.WriteProperties(typeModel.GetProperties(includeInherited: includeInherited), containingType: typeSymbol); - break; - } + { + writer.WriteProperties(typeModel.GetProperties(includeInherited: includeInherited), containingType: typeSymbol); + break; + } case TypeDocumentationParts.Methods: - { - writer.WriteMethods(typeModel.GetMethods(includeInherited: includeInherited), containingType: typeSymbol); - break; - } + { + writer.WriteMethods(typeModel.GetMethods(includeInherited: includeInherited), containingType: typeSymbol); + break; + } case TypeDocumentationParts.Operators: - { - writer.WriteOperators(typeModel.GetOperators(includeInherited: true), containingType: typeSymbol); - break; - } + { + writer.WriteOperators(typeModel.GetOperators(includeInherited: true), containingType: typeSymbol); + break; + } case TypeDocumentationParts.Events: - { - writer.WriteEvents(typeModel.GetEvents(includeInherited: includeInherited), containingType: typeSymbol); - break; - } + { + writer.WriteEvents(typeModel.GetEvents(includeInherited: includeInherited), containingType: typeSymbol); + break; + } case TypeDocumentationParts.ExplicitInterfaceImplementations: - { - writer.WriteExplicitInterfaceImplementations(typeModel.GetExplicitImplementations()); - break; - } + { + writer.WriteExplicitInterfaceImplementations(typeModel.GetExplicitImplementations()); + break; + } case TypeDocumentationParts.ExtensionMethods: - { - writer.WriteExtensionMethods(DocumentationModel.GetExtensionMethods(typeSymbol)); - break; - } + { + writer.WriteExtensionMethods(DocumentationModel.GetExtensionMethods(typeSymbol)); + break; + } case TypeDocumentationParts.Classes: - { - writer.WriteNestedTypes(typeModel.GetClasses(includeInherited: includeInherited), TypeKind.Class, typeSymbol); - break; - } + { + writer.WriteNestedTypes(typeModel.GetClasses(includeInherited: includeInherited), TypeKind.Class, typeSymbol); + break; + } case TypeDocumentationParts.Structs: - { - writer.WriteNestedTypes(typeModel.GetStructs(includeInherited: includeInherited), TypeKind.Struct, typeSymbol); - break; - } + { + writer.WriteNestedTypes(typeModel.GetStructs(includeInherited: includeInherited), TypeKind.Struct, typeSymbol); + break; + } case TypeDocumentationParts.Interfaces: - { - writer.WriteNestedTypes(typeModel.GetInterfaces(includeInherited: includeInherited), TypeKind.Interface, typeSymbol); - break; - } + { + writer.WriteNestedTypes(typeModel.GetInterfaces(includeInherited: includeInherited), TypeKind.Interface, typeSymbol); + break; + } case TypeDocumentationParts.Enums: - { - writer.WriteNestedTypes(typeModel.GetEnums(includeInherited: includeInherited), TypeKind.Enum, typeSymbol); - break; - } + { + writer.WriteNestedTypes(typeModel.GetEnums(includeInherited: includeInherited), TypeKind.Enum, typeSymbol); + break; + } case TypeDocumentationParts.Delegates: - { - writer.WriteNestedTypes(typeModel.GetDelegates(includeInherited: includeInherited), TypeKind.Delegate, typeSymbol); - break; - } + { + writer.WriteNestedTypes(typeModel.GetDelegates(includeInherited: includeInherited), TypeKind.Delegate, typeSymbol); + break; + } case TypeDocumentationParts.AppliesTo: - { - if (SourceReferenceProvider is not null) - writer.WriteAppliesTo(typeSymbol, SourceReferenceProvider.GetSourceReferences(typeSymbol)); + { + if (SourceReferenceProvider is not null) + writer.WriteAppliesTo(typeSymbol, SourceReferenceProvider.GetSourceReferences(typeSymbol)); - break; - } + break; + } case TypeDocumentationParts.SeeAlso: - { - if (xmlDocumentation is not null) - writer.WriteSeeAlso(typeSymbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteSeeAlso(typeSymbol, xmlDocumentation); - break; - } + break; + } } } @@ -845,88 +845,88 @@ bool HasContent(TypeDocumentationParts part) case TypeDocumentationParts.Derived: case TypeDocumentationParts.Implements: case TypeDocumentationParts.AppliesTo: - { - return false; - } + { + return false; + } case TypeDocumentationParts.Examples: - { - return xmlDocumentation?.HasElement(WellKnownXmlTags.Example) == true; - } + { + return xmlDocumentation?.HasElement(WellKnownXmlTags.Example) == true; + } case TypeDocumentationParts.Remarks: - { - return xmlDocumentation?.HasElement(WellKnownXmlTags.Remarks) == true; - } + { + return xmlDocumentation?.HasElement(WellKnownXmlTags.Remarks) == true; + } case TypeDocumentationParts.Constructors: - { - return typeModel.GetConstructors().Any(); - } + { + return typeModel.GetConstructors().Any(); + } case TypeDocumentationParts.Fields: + { + if (typeModel.TypeKind == TypeKind.Enum) { - if (typeModel.TypeKind == TypeKind.Enum) - { - return typeModel.GetFields().Any(); - } - else - { - return typeModel.GetFields(includeInherited: true).Any(); - } + return typeModel.GetFields().Any(); } - case TypeDocumentationParts.Indexers: + else { - return typeModel.GetIndexers(includeInherited: includeInherited).Any(); + return typeModel.GetFields(includeInherited: true).Any(); } + } + case TypeDocumentationParts.Indexers: + { + return typeModel.GetIndexers(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Properties: - { - return typeModel.GetProperties(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetProperties(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Methods: - { - return typeModel.GetMethods(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetMethods(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Operators: - { - return typeModel.GetOperators(includeInherited: true).Any(); - } + { + return typeModel.GetOperators(includeInherited: true).Any(); + } case TypeDocumentationParts.Events: - { - return typeModel.GetEvents(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetEvents(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.ExplicitInterfaceImplementations: - { - return typeModel.GetExplicitImplementations().Any(); - } + { + return typeModel.GetExplicitImplementations().Any(); + } case TypeDocumentationParts.ExtensionMethods: - { - return DocumentationModel.GetExtensionMethods(typeSymbol).Any(); - } + { + return DocumentationModel.GetExtensionMethods(typeSymbol).Any(); + } case TypeDocumentationParts.Classes: - { - return typeModel.GetClasses(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetClasses(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Structs: - { - return typeModel.GetStructs(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetStructs(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Interfaces: - { - return typeModel.GetInterfaces(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetInterfaces(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Enums: - { - return typeModel.GetEnums(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetEnums(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.Delegates: - { - return typeModel.GetDelegates(includeInherited: includeInherited).Any(); - } + { + return typeModel.GetDelegates(includeInherited: includeInherited).Any(); + } case TypeDocumentationParts.SeeAlso: - { - return xmlDocumentation?.GetElements(WellKnownXmlTags.SeeAlso).Any() == true; - } + { + return xmlDocumentation?.GetElements(WellKnownXmlTags.SeeAlso).Any() == true; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } @@ -1017,86 +1017,86 @@ void GenerateMemberContent(DocumentationWriter writer, ISymbol symbol, int headi switch (part) { case MemberDocumentationParts.ObsoleteMessage: - { - if (symbol.HasAttribute(MetadataNames.System_ObsoleteAttribute)) - writer.WriteObsoleteMessage(symbol); + { + if (symbol.HasAttribute(MetadataNames.System_ObsoleteAttribute)) + writer.WriteObsoleteMessage(symbol); - break; - } + break; + } case MemberDocumentationParts.Summary: - { - if (xmlDocumentation is not null) - writer.WriteSummary(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); + { + if (xmlDocumentation is not null) + writer.WriteSummary(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); - break; - } + break; + } case MemberDocumentationParts.Declaration: - { - writer.WriteDefinition(symbol); - break; - } + { + writer.WriteDefinition(symbol); + break; + } case MemberDocumentationParts.TypeParameters: - { - writer.WriteTypeParameters(symbol.GetTypeParameters()); - break; - } + { + writer.WriteTypeParameters(symbol.GetTypeParameters()); + break; + } case MemberDocumentationParts.Parameters: - { - writer.WriteParameters(symbol.GetParameters()); - break; - } + { + writer.WriteParameters(symbol.GetParameters()); + break; + } case MemberDocumentationParts.ReturnValue: - { - writer.WriteReturnType(symbol, xmlDocumentation); - break; - } + { + writer.WriteReturnType(symbol, xmlDocumentation); + break; + } case MemberDocumentationParts.Implements: - { - writer.WriteImplementedInterfaceMembers(symbol.FindImplementedInterfaceMembers()); - break; - } + { + writer.WriteImplementedInterfaceMembers(symbol.FindImplementedInterfaceMembers()); + break; + } case MemberDocumentationParts.Attributes: - { - writer.WriteAttributes(symbol); - break; - } + { + writer.WriteAttributes(symbol); + break; + } case MemberDocumentationParts.Exceptions: - { - if (xmlDocumentation is not null) - writer.WriteExceptions(symbol, xmlDocumentation); + { + if (xmlDocumentation is not null) + writer.WriteExceptions(symbol, xmlDocumentation); - break; - } + break; + } case MemberDocumentationParts.Examples: - { - if (xmlDocumentation is not null) - writer.WriteExamples(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); + { + if (xmlDocumentation is not null) + writer.WriteExamples(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); - break; - } + break; + } case MemberDocumentationParts.Remarks: - { - if (xmlDocumentation is not null) - writer.WriteRemarks(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); + { + if (xmlDocumentation is not null) + writer.WriteRemarks(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); - break; - } + break; + } case MemberDocumentationParts.AppliesTo: - { - if (SourceReferenceProvider is null) - break; + { + if (SourceReferenceProvider is null) + break; - writer.WriteAppliesTo(symbol, SourceReferenceProvider.GetSourceReferences(symbol), headingLevelBase: headingLevelBase); + writer.WriteAppliesTo(symbol, SourceReferenceProvider.GetSourceReferences(symbol), headingLevelBase: headingLevelBase); - break; - } + break; + } case MemberDocumentationParts.SeeAlso: - { - if (xmlDocumentation is not null) - writer.WriteSeeAlso(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); + { + if (xmlDocumentation is not null) + writer.WriteSeeAlso(symbol, xmlDocumentation, headingLevelBase: headingLevelBase); - break; - } + break; + } } } } diff --git a/src/Documentation/DocumentationResources.cs b/src/Documentation/DocumentationResources.cs index 9c226d4d5e..a3391d7c0c 100644 --- a/src/Documentation/DocumentationResources.cs +++ b/src/Documentation/DocumentationResources.cs @@ -102,29 +102,29 @@ public string GetName(ISymbol symbol) case SymbolKind.Field: return FieldTitle; case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; - - switch (methodSymbol.MethodKind) - { - case MethodKind.Constructor: - return ConstructorTitle; - case MethodKind.Conversion: - case MethodKind.UserDefinedOperator: - return OperatorTitle; - case MethodKind.ExplicitInterfaceImplementation: - case MethodKind.Ordinary: - return MethodTitle; - } + { + var methodSymbol = (IMethodSymbol)symbol; - throw new InvalidOperationException(); + switch (methodSymbol.MethodKind) + { + case MethodKind.Constructor: + return ConstructorTitle; + case MethodKind.Conversion: + case MethodKind.UserDefinedOperator: + return OperatorTitle; + case MethodKind.ExplicitInterfaceImplementation: + case MethodKind.Ordinary: + return MethodTitle; } + + throw new InvalidOperationException(); + } case SymbolKind.Namespace: return NamespaceTitle; case SymbolKind.Property: - { - return (((IPropertySymbol)symbol).IsIndexer) ? IndexerTitle : PropertyTitle; - } + { + return (((IPropertySymbol)symbol).IsIndexer) ? IndexerTitle : PropertyTitle; + } case SymbolKind.NamedType: return GetName(((ITypeSymbol)symbol).TypeKind); } @@ -141,23 +141,23 @@ internal string GetPluralName(ISymbol symbol) case SymbolKind.Field: return FieldsTitle; case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; - - switch (methodSymbol.MethodKind) - { - case MethodKind.Constructor: - return ConstructorsTitle; - case MethodKind.Conversion: - case MethodKind.UserDefinedOperator: - return OperatorsTitle; - case MethodKind.ExplicitInterfaceImplementation: - case MethodKind.Ordinary: - return MethodsTitle; - } + { + var methodSymbol = (IMethodSymbol)symbol; - throw new InvalidOperationException(); + switch (methodSymbol.MethodKind) + { + case MethodKind.Constructor: + return ConstructorsTitle; + case MethodKind.Conversion: + case MethodKind.UserDefinedOperator: + return OperatorsTitle; + case MethodKind.ExplicitInterfaceImplementation: + case MethodKind.Ordinary: + return MethodsTitle; } + + throw new InvalidOperationException(); + } case SymbolKind.Namespace: return NamespacesTitle; case SymbolKind.Property: diff --git a/src/Documentation/DocumentationUtility.cs b/src/Documentation/DocumentationUtility.cs index f4f1abb7c4..191578be35 100644 --- a/src/Documentation/DocumentationUtility.cs +++ b/src/Documentation/DocumentationUtility.cs @@ -19,43 +19,43 @@ public static string GetSymbolLabel(ISymbol symbol, DocumentationContext context switch (context.Options.FilesLayout) { case FilesLayout.FlatNamespaces: + { + string label = symbol.ToDisplayString(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_OmittedAsContaining); + + if (context.CommonNamespaces.Count > 0 + && !context.CommonNamespaces.Contains((INamespaceSymbol)symbol, MetadataNameEqualityComparer.Instance)) { - string label = symbol.ToDisplayString(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_OmittedAsContaining); + (INamespaceSymbol symbol, string displayString) commonNamespace = default; - if (context.CommonNamespaces.Count > 0 - && !context.CommonNamespaces.Contains((INamespaceSymbol)symbol, MetadataNameEqualityComparer.Instance)) + foreach ((INamespaceSymbol _, string displayString) cn in context.CommonNamespacesAsText) { - (INamespaceSymbol symbol, string displayString) commonNamespace = default; - - foreach ((INamespaceSymbol _, string displayString) cn in context.CommonNamespacesAsText) + if (label.StartsWith(cn.displayString) + && label[cn.displayString.Length] == '.') { - if (label.StartsWith(cn.displayString) - && label[cn.displayString.Length] == '.') - { - Debug.Assert(commonNamespace == default); - commonNamespace = cn; - } + Debug.Assert(commonNamespace == default); + commonNamespace = cn; } - - Debug.Assert(commonNamespace != default); - - if (commonNamespace != default) - label = label.Substring(commonNamespace.displayString.Length + 1); } - return label; + Debug.Assert(commonNamespace != default); + + if (commonNamespace != default) + label = label.Substring(commonNamespace.displayString.Length + 1); } + + return label; + } case FilesLayout.Hierarchical: - { - if (context.CommonNamespaces.Contains((INamespaceSymbol)symbol, MetadataNameEqualityComparer.Instance)) - return symbol.ToDisplayString(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_OmittedAsContaining); + { + if (context.CommonNamespaces.Contains((INamespaceSymbol)symbol, MetadataNameEqualityComparer.Instance)) + return symbol.ToDisplayString(TypeSymbolDisplayFormats.Name_ContainingTypes_Namespaces_GlobalNamespace_OmittedAsContaining); - return symbol.Name; - } + return symbol.Name; + } default: - { - throw new InvalidOperationException($"Unknown value '{context.Options.FilesLayout}'."); - } + { + throw new InvalidOperationException($"Unknown value '{context.Options.FilesLayout}'."); + } } } else if (symbol.IsKind(SymbolKind.NamedType)) diff --git a/src/Documentation/DocumentationWriter.cs b/src/Documentation/DocumentationWriter.cs index 4c76aec13c..c6df7d2ee9 100644 --- a/src/Documentation/DocumentationWriter.cs +++ b/src/Documentation/DocumentationWriter.cs @@ -671,73 +671,73 @@ public virtual void WriteReturnType(ISymbol symbol, SymbolXmlDocumentation xmlDo switch (symbol.Kind) { case SymbolKind.NamedType: - { - var namedTypeSymbol = (INamedTypeSymbol)symbol; - - IMethodSymbol methodSymbol = namedTypeSymbol.DelegateInvokeMethod; + { + var namedTypeSymbol = (INamedTypeSymbol)symbol; - if (methodSymbol is not null) - { - ITypeSymbol returnType = methodSymbol.ReturnType; + IMethodSymbol methodSymbol = namedTypeSymbol.DelegateInvokeMethod; - if (returnType.SpecialType == SpecialType.System_Void) - return; + if (methodSymbol is not null) + { + ITypeSymbol returnType = methodSymbol.ReturnType; - WriteReturnType(returnType, Resources.ReturnValueTitle); + if (returnType.SpecialType == SpecialType.System_Void) + return; - xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); - } + WriteReturnType(returnType, Resources.ReturnValueTitle); - break; + xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); } + + break; + } case SymbolKind.Field: - { - var fieldSymbol = (IFieldSymbol)symbol; + { + var fieldSymbol = (IFieldSymbol)symbol; - WriteReturnType(fieldSymbol.Type, Resources.FieldValueTitle); - break; - } + WriteReturnType(fieldSymbol.Type, Resources.FieldValueTitle); + break; + } case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; + { + var methodSymbol = (IMethodSymbol)symbol; - switch (methodSymbol.MethodKind) + switch (methodSymbol.MethodKind) + { + case MethodKind.UserDefinedOperator: + case MethodKind.Conversion: { - case MethodKind.UserDefinedOperator: - case MethodKind.Conversion: - { - WriteReturnType(methodSymbol.ReturnType, Resources.ReturnsTitle); + WriteReturnType(methodSymbol.ReturnType, Resources.ReturnsTitle); - xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); - break; - } - default: - { - ITypeSymbol returnType = methodSymbol.ReturnType; + xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); + break; + } + default: + { + ITypeSymbol returnType = methodSymbol.ReturnType; - if (returnType.SpecialType == SpecialType.System_Void) - return; + if (returnType.SpecialType == SpecialType.System_Void) + return; - WriteReturnType(returnType, Resources.ReturnsTitle); + WriteReturnType(returnType, Resources.ReturnsTitle); - xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); - break; - } + xmlDocumentation?.GetElement(WellKnownXmlTags.Returns)?.WriteContentTo(this); + break; } - - break; } + + break; + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)symbol; + { + var propertySymbol = (IPropertySymbol)symbol; - WriteReturnType(propertySymbol.Type, Resources.PropertyValueTitle); + WriteReturnType(propertySymbol.Type, Resources.PropertyValueTitle); - string elementName = (propertySymbol.IsIndexer) ? WellKnownXmlTags.Returns : WellKnownXmlTags.Value; + string elementName = (propertySymbol.IsIndexer) ? WellKnownXmlTags.Returns : WellKnownXmlTags.Value; - xmlDocumentation?.GetElement(elementName)?.WriteContentTo(this); - break; - } + xmlDocumentation?.GetElement(elementName)?.WriteContentTo(this); + break; + } } void WriteReturnType(ITypeSymbol typeSymbol, string heading) @@ -754,16 +754,16 @@ public virtual void WriteInheritance(INamedTypeSymbol typeSymbol) switch (typeSymbol.TypeKind) { case TypeKind.Interface: - { - return; - } + { + return; + } case TypeKind.Class: - { - if (typeSymbol.IsStatic) - return; + { + if (typeSymbol.IsStatic) + return; - break; - } + break; + } } if (typeSymbol.BaseType is null) @@ -1952,27 +1952,27 @@ private string GetUrl( switch (symbol.Kind) { case SymbolKind.NamedType: - { - if (!CanCreateTypeLocalUrl) - return null; + { + if (!CanCreateTypeLocalUrl) + return null; - break; - } + break; + } case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: - { - if (!CanCreateMemberLocalUrl) - return null; + { + if (!CanCreateMemberLocalUrl) + return null; - break; - } + break; + } case SymbolKind.Parameter: case SymbolKind.TypeParameter: - { - return null; - } + { + return null; + } } if (DocumentationModel.IsExternal(symbol)) @@ -2035,57 +2035,57 @@ IEnumerable GetMembers(TypeDocumentationModel model) switch (symbol.Kind) { case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; + { + var methodSymbol = (IMethodSymbol)symbol; - switch (methodSymbol.MethodKind) + switch (methodSymbol.MethodKind) + { + case MethodKind.Constructor: + { + return model.GetConstructors(); + } + case MethodKind.Ordinary: + { + return model.GetMethods(); + } + case MethodKind.Conversion: + case MethodKind.UserDefinedOperator: { - case MethodKind.Constructor: - { - return model.GetConstructors(); - } - case MethodKind.Ordinary: - { - return model.GetMethods(); - } - case MethodKind.Conversion: - case MethodKind.UserDefinedOperator: - { - return model.GetOperators(); - } - case MethodKind.ExplicitInterfaceImplementation: - { - ImmutableArray explicitInterfaceImplementations = methodSymbol.ExplicitInterfaceImplementations; - - if (!explicitInterfaceImplementations.IsDefaultOrEmpty) - return model.GetExplicitImplementations(); - - break; - } + return model.GetOperators(); } + case MethodKind.ExplicitInterfaceImplementation: + { + ImmutableArray explicitInterfaceImplementations = methodSymbol.ExplicitInterfaceImplementations; - break; + if (!explicitInterfaceImplementations.IsDefaultOrEmpty) + return model.GetExplicitImplementations(); + + break; + } } + + break; + } case SymbolKind.Property: + { + var propertySymbol = (IPropertySymbol)symbol; + + if (propertySymbol.IsIndexer) { - var propertySymbol = (IPropertySymbol)symbol; + ImmutableArray explicitInterfaceImplementations = propertySymbol.ExplicitInterfaceImplementations; - if (propertySymbol.IsIndexer) + if (!explicitInterfaceImplementations.IsDefaultOrEmpty) { - ImmutableArray explicitInterfaceImplementations = propertySymbol.ExplicitInterfaceImplementations; - - if (!explicitInterfaceImplementations.IsDefaultOrEmpty) - { - return model.GetExplicitImplementations(); - } - else - { - return model.GetIndexers(); - } + return model.GetExplicitImplementations(); + } + else + { + return model.GetIndexers(); } - - break; } + + break; + } } return null; diff --git a/src/Documentation/Extensions/SymbolExtensions.cs b/src/Documentation/Extensions/SymbolExtensions.cs index 0187ce4bc2..1b1da86f47 100644 --- a/src/Documentation/Extensions/SymbolExtensions.cs +++ b/src/Documentation/Extensions/SymbolExtensions.cs @@ -185,95 +185,95 @@ public static ImmutableArray ToDisplayParts(this ISymbol symb switch (part.Kind) { case SymbolDisplayPartKind.Keyword: + { + switch (part.ToString()) { - switch (part.ToString()) + case "this": { - case "this": - { - if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseItemPropertyName) != 0 - && symbol is IPropertySymbol { IsIndexer: true }) - { - parts = parts.Replace(part, SymbolDisplayPartFactory.PropertyName("Item", part.Symbol)); - } + if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseItemPropertyName) != 0 + && symbol is IPropertySymbol { IsIndexer: true }) + { + parts = parts.Replace(part, SymbolDisplayPartFactory.PropertyName("Item", part.Symbol)); + } - break; + break; + } + case "operator": + { + if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseOperatorName) != 0 + && symbol is IMethodSymbol methodSymbol + && methodSymbol.MethodKind == MethodKind.UserDefinedOperator) + { + string name = methodSymbol.Name; + + Debug.Assert(name.StartsWith("op_", StringComparison.Ordinal), name); + + if (name.StartsWith("op_", StringComparison.Ordinal) + && i < length - 2 + && parts[i + 1].IsSpace() + && parts[i + 2].Kind == SymbolDisplayPartKind.Operator + && parts[i + 2].Symbol is IMethodSymbol { MethodKind: MethodKind.UserDefinedOperator }) + { + parts = parts.Replace(parts[i + 2], SymbolDisplayPartFactory.MethodName(name.Substring(3), parts[i + 2].Symbol)); + parts = parts.RemoveRange(i, 2); + length -= 2; } - case "operator": + } + + break; + } + case "implicit": + case "explicit": + { + if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseOperatorName) != 0 + && symbol is IMethodSymbol methodSymbol + && methodSymbol.MethodKind == MethodKind.Conversion) + { + string name = methodSymbol.Name; + + Debug.Assert(name.StartsWith("op_", StringComparison.Ordinal), name); + + if (name.StartsWith("op_", StringComparison.Ordinal) + && i < length - 2 + && parts[i + 1].IsSpace() + && parts[i + 2].IsKeyword("operator")) { - if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseOperatorName) != 0 - && symbol is IMethodSymbol methodSymbol - && methodSymbol.MethodKind == MethodKind.UserDefinedOperator) + List list = parts.ToList(); + + list[i + 2] = SymbolDisplayPartFactory.MethodName(name.Substring(3), list[i + 4].Symbol); + list.RemoveRange(i, 2); + length -= 2; + + if (i == length - 3 + && list[i + 1].IsSpace() + && list[i + 2].IsName()) { - string name = methodSymbol.Name; - - Debug.Assert(name.StartsWith("op_", StringComparison.Ordinal), name); - - if (name.StartsWith("op_", StringComparison.Ordinal) - && i < length - 2 - && parts[i + 1].IsSpace() - && parts[i + 2].Kind == SymbolDisplayPartKind.Operator - && parts[i + 2].Symbol is IMethodSymbol { MethodKind: MethodKind.UserDefinedOperator }) - { - parts = parts.Replace(parts[i + 2], SymbolDisplayPartFactory.MethodName(name.Substring(3), parts[i + 2].Symbol)); - parts = parts.RemoveRange(i, 2); - length -= 2; - } + list.RemoveRange(i + 1, 2); + length -= 2; } - - break; - } - case "implicit": - case "explicit": - { - if ((additionalOptions & SymbolDisplayAdditionalMemberOptions.UseOperatorName) != 0 - && symbol is IMethodSymbol methodSymbol - && methodSymbol.MethodKind == MethodKind.Conversion) + else if (i < length - 5 + && list[i + 1].IsSpace() + && list[i + 2].IsName() + && list[i + 3].IsPunctuation() + && list[i + 4].IsName() + && list[i + 5].IsPunctuation()) { - string name = methodSymbol.Name; - - Debug.Assert(name.StartsWith("op_", StringComparison.Ordinal), name); - - if (name.StartsWith("op_", StringComparison.Ordinal) - && i < length - 2 - && parts[i + 1].IsSpace() - && parts[i + 2].IsKeyword("operator")) - { - List list = parts.ToList(); - - list[i + 2] = SymbolDisplayPartFactory.MethodName(name.Substring(3), list[i + 4].Symbol); - list.RemoveRange(i, 2); - length -= 2; - - if (i == length - 3 - && list[i + 1].IsSpace() - && list[i + 2].IsName()) - { - list.RemoveRange(i + 1, 2); - length -= 2; - } - else if (i < length - 5 - && list[i + 1].IsSpace() - && list[i + 2].IsName() - && list[i + 3].IsPunctuation() - && list[i + 4].IsName() - && list[i + 5].IsPunctuation()) - { - list.Insert(i + 5, list[i + 2]); - list.Insert(i + 5, SymbolDisplayPartFactory.Text(" to ")); - list.RemoveRange(i + 1, 2); - length -= 5; - } - - parts = list.ToImmutableArray(); - } + list.Insert(i + 5, list[i + 2]); + list.Insert(i + 5, SymbolDisplayPartFactory.Text(" to ")); + list.RemoveRange(i + 1, 2); + length -= 5; } - break; + parts = list.ToImmutableArray(); } - } + } - break; + break; + } } + + break; + } } } @@ -346,45 +346,45 @@ public static bool IsExplicitImplementation(this ISymbol symbol, bool includeAcc switch (symbol.Kind) { case SymbolKind.Event: - { - var eventSymbol = (IEventSymbol)symbol; + { + var eventSymbol = (IEventSymbol)symbol; - return !eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty; - } + return !eventSymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty; + } case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; + { + var methodSymbol = (IMethodSymbol)symbol; - if (methodSymbol.MethodKind != MethodKind.ExplicitInterfaceImplementation) - return false; + if (methodSymbol.MethodKind != MethodKind.ExplicitInterfaceImplementation) + return false; - ImmutableArray explicitInterfaceImplementations = methodSymbol.ExplicitInterfaceImplementations; + ImmutableArray explicitInterfaceImplementations = methodSymbol.ExplicitInterfaceImplementations; - if (explicitInterfaceImplementations.IsDefaultOrEmpty) - return false; + if (explicitInterfaceImplementations.IsDefaultOrEmpty) + return false; - if (!includeAccessors) + if (!includeAccessors) + { + if (methodSymbol.MetadataName.EndsWith(".get_Item", StringComparison.Ordinal)) { - if (methodSymbol.MetadataName.EndsWith(".get_Item", StringComparison.Ordinal)) - { - if (explicitInterfaceImplementations[0].MethodKind == MethodKind.PropertyGet) - return false; - } - else if (methodSymbol.MetadataName.EndsWith(".set_Item", StringComparison.Ordinal)) - { - if (explicitInterfaceImplementations[0].MethodKind == MethodKind.PropertySet) - return false; - } + if (explicitInterfaceImplementations[0].MethodKind == MethodKind.PropertyGet) + return false; + } + else if (methodSymbol.MetadataName.EndsWith(".set_Item", StringComparison.Ordinal)) + { + if (explicitInterfaceImplementations[0].MethodKind == MethodKind.PropertySet) + return false; } - - return true; } + + return true; + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)symbol; + { + var propertySymbol = (IPropertySymbol)symbol; - return !propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty; - } + return !propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty; + } } return false; diff --git a/src/Documentation/Extensions/XmlExtensions.cs b/src/Documentation/Extensions/XmlExtensions.cs index a275397c64..77298dec8e 100644 --- a/src/Documentation/Extensions/XmlExtensions.cs +++ b/src/Documentation/Extensions/XmlExtensions.cs @@ -42,131 +42,131 @@ public static void WriteContentTo(this XElement element, DocumentationWriter wri switch (XmlTagMapper.GetTagOrDefault(e.Name.LocalName)) { case XmlTag.C: - { - string value = e.Value; - value = TextUtility.ToSingleLine(value); - writer.WriteInlineCode(value); - break; - } + { + string value = e.Value; + value = TextUtility.ToSingleLine(value); + writer.WriteInlineCode(value); + break; + } case XmlTag.Code: - { - if (inlineOnly) - break; + { + if (inlineOnly) + break; - string value = e.Value; - value = TextUtility.RemoveLeadingTrailingNewLine(value); + string value = e.Value; + value = TextUtility.RemoveLeadingTrailingNewLine(value); - writer.WriteCodeBlock(value); + writer.WriteCodeBlock(value); - break; - } + break; + } case XmlTag.List: - { - if (inlineOnly) - break; + { + if (inlineOnly) + break; - string type = e.Attribute("type")?.Value; + string type = e.Attribute("type")?.Value; - if (!string.IsNullOrEmpty(type)) + if (!string.IsNullOrEmpty(type)) + { + switch (type) { - switch (type) + case "bullet": { - case "bullet": - { - WriteList(writer, e.Elements()); - break; - } - case "number": - { - WriteList(writer, e.Elements(), isOrdered: true); - break; - } - case "table": - { - WriteTable(writer, e.Elements()); - break; - } - default: - { - Debug.Fail(type); - break; - } + WriteList(writer, e.Elements()); + break; + } + case "number": + { + WriteList(writer, e.Elements(), isOrdered: true); + break; + } + case "table": + { + WriteTable(writer, e.Elements()); + break; + } + default: + { + Debug.Fail(type); + break; } } - - break; } + + break; + } case XmlTag.Para: - { - if (inlineOnly) - break; - - writer.WriteLine(); - writer.WriteLine(); - WriteContentTo(e, writer); - writer.WriteLine(); - writer.WriteLine(); + { + if (inlineOnly) break; - } + + writer.WriteLine(); + writer.WriteLine(); + WriteContentTo(e, writer); + writer.WriteLine(); + writer.WriteLine(); + break; + } case XmlTag.ParamRef: - { - string parameterName = e.Attribute("name")?.Value; + { + string parameterName = e.Attribute("name")?.Value; - if (parameterName is not null) - writer.WriteBold(parameterName); + if (parameterName is not null) + writer.WriteBold(parameterName); - break; - } + break; + } case XmlTag.See: - { - string commentId = e.Attribute("cref")?.Value; + { + string commentId = e.Attribute("cref")?.Value; - if (commentId is not null) + if (commentId is not null) + { + ISymbol symbol = writer.DocumentationModel.GetFirstSymbolForDeclarationId(commentId); + + //TODO: repair roslyn documentation + Debug.Assert( + symbol is not null + || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxNode" + || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxToken" + || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxTrivia" + || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxNode" + || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxToken" + || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxTrivia", + commentId); + + if (symbol is not null) { - ISymbol symbol = writer.DocumentationModel.GetFirstSymbolForDeclarationId(commentId); - - //TODO: repair roslyn documentation - Debug.Assert( - symbol is not null - || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxNode" - || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxToken" - || commentId == "T:Microsoft.CodeAnalysis.CSharp.SyntaxTrivia" - || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxNode" - || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxToken" - || commentId == "T:Microsoft.CodeAnalysis.VisualBasic.SyntaxTrivia", - commentId); - - if (symbol is not null) + if (symbol.IsKind(SymbolKind.Field) + && symbol.ContainingType?.TypeKind == TypeKind.Enum) { - if (symbol.IsKind(SymbolKind.Field) - && symbol.ContainingType?.TypeKind == TypeKind.Enum) - { - writer.WriteLink(symbol.ContainingType, TypeSymbolDisplayFormats.Name_ContainingTypes_TypeParameters, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); - writer.WriteString("."); - writer.WriteSymbol(symbol, DocumentationDisplayFormats.SimpleDeclaration, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); - } - else - { - writer.WriteLink(symbol, TypeSymbolDisplayFormats.Name_ContainingTypes_TypeParameters, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); - } + writer.WriteLink(symbol.ContainingType, TypeSymbolDisplayFormats.Name_ContainingTypes_TypeParameters, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); + writer.WriteString("."); + writer.WriteSymbol(symbol, DocumentationDisplayFormats.SimpleDeclaration, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); } else { - writer.WriteBold(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); + writer.WriteLink(symbol, TypeSymbolDisplayFormats.Name_ContainingTypes_TypeParameters, SymbolDisplayAdditionalMemberOptions.UseItemPropertyName | SymbolDisplayAdditionalMemberOptions.UseOperatorName); } } - - break; + else + { + writer.WriteBold(TextUtility.RemovePrefixFromDocumentationCommentId(commentId)); + } } + + break; + } case XmlTag.TypeParamRef: - { - string typeParameterName = e.Attribute("name")?.Value; + { + string typeParameterName = e.Attribute("name")?.Value; - if (typeParameterName is not null) - writer.WriteBold(typeParameterName); + if (typeParameterName is not null) + writer.WriteBold(typeParameterName); - break; - } + break; + } case XmlTag.Example: case XmlTag.Exception: case XmlTag.Exclude: @@ -180,14 +180,14 @@ symbol is not null case XmlTag.Summary: case XmlTag.TypeParam: case XmlTag.Value: - { - break; - } + { + break; + } default: - { - Debug.Fail(e.Name.LocalName); - break; - } + { + Debug.Fail(e.Name.LocalName); + break; + } } } else diff --git a/src/Documentation/MemberSymbolEqualityComparer.cs b/src/Documentation/MemberSymbolEqualityComparer.cs index d831893efa..5ae2821515 100644 --- a/src/Documentation/MemberSymbolEqualityComparer.cs +++ b/src/Documentation/MemberSymbolEqualityComparer.cs @@ -29,109 +29,109 @@ public override bool Equals(ISymbol x, ISymbol y) { case SymbolKind.Event: case SymbolKind.Field: + { + switch (y.Kind) { - switch (y.Kind) - { - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - case SymbolKind.Property: - return true; - default: - return false; - } + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: + case SymbolKind.Property: + return true; + default: + return false; } + } case SymbolKind.Method: + { + switch (y.Kind) { - switch (y.Kind) + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Property: { - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Property: - { - return true; - } - case SymbolKind.Method: - { - var a = (IMethodSymbol)x; - var b = (IMethodSymbol)y; - - return a.MethodKind == MethodKind.Ordinary - && b.MethodKind == MethodKind.Ordinary - && a.TypeParameters.Length == b.TypeParameters.Length - && ParameterEqualityComparer.ParametersEqual(a.Parameters, b.Parameters); - } - default: - { - return false; - } + return true; + } + case SymbolKind.Method: + { + var a = (IMethodSymbol)x; + var b = (IMethodSymbol)y; + + return a.MethodKind == MethodKind.Ordinary + && b.MethodKind == MethodKind.Ordinary + && a.TypeParameters.Length == b.TypeParameters.Length + && ParameterEqualityComparer.ParametersEqual(a.Parameters, b.Parameters); + } + default: + { + return false; } } + } case SymbolKind.Property: + { + switch (y.Kind) { - switch (y.Kind) + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: { - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - { - return true; - } - case SymbolKind.Property: - { - var a = (IPropertySymbol)x; - var b = (IPropertySymbol)y; - - return a.IsIndexer == b.IsIndexer - && ParameterEqualityComparer.ParametersEqual(a.Parameters, b.Parameters); - } - default: - { - return false; - } + return true; + } + case SymbolKind.Property: + { + var a = (IPropertySymbol)x; + var b = (IPropertySymbol)y; + + return a.IsIndexer == b.IsIndexer + && ParameterEqualityComparer.ParametersEqual(a.Parameters, b.Parameters); + } + default: + { + return false; } } + } case SymbolKind.NamedType: - { - if (y.Kind != SymbolKind.NamedType) - return false; + { + if (y.Kind != SymbolKind.NamedType) + return false; - var a = (INamedTypeSymbol)x; - var b = (INamedTypeSymbol)y; + var a = (INamedTypeSymbol)x; + var b = (INamedTypeSymbol)y; - if (a.TypeParameters.Length != b.TypeParameters.Length) - return false; + if (a.TypeParameters.Length != b.TypeParameters.Length) + return false; - switch (a.TypeKind) + switch (a.TypeKind) + { + case TypeKind.Class: + case TypeKind.Delegate: + case TypeKind.Enum: + case TypeKind.Interface: + case TypeKind.Struct: { - case TypeKind.Class: - case TypeKind.Delegate: - case TypeKind.Enum: - case TypeKind.Interface: - case TypeKind.Struct: - { - switch (b.TypeKind) - { - case TypeKind.Class: - case TypeKind.Delegate: - case TypeKind.Enum: - case TypeKind.Interface: - case TypeKind.Struct: - return true; - default: - return false; - } - } - default: - { + switch (b.TypeKind) + { + case TypeKind.Class: + case TypeKind.Delegate: + case TypeKind.Enum: + case TypeKind.Interface: + case TypeKind.Struct: + return true; + default: return false; - } + } + } + default: + { + return false; } } + } default: - { - return false; - } + { + return false; + } } } diff --git a/src/Documentation/SymbolDefinitionDisplay.cs b/src/Documentation/SymbolDefinitionDisplay.cs index e7d455339f..ab586ef1e8 100644 --- a/src/Documentation/SymbolDefinitionDisplay.cs +++ b/src/Documentation/SymbolDefinitionDisplay.cs @@ -487,106 +487,106 @@ void AddConstantValue(TypedConstant typedConstant) switch (typedConstant.Kind) { case TypedConstantKind.Primitive: - { - parts.Add(new SymbolDisplayPart( - GetSymbolDisplayPart(typedConstant.Type.SpecialType), - null, - SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false))); + { + parts.Add(new SymbolDisplayPart( + GetSymbolDisplayPart(typedConstant.Type.SpecialType), + null, + SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false))); - break; - } + break; + } case TypedConstantKind.Enum: - { - OneOrMany oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type); + { + OneOrMany oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type); - OneOrMany.Enumerator en = oneOrMany.GetEnumerator(); + OneOrMany.Enumerator en = oneOrMany.GetEnumerator(); - if (en.MoveNext()) + if (en.MoveNext()) + { + while (true) { - while (true) + AddDisplayParts(parts, en.Current.Symbol, format, additionalOptions); + + if (en.MoveNext()) { - AddDisplayParts(parts, en.Current.Symbol, format, additionalOptions); - - if (en.MoveNext()) - { - parts.AddSpace(); - parts.AddPunctuation("|"); - parts.AddSpace(); - } - else - { - break; - } + parts.AddSpace(); + parts.AddPunctuation("|"); + parts.AddSpace(); + } + else + { + break; } } - else - { - parts.AddPunctuation("("); - AddDisplayParts(parts, (INamedTypeSymbol)typedConstant.Type, format, additionalOptions); - parts.AddPunctuation(")"); - parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.NumericLiteral, null, typedConstant.Value.ToString())); - } - - break; } - case TypedConstantKind.Type: + else { - if (typedConstant.Value is null) - { - parts.AddKeyword("null"); - } - else - { - parts.AddKeyword("typeof"); - parts.AddPunctuation("("); - AddDisplayParts(parts, (ISymbol)typedConstant.Value, format, additionalOptions); - parts.AddPunctuation(")"); - } + parts.AddPunctuation("("); + AddDisplayParts(parts, (INamedTypeSymbol)typedConstant.Type, format, additionalOptions); + parts.AddPunctuation(")"); + parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.NumericLiteral, null, typedConstant.Value.ToString())); + } - break; + break; + } + case TypedConstantKind.Type: + { + if (typedConstant.Value is null) + { + parts.AddKeyword("null"); } - case TypedConstantKind.Array: + else { - var arrayType = (IArrayTypeSymbol)typedConstant.Type; + parts.AddKeyword("typeof"); + parts.AddPunctuation("("); + AddDisplayParts(parts, (ISymbol)typedConstant.Value, format, additionalOptions); + parts.AddPunctuation(")"); + } - parts.AddKeyword("new"); - parts.AddSpace(); - AddDisplayParts(parts, arrayType.ElementType, format, additionalOptions); + break; + } + case TypedConstantKind.Array: + { + var arrayType = (IArrayTypeSymbol)typedConstant.Type; - parts.AddPunctuation("["); - parts.AddPunctuation("]"); - parts.AddSpace(); - parts.AddPunctuation("{"); - parts.AddSpace(); + parts.AddKeyword("new"); + parts.AddSpace(); + AddDisplayParts(parts, arrayType.ElementType, format, additionalOptions); - ImmutableArray.Enumerator en = typedConstant.Values.GetEnumerator(); + parts.AddPunctuation("["); + parts.AddPunctuation("]"); + parts.AddSpace(); + parts.AddPunctuation("{"); + parts.AddSpace(); - if (en.MoveNext()) + ImmutableArray.Enumerator en = typedConstant.Values.GetEnumerator(); + + if (en.MoveNext()) + { + while (true) { - while (true) + AddConstantValue(en.Current); + + if (en.MoveNext()) + { + parts.AddPunctuation(","); + parts.AddSpace(); + } + else { - AddConstantValue(en.Current); - - if (en.MoveNext()) - { - parts.AddPunctuation(","); - parts.AddSpace(); - } - else - { - break; - } + break; } } - - parts.AddSpace(); - parts.AddPunctuation("}"); - break; } + + parts.AddSpace(); + parts.AddPunctuation("}"); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } static SymbolDisplayPartKind GetSymbolDisplayPart(SpecialType specialType) @@ -650,83 +650,83 @@ private static void AddParameterAttributes( switch (part.ToString()) { case ",": + { + if (((angleBracketsDepth == 0 && parenthesesDepth == 1 && bracesDepth == 0 && bracketsDepth == 0) + || (angleBracketsDepth == 0 && parenthesesDepth == 0 && bracesDepth == 0 && bracketsDepth == 1)) + && i < parts.Count - 1) { - if (((angleBracketsDepth == 0 && parenthesesDepth == 1 && bracesDepth == 0 && bracketsDepth == 0) - || (angleBracketsDepth == 0 && parenthesesDepth == 0 && bracesDepth == 0 && bracketsDepth == 1)) - && i < parts.Count - 1) - { - SymbolDisplayPart nextPart = parts[i + 1]; + SymbolDisplayPart nextPart = parts[i + 1]; - if (nextPart.Kind == SymbolDisplayPartKind.Space) - { - i += 2; - parameterIndex++; + if (nextPart.Kind == SymbolDisplayPartKind.Space) + { + i += 2; + parameterIndex++; - AddParameterAttributes(); - continue; - } + AddParameterAttributes(); + continue; } - - break; } + + break; + } case "(": - { - parenthesesDepth++; - break; - } + { + parenthesesDepth++; + break; + } case ")": - { - Debug.Assert(parenthesesDepth >= 0); - parenthesesDepth--; - - if (parenthesesDepth == 0 - && symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType)) - { - return; - } + { + Debug.Assert(parenthesesDepth >= 0); + parenthesesDepth--; - break; - } - case "[": + if (parenthesesDepth == 0 + && symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType)) { - bracketsDepth++; - break; + return; } - case "]": - { - Debug.Assert(bracketsDepth >= 0); - bracketsDepth--; - if (bracketsDepth == 0 - && symbol.Kind == SymbolKind.Property) - { - return; - } + break; + } + case "[": + { + bracketsDepth++; + break; + } + case "]": + { + Debug.Assert(bracketsDepth >= 0); + bracketsDepth--; - break; - } - case "{": + if (bracketsDepth == 0 + && symbol.Kind == SymbolKind.Property) { - bracesDepth++; - break; + return; } + + break; + } + case "{": + { + bracesDepth++; + break; + } case "}": - { - Debug.Assert(bracesDepth >= 0); - bracesDepth--; - break; - } + { + Debug.Assert(bracesDepth >= 0); + bracesDepth--; + break; + } case "<": - { - angleBracketsDepth++; - break; - } + { + angleBracketsDepth++; + break; + } case ">": - { - Debug.Assert(angleBracketsDepth >= 0); - angleBracketsDepth--; - break; - } + { + Debug.Assert(angleBracketsDepth >= 0); + angleBracketsDepth--; + break; + } } } @@ -872,80 +872,80 @@ private static void FormatParameters( switch (part.ToString()) { case ",": + { + if (((angleBracketsDepth == 0 && parenthesesDepth == 1 && bracesDepth == 0 && bracketsDepth == 0) + || (angleBracketsDepth == 0 && parenthesesDepth == 0 && bracesDepth == 0 && bracketsDepth == 1)) + && i < parts.Count - 1) { - if (((angleBracketsDepth == 0 && parenthesesDepth == 1 && bracesDepth == 0 && bracketsDepth == 0) - || (angleBracketsDepth == 0 && parenthesesDepth == 0 && bracesDepth == 0 && bracketsDepth == 1)) - && i < parts.Count - 1) - { - SymbolDisplayPart nextPart = parts[i + 1]; + SymbolDisplayPart nextPart = parts[i + 1]; - if (nextPart.Kind == SymbolDisplayPartKind.Space) - { - parts[i + 1] = SymbolDisplayPartFactory.LineBreak(); - parts.Insert(i + 2, SymbolDisplayPartFactory.Indentation(indentChars)); - } + if (nextPart.Kind == SymbolDisplayPartKind.Space) + { + parts[i + 1] = SymbolDisplayPartFactory.LineBreak(); + parts.Insert(i + 2, SymbolDisplayPartFactory.Indentation(indentChars)); } - - break; } + + break; + } case "(": - { - parenthesesDepth++; - break; - } + { + parenthesesDepth++; + break; + } case ")": - { - Debug.Assert(parenthesesDepth >= 0); - parenthesesDepth--; - - if (parenthesesDepth == 0 - && symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType)) - { - return; - } + { + Debug.Assert(parenthesesDepth >= 0); + parenthesesDepth--; - break; - } - case "[": + if (parenthesesDepth == 0 + && symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType)) { - bracketsDepth++; - break; + return; } - case "]": - { - Debug.Assert(bracketsDepth >= 0); - bracketsDepth--; - if (bracketsDepth == 0 - && symbol.Kind == SymbolKind.Property) - { - return; - } + break; + } + case "[": + { + bracketsDepth++; + break; + } + case "]": + { + Debug.Assert(bracketsDepth >= 0); + bracketsDepth--; - break; - } - case "{": + if (bracketsDepth == 0 + && symbol.Kind == SymbolKind.Property) { - bracesDepth++; - break; + return; } + + break; + } + case "{": + { + bracesDepth++; + break; + } case "}": - { - Debug.Assert(bracesDepth >= 0); - bracesDepth--; - break; - } + { + Debug.Assert(bracesDepth >= 0); + bracesDepth--; + break; + } case "<": - { - angleBracketsDepth++; - break; - } + { + angleBracketsDepth++; + break; + } case ">": - { - Debug.Assert(angleBracketsDepth >= 0); - angleBracketsDepth--; - break; - } + { + Debug.Assert(angleBracketsDepth >= 0); + angleBracketsDepth--; + break; + } } } @@ -971,69 +971,69 @@ private static int FindParameterListStart( switch (part.ToString()) { case "(": - { - parenthesesDepth++; - - if (symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType) - && parenthesesDepth == 1 - && bracesDepth == 0 - && bracketsDepth == 0 - && angleBracketsDepth == 0) - { - return i; - } + { + parenthesesDepth++; - break; - } - case ")": + if (symbol.IsKind(SymbolKind.Method, SymbolKind.NamedType) + && parenthesesDepth == 1 + && bracesDepth == 0 + && bracketsDepth == 0 + && angleBracketsDepth == 0) { - Debug.Assert(parenthesesDepth >= 0); - parenthesesDepth--; - break; + return i; } - case "[": - { - bracketsDepth++; - if (symbol.Kind == SymbolKind.Property - && parenthesesDepth == 0 - && bracesDepth == 0 - && bracketsDepth == 1 - && angleBracketsDepth == 0) - { - return i; - } + break; + } + case ")": + { + Debug.Assert(parenthesesDepth >= 0); + parenthesesDepth--; + break; + } + case "[": + { + bracketsDepth++; - break; - } - case "]": + if (symbol.Kind == SymbolKind.Property + && parenthesesDepth == 0 + && bracesDepth == 0 + && bracketsDepth == 1 + && angleBracketsDepth == 0) { - Debug.Assert(bracketsDepth >= 0); - bracketsDepth--; - break; + return i; } + + break; + } + case "]": + { + Debug.Assert(bracketsDepth >= 0); + bracketsDepth--; + break; + } case "{": - { - bracesDepth++; - break; - } + { + bracesDepth++; + break; + } case "}": - { - Debug.Assert(bracesDepth >= 0); - bracesDepth--; - break; - } + { + Debug.Assert(bracesDepth >= 0); + bracesDepth--; + break; + } case "<": - { - angleBracketsDepth++; - break; - } + { + angleBracketsDepth++; + break; + } case ">": - { - Debug.Assert(angleBracketsDepth >= 0); - angleBracketsDepth--; - break; - } + { + Debug.Assert(angleBracketsDepth >= 0); + angleBracketsDepth--; + break; + } } } } diff --git a/src/Documentation/SymbolDefinitionWriter.cs b/src/Documentation/SymbolDefinitionWriter.cs index a091e5e5c6..23f4983783 100644 --- a/src/Documentation/SymbolDefinitionWriter.cs +++ b/src/Documentation/SymbolDefinitionWriter.cs @@ -620,30 +620,30 @@ internal void WriteMembers(INamedTypeSymbol type) case TypeKind.Class: case TypeKind.Interface: case TypeKind.Struct: - { - if (Filter.Includes(SymbolGroupFilter.Member)) - WriteMembers(); - - if (Layout != SymbolDefinitionListLayout.TypeHierarchy - && (Filter.Includes(SymbolGroupFilter.Type))) - { - WriteTypes(type.GetTypeMembers().Where(f => Filter.IsMatch(f))); - } + { + if (Filter.Includes(SymbolGroupFilter.Member)) + WriteMembers(); - break; + if (Layout != SymbolDefinitionListLayout.TypeHierarchy + && (Filter.Includes(SymbolGroupFilter.Type))) + { + WriteTypes(type.GetTypeMembers().Where(f => Filter.IsMatch(f))); } + + break; + } case TypeKind.Enum: - { - if (Filter.Includes(SymbolGroupFilter.EnumField)) - WriteEnumMembers(); + { + if (Filter.Includes(SymbolGroupFilter.EnumField)) + WriteEnumMembers(); - break; - } + break; + } default: - { - Debug.Assert(type.TypeKind == TypeKind.Delegate, type.TypeKind.ToString()); - break; - } + { + Debug.Assert(type.TypeKind == TypeKind.Delegate, type.TypeKind.ToString()); + break; + } } void WriteMembers() @@ -863,95 +863,95 @@ void AddConstantValue(TypedConstant typedConstant) switch (typedConstant.Kind) { case TypedConstantKind.Primitive: - { - Write(SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false)); - break; - } + { + Write(SymbolDisplay.FormatPrimitive(typedConstant.Value, quoteStrings: true, useHexadecimalNumbers: false)); + break; + } case TypedConstantKind.Enum: - { - OneOrMany oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type); + { + OneOrMany oneOrMany = EnumUtility.GetConstituentFields(typedConstant.Value, (INamedTypeSymbol)typedConstant.Type); - OneOrMany.Enumerator en = oneOrMany.GetEnumerator(); + OneOrMany.Enumerator en = oneOrMany.GetEnumerator(); - if (en.MoveNext()) + if (en.MoveNext()) + { + while (true) { - while (true) + WriteSymbol(en.Current.Symbol.ContainingType); + Write("."); + Write(en.Current.Symbol.Name); + + if (en.MoveNext()) { - WriteSymbol(en.Current.Symbol.ContainingType); - Write("."); - Write(en.Current.Symbol.Name); - - if (en.MoveNext()) - { - Write(" | "); - } - else - { - break; - } + Write(" | "); + } + else + { + break; } } - else - { - Write("("); - WriteSymbol((INamedTypeSymbol)typedConstant.Type); - Write(")"); - Write(typedConstant.Value.ToString()); - } - - break; } - case TypedConstantKind.Type: + else { - if (typedConstant.Value is null) - { - Write("null"); - } - else - { - Write("typeof"); - Write("("); - WriteSymbol((ISymbol)typedConstant.Value); - Write(")"); - } + Write("("); + WriteSymbol((INamedTypeSymbol)typedConstant.Type); + Write(")"); + Write(typedConstant.Value.ToString()); + } - break; + break; + } + case TypedConstantKind.Type: + { + if (typedConstant.Value is null) + { + Write("null"); } - case TypedConstantKind.Array: + else { - var arrayType = (IArrayTypeSymbol)typedConstant.Type; + Write("typeof"); + Write("("); + WriteSymbol((ISymbol)typedConstant.Value); + Write(")"); + } - Write("new "); - WriteSymbol(arrayType.ElementType); + break; + } + case TypedConstantKind.Array: + { + var arrayType = (IArrayTypeSymbol)typedConstant.Type; - Write("[] { "); + Write("new "); + WriteSymbol(arrayType.ElementType); - ImmutableArray.Enumerator en = typedConstant.Values.GetEnumerator(); + Write("[] { "); - if (en.MoveNext()) + ImmutableArray.Enumerator en = typedConstant.Values.GetEnumerator(); + + if (en.MoveNext()) + { + while (true) { - while (true) + AddConstantValue(en.Current); + + if (en.MoveNext()) + { + Write(", "); + } + else { - AddConstantValue(en.Current); - - if (en.MoveNext()) - { - Write(", "); - } - else - { - break; - } + break; } } - - Write(" }"); - break; } + + Write(" }"); + break; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/Documentation/SymbolDefinitionWriterHelpers.cs b/src/Documentation/SymbolDefinitionWriterHelpers.cs index 75185311a7..1cbec4fc48 100644 --- a/src/Documentation/SymbolDefinitionWriterHelpers.cs +++ b/src/Documentation/SymbolDefinitionWriterHelpers.cs @@ -69,53 +69,53 @@ public static bool HasAttributes(ISymbol symbol, SymbolFilterOptions filter) switch (symbol.Kind) { case SymbolKind.NamedType: - { - var typeSymbol = (INamedTypeSymbol)symbol; - - if (typeSymbol.TypeKind == TypeKind.Delegate - && HasAttributes(typeSymbol.DelegateInvokeMethod?.Parameters ?? ImmutableArray.Empty)) - { - return true; - } + { + var typeSymbol = (INamedTypeSymbol)symbol; - break; + if (typeSymbol.TypeKind == TypeKind.Delegate + && HasAttributes(typeSymbol.DelegateInvokeMethod?.Parameters ?? ImmutableArray.Empty)) + { + return true; } + + break; + } case SymbolKind.Event: - { - var eventSymbol = (IEventSymbol)symbol; + { + var eventSymbol = (IEventSymbol)symbol; - if (IsMatch(eventSymbol.AddMethod)) - return true; + if (IsMatch(eventSymbol.AddMethod)) + return true; - if (IsMatch(eventSymbol.RemoveMethod)) - return true; + if (IsMatch(eventSymbol.RemoveMethod)) + return true; - break; - } + break; + } case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; + { + var methodSymbol = (IMethodSymbol)symbol; - if (HasAttributes(methodSymbol.Parameters)) - return true; + if (HasAttributes(methodSymbol.Parameters)) + return true; - break; - } + break; + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)symbol; + { + var propertySymbol = (IPropertySymbol)symbol; - if (HasAttributes(propertySymbol.Parameters)) - return true; + if (HasAttributes(propertySymbol.Parameters)) + return true; - if (IsMatch(propertySymbol.GetMethod)) - return true; + if (IsMatch(propertySymbol.GetMethod)) + return true; - if (IsMatch(propertySymbol.SetMethod)) - return true; + if (IsMatch(propertySymbol.SetMethod)) + return true; - break; - } + break; + } } return false; @@ -173,17 +173,17 @@ public static (IMethodSymbol accessor1, IMethodSymbol accessor2) GetAccessors(IS switch (symbol.Kind) { case SymbolKind.Event: - { - var eventSymbol = (IEventSymbol)symbol; + { + var eventSymbol = (IEventSymbol)symbol; - return (eventSymbol.AddMethod, eventSymbol.RemoveMethod); - } + return (eventSymbol.AddMethod, eventSymbol.RemoveMethod); + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)symbol; + { + var propertySymbol = (IPropertySymbol)symbol; - return (propertySymbol.GetMethod, propertySymbol.SetMethod); - } + return (propertySymbol.GetMethod, propertySymbol.SetMethod); + } } return default; @@ -240,44 +240,44 @@ public static (int start, int end, ISymbol symbol) FindDefinitionName( switch (Peek(j).ToString()) { case "operator": + { + if (Peek(j + 1).IsSpace() + && Peek(j + 2).Kind == SymbolDisplayPartKind.Operator + && Peek(j + 2).Symbol is IMethodSymbol { MethodKind: MethodKind.UserDefinedOperator }) { - if (Peek(j + 1).IsSpace() - && Peek(j + 2).Kind == SymbolDisplayPartKind.Operator - && Peek(j + 2).Symbol is IMethodSymbol { MethodKind: MethodKind.UserDefinedOperator }) - { - j += 3; - return (i, j, parts[j].Symbol); - } - - break; + j += 3; + return (i, j, parts[j].Symbol); } + + break; + } case "this": - { - j++; - return (i, j, symbol); - } + { + j++; + return (i, j, symbol); + } case "implicit": case "explicit": + { + if (Peek(j + 1).IsSpace() + && Peek(j + 2).IsKeyword("operator") + && Peek(j + 3).IsSpace()) { - if (Peek(j + 1).IsSpace() - && Peek(j + 2).IsKeyword("operator") - && Peek(j + 3).IsSpace()) - { - j += 4; + j += 4; - if (IsGlobalPrefix(j + 1)) - { - j += 2; + if (IsGlobalPrefix(j + 1)) + { + j += 2; - ReadNamespaces(); + ReadNamespaces(); - if (ReadTypeNames()) - return (i, j, symbol); - } + if (ReadTypeNames()) + return (i, j, symbol); } - - break; } + + break; + } } } } @@ -374,24 +374,24 @@ bool ReadTypeParameterList() switch (Peek(j).ToString()) { case "<": - { - depth++; - break; - } + { + depth++; + break; + } case ">": - { - Debug.Assert(depth > 0); - - depth--; + { + Debug.Assert(depth > 0); - if (depth == 0) - { - j++; - return true; - } + depth--; - break; + if (depth == 0) + { + j++; + return true; } + + break; + } } } diff --git a/src/Documentation/SymbolXmlDocumentation.cs b/src/Documentation/SymbolXmlDocumentation.cs index 1b2458625b..565673861b 100644 --- a/src/Documentation/SymbolXmlDocumentation.cs +++ b/src/Documentation/SymbolXmlDocumentation.cs @@ -93,56 +93,56 @@ public IEnumerable GetElementsAsText(bool skipEmptyElement = false, bool case "summary": case "typeparam": case "value": + { + if (skipEmptyElement + && string.IsNullOrWhiteSpace(element.Value)) { - if (skipEmptyElement - && string.IsNullOrWhiteSpace(element.Value)) - { - break; - } - - yield return GetElementXml(element); break; } + + yield return GetElementXml(element); + break; + } case "c": case "para": - { - Debug.Fail(element.Name.LocalName); + { + Debug.Fail(element.Name.LocalName); - if (skipEmptyElement - && string.IsNullOrWhiteSpace(element.Value)) - { - break; - } - - yield return GetElementXml(element); + if (skipEmptyElement + && string.IsNullOrWhiteSpace(element.Value)) + { break; } + + yield return GetElementXml(element); + break; + } case "see": case "paramref": case "typeparamref": - { - Debug.Fail(element.Name.LocalName); + { + Debug.Fail(element.Name.LocalName); - yield return GetElementXml(element); - break; - } + yield return GetElementXml(element); + break; + } case "exception": case "permission": case "seealso": - { - yield return GetElementXml(element); - break; - } + { + yield return GetElementXml(element); + break; + } case "filterpriority": case "completionlist": - { - break; - } + { + break; + } default: - { - Debug.Fail(element.Name.LocalName); - break; - } + { + Debug.Fail(element.Name.LocalName); + break; + } } } diff --git a/src/Documentation/TypeDocumentationModel.cs b/src/Documentation/TypeDocumentationModel.cs index 8a529a62c8..2a53e80021 100644 --- a/src/Documentation/TypeDocumentationModel.cs +++ b/src/Documentation/TypeDocumentationModel.cs @@ -201,19 +201,19 @@ public IEnumerable GetOperators( switch (methodSymbol.MethodKind) { case MethodKind.UserDefinedOperator: - { - if (includeUserDefinedOperator) - yield return methodSymbol; + { + if (includeUserDefinedOperator) + yield return methodSymbol; - break; - } + break; + } case MethodKind.Conversion: - { - if (includeConversion) - yield return methodSymbol; + { + if (includeConversion) + yield return methodSymbol; - break; - } + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorDeclarationCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorDeclarationCodeFixProvider.cs index 4756655c4a..79b84551ad 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorDeclarationCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorDeclarationCodeFixProvider.cs @@ -42,32 +42,32 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case DiagnosticIdentifiers.FormatAccessorBraces: case DiagnosticIdentifiers.FormatAccessorBracesOnSingleLineWhenExpressionIsOnSingleLine: - { - bool isSingleLine = accessorDeclaration.IsSingleLine(includeExteriorTrivia: false); - string title = (isSingleLine) - ? "Format braces on multiple lines" - : "Format braces on a single line"; - - CodeAction codeAction = CodeAction.Create( - title, - ct => (isSingleLine) - ? FormatAccessorBracesOnMultipleLinesAsync(document, accessorDeclaration, ct) - : FormatAccessorBracesOnSingleLineAsync(document, accessorDeclaration, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + bool isSingleLine = accessorDeclaration.IsSingleLine(includeExteriorTrivia: false); + string title = (isSingleLine) + ? "Format braces on multiple lines" + : "Format braces on a single line"; + + CodeAction codeAction = CodeAction.Create( + title, + ct => (isSingleLine) + ? FormatAccessorBracesOnMultipleLinesAsync(document, accessorDeclaration, ct) + : FormatAccessorBracesOnSingleLineAsync(document, accessorDeclaration, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.PutFullAccessorOnItsOwnLine: - { - CodeAction codeAction = CodeAction.Create( - "Put accessor on its own line", - ct => PutAccessorOnItsOwnLineAsync(accessorDeclaration, document, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Put accessor on its own line", + ct => PutAccessorOnItsOwnLineAsync(accessorDeclaration, document, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorListCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorListCodeFixProvider.cs index fa83337fff..97b90ee887 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorListCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/AccessorListCodeFixProvider.cs @@ -36,15 +36,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.PutAutoAccessorsOnSingleLine: - { - CodeAction codeAction = CodeAction.Create( - (accessorList.Accessors.Count == 1) ? "Put accessor on a single line" : "Put accessors on a single line", - ct => PutAccessorsOnSingleLine(document, accessorList, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + (accessorList.Accessors.Count == 1) ? "Put accessor on a single line" : "Put accessors on a single line", + ct => PutAccessorsOnSingleLine(document, accessorList, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/BlockCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/BlockCodeFixProvider.cs index d0f3a02c0b..092359eb43 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/BlockCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/BlockCodeFixProvider.cs @@ -41,22 +41,22 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case DiagnosticIdentifiers.FormatBlockBraces: case DiagnosticIdentifiers.AddNewLineAfterOpeningBraceOfEmptyBlock: - { - bool isSingleLine = block.IsSingleLine(includeExteriorTrivia: false); - string title = (isSingleLine) - ? "Format braces on multiple lines" - : "Format braces on a single line"; + { + bool isSingleLine = block.IsSingleLine(includeExteriorTrivia: false); + string title = (isSingleLine) + ? "Format braces on multiple lines" + : "Format braces on a single line"; - CodeAction codeAction = CodeAction.Create( - title, - ct => (isSingleLine) - ? FormatBlockBracesOnMultipleLinesAsync(document, block, ct) - : FormatBlockBracesOnSingleLineAsync(document, block, ct), - GetEquivalenceKey(diagnostic)); + CodeAction codeAction = CodeAction.Create( + title, + ct => (isSingleLine) + ? FormatBlockBracesOnMultipleLinesAsync(document, block, ct) + : FormatBlockBracesOnSingleLineAsync(document, block, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/CompilationUnitCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/CompilationUnitCodeFixProvider.cs index 940abb1d7d..9da7f29429 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/CompilationUnitCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/CompilationUnitCodeFixProvider.cs @@ -35,48 +35,48 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.NormalizeWhitespaceAtBeginningOfFile: - { - SyntaxToken token = compilationUnit.EndOfFileToken; + { + SyntaxToken token = compilationUnit.EndOfFileToken; - if (token.FullSpan.Start > 0) - token = compilationUnit.GetFirstToken(); + if (token.FullSpan.Start > 0) + token = compilationUnit.GetFirstToken(); - SyntaxTriviaList leading = token.LeadingTrivia; + SyntaxTriviaList leading = token.LeadingTrivia; - string title; - if (leading[0].IsWhitespaceTrivia() - && (leading.Count == 1 - || leading[1].IsEndOfLineTrivia())) - { - title = "Remove whitespace"; - } - else - { - title = CodeFixTitles.RemoveNewLine; - } + string title; + if (leading[0].IsWhitespaceTrivia() + && (leading.Count == 1 + || leading[1].IsEndOfLineTrivia())) + { + title = "Remove whitespace"; + } + else + { + title = CodeFixTitles.RemoveNewLine; + } - CodeAction codeAction = CodeAction.Create( - title, - ct => - { - SyntaxToken token = compilationUnit.EndOfFileToken; + CodeAction codeAction = CodeAction.Create( + title, + ct => + { + SyntaxToken token = compilationUnit.EndOfFileToken; - if (token.FullSpan.Start > 0) - token = compilationUnit.GetFirstToken(); + if (token.FullSpan.Start > 0) + token = compilationUnit.GetFirstToken(); - SyntaxTriviaList leading = token.LeadingTrivia; + SyntaxTriviaList leading = token.LeadingTrivia; - int count = leading.TakeWhile(f => f.IsWhitespaceOrEndOfLineTrivia()).Count(); + int count = leading.TakeWhile(f => f.IsWhitespaceOrEndOfLineTrivia()).Count(); - SyntaxToken newToken = token.WithLeadingTrivia(leading.RemoveRange(0, count)); + SyntaxToken newToken = token.WithLeadingTrivia(leading.RemoveRange(0, count)); - return document.ReplaceTokenAsync(token, newToken, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceTokenAsync(token, newToken, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/DirectiveTriviaCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/DirectiveTriviaCodeFixProvider.cs index 6c8c833846..e8f51b3155 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/DirectiveTriviaCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/DirectiveTriviaCodeFixProvider.cs @@ -42,15 +42,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { case DiagnosticIdentifiers.AddBlankLineAfterRegionDirective: case DiagnosticIdentifiers.AddBlankLineBeforeEndRegionDirective: - { - CodeAction codeAction = CodeAction.Create( - CodeFixTitles.AddBlankLine, - ct => AddBlankLineAfterRegionDirectiveAndBeforeEndRegionAsync(document, directiveTrivia, ct), - GetEquivalenceKey(diagnostic)); + { + CodeAction codeAction = CodeAction.Create( + CodeFixTitles.AddBlankLine, + ct => AddBlankLineAfterRegionDirectiveAndBeforeEndRegionAsync(document, directiveTrivia, ct), + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/FixFormattingOfListCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/FixFormattingOfListCodeFixProvider.cs index 1c97bd4e7e..d43f36a793 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/FixFormattingOfListCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/FixFormattingOfListCodeFixProvider.cs @@ -72,93 +72,93 @@ CodeAction CreateCodeAction() switch (node) { case ParameterListSyntax parameterList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, parameterList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, parameterList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case BracketedParameterListSyntax bracketedParameterList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, bracketedParameterList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, bracketedParameterList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case TypeParameterListSyntax typeParameterList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, typeParameterList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, typeParameterList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case ArgumentListSyntax argumentList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, argumentList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, argumentList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case BracketedArgumentListSyntax bracketedArgumentList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, bracketedArgumentList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, bracketedArgumentList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case AttributeArgumentListSyntax attributeArgumentList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, attributeArgumentList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, attributeArgumentList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case TypeArgumentListSyntax typeArgumentList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, typeArgumentList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, typeArgumentList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case AttributeListSyntax attributeList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, attributeList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, attributeList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case BaseListSyntax baseList: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, baseList, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, baseList, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case TupleTypeSyntax tupleType: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, tupleType, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, tupleType, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case TupleExpressionSyntax tupleExpression: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, tupleExpression, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, tupleExpression, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } case InitializerExpressionSyntax initializerExpression: - { - return CodeAction.Create( - Title, - ct => FixListAsync(document, initializerExpression, ListFixMode.Fix, ct), - GetEquivalenceKey(diagnostic)); - } + { + return CodeAction.Create( + Title, + ct => FixListAsync(document, initializerExpression, ListFixMode.Fix, ct), + GetEquivalenceKey(diagnostic)); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/InitializerCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/InitializerCodeFixProvider.cs index f06d897bb2..9a2328be43 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/InitializerCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/InitializerCodeFixProvider.cs @@ -34,15 +34,15 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.PutInitializerOnSingleLine: - { - CodeAction codeAction = CodeAction.Create( - "Put initializer on a single line", - ct => SyntaxFormatter.ToSingleLineAsync(document, initializer, removeTrailingComma: false, ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Put initializer on a single line", + ct => SyntaxFormatter.ToSingleLineAsync(document, initializer, removeTrailingComma: false, ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs index e68ea73937..3434af4733 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/LineIsTooLong/WrapLineNodeFinder.cs @@ -130,209 +130,209 @@ private SyntaxNode GetFixableNode(SyntaxNode node) switch (node.Kind()) { case SyntaxKind.ArrowExpressionClause: - { - var expressionBody = (ArrowExpressionClauseSyntax)node; + { + var expressionBody = (ArrowExpressionClauseSyntax)node; - SyntaxToken arrowToken = expressionBody.ArrowToken; - SyntaxToken previousToken = arrowToken.GetPreviousToken(); + SyntaxToken arrowToken = expressionBody.ArrowToken; + SyntaxToken previousToken = arrowToken.GetPreviousToken(); - if (previousToken.SpanStart < Span.Start) - return null; + if (previousToken.SpanStart < Span.Start) + return null; - bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetArrowTokenNewLinePosition() == NewLinePosition.After; - int wrapPosition = (addNewLineAfter) ? arrowToken.Span.End : previousToken.Span.End; - int start = (addNewLineAfter) ? expressionBody.Expression.SpanStart : arrowToken.SpanStart; - int longestLength = expressionBody.GetLastToken().GetNextToken().Span.End - start; + bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetArrowTokenNewLinePosition() == NewLinePosition.After; + int wrapPosition = (addNewLineAfter) ? arrowToken.Span.End : previousToken.Span.End; + int start = (addNewLineAfter) ? expressionBody.Expression.SpanStart : arrowToken.SpanStart; + int longestLength = expressionBody.GetLastToken().GetNextToken().Span.End - start; - if (!CanWrap(expressionBody, wrapPosition, longestLength)) - return null; + if (!CanWrap(expressionBody, wrapPosition, longestLength)) + return null; - return expressionBody; - } + return expressionBody; + } case SyntaxKind.EqualsValueClause: - { - var equalsValueClause = (EqualsValueClauseSyntax)node; + { + var equalsValueClause = (EqualsValueClauseSyntax)node; - SyntaxToken equalsToken = equalsValueClause.EqualsToken; - SyntaxToken previousToken = equalsToken.GetPreviousToken(); + SyntaxToken equalsToken = equalsValueClause.EqualsToken; + SyntaxToken previousToken = equalsToken.GetPreviousToken(); - if (previousToken.SpanStart < Span.Start) - return null; + if (previousToken.SpanStart < Span.Start) + return null; - bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetEqualsTokenNewLinePosition() == NewLinePosition.After; + bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetEqualsTokenNewLinePosition() == NewLinePosition.After; - int wrapPosition = (addNewLineAfter) ? equalsToken.Span.End : previousToken.Span.End; - int start = (addNewLineAfter) ? equalsValueClause.Value.SpanStart : equalsToken.SpanStart; - int longestLength = Span.End - start; + int wrapPosition = (addNewLineAfter) ? equalsToken.Span.End : previousToken.Span.End; + int start = (addNewLineAfter) ? equalsValueClause.Value.SpanStart : equalsToken.SpanStart; + int longestLength = Span.End - start; - if (!CanWrap(equalsValueClause, wrapPosition, longestLength)) - return null; + if (!CanWrap(equalsValueClause, wrapPosition, longestLength)) + return null; - return equalsValueClause; - } + return equalsValueClause; + } case SyntaxKind.AttributeList: - { - var attributeList = (AttributeListSyntax)node; + { + var attributeList = (AttributeListSyntax)node; - if (!CanWrap(attributeList.Attributes, attributeList.OpenBracketToken.Span.End, 2)) - return null; + if (!CanWrap(attributeList.Attributes, attributeList.OpenBracketToken.Span.End, 2)) + return null; - return attributeList; - } + return attributeList; + } case SyntaxKind.BaseList: - { - var baseList = (BaseListSyntax)node; + { + var baseList = (BaseListSyntax)node; - if (!CanWrap(baseList.Types, baseList.ColonToken.Span.End, 2)) - return null; + if (!CanWrap(baseList.Types, baseList.ColonToken.Span.End, 2)) + return null; - return baseList; - } + return baseList; + } case SyntaxKind.ParameterList: - { - if (node.Parent is AnonymousFunctionExpressionSyntax) - return null; + { + if (node.Parent is AnonymousFunctionExpressionSyntax) + return null; - var parameterList = (ParameterListSyntax)node; + var parameterList = (ParameterListSyntax)node; - if (!CanWrap(parameterList.Parameters, parameterList.OpenParenToken.Span.End)) - return null; + if (!CanWrap(parameterList.Parameters, parameterList.OpenParenToken.Span.End)) + return null; - return parameterList; - } + return parameterList; + } case SyntaxKind.BracketedParameterList: - { - var parameterList = (BracketedParameterListSyntax)node; + { + var parameterList = (BracketedParameterListSyntax)node; - if (!CanWrap(parameterList.Parameters, parameterList.OpenBracketToken.Span.End)) - return null; + if (!CanWrap(parameterList.Parameters, parameterList.OpenBracketToken.Span.End)) + return null; - return parameterList; - } + return parameterList; + } case SyntaxKind.ForStatement: - { - var forStatement = (ForStatementSyntax)node; + { + var forStatement = (ForStatementSyntax)node; - if (forStatement.CloseParenToken.Span.End > Span.End) - return null; + if (forStatement.CloseParenToken.Span.End > Span.End) + return null; - if (forStatement.OpenParenToken.Span.End - Span.Start > MaxLineLength) - return null; + if (forStatement.OpenParenToken.Span.End - Span.Start > MaxLineLength) + return null; - int longestLength = Math.Max( - forStatement.FirstSemicolonToken.Span.End - forStatement.Declaration.SpanStart, - Math.Max( - forStatement.SecondSemicolonToken.Span.End - forStatement.Condition.SpanStart, - forStatement.CloseParenToken.Span.End - forStatement.Incrementors.Span.Start)); + int longestLength = Math.Max( + forStatement.FirstSemicolonToken.Span.End - forStatement.Declaration.SpanStart, + Math.Max( + forStatement.SecondSemicolonToken.Span.End - forStatement.Condition.SpanStart, + forStatement.CloseParenToken.Span.End - forStatement.Incrementors.Span.Start)); - IndentationAnalysis indentationAnalysis = IndentationAnalysis.Create(node, Document.GetConfigOptions(node.SyntaxTree)); - int indentationLength = indentationAnalysis.IncreasedIndentationLength; + IndentationAnalysis indentationAnalysis = IndentationAnalysis.Create(node, Document.GetConfigOptions(node.SyntaxTree)); + int indentationLength = indentationAnalysis.IncreasedIndentationLength; - if (indentationAnalysis.IndentStyle == IndentStyle.Tab) - indentationLength *= indentationAnalysis.IndentSize; + if (indentationAnalysis.IndentStyle == IndentStyle.Tab) + indentationLength *= indentationAnalysis.IndentSize; - if (indentationLength + longestLength > MaxLineLength) - return null; + if (indentationLength + longestLength > MaxLineLength) + return null; - return forStatement; - } + return forStatement; + } case SyntaxKind.ArgumentList: - { - var argumentList = (ArgumentListSyntax)node; + { + var argumentList = (ArgumentListSyntax)node; - if (argumentList.Arguments.Count == 1 - && argumentList.Parent is InvocationExpressionSyntax invocationExpression - && invocationExpression.Expression is IdentifierNameSyntax identifierName - && identifierName.Identifier.ValueText == "nameof") - { - return null; - } + if (argumentList.Arguments.Count == 1 + && argumentList.Parent is InvocationExpressionSyntax invocationExpression + && invocationExpression.Expression is IdentifierNameSyntax identifierName + && identifierName.Identifier.ValueText == "nameof") + { + return null; + } - if (!CanWrap(argumentList.Arguments, argumentList.OpenParenToken.Span.End)) - return null; + if (!CanWrap(argumentList.Arguments, argumentList.OpenParenToken.Span.End)) + return null; - return argumentList; - } + return argumentList; + } case SyntaxKind.BracketedArgumentList: - { - var argumentList = (BracketedArgumentListSyntax)node; + { + var argumentList = (BracketedArgumentListSyntax)node; - if (!CanWrap(argumentList.Arguments, argumentList.OpenBracketToken.Span.End)) - return null; + if (!CanWrap(argumentList.Arguments, argumentList.OpenBracketToken.Span.End)) + return null; - return argumentList; - } + return argumentList; + } case SyntaxKind.AttributeArgumentList: - { - var argumentList = (AttributeArgumentListSyntax)node; + { + var argumentList = (AttributeArgumentListSyntax)node; - if (!CanWrap(argumentList.Arguments, argumentList.OpenParenToken.Span.End)) - return null; + if (!CanWrap(argumentList.Arguments, argumentList.OpenParenToken.Span.End)) + return null; - return argumentList; - } + return argumentList; + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccessExpression = (MemberAccessExpressionSyntax)node; + { + var memberAccessExpression = (MemberAccessExpressionSyntax)node; - if (!CanWrap(memberAccessExpression)) - return null; + if (!CanWrap(memberAccessExpression)) + return null; - SyntaxToken dotToken = memberAccessExpression.OperatorToken; + SyntaxToken dotToken = memberAccessExpression.OperatorToken; - if (!CanWrap(memberAccessExpression, dotToken.SpanStart, Span.End - dotToken.SpanStart)) - return null; + if (!CanWrap(memberAccessExpression, dotToken.SpanStart, Span.End - dotToken.SpanStart)) + return null; - return memberAccessExpression; - } + return memberAccessExpression; + } case SyntaxKind.MemberBindingExpression: - { - var memberBindingExpression = (MemberBindingExpressionSyntax)node; + { + var memberBindingExpression = (MemberBindingExpressionSyntax)node; - SyntaxToken dotToken = memberBindingExpression.OperatorToken; + SyntaxToken dotToken = memberBindingExpression.OperatorToken; - if (!CanWrap(memberBindingExpression, dotToken.SpanStart, Span.End - dotToken.SpanStart)) - return null; + if (!CanWrap(memberBindingExpression, dotToken.SpanStart, Span.End - dotToken.SpanStart)) + return null; - return memberBindingExpression; - } + return memberBindingExpression; + } case SyntaxKind.ConditionalExpression: - { - var conditionalExpression = (ConditionalExpressionSyntax)node; + { + var conditionalExpression = (ConditionalExpressionSyntax)node; - SyntaxToken questionToken = conditionalExpression.QuestionToken; - SyntaxToken colonToken = conditionalExpression.ColonToken; + SyntaxToken questionToken = conditionalExpression.QuestionToken; + SyntaxToken colonToken = conditionalExpression.ColonToken; - bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetConditionalOperatorNewLinePosition() == NewLinePosition.After; + bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetConditionalOperatorNewLinePosition() == NewLinePosition.After; - int wrapPosition = (addNewLineAfter) - ? questionToken.Span.End - : conditionalExpression.Condition.Span.End; + int wrapPosition = (addNewLineAfter) + ? questionToken.Span.End + : conditionalExpression.Condition.Span.End; - int start = (addNewLineAfter) ? conditionalExpression.WhenTrue.SpanStart : questionToken.SpanStart; - int end = (addNewLineAfter) ? colonToken.Span.End : conditionalExpression.WhenTrue.Span.End; - int longestLength = end - start; + int start = (addNewLineAfter) ? conditionalExpression.WhenTrue.SpanStart : questionToken.SpanStart; + int end = (addNewLineAfter) ? colonToken.Span.End : conditionalExpression.WhenTrue.Span.End; + int longestLength = end - start; - start = (addNewLineAfter) ? conditionalExpression.WhenFalse.SpanStart : colonToken.SpanStart; - int longestLength2 = Span.End - start; + start = (addNewLineAfter) ? conditionalExpression.WhenFalse.SpanStart : colonToken.SpanStart; + int longestLength2 = Span.End - start; - if (!CanWrap(conditionalExpression, wrapPosition, Math.Max(longestLength, longestLength2))) - return null; + if (!CanWrap(conditionalExpression, wrapPosition, Math.Max(longestLength, longestLength2))) + return null; - return conditionalExpression; - } + return conditionalExpression; + } case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.ObjectInitializerExpression: - { - var initializer = (InitializerExpressionSyntax)node; + { + var initializer = (InitializerExpressionSyntax)node; - if (!CanWrap(initializer.Expressions, initializer.OpenBraceToken.Span.End)) - return null; + if (!CanWrap(initializer.Expressions, initializer.OpenBraceToken.Span.End)) + return null; - return initializer; - } + return initializer; + } case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: @@ -354,56 +354,56 @@ private SyntaxNode GetFixableNode(SyntaxNode node) case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: - { - var binaryExpression = (BinaryExpressionSyntax)node; + { + var binaryExpression = (BinaryExpressionSyntax)node; + + SyntaxToken operatorToken = binaryExpression.OperatorToken; - SyntaxToken operatorToken = binaryExpression.OperatorToken; + bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetBinaryOperatorNewLinePosition() == NewLinePosition.After; - bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetBinaryOperatorNewLinePosition() == NewLinePosition.After; + int wrapPosition = (addNewLineAfter) + ? operatorToken.Span.End + : binaryExpression.Left.Span.End; - int wrapPosition = (addNewLineAfter) - ? operatorToken.Span.End - : binaryExpression.Left.Span.End; + int longestLength = 0; - int longestLength = 0; + while (true) + { + BinaryExpressionSyntax parentBinaryExpression = null; + if (binaryExpression.IsParentKind(binaryExpression.Kind())) + { + parentBinaryExpression = (BinaryExpressionSyntax)binaryExpression.Parent; + } - while (true) + int end; + if (parentBinaryExpression is not null) { - BinaryExpressionSyntax parentBinaryExpression = null; - if (binaryExpression.IsParentKind(binaryExpression.Kind())) - { - parentBinaryExpression = (BinaryExpressionSyntax)binaryExpression.Parent; - } - - int end; - if (parentBinaryExpression is not null) - { - end = (addNewLineAfter) - ? parentBinaryExpression.OperatorToken.Span.End - : binaryExpression.Right.Span.End; - } - else - { - end = Span.End; - } - - int start = (addNewLineAfter) - ? binaryExpression.Right.SpanStart - : binaryExpression.OperatorToken.SpanStart; - - longestLength = Math.Max(longestLength, end - start); - - if (parentBinaryExpression is null) - break; - - binaryExpression = parentBinaryExpression; + end = (addNewLineAfter) + ? parentBinaryExpression.OperatorToken.Span.End + : binaryExpression.Right.Span.End; } + else + { + end = Span.End; + } + + int start = (addNewLineAfter) + ? binaryExpression.Right.SpanStart + : binaryExpression.OperatorToken.SpanStart; + + longestLength = Math.Max(longestLength, end - start); - if (!CanWrap(node, wrapPosition, longestLength)) - return null; + if (parentBinaryExpression is null) + break; - return node; + binaryExpression = parentBinaryExpression; } + + if (!CanWrap(node, wrapPosition, longestLength)) + return null; + + return node; + } case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: @@ -416,25 +416,25 @@ private SyntaxNode GetFixableNode(SyntaxNode node) case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: - { - var assignment = (AssignmentExpressionSyntax)node; + { + var assignment = (AssignmentExpressionSyntax)node; - SyntaxToken operatorToken = assignment.OperatorToken; - SyntaxNode left = assignment.Left; + SyntaxToken operatorToken = assignment.OperatorToken; + SyntaxNode left = assignment.Left; - if (left.SpanStart < Span.Start) - return null; + if (left.SpanStart < Span.Start) + return null; - bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetEqualsTokenNewLinePosition() == NewLinePosition.After; - int wrapPosition = (addNewLineAfter) ? operatorToken.Span.End : left.Span.End; - int start = (addNewLineAfter) ? assignment.Right.SpanStart : operatorToken.SpanStart; - int longestLength = Span.End - start; + bool addNewLineAfter = Document.GetConfigOptions(node.SyntaxTree).GetEqualsTokenNewLinePosition() == NewLinePosition.After; + int wrapPosition = (addNewLineAfter) ? operatorToken.Span.End : left.Span.End; + int start = (addNewLineAfter) ? assignment.Right.SpanStart : operatorToken.SpanStart; + int longestLength = Span.End - start; - if (!CanWrap(assignment, wrapPosition, longestLength)) - return null; + if (!CanWrap(assignment, wrapPosition, longestLength)) + return null; - return assignment; - } + return assignment; + } } return null; @@ -508,12 +508,12 @@ private bool ShouldAnalyze(SyntaxNode node, SyntaxGroup syntaxGroup) case SyntaxGroup.BinaryExpression: case SyntaxGroup.Is_As_EqualityExpression: case SyntaxGroup.ConditionalExpression: - { - if (IsInsideInterpolation(node.Parent)) - return false; + { + if (IsInsideInterpolation(node.Parent)) + return false; - break; - } + break; + } } if (_nodes is null) @@ -528,12 +528,12 @@ private bool ShouldAnalyze(SyntaxNode node, SyntaxGroup syntaxGroup) case SyntaxGroup.BinaryExpression: case SyntaxGroup.MemberExpression: case SyntaxGroup.ArgumentList: - { - if (kvp.Value.FullSpan.Contains(node.FullSpan)) - return false; + { + if (kvp.Value.FullSpan.Contains(node.FullSpan)) + return false; - break; - } + break; + } } } @@ -596,34 +596,34 @@ private bool CanWrap(MemberAccessExpressionSyntax memberAccessExpression) { case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: - { - return false; - } + { + return false; + } case SyntaxKind.IdentifierName: case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.AliasQualifiedName: + { + ISymbol symbol = SemanticModel.GetSymbol(memberAccessExpression); + + if (symbol is not null) { - ISymbol symbol = SemanticModel.GetSymbol(memberAccessExpression); + if (symbol.IsKind(SymbolKind.Namespace)) + return false; - if (symbol is not null) + if (symbol.IsKind(SymbolKind.Field) + && symbol.ContainingType?.TypeKind == TypeKind.Enum) { - if (symbol.IsKind(SymbolKind.Namespace)) - return false; - - if (symbol.IsKind(SymbolKind.Field) - && symbol.ContainingType?.TypeKind == TypeKind.Enum) - { - return false; - } + return false; } + } - symbol = SemanticModel.GetSymbol(memberAccessExpression.Expression); + symbol = SemanticModel.GetSymbol(memberAccessExpression.Expression); - if (symbol.IsKind(SymbolKind.Namespace)) - return false; + if (symbol.IsKind(SymbolKind.Namespace)) + return false; - break; - } + break; + } } return true; diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/NormalizeWhitespaceAtEndOfFileCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/NormalizeWhitespaceAtEndOfFileCodeFixProvider.cs index 7cc252c49b..da2c618c54 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/NormalizeWhitespaceAtEndOfFileCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/NormalizeWhitespaceAtEndOfFileCodeFixProvider.cs @@ -34,80 +34,80 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.NormalizeWhitespaceAtEndOfFile: - { - bool preferNewLineAtEndOfFile = document.GetConfigOptions(compilationUnit.SyntaxTree).PreferNewLineAtEndOfFile() ?? false; - - CodeAction codeAction = CodeAction.Create( - (preferNewLineAtEndOfFile) ? CodeFixTitles.AddNewLine : CodeFixTitles.RemoveNewLine, - ct => + { + bool preferNewLineAtEndOfFile = document.GetConfigOptions(compilationUnit.SyntaxTree).PreferNewLineAtEndOfFile() ?? false; + + CodeAction codeAction = CodeAction.Create( + (preferNewLineAtEndOfFile) ? CodeFixTitles.AddNewLine : CodeFixTitles.RemoveNewLine, + ct => + { + SyntaxToken endOfFile = compilationUnit.EndOfFileToken; + SyntaxTriviaList leading = endOfFile.LeadingTrivia; + SyntaxToken oldToken; + SyntaxToken newToken; + + if (!preferNewLineAtEndOfFile) { - SyntaxToken endOfFile = compilationUnit.EndOfFileToken; - SyntaxTriviaList leading = endOfFile.LeadingTrivia; - SyntaxToken oldToken; - SyntaxToken newToken; - - if (!preferNewLineAtEndOfFile) + if (leading.Any()) { - if (leading.Any()) - { - SyntaxTrivia last = leading.Last(); + SyntaxTrivia last = leading.Last(); - if (last.GetStructure() is DirectiveTriviaSyntax directive) - { - SyntaxTriviaList trailing = directive.GetTrailingTrivia(); - - DirectiveTriviaSyntax newDirective = directive.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1)); - - return document.ReplaceNodeAsync(directive, newDirective, ct); - } - else - { - oldToken = endOfFile; - int index = leading.Count - 1; + if (last.GetStructure() is DirectiveTriviaSyntax directive) + { + SyntaxTriviaList trailing = directive.GetTrailingTrivia(); - for (int i = leading.Count - 2; i >= 0; i--) - { - if (leading[i].IsWhitespaceOrEndOfLineTrivia()) - index--; - } + DirectiveTriviaSyntax newDirective = directive.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1)); - newToken = oldToken.WithLeadingTrivia(leading.RemoveRange(index, leading.Count - index)); - } + return document.ReplaceNodeAsync(directive, newDirective, ct); } else { - oldToken = endOfFile.GetPreviousToken(); - SyntaxTriviaList trailing = oldToken.TrailingTrivia; - newToken = oldToken.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1)); + oldToken = endOfFile; + int index = leading.Count - 1; + + for (int i = leading.Count - 2; i >= 0; i--) + { + if (leading[i].IsWhitespaceOrEndOfLineTrivia()) + index--; + } + + newToken = oldToken.WithLeadingTrivia(leading.RemoveRange(index, leading.Count - index)); } } - else if (leading.Any()) + else { - oldToken = endOfFile; + oldToken = endOfFile.GetPreviousToken(); + SyntaxTriviaList trailing = oldToken.TrailingTrivia; + newToken = oldToken.WithTrailingTrivia(trailing.RemoveAt(trailing.Count - 1)); + } + } + else if (leading.Any()) + { + oldToken = endOfFile; - if (leading.Span.Start == 0 - && leading.All(f => f.IsWhitespaceOrEndOfLineTrivia())) - { - newToken = oldToken.WithoutLeadingTrivia(); - } - else - { - newToken = oldToken.AppendEndOfLineToLeadingTrivia(); - } + if (leading.Span.Start == 0 + && leading.All(f => f.IsWhitespaceOrEndOfLineTrivia())) + { + newToken = oldToken.WithoutLeadingTrivia(); } else { - oldToken = endOfFile.GetPreviousToken(); - newToken = oldToken.AppendEndOfLineToTrailingTrivia(); + newToken = oldToken.AppendEndOfLineToLeadingTrivia(); } + } + else + { + oldToken = endOfFile.GetPreviousToken(); + newToken = oldToken.AppendEndOfLineToTrailingTrivia(); + } - return document.ReplaceTokenAsync(oldToken, newToken, ct); - }, - GetEquivalenceKey(diagnostic)); + return document.ReplaceTokenAsync(oldToken, newToken, ct); + }, + GetEquivalenceKey(diagnostic)); - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/StatementCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/StatementCodeFixProvider.cs index 0fdd935c4d..68d234b069 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/StatementCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/StatementCodeFixProvider.cs @@ -33,21 +33,21 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.PutStatementOnItsOwnLine: - { - await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.PutEmbeddedStatementOnItsOwnLine: case DiagnosticIdentifiers.AddNewLineAfterSwitchLabel: - { - await CodeActionFactory.RegisterCodeActionForNewLineAsync(context, increaseIndentation: true).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAsync(context, increaseIndentation: true).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.AddBlankLineAfterEmbeddedStatement: - { - await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTokenCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTokenCodeFixProvider.cs index 3060b97327..6d6330cd05 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTokenCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTokenCodeFixProvider.cs @@ -36,31 +36,31 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.AddBlankLineBetweenClosingBraceAndNextStatement: - { - await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.PlaceNewLineAfterOrBeforeConditionalOperator: - { - await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsParentKind(SyntaxKind.ConditionalExpression)).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsParentKind(SyntaxKind.ConditionalExpression)).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.PlaceNewLineAfterOrBeforeArrowToken: - { - await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsKind(SyntaxKind.EqualsGreaterThanToken)).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsKind(SyntaxKind.EqualsGreaterThanToken)).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.PlaceNewLineAfterOrBeforeEqualsToken: - { - await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsKind(SyntaxKind.EqualsToken)).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAroundTokenAsync(context, token => token.IsKind(SyntaxKind.EqualsToken)).ConfigureAwait(false); + break; + } case DiagnosticIdentifiers.PutAttributeListOnItsOwnLine: case DiagnosticIdentifiers.AddOrRemoveNewLineBeforeWhileInDoStatement: - { - await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTriviaCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTriviaCodeFixProvider.cs index d63f1ef069..244dc9ac8b 100644 --- a/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTriviaCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/CSharp/SyntaxTriviaCodeFixProvider.cs @@ -42,16 +42,16 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) case DiagnosticIdentifiers.BlankLineBetweenUsingDirectives: case DiagnosticIdentifiers.AddBlankLineAfterTopComment: case DiagnosticIdentifiers.RemoveBlankLineBetweenUsingDirectivesWithSameRootNamespace: - { - await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); - return; - } + { + await CodeActionFactory.RegisterCodeActionForBlankLineAsync(context).ConfigureAwait(false); + return; + } case DiagnosticIdentifiers.RemoveNewLineBeforeBaseList: case DiagnosticIdentifiers.RemoveNewLineBetweenIfKeywordAndElseKeyword: - { - await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); - break; - } + { + await CodeActionFactory.RegisterCodeActionForNewLineAsync(context).ConfigureAwait(false); + break; + } } } } diff --git a/src/Formatting.Analyzers.CodeFixes/NewLineCodeFixProvider.cs b/src/Formatting.Analyzers.CodeFixes/NewLineCodeFixProvider.cs index dcdd235f63..450d75dd13 100644 --- a/src/Formatting.Analyzers.CodeFixes/NewLineCodeFixProvider.cs +++ b/src/Formatting.Analyzers.CodeFixes/NewLineCodeFixProvider.cs @@ -34,25 +34,25 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) switch (diagnostic.Id) { case DiagnosticIdentifiers.UseLinefeedAsNewLine: - { - CodeAction codeAction = CodeAction.Create( - "Use linefeed as newline", - ct => document.WithTextChangeAsync(span, "\n", ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use linefeed as newline", + ct => document.WithTextChangeAsync(span, "\n", ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } case DiagnosticIdentifiers.UseCarriageReturnAndLinefeedAsNewLine: - { - CodeAction codeAction = CodeAction.Create( - "Use carriage return + linefeed as newline", - ct => document.WithTextChangeAsync(span, "\r\n", ct), - GetEquivalenceKey(diagnostic)); - - context.RegisterCodeFix(codeAction, diagnostic); - break; - } + { + CodeAction codeAction = CodeAction.Create( + "Use carriage return + linefeed as newline", + ct => document.WithTextChangeAsync(span, "\r\n", ct), + GetEquivalenceKey(diagnostic)); + + context.RegisterCodeFix(codeAction, diagnostic); + break; + } } return Task.CompletedTask; diff --git a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs index 2506ab714d..0a42363dec 100644 --- a/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AccessorListAnalyzer.cs @@ -78,67 +78,67 @@ private static void AnalyzeAccessorList(SyntaxNodeAnalysisContext context) switch (parent?.Kind()) { case SyntaxKind.PropertyDeclaration: + { + if (accessors.All(f => !f.AttributeLists.Any()) + && !accessorList.IsSingleLine(includeExteriorTrivia: false)) { - if (accessors.All(f => !f.AttributeLists.Any()) - && !accessorList.IsSingleLine(includeExteriorTrivia: false)) + var propertyDeclaration = (PropertyDeclarationSyntax)parent; + SyntaxToken identifier = propertyDeclaration.Identifier; + + if (!identifier.IsMissing) { - var propertyDeclaration = (PropertyDeclarationSyntax)parent; - SyntaxToken identifier = propertyDeclaration.Identifier; + SyntaxToken closeBrace = accessorList.CloseBraceToken; - if (!identifier.IsMissing) + if (!closeBrace.IsMissing) { - SyntaxToken closeBrace = accessorList.CloseBraceToken; + TextSpan span = TextSpan.FromBounds(identifier.Span.End, closeBrace.SpanStart); - if (!closeBrace.IsMissing) + if (propertyDeclaration + .DescendantTrivia(span) + .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { - TextSpan span = TextSpan.FromBounds(identifier.Span.End, closeBrace.SpanStart); - - if (propertyDeclaration - .DescendantTrivia(span) - .All(f => f.IsWhitespaceOrEndOfLineTrivia())) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.PutAutoAccessorsOnSingleLine, accessorList); - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.PutAutoAccessorsOnSingleLine, accessorList); } } } - - break; } + + break; + } case SyntaxKind.IndexerDeclaration: + { + if (accessors.All(f => !f.AttributeLists.Any()) + && !accessorList.IsSingleLine(includeExteriorTrivia: false)) { - if (accessors.All(f => !f.AttributeLists.Any()) - && !accessorList.IsSingleLine(includeExteriorTrivia: false)) - { - var indexerDeclaration = (IndexerDeclarationSyntax)parent; + var indexerDeclaration = (IndexerDeclarationSyntax)parent; - BracketedParameterListSyntax parameterList = indexerDeclaration.ParameterList; + BracketedParameterListSyntax parameterList = indexerDeclaration.ParameterList; + + if (parameterList is not null) + { + SyntaxToken closeBracket = parameterList.CloseBracketToken; - if (parameterList is not null) + if (!closeBracket.IsMissing) { - SyntaxToken closeBracket = parameterList.CloseBracketToken; + SyntaxToken closeBrace = accessorList.CloseBraceToken; - if (!closeBracket.IsMissing) + if (!closeBrace.IsMissing) { - SyntaxToken closeBrace = accessorList.CloseBraceToken; + TextSpan span = TextSpan.FromBounds(closeBracket.Span.End, closeBrace.SpanStart); - if (!closeBrace.IsMissing) + if (indexerDeclaration + .DescendantTrivia(span) + .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { - TextSpan span = TextSpan.FromBounds(closeBracket.Span.End, closeBrace.SpanStart); - - if (indexerDeclaration - .DescendantTrivia(span) - .All(f => f.IsWhitespaceOrEndOfLineTrivia())) - { - DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.PutAutoAccessorsOnSingleLine, accessorList); - } + DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.PutAutoAccessorsOnSingleLine, accessorList); } } } } - - break; } + + break; + } } } } diff --git a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs index 153aeaf0bd..07be46030f 100644 --- a/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/AddBlankLineBetweenClosingBraceAndNextStatementAnalyzer.cs @@ -45,10 +45,10 @@ private static void AnalyzeBlock(SyntaxNodeAnalysisContext context) switch (block.Parent.Kind()) { case SyntaxKind.Block: - { - blockOrStatement = block; - break; - } + { + blockOrStatement = block; + break; + } case SyntaxKind.FixedStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: @@ -59,35 +59,35 @@ private static void AnalyzeBlock(SyntaxNodeAnalysisContext context) case SyntaxKind.UnsafeStatement: case SyntaxKind.UsingStatement: case SyntaxKind.WhileStatement: + { + blockOrStatement = (StatementSyntax)block.Parent; + break; + } + case SyntaxKind.IfStatement: + { + var ifStatement = (IfStatementSyntax)block.Parent; + + if (ifStatement.Else is null) { - blockOrStatement = (StatementSyntax)block.Parent; + blockOrStatement = ifStatement; break; } - case SyntaxKind.IfStatement: + else { - var ifStatement = (IfStatementSyntax)block.Parent; - - if (ifStatement.Else is null) - { - blockOrStatement = ifStatement; - break; - } - else - { - return; - } + return; } + } case SyntaxKind.ElseClause: - { - var elseClause = (ElseClauseSyntax)block.Parent; + { + var elseClause = (ElseClauseSyntax)block.Parent; - blockOrStatement = elseClause.GetTopmostIf(); - break; - } + blockOrStatement = elseClause.GetTopmostIf(); + break; + } default: - { - return; - } + { + return; + } } Analyze(context, block.CloseBraceToken, blockOrStatement); diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs index 66e7b8cc35..3a8f812978 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfBinaryExpressionChainAnalyzer.cs @@ -113,40 +113,40 @@ bool Analyze(SyntaxNodeOrToken nodeOrToken) switch (en.Current.Kind()) { case SyntaxKind.WhitespaceTrivia: - { - if ((indentationLength ??= GetIndentationLength()) == -1) - return true; + { + if ((indentationLength ??= GetIndentationLength()) == -1) + return true; - if (en.Current.Span.Length != indentationLength) + if (en.Current.Span.Length != indentationLength) + { + if (!en.MoveNext() + || en.Current.IsEndOfLineTrivia()) { - if (!en.MoveNext() - || en.Current.IsEndOfLineTrivia()) + if (topBinaryExpression.FindTrivia(nodeOrToken.FullSpan.Start - 1).IsEndOfLineTrivia()) { - if (topBinaryExpression.FindTrivia(nodeOrToken.FullSpan.Start - 1).IsEndOfLineTrivia()) - { - ReportDiagnostic(); - return true; - } + ReportDiagnostic(); + return true; } - - break; } break; } + + break; + } case SyntaxKind.EndOfLineTrivia: + { + if (topBinaryExpression.FindTrivia(nodeOrToken.FullSpan.Start - 1).IsEndOfLineTrivia()) { - if (topBinaryExpression.FindTrivia(nodeOrToken.FullSpan.Start - 1).IsEndOfLineTrivia()) - { - if ((indentationLength ??= GetIndentationLength()) == -1) - return true; - - ReportDiagnostic(); + if ((indentationLength ??= GetIndentationLength()) == -1) return true; - } - break; + ReportDiagnostic(); + return true; } + + break; + } } return false; diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs index f062572c57..8140fdc8a3 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfCallChainAnalyzer.cs @@ -134,46 +134,46 @@ bool AnalyzeToken(SyntaxToken token) switch (en.Current.Kind()) { case SyntaxKind.WhitespaceTrivia: + { + if (indentationAnalysis is null) { - if (indentationAnalysis is null) - { - indentationAnalysis = AnalyzeIndentation(expression, context.GetConfigOptions()); + indentationAnalysis = AnalyzeIndentation(expression, context.GetConfigOptions()); - if (indentationAnalysis.IndentSize == 0) - return true; - } + if (indentationAnalysis.IndentSize == 0) + return true; + } - if (en.Current.Span.Length != indentationAnalysis.IncreasedIndentationLength) + if (en.Current.Span.Length != indentationAnalysis.IncreasedIndentationLength) + { + if (!en.MoveNext() + || en.Current.IsEndOfLineTrivia()) { - if (!en.MoveNext() - || en.Current.IsEndOfLineTrivia()) + if (expression.FindTrivia(token.FullSpan.Start - 1).IsEndOfLineTrivia()) { - if (expression.FindTrivia(token.FullSpan.Start - 1).IsEndOfLineTrivia()) - { - ReportDiagnostic(); - return true; - } + ReportDiagnostic(); + return true; } - - break; } break; } + + break; + } case SyntaxKind.EndOfLineTrivia: + { + if (expression.FindTrivia(token.FullSpan.Start - 1).IsEndOfLineTrivia()) { - if (expression.FindTrivia(token.FullSpan.Start - 1).IsEndOfLineTrivia()) + if ((indentationAnalysis ?? AnalyzeIndentation(expression, context.GetConfigOptions())).IndentSize > 0) { - if ((indentationAnalysis ?? AnalyzeIndentation(expression, context.GetConfigOptions())).IndentSize > 0) - { - ReportDiagnostic(); - } - - return true; + ReportDiagnostic(); } - break; + return true; } + + break; + } } return false; diff --git a/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs b/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs index 2d464d8257..e9566a80b0 100644 --- a/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/FixFormattingOfListAnalyzer.cs @@ -263,22 +263,22 @@ static bool ShouldFixIndentation(SyntaxTriviaList leading, int indentationLength switch (en.Current.Kind()) { case SyntaxKind.WhitespaceTrivia: + { + if (en.Current.Span.Length != indentationLength) { - if (en.Current.Span.Length != indentationLength) + if (!en.MoveNext() + || en.Current.IsEndOfLineTrivia()) { - if (!en.MoveNext() - || en.Current.IsEndOfLineTrivia()) - { - return true; - } + return true; } - - break; } + + break; + } case SyntaxKind.EndOfLineTrivia: - { - return true; - } + { + return true; + } } return false; diff --git a/src/Formatting.Analyzers/CSharp/PlaceNewLineAfterOrBeforeEqualsTokenAnalyzer.cs b/src/Formatting.Analyzers/CSharp/PlaceNewLineAfterOrBeforeEqualsTokenAnalyzer.cs index 2ebeae0e10..211224cc9f 100644 --- a/src/Formatting.Analyzers/CSharp/PlaceNewLineAfterOrBeforeEqualsTokenAnalyzer.cs +++ b/src/Formatting.Analyzers/CSharp/PlaceNewLineAfterOrBeforeEqualsTokenAnalyzer.cs @@ -55,31 +55,31 @@ private static void AnalyzeNameEquals(SyntaxNodeAnalysisContext context) switch (node.Parent.Kind()) { case SyntaxKind.AttributeArgument: - { - var attributeArgument = (AttributeArgumentSyntax)node.Parent; + { + var attributeArgument = (AttributeArgumentSyntax)node.Parent; - Analyze(context, attributeArgument.NameEquals.EqualsToken, attributeArgument.Expression); - break; - } + Analyze(context, attributeArgument.NameEquals.EqualsToken, attributeArgument.Expression); + break; + } case SyntaxKind.AnonymousObjectMemberDeclarator: - { - var declarator = (AnonymousObjectMemberDeclaratorSyntax)node.Parent; + { + var declarator = (AnonymousObjectMemberDeclaratorSyntax)node.Parent; - Analyze(context, declarator.NameEquals.EqualsToken, declarator.Expression); - break; - } + Analyze(context, declarator.NameEquals.EqualsToken, declarator.Expression); + break; + } case SyntaxKind.UsingDirective: - { - var usingDirective = (UsingDirectiveSyntax)node.Parent; + { + var usingDirective = (UsingDirectiveSyntax)node.Parent; - Analyze(context, usingDirective.Alias.EqualsToken, usingDirective.Name); - break; - } + Analyze(context, usingDirective.Alias.EqualsToken, usingDirective.Name); + break; + } default: - { - SyntaxDebug.Fail(node.Parent); - break; - } + { + SyntaxDebug.Fail(node.Parent); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs index 5f07b7f7dd..02882e3222 100644 --- a/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddGenericParameterToDeclarationRefactoring.cs @@ -250,43 +250,43 @@ private static async Task RefactorAsync( switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - newNode = GetNewNode((MethodDeclarationSyntax)node, constraint, semanticModel, cancellationToken); - break; - } + { + newNode = GetNewNode((MethodDeclarationSyntax)node, constraint, semanticModel, cancellationToken); + break; + } case SyntaxKind.ClassDeclaration: - { - newNode = GetNewNode((ClassDeclarationSyntax)node, constraint, semanticModel); - break; - } + { + newNode = GetNewNode((ClassDeclarationSyntax)node, constraint, semanticModel); + break; + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - newNode = GetNewNode((RecordDeclarationSyntax)node, constraint, semanticModel); - break; - } + { + newNode = GetNewNode((RecordDeclarationSyntax)node, constraint, semanticModel); + break; + } case SyntaxKind.StructDeclaration: - { - newNode = GetNewNode((StructDeclarationSyntax)node, constraint, semanticModel); - break; - } + { + newNode = GetNewNode((StructDeclarationSyntax)node, constraint, semanticModel); + break; + } case SyntaxKind.InterfaceDeclaration: - { - newNode = GetNewNode((InterfaceDeclarationSyntax)node, constraint, semanticModel); - break; - } + { + newNode = GetNewNode((InterfaceDeclarationSyntax)node, constraint, semanticModel); + break; + } case SyntaxKind.DelegateDeclaration: - { - newNode = GetNewNode((DelegateDeclarationSyntax)node, constraint, semanticModel); - break; - } + { + newNode = GetNewNode((DelegateDeclarationSyntax)node, constraint, semanticModel); + break; + } case SyntaxKind.LocalFunctionStatement: - { - newNode = GetNewNode((LocalFunctionStatementSyntax)node, constraint, semanticModel, cancellationToken); - break; - } + { + newNode = GetNewNode((LocalFunctionStatementSyntax)node, constraint, semanticModel, cancellationToken); + break; + } } return await document.ReplaceNodeAsync(node, newNode, cancellationToken).ConfigureAwait(false); diff --git a/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs index 18956e3747..9ea253dc36 100644 --- a/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddMemberToInterfaceRefactoring.cs @@ -172,28 +172,28 @@ private static bool CheckKind(ISymbol symbol, SyntaxKind kind) switch (kind) { case SyntaxKind.MethodDeclaration: - { - return symbol.Kind == SymbolKind.Method; - } + { + return symbol.Kind == SymbolKind.Method; + } case SyntaxKind.PropertyDeclaration: - { - return symbol.Kind == SymbolKind.Property - && !((IPropertySymbol)symbol).IsIndexer; - } + { + return symbol.Kind == SymbolKind.Property + && !((IPropertySymbol)symbol).IsIndexer; + } case SyntaxKind.IndexerDeclaration: - { - return symbol.Kind == SymbolKind.Property - && ((IPropertySymbol)symbol).IsIndexer; - } + { + return symbol.Kind == SymbolKind.Property + && ((IPropertySymbol)symbol).IsIndexer; + } case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: - { - return symbol.Kind == SymbolKind.Event; - } + { + return symbol.Kind == SymbolKind.Event; + } default: - { - return false; - } + { + return false; + } } } @@ -220,62 +220,62 @@ private static MemberDeclarationSyntax CreateInterfaceMemberDeclaration(MemberDe switch (memberDeclaration) { case MethodDeclarationSyntax methodDeclaration: - { - return MethodDeclaration( - default(SyntaxList), - default(SyntaxTokenList), - methodDeclaration.ReturnType.WithoutTrivia(), - default(ExplicitInterfaceSpecifierSyntax), - methodDeclaration.Identifier.WithoutTrivia(), - methodDeclaration.TypeParameterList?.WithoutTrivia(), - methodDeclaration.ParameterList.WithoutTrivia(), - default(SyntaxList), - default(BlockSyntax), - default(ArrowExpressionClauseSyntax), - SemicolonToken()); - } + { + return MethodDeclaration( + default(SyntaxList), + default(SyntaxTokenList), + methodDeclaration.ReturnType.WithoutTrivia(), + default(ExplicitInterfaceSpecifierSyntax), + methodDeclaration.Identifier.WithoutTrivia(), + methodDeclaration.TypeParameterList?.WithoutTrivia(), + methodDeclaration.ParameterList.WithoutTrivia(), + default(SyntaxList), + default(BlockSyntax), + default(ArrowExpressionClauseSyntax), + SemicolonToken()); + } case PropertyDeclarationSyntax propertyDeclaration: - { - return PropertyDeclaration( - default(SyntaxList), - default(SyntaxTokenList), - propertyDeclaration.Type.WithoutTrivia(), - default(ExplicitInterfaceSpecifierSyntax), - propertyDeclaration.Identifier.WithoutTrivia(), - CreateInterfaceAccessorList(propertyDeclaration.AccessorList)); - } + { + return PropertyDeclaration( + default(SyntaxList), + default(SyntaxTokenList), + propertyDeclaration.Type.WithoutTrivia(), + default(ExplicitInterfaceSpecifierSyntax), + propertyDeclaration.Identifier.WithoutTrivia(), + CreateInterfaceAccessorList(propertyDeclaration.AccessorList)); + } case IndexerDeclarationSyntax indexerDeclaration: - { - return IndexerDeclaration( - default(SyntaxList), - default(SyntaxTokenList), - indexerDeclaration.Type.WithoutTrivia(), - default(ExplicitInterfaceSpecifierSyntax), - indexerDeclaration.ParameterList.WithoutTrivia(), - CreateInterfaceAccessorList(indexerDeclaration.AccessorList)); - } + { + return IndexerDeclaration( + default(SyntaxList), + default(SyntaxTokenList), + indexerDeclaration.Type.WithoutTrivia(), + default(ExplicitInterfaceSpecifierSyntax), + indexerDeclaration.ParameterList.WithoutTrivia(), + CreateInterfaceAccessorList(indexerDeclaration.AccessorList)); + } case EventDeclarationSyntax eventDeclaration: - { - return EventFieldDeclaration( - default(SyntaxList), - default(SyntaxTokenList), - Token(SyntaxKind.EventKeyword), - VariableDeclaration(eventDeclaration.Type.WithoutTrivia(), eventDeclaration.Identifier.WithoutTrivia()), - SemicolonToken()); - } + { + return EventFieldDeclaration( + default(SyntaxList), + default(SyntaxTokenList), + Token(SyntaxKind.EventKeyword), + VariableDeclaration(eventDeclaration.Type.WithoutTrivia(), eventDeclaration.Identifier.WithoutTrivia()), + SemicolonToken()); + } case EventFieldDeclarationSyntax eventFieldDeclaration: - { - return EventFieldDeclaration( - default(SyntaxList), - default(SyntaxTokenList), - Token(SyntaxKind.EventKeyword), - eventFieldDeclaration.Declaration.WithoutTrivia(), - SemicolonToken()); - } + { + return EventFieldDeclaration( + default(SyntaxList), + default(SyntaxTokenList), + Token(SyntaxKind.EventKeyword), + eventFieldDeclaration.Declaration.WithoutTrivia(), + SemicolonToken()); + } default: - { - throw new ArgumentException("", nameof(memberDeclaration)); - } + { + throw new ArgumentException("", nameof(memberDeclaration)); + } } } diff --git a/src/Refactorings/CSharp/Refactorings/AddUsingDirectiveRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AddUsingDirectiveRefactoring.cs index e962915e69..95b0480b40 100644 --- a/src/Refactorings/CSharp/Refactorings/AddUsingDirectiveRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AddUsingDirectiveRefactoring.cs @@ -101,17 +101,17 @@ private static SyntaxNode GetNewNode(SyntaxNode node) switch (node.Parent.Kind()) { case SyntaxKind.QualifiedName: - { - var qualifiedName = (QualifiedNameSyntax)node.Parent; + { + var qualifiedName = (QualifiedNameSyntax)node.Parent; - return qualifiedName.Right.WithLeadingTrivia(node.GetLeadingTrivia()); - } + return qualifiedName.Right.WithLeadingTrivia(node.GetLeadingTrivia()); + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)node.Parent; + { + var memberAccess = (MemberAccessExpressionSyntax)node.Parent; - return memberAccess.Name.WithLeadingTrivia(node.GetLeadingTrivia()); - } + return memberAccess.Name.WithLeadingTrivia(node.GetLeadingTrivia()); + } } Debug.Fail(node.Parent?.Kind().ToString()); diff --git a/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs b/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs index 739d444b16..999b83d325 100644 --- a/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/AttributeListRefactoring.cs @@ -153,10 +153,10 @@ public static SyntaxList GetAttributeLists(this SyntaxNode case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)node).AttributeLists; default: - { - SyntaxDebug.Assert(node.IsKind(SyntaxKind.GlobalStatement), node); - return default; - } + { + SyntaxDebug.Assert(node.IsKind(SyntaxKind.GlobalStatement), node); + return default; + } } } @@ -216,10 +216,10 @@ public static CSharpSyntaxNode WithAttributeLists(this CSharpSyntaxNode node, Sy case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)node).WithAttributeLists(attributeLists); default: - { - SyntaxDebug.Fail(node); - return node; - } + { + SyntaxDebug.Fail(node); + return node; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs index a5c31d5a5d..7a898793f1 100644 --- a/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CheckParameterForNullRefactoring.cs @@ -232,14 +232,14 @@ private static BlockSyntax GetBody(ParameterSyntax parameter) #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - break; - } + { + break; + } default: - { - SyntaxDebug.Fail(parent); - break; - } + { + SyntaxDebug.Fail(parent); + break; + } } #endif return null; diff --git a/src/Refactorings/CSharp/Refactorings/CommentTriviaRefactoring.cs b/src/Refactorings/CSharp/Refactorings/CommentTriviaRefactoring.cs index 5fae1f6761..5d81949826 100644 --- a/src/Refactorings/CSharp/Refactorings/CommentTriviaRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/CommentTriviaRefactoring.cs @@ -54,16 +54,16 @@ public static void ComputeRefactorings(RefactoringContext context, SyntaxNode no { case SyntaxKind.SingleLineCommentTrivia: case SyntaxKind.MultiLineCommentTrivia: - { - fComment = true; - break; - } + { + fComment = true; + break; + } case SyntaxKind.SingleLineDocumentationCommentTrivia: case SyntaxKind.MultiLineDocumentationCommentTrivia: - { - fDocComment = true; - break; - } + { + fDocComment = true; + break; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs index ced0a4ca4f..e61ed5fa1d 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertBodyAndExpressionBodyRefactoring.cs @@ -45,117 +45,117 @@ private static RefactoringDescriptor GetRefactoringDescriptor(MemberDeclarationS switch (memberDeclaration) { case MethodDeclarationSyntax methodDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; + + if (expressionBody is not null) + { + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; + } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(methodDeclaration)) { - ArrowExpressionClauseSyntax expressionBody = methodDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(methodDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; } + + return default; + } case PropertyDeclarationSyntax propertyDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; + + if (expressionBody is not null) + { + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; + } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(propertyDeclaration)) { - ArrowExpressionClauseSyntax expressionBody = propertyDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(propertyDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; } + + return default; + } case IndexerDeclarationSyntax indexerDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; + + if (expressionBody is not null) + { + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; + } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(indexerDeclaration)) { - ArrowExpressionClauseSyntax expressionBody = indexerDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(indexerDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; } + + return default; + } case OperatorDeclarationSyntax operatorDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; + + if (expressionBody is not null) + { + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; + } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(operatorDeclaration)) { - ArrowExpressionClauseSyntax expressionBody = operatorDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(operatorDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; } + + return default; + } case ConversionOperatorDeclarationSyntax conversionOperatorDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = conversionOperatorDeclaration.ExpressionBody; + + if (expressionBody is not null) { - ArrowExpressionClauseSyntax expressionBody = conversionOperatorDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(conversionOperatorDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(conversionOperatorDeclaration)) + { + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; + } + + return default; + } case ConstructorDeclarationSyntax constructorDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = constructorDeclaration.ExpressionBody; + + if (expressionBody is not null) { - ArrowExpressionClauseSyntax expressionBody = constructorDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(constructorDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(constructorDeclaration)) + { + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; + } + + return default; + } case DestructorDeclarationSyntax destructorDeclaration: + { + ArrowExpressionClauseSyntax expressionBody = destructorDeclaration.ExpressionBody; + + if (expressionBody is not null) { - ArrowExpressionClauseSyntax expressionBody = destructorDeclaration.ExpressionBody; - - if (expressionBody is not null) - { - if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) - return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; - } - else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(destructorDeclaration)) - { - return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; - } - - return default; + if (ExpandExpressionBodyAnalysis.IsFixable(expressionBody)) + return RefactoringDescriptors.ConvertExpressionBodyToBlockBody; } + else if (ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(destructorDeclaration)) + { + return RefactoringDescriptors.ConvertBlockBodyToExpressionBody; + } + + return default; + } } return default; diff --git a/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs index 109c2e552a..c9e393e0ad 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs @@ -66,61 +66,61 @@ private static (bool success, ExpressionSyntax switchExpression) Analyze( switch (condition.Kind()) { case SyntaxKind.LogicalOrExpression: - { - var logicalOrExpression = (BinaryExpressionSyntax)condition; - - foreach (ExpressionSyntax expression in logicalOrExpression.AsChain()) - { - ExpressionSyntax expression2 = expression.WalkDownParentheses(); + { + var logicalOrExpression = (BinaryExpressionSyntax)condition; - if (!expression2.IsKind(SyntaxKind.EqualsExpression)) - return default; + foreach (ExpressionSyntax expression in logicalOrExpression.AsChain()) + { + ExpressionSyntax expression2 = expression.WalkDownParentheses(); - var equalsExpression = (BinaryExpressionSyntax)expression2; + if (!expression2.IsKind(SyntaxKind.EqualsExpression)) + return default; - if (!IsFixableEqualsExpression(equalsExpression)) - return default; - } + var equalsExpression = (BinaryExpressionSyntax)expression2; - break; + if (!IsFixableEqualsExpression(equalsExpression)) + return default; } + + break; + } case SyntaxKind.EqualsExpression: - { - var equalsExpression = (BinaryExpressionSyntax)condition; + { + var equalsExpression = (BinaryExpressionSyntax)condition; - if (!IsFixableEqualsExpression(equalsExpression)) - return default; + if (!IsFixableEqualsExpression(equalsExpression)) + return default; - break; - } + break; + } case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)condition; - - PatternSyntax pattern = isPatternExpression.Pattern; + { + var isPatternExpression = (IsPatternExpressionSyntax)condition; - SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern), pattern); + PatternSyntax pattern = isPatternExpression.Pattern; - if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern)) - return default; + SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern), pattern); - ExpressionSyntax expression = isPatternExpression.Expression.WalkDownParentheses(); + if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern)) + return default; - if (switchExpression is null) - { - switchExpression = expression; - } - else if (!CSharpFactory.AreEquivalent(expression, switchExpression)) - { - return default; - } + ExpressionSyntax expression = isPatternExpression.Expression.WalkDownParentheses(); - break; + if (switchExpression is null) + { + switchExpression = expression; } - default: + else if (!CSharpFactory.AreEquivalent(expression, switchExpression)) { return default; } + + break; + } + default: + { + return default; + } } return (true, switchExpression); @@ -186,29 +186,29 @@ private static ExpressionSyntax GetSwitchExpression(IfStatementSyntax ifStatemen switch (expression.Kind()) { case SyntaxKind.LogicalOrExpression: - { - var logicalOrExpression = (BinaryExpressionSyntax)expression; + { + var logicalOrExpression = (BinaryExpressionSyntax)expression; - var right = (BinaryExpressionSyntax)logicalOrExpression.Right.WalkDownParentheses(); + var right = (BinaryExpressionSyntax)logicalOrExpression.Right.WalkDownParentheses(); - return right.Left; - } + return right.Left; + } case SyntaxKind.EqualsExpression: - { - var equalsExpression = (BinaryExpressionSyntax)expression; + { + var equalsExpression = (BinaryExpressionSyntax)expression; - return equalsExpression.Left; - } + return equalsExpression.Left; + } case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; + { + var isPatternExpression = (IsPatternExpressionSyntax)expression; - return isPatternExpression.Expression; - } + return isPatternExpression.Expression; + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } @@ -238,52 +238,52 @@ private static SyntaxList CreateSwitchLabels(IfStatementSynta switch (expression.Kind()) { case SyntaxKind.LogicalOrExpression: - { - var logicalOrExpression = (BinaryExpressionSyntax)expression; - - return logicalOrExpression.AsChain() - .Select(exp => - { - var binaryExpression = (BinaryExpressionSyntax)exp.WalkDownParentheses(); - return CreateCaseSwitchLabel(binaryExpression.Right.WalkDownParentheses()); - }) - .ToSyntaxList(); - } + { + var logicalOrExpression = (BinaryExpressionSyntax)expression; + + return logicalOrExpression.AsChain() + .Select(exp => + { + var binaryExpression = (BinaryExpressionSyntax)exp.WalkDownParentheses(); + return CreateCaseSwitchLabel(binaryExpression.Right.WalkDownParentheses()); + }) + .ToSyntaxList(); + } case SyntaxKind.EqualsExpression: - { - var equalsExpression = (BinaryExpressionSyntax)expression; + { + var equalsExpression = (BinaryExpressionSyntax)expression; - return SingletonList(CreateCaseSwitchLabel(equalsExpression.Right.WalkDownParentheses())); - } + return SingletonList(CreateCaseSwitchLabel(equalsExpression.Right.WalkDownParentheses())); + } case SyntaxKind.IsPatternExpression: - { - var isPatternExpression = (IsPatternExpressionSyntax)expression; + { + var isPatternExpression = (IsPatternExpressionSyntax)expression; - PatternSyntax pattern = isPatternExpression.Pattern; + PatternSyntax pattern = isPatternExpression.Pattern; - if (pattern is ConstantPatternSyntax constantPattern) - { - return SingletonList(CreateCaseSwitchLabel(constantPattern.Expression)); - } - else if (pattern is DeclarationPatternSyntax) - { - return SingletonList(CasePatternSwitchLabel(pattern, Token(SyntaxKind.ColonToken))); - } - else if (pattern.IsKind(SyntaxKind.NotPattern)) - { - var notPattern = (UnaryPatternSyntax)pattern; + if (pattern is ConstantPatternSyntax constantPattern) + { + return SingletonList(CreateCaseSwitchLabel(constantPattern.Expression)); + } + else if (pattern is DeclarationPatternSyntax) + { + return SingletonList(CasePatternSwitchLabel(pattern, Token(SyntaxKind.ColonToken))); + } + else if (pattern.IsKind(SyntaxKind.NotPattern)) + { + var notPattern = (UnaryPatternSyntax)pattern; - return SingletonList(CasePatternSwitchLabel(notPattern, Token(SyntaxKind.ColonToken))); - } - else - { - throw new InvalidOperationException(); - } + return SingletonList(CasePatternSwitchLabel(notPattern, Token(SyntaxKind.ColonToken))); } - default: + else { throw new InvalidOperationException(); } + } + default: + { + throw new InvalidOperationException(); + } } static SwitchLabelSyntax CreateCaseSwitchLabel(ExpressionSyntax expression) diff --git a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs index adb5bd524d..8a18fb5970 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertInterpolatedStringToStringFormatRefactoring.cs @@ -41,23 +41,23 @@ void Analyze() switch (content.Kind()) { case SyntaxKind.Interpolation: - { - containsInterpolation = true; + { + containsInterpolation = true; - if (containsInterpolatedText) - return; + if (containsInterpolatedText) + return; - break; - } + break; + } case SyntaxKind.InterpolatedStringText: - { - containsInterpolatedText = true; + { + containsInterpolatedText = true; - if (containsInterpolation) - return; + if (containsInterpolation) + return; - break; - } + break; + } } } } @@ -86,37 +86,37 @@ private static Task RefactorAsync( switch (content.Kind()) { case SyntaxKind.Interpolation: - { - var interpolation = (InterpolationSyntax)content; + { + var interpolation = (InterpolationSyntax)content; - b.Append("{"); - b.Append(index.ToString(CultureInfo.InvariantCulture)); - index++; + b.Append("{"); + b.Append(index.ToString(CultureInfo.InvariantCulture)); + index++; - InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; - if (alignmentClause is not null) - { - b.Append(","); - b.AppendSpan(alignmentClause.Value); - } + InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; + if (alignmentClause is not null) + { + b.Append(","); + b.AppendSpan(alignmentClause.Value); + } - InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; - if (formatClause is not null) - { - b.Append(":"); - b.AppendSpan(formatClause.FormatStringToken); - } + InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; + if (formatClause is not null) + { + b.Append(":"); + b.AppendSpan(formatClause.FormatStringToken); + } - b.Append("}"); + b.Append("}"); - arguments.Add(Argument(interpolation.Expression)); - break; - } + arguments.Add(Argument(interpolation.Expression)); + break; + } case SyntaxKind.InterpolatedStringText: - { - b.AppendSpan(content); - break; - } + { + b.AppendSpan(content); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertLambdaExpressionBodyToBlockBodyRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertLambdaExpressionBodyToBlockBodyRefactoring.cs index e41c4cc772..ef0ab5dab4 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertLambdaExpressionBodyToBlockBodyRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertLambdaExpressionBodyToBlockBodyRefactoring.cs @@ -52,15 +52,15 @@ public static async Task RefactorAsync( switch (lambda.Kind()) { case SyntaxKind.SimpleLambdaExpression: - { - newLambda = ((SimpleLambdaExpressionSyntax)lambda).WithBody(block); - break; - } + { + newLambda = ((SimpleLambdaExpressionSyntax)lambda).WithBody(block); + break; + } case SyntaxKind.ParenthesizedLambdaExpression: - { - newLambda = ((ParenthesizedLambdaExpressionSyntax)lambda).WithBody(block); - break; - } + { + newLambda = ((ParenthesizedLambdaExpressionSyntax)lambda).WithBody(block); + break; + } } newLambda = newLambda.WithFormatterAnnotation(); diff --git a/src/Refactorings/CSharp/Refactorings/ConvertStringLiteralRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertStringLiteralRefactoring.cs index 88f0396a9f..ed16543322 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertStringLiteralRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertStringLiteralRefactoring.cs @@ -142,30 +142,30 @@ private static string CreateRegularStringLiteral(string text) switch (text[i]) { case '"': - { - sb.Append("\\\""); - break; - } + { + sb.Append("\\\""); + break; + } case '\\': - { - sb.Append(@"\\"); - break; - } + { + sb.Append(@"\\"); + break; + } case '\r': - { - sb.Append(@"\r"); - break; - } + { + sb.Append(@"\r"); + break; + } case '\n': - { - sb.Append(@"\n"); - break; - } + { + sb.Append(@"\n"); + break; + } default: - { - sb.Append(text[i]); - break; - } + { + sb.Append(text[i]); + break; + } } } @@ -183,38 +183,38 @@ private static List CreateRegularStringLiterals(string text) switch (text[i]) { case '"': - { - sb.Append("\\\""); - break; - } + { + sb.Append("\\\""); + break; + } case '\\': - { - sb.Append(@"\\"); - break; - } + { + sb.Append(@"\\"); + break; + } case '\r': + { + if (i < text.Length - 1 + && text[i + 1] == '\n') { - if (i < text.Length - 1 - && text[i + 1] == '\n') - { - i++; - } - - values.Add(sb.ToString()); - sb.Clear(); - break; + i++; } + + values.Add(sb.ToString()); + sb.Clear(); + break; + } case '\n': - { - values.Add(sb.ToString()); - sb.Clear(); - break; - } + { + values.Add(sb.ToString()); + sb.Clear(); + break; + } default: - { - sb.Append(text[i]); - break; - } + { + sb.Append(text[i]); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs index c4f953507c..f97d15bd1e 100644 --- a/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ConvertSwitchToIfRefactoring.cs @@ -31,24 +31,24 @@ public static void ComputeRefactoring(RefactoringContext context, SwitchStatemen switch (label.Kind()) { case SyntaxKind.CasePatternSwitchLabel: - { - containsPattern = true; - break; - } + { + containsPattern = true; + break; + } case SyntaxKind.CaseSwitchLabel: - { - break; - } + { + break; + } case SyntaxKind.DefaultSwitchLabel: - { - containsDefault = true; - break; - } + { + containsDefault = true; + break; + } default: - { - SyntaxDebug.Fail(label); - return; - } + { + SyntaxDebug.Fail(label); + return; + } } if (containsDefault) @@ -147,41 +147,41 @@ private static ExpressionSyntax CreateCondition( switch (labels[i]) { case CaseSwitchLabelSyntax constantLabel: - { - BinaryExpressionSyntax equalsExpression = EqualsExpression(switchExpression, constantLabel.Value); - - if (semanticModel.GetSpeculativeMethodSymbol(switchSection.SpanStart, equalsExpression) is not null) - { - expression = equalsExpression; - } - else - { - expression = SimpleMemberInvocationExpression( - ObjectType(), - IdentifierName("Equals"), - ArgumentList(Argument(switchExpression), Argument(constantLabel.Value))); - } + { + BinaryExpressionSyntax equalsExpression = EqualsExpression(switchExpression, constantLabel.Value); - break; + if (semanticModel.GetSpeculativeMethodSymbol(switchSection.SpanStart, equalsExpression) is not null) + { + expression = equalsExpression; } - case CasePatternSwitchLabelSyntax patternLabel: + else { - expression = IsPatternExpression(switchExpression.Parenthesize(), patternLabel.Pattern).Parenthesize(); + expression = SimpleMemberInvocationExpression( + ObjectType(), + IdentifierName("Equals"), + ArgumentList(Argument(switchExpression), Argument(constantLabel.Value))); + } - if (patternLabel.WhenClause is not null) - { - expression = LogicalAndExpression( - expression, - patternLabel.WhenClause.Condition.Parenthesize()) - .Parenthesize(); - } + break; + } + case CasePatternSwitchLabelSyntax patternLabel: + { + expression = IsPatternExpression(switchExpression.Parenthesize(), patternLabel.Pattern).Parenthesize(); - break; - } - default: + if (patternLabel.WhenClause is not null) { - throw new InvalidOperationException(); + expression = LogicalAndExpression( + expression, + patternLabel.WhenClause.Condition.Parenthesize()) + .Parenthesize(); } + + break; + } + default: + { + throw new InvalidOperationException(); + } } if (condition is not null) diff --git a/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs index f851e521be..7bcc1e65e7 100644 --- a/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ExtractCondition/ExtractConditionRefactoring.cs @@ -28,47 +28,47 @@ internal static void ComputeRefactoring(RefactoringContext context, ExpressionCh switch (parent?.Kind()) { case SyntaxKind.IfStatement: + { + if (kind == SyntaxKind.LogicalAndExpression) { - if (kind == SyntaxKind.LogicalAndExpression) - { - ExtractConditionFromIfToNestedIfRefactoring refactoring = ExtractConditionFromIfToNestedIfRefactoring.Instance; - - context.RegisterRefactoring( - refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, (IfStatementSyntax)parent, condition, expressionChain, ct), - RefactoringDescriptors.ExtractExpressionFromCondition); - } - else if (kind == SyntaxKind.LogicalOrExpression) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); - - if (statementsInfo.Success) - { - ExtractConditionFromIfToIfRefactoring refactoring = ExtractConditionFromIfToIfRefactoring.Instance; - - context.RegisterRefactoring( - refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, statementsInfo, condition, expressionChain, ct), - RefactoringDescriptors.ExtractExpressionFromCondition); - } - } + ExtractConditionFromIfToNestedIfRefactoring refactoring = ExtractConditionFromIfToNestedIfRefactoring.Instance; - break; + context.RegisterRefactoring( + refactoring.Title, + ct => refactoring.RefactorAsync(context.Document, (IfStatementSyntax)parent, condition, expressionChain, ct), + RefactoringDescriptors.ExtractExpressionFromCondition); } - case SyntaxKind.WhileStatement: + else if (kind == SyntaxKind.LogicalOrExpression) { - if (kind == SyntaxKind.LogicalAndExpression) + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); + + if (statementsInfo.Success) { - ExtractConditionFromWhileToNestedIfRefactoring refactoring = ExtractConditionFromWhileToNestedIfRefactoring.Instance; + ExtractConditionFromIfToIfRefactoring refactoring = ExtractConditionFromIfToIfRefactoring.Instance; context.RegisterRefactoring( refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, (WhileStatementSyntax)parent, condition, expressionChain, ct), + ct => refactoring.RefactorAsync(context.Document, statementsInfo, condition, expressionChain, ct), RefactoringDescriptors.ExtractExpressionFromCondition); } + } - break; + break; + } + case SyntaxKind.WhileStatement: + { + if (kind == SyntaxKind.LogicalAndExpression) + { + ExtractConditionFromWhileToNestedIfRefactoring refactoring = ExtractConditionFromWhileToNestedIfRefactoring.Instance; + + context.RegisterRefactoring( + refactoring.Title, + ct => refactoring.RefactorAsync(context.Document, (WhileStatementSyntax)parent, condition, expressionChain, ct), + RefactoringDescriptors.ExtractExpressionFromCondition); } + + break; + } } } @@ -94,52 +94,52 @@ public static void ComputeRefactoring(RefactoringContext context, ExpressionSynt switch (parent?.Kind()) { case SyntaxKind.IfStatement: + { + if (kind == SyntaxKind.LogicalAndExpression) + { + ExtractConditionFromIfToNestedIfRefactoring refactoring = ExtractConditionFromIfToNestedIfRefactoring.Instance; + + context.RegisterRefactoring( + refactoring.Title, + ct => refactoring.RefactorAsync(context.Document, binaryExpression, expression, ct), + RefactoringDescriptors.ExtractExpressionFromCondition); + } + else if (kind == SyntaxKind.LogicalOrExpression) { - if (kind == SyntaxKind.LogicalAndExpression) + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); + + if (statementsInfo.Success) { - ExtractConditionFromIfToNestedIfRefactoring refactoring = ExtractConditionFromIfToNestedIfRefactoring.Instance; + ExtractConditionFromIfToIfRefactoring refactoring = ExtractConditionFromIfToIfRefactoring.Instance; context.RegisterRefactoring( refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, binaryExpression, expression, ct), + ct => refactoring.RefactorAsync(context.Document, statementsInfo, binaryExpression, expression, ct), RefactoringDescriptors.ExtractExpressionFromCondition); } - else if (kind == SyntaxKind.LogicalOrExpression) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); - - if (statementsInfo.Success) - { - ExtractConditionFromIfToIfRefactoring refactoring = ExtractConditionFromIfToIfRefactoring.Instance; - - context.RegisterRefactoring( - refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, statementsInfo, binaryExpression, expression, ct), - RefactoringDescriptors.ExtractExpressionFromCondition); - } - } - - break; } + + break; + } case SyntaxKind.WhileStatement: + { + if (kind == SyntaxKind.LogicalAndExpression) { - if (kind == SyntaxKind.LogicalAndExpression) - { - StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); + StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo((StatementSyntax)parent); - if (statementsInfo.Success) - { - ExtractConditionFromWhileToNestedIfRefactoring refactoring = ExtractConditionFromWhileToNestedIfRefactoring.Instance; + if (statementsInfo.Success) + { + ExtractConditionFromWhileToNestedIfRefactoring refactoring = ExtractConditionFromWhileToNestedIfRefactoring.Instance; - context.RegisterRefactoring( - refactoring.Title, - ct => refactoring.RefactorAsync(context.Document, (WhileStatementSyntax)parent, binaryExpression, expression, ct), - RefactoringDescriptors.ExtractExpressionFromCondition); - } + context.RegisterRefactoring( + refactoring.Title, + ct => refactoring.RefactorAsync(context.Document, (WhileStatementSyntax)parent, binaryExpression, expression, ct), + RefactoringDescriptors.ExtractExpressionFromCondition); } - - break; } + + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs b/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs index d9bd141079..9ff0d24860 100644 --- a/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/GeneratePropertyForDebuggerDisplayAttributeRefactoring.cs @@ -100,35 +100,35 @@ void FindOpenBrace() switch (value[i]) { case '{': - { - return; - } + { + return; + } case '}': - { - i = -1; - return; - } + { + i = -1; + return; + } case '\\': - { - i++; - - if (i < length) - { - char ch = value[i]; + { + i++; - if (ch == '{' - || ch == '}') - { - i++; - } + if (i < length) + { + char ch = value[i]; - continue; - } - else + if (ch == '{' + || ch == '}') { - return; + i++; } + + continue; } + else + { + return; + } + } } i++; @@ -142,49 +142,49 @@ void FindCloseBrace() switch (value[i]) { case '{': - { - i = -1; - return; - } + { + i = -1; + return; + } case '}': - { - return; - } + { + return; + } case '(': - { - i++; - - if (i < length - && value[i] == ')') - { - break; - } + { + i++; - i = -1; - return; + if (i < length + && value[i] == ')') + { + break; } + + i = -1; + return; + } case ',': + { + i++; + if (i < length + && value[i] == 'n') { i++; if (i < length - && value[i] == 'n') + && value[i] == 'q') { i++; if (i < length - && value[i] == 'q') + && value[i] == '}') { - i++; - if (i < length - && value[i] == '}') - { - return; - } + return; } } - - i = -1; - return; } + + i = -1; + return; + } } i++; @@ -279,43 +279,43 @@ void AppendInterpolatedText() switch (value[i]) { case '{': - { - sb.Append(value, lastPos, i - lastPos); - return; - } + { + sb.Append(value, lastPos, i - lastPos); + return; + } case '\\': - { - sb.Append(value, lastPos, i - lastPos); + { + sb.Append(value, lastPos, i - lastPos); - i++; + i++; - if (i < length) - { - char ch = value[i]; + if (i < length) + { + char ch = value[i]; - if (ch == '{' - || ch == '}') - { - sb.Append(ch); - sb.Append(ch); - i++; - lastPos = i; - continue; - } + if (ch == '{' + || ch == '}') + { + sb.Append(ch); + sb.Append(ch); + i++; + lastPos = i; + continue; } - - sb.Append((isVerbatim) ? "\\" : "\\\\"); - lastPos = i; - continue; } + + sb.Append((isVerbatim) ? "\\" : "\\\\"); + lastPos = i; + continue; + } case '"': - { - sb.Append(value, lastPos, i - lastPos); - sb.Append((isVerbatim) ? "\"\"" : "\\\""); - i++; - lastPos = i; - continue; - } + { + sb.Append(value, lastPos, i - lastPos); + sb.Append((isVerbatim) ? "\"\"" : "\\\""); + i++; + lastPos = i; + continue; + } } i++; @@ -329,26 +329,26 @@ void AppendInterpolation() switch (value[i]) { case '}': - { - sb.Append('{'); - sb.Append(value, lastPos, i - lastPos); - sb.Append('}'); - return; - } + { + sb.Append('{'); + sb.Append(value, lastPos, i - lastPos); + sb.Append('}'); + return; + } case '(': - { - i++; - break; - } + { + i++; + break; + } case ',': - { - sb.Append('{'); - sb.Append(value, lastPos, i - lastPos); - sb.Append('}'); - - i += 3; - return; - } + { + sb.Append('{'); + sb.Append(value, lastPos, i - lastPos); + sb.Append('}'); + + i += 3; + return; + } } i++; diff --git a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs index af9baa752d..1b8a36aa22 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineDefinition/InlineRefactoring.cs @@ -281,19 +281,19 @@ private Dictionary GetReplacementMap(SyntaxNode node, Dictio case SyntaxKind.TypeParameter: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: - { - ISymbol symbol = DeclarationSemanticModel.GetDeclaredSymbol(descendant, cancellationToken); - - Debug.Assert(symbol is not null || (descendant as ForEachVariableStatementSyntax)?.Variable?.Kind() == SyntaxKind.TupleExpression, kind.ToString()); + { + ISymbol symbol = DeclarationSemanticModel.GetDeclaredSymbol(descendant, cancellationToken); - if (symbol is not null - && symbolMap.TryGetValue(symbol, out string name)) - { - replacementMap.Add(descendant, name); - } + Debug.Assert(symbol is not null || (descendant as ForEachVariableStatementSyntax)?.Variable?.Kind() == SyntaxKind.TupleExpression, kind.ToString()); - break; + if (symbol is not null + && symbolMap.TryGetValue(symbol, out string name)) + { + replacementMap.Add(descendant, name); } + + break; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/InlineUsingStaticDirectiveRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InlineUsingStaticDirectiveRefactoring.cs index 9771aeb495..af4bdc7771 100644 --- a/src/Refactorings/CSharp/Refactorings/InlineUsingStaticDirectiveRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InlineUsingStaticDirectiveRefactoring.cs @@ -78,15 +78,15 @@ private static SyntaxNode RemoveUsingDirective(SyntaxNode node, int index) switch (node) { case CompilationUnitSyntax compilationUnit: - { - UsingDirectiveSyntax usingDirective = compilationUnit.Usings[index]; - return compilationUnit.RemoveNode(usingDirective); - } + { + UsingDirectiveSyntax usingDirective = compilationUnit.Usings[index]; + return compilationUnit.RemoveNode(usingDirective); + } case NamespaceDeclarationSyntax namespaceDeclaration: - { - UsingDirectiveSyntax usingDirective = namespaceDeclaration.Usings[index]; - return namespaceDeclaration.RemoveNode(usingDirective); - } + { + UsingDirectiveSyntax usingDirective = namespaceDeclaration.Usings[index]; + return namespaceDeclaration.RemoveNode(usingDirective); + } } return node; diff --git a/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs index 717a34a5e4..70d14230d6 100644 --- a/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/IntroduceConstructorRefactoring.cs @@ -290,12 +290,12 @@ private static bool IsIdentifierNameOptionallyQualifiedWithThis(ExpressionSyntax switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - return memberAccess.Expression.IsKind(SyntaxKind.ThisExpression) - && memberAccess.Name.IsKind(SyntaxKind.IdentifierName); - } + return memberAccess.Expression.IsKind(SyntaxKind.ThisExpression) + && memberAccess.Name.IsKind(SyntaxKind.IdentifierName); + } case SyntaxKind.IdentifierName: return true; default: @@ -348,10 +348,10 @@ private static MemberDeclarationSyntax GetContainingDeclaration(MemberDeclaratio #endif return declaration; default: - { - Debug.Assert(declaration.Parent is MemberDeclarationSyntax); - return declaration.Parent as MemberDeclarationSyntax; - } + { + Debug.Assert(declaration.Parent is MemberDeclarationSyntax); + return declaration.Parent as MemberDeclarationSyntax; + } } } @@ -457,13 +457,13 @@ private static SyntaxToken GetIdentifier(ExpressionSyntax expression) case SyntaxKind.IdentifierName: return ((IdentifierNameSyntax)expression).Identifier; case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - var identifierName = (IdentifierNameSyntax)memberAccess.Name; + var identifierName = (IdentifierNameSyntax)memberAccess.Name; - return identifierName.Identifier; - } + return identifierName.Identifier; + } } SyntaxDebug.Fail(expression); diff --git a/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs index 2e4575bedd..1177e5310b 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertIfRefactoring.cs @@ -222,22 +222,22 @@ bool IsLastStatementRedundant() switch (jumpStatement.Kind()) { case SyntaxKind.ReturnStatement: + { + if (((ReturnStatementSyntax)jumpStatement).Expression is null + && RemoveRedundantStatementAnalysis.IsFixable(lastStatement, SyntaxKind.ReturnStatement)) { - if (((ReturnStatementSyntax)jumpStatement).Expression is null - && RemoveRedundantStatementAnalysis.IsFixable(lastStatement, SyntaxKind.ReturnStatement)) - { - return true; - } - - break; + return true; } + + break; + } case SyntaxKind.ContinueStatement: - { - if (RemoveRedundantStatementAnalysis.IsFixable(lastStatement, SyntaxKind.ContinueStatement)) - return true; + { + if (RemoveRedundantStatementAnalysis.IsFixable(lastStatement, SyntaxKind.ContinueStatement)) + return true; - break; - } + break; + } } return false; diff --git a/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs index ce99dc4001..a5eecaaf3d 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertLinqMethodCallRefactoring.cs @@ -56,9 +56,9 @@ private static ExpressionSyntax GetExpression(InvocationExpressionSyntax invocat { case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: - { - return ((LambdaExpressionSyntax)expression).Body as ExpressionSyntax; - } + { + return ((LambdaExpressionSyntax)expression).Body as ExpressionSyntax; + } } return null; diff --git a/src/Refactorings/CSharp/Refactorings/InvertOperatorRefactoring.cs b/src/Refactorings/CSharp/Refactorings/InvertOperatorRefactoring.cs index 8bd4149b4e..98a4283eac 100644 --- a/src/Refactorings/CSharp/Refactorings/InvertOperatorRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/InvertOperatorRefactoring.cs @@ -62,10 +62,10 @@ private static SyntaxKind GetInvertedOperatorKind(SyntaxToken operatorToken) case SyntaxKind.LessThanEqualsToken: return SyntaxKind.GreaterThanToken; default: - { - SyntaxDebug.Fail(operatorToken); - return operatorToken.Kind(); - } + { + SyntaxDebug.Fail(operatorToken); + return operatorToken.Kind(); + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/LiteralExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/LiteralExpressionRefactoring.cs index a0edaa9a6f..73d5a34243 100644 --- a/src/Refactorings/CSharp/Refactorings/LiteralExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/LiteralExpressionRefactoring.cs @@ -14,35 +14,35 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Li { case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: + { + if (context.IsRefactoringEnabled(RefactoringDescriptors.InvertBooleanLiteral) + && literalExpression.Span.Contains(context.Span)) { - if (context.IsRefactoringEnabled(RefactoringDescriptors.InvertBooleanLiteral) - && literalExpression.Span.Contains(context.Span)) - { - context.RegisterRefactoring( - "Invert boolean literal", - ct => InvertBooleanLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), - RefactoringDescriptors.InvertBooleanLiteral); - } - - break; + context.RegisterRefactoring( + "Invert boolean literal", + ct => InvertBooleanLiteralRefactoring.RefactorAsync(context.Document, literalExpression, ct), + RefactoringDescriptors.InvertBooleanLiteral); } + + break; + } case SyntaxKind.StringLiteralExpression: - { - if (context.Span.IsContainedInSpanOrBetweenSpans(literalExpression)) - await StringLiteralExpressionRefactoring.ComputeRefactoringsAsync(context, literalExpression).ConfigureAwait(false); + { + if (context.Span.IsContainedInSpanOrBetweenSpans(literalExpression)) + await StringLiteralExpressionRefactoring.ComputeRefactoringsAsync(context, literalExpression).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.NumericLiteralExpression: + { + if (context.IsRefactoringEnabled(RefactoringDescriptors.ConvertHexadecimalLiteralToDecimalLiteral) + && context.Span.IsBetweenSpans(literalExpression)) { - if (context.IsRefactoringEnabled(RefactoringDescriptors.ConvertHexadecimalLiteralToDecimalLiteral) - && context.Span.IsBetweenSpans(literalExpression)) - { - ConvertHexadecimalLiteralToDecimalLiteralRefactoring.ComputeRefactoring(context, literalExpression); - } - - break; + ConvertHexadecimalLiteralToDecimalLiteralRefactoring.ComputeRefactoring(context, literalExpression); } + + break; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs b/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs index 89a97c4568..4f4afb8bf8 100644 --- a/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/MemberDeclarationRefactoring.cs @@ -31,47 +31,47 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me #endif case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: + { + if (context.IsAnyRefactoringEnabled( + RefactoringDescriptors.RemoveMemberDeclaration, + RefactoringDescriptors.CopyMemberDeclaration, + RefactoringDescriptors.CommentOutMemberDeclaration)) { - if (context.IsAnyRefactoringEnabled( - RefactoringDescriptors.RemoveMemberDeclaration, - RefactoringDescriptors.CopyMemberDeclaration, - RefactoringDescriptors.CommentOutMemberDeclaration)) - { - (SyntaxToken openBrace, SyntaxToken closeBrace) = GetBraces(member); + (SyntaxToken openBrace, SyntaxToken closeBrace) = GetBraces(member); - if ((!openBrace.IsKind(SyntaxKind.None) - && openBrace.Span.Contains(context.Span)) - || (!closeBrace.IsKind(SyntaxKind.None) - && closeBrace.Span.Contains(context.Span))) + if ((!openBrace.IsKind(SyntaxKind.None) + && openBrace.Span.Contains(context.Span)) + || (!closeBrace.IsKind(SyntaxKind.None) + && closeBrace.Span.Contains(context.Span))) + { + if (member.Parent is not null + && CSharpFacts.CanHaveMembers(member.Parent.Kind())) { - if (member.Parent is not null - && CSharpFacts.CanHaveMembers(member.Parent.Kind())) + if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveMemberDeclaration)) { - if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveMemberDeclaration)) - { - context.RegisterRefactoring(CodeActionFactory.RemoveMemberDeclaration(context.Document, member, equivalenceKey: EquivalenceKey.Create(RefactoringDescriptors.RemoveMemberDeclaration))); - } - - if (context.IsRefactoringEnabled(RefactoringDescriptors.CopyMemberDeclaration)) - { - context.RegisterRefactoring( - $"Copy {CSharpFacts.GetTitle(member)}", - ct => CopyMemberDeclarationRefactoring.RefactorAsync( - context.Document, - member, - copyAfter: closeBrace.Span.Contains(context.Span), - ct), - RefactoringDescriptors.CopyMemberDeclaration); - } + context.RegisterRefactoring(CodeActionFactory.RemoveMemberDeclaration(context.Document, member, equivalenceKey: EquivalenceKey.Create(RefactoringDescriptors.RemoveMemberDeclaration))); } - if (context.IsRefactoringEnabled(RefactoringDescriptors.CommentOutMemberDeclaration)) - CommentOutRefactoring.RegisterRefactoring(context, member); + if (context.IsRefactoringEnabled(RefactoringDescriptors.CopyMemberDeclaration)) + { + context.RegisterRefactoring( + $"Copy {CSharpFacts.GetTitle(member)}", + ct => CopyMemberDeclarationRefactoring.RefactorAsync( + context.Document, + member, + copyAfter: closeBrace.Span.Contains(context.Span), + ct), + RefactoringDescriptors.CopyMemberDeclaration); + } } - } - break; + if (context.IsRefactoringEnabled(RefactoringDescriptors.CommentOutMemberDeclaration)) + CommentOutRefactoring.RegisterRefactoring(context, member); + } } + + break; + } } if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveAllStatements)) @@ -91,123 +91,123 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Me switch (kind) { case SyntaxKind.NamespaceDeclaration: - { - var namespaceDeclaration = (NamespaceDeclarationSyntax)member; - NamespaceDeclarationRefactoring.ComputeRefactorings(context, namespaceDeclaration); + { + var namespaceDeclaration = (NamespaceDeclarationSyntax)member; + NamespaceDeclarationRefactoring.ComputeRefactorings(context, namespaceDeclaration); - if (MemberDeclarationListSelection.TryCreate(namespaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) - await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); + if (MemberDeclarationListSelection.TryCreate(namespaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) + await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.ClassDeclaration: - { - var classDeclaration = (ClassDeclarationSyntax)member; - await ClassDeclarationRefactoring.ComputeRefactoringsAsync(context, classDeclaration).ConfigureAwait(false); + { + var classDeclaration = (ClassDeclarationSyntax)member; + await ClassDeclarationRefactoring.ComputeRefactoringsAsync(context, classDeclaration).ConfigureAwait(false); - if (MemberDeclarationListSelection.TryCreate(classDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) - await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); + if (MemberDeclarationListSelection.TryCreate(classDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) + await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var recordDeclaration = (RecordDeclarationSyntax)member; - await RecordDeclarationRefactoring.ComputeRefactoringsAsync(context, recordDeclaration).ConfigureAwait(false); + { + var recordDeclaration = (RecordDeclarationSyntax)member; + await RecordDeclarationRefactoring.ComputeRefactoringsAsync(context, recordDeclaration).ConfigureAwait(false); - if (MemberDeclarationListSelection.TryCreate(recordDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) - await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); + if (MemberDeclarationListSelection.TryCreate(recordDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) + await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.StructDeclaration: - { - var structDeclaration = (StructDeclarationSyntax)member; - await StructDeclarationRefactoring.ComputeRefactoringsAsync(context, structDeclaration).ConfigureAwait(false); + { + var structDeclaration = (StructDeclarationSyntax)member; + await StructDeclarationRefactoring.ComputeRefactoringsAsync(context, structDeclaration).ConfigureAwait(false); - if (MemberDeclarationListSelection.TryCreate(structDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) - await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); + if (MemberDeclarationListSelection.TryCreate(structDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) + await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.InterfaceDeclaration: - { - var interfaceDeclaration = (InterfaceDeclarationSyntax)member; - InterfaceDeclarationRefactoring.ComputeRefactorings(context, interfaceDeclaration); + { + var interfaceDeclaration = (InterfaceDeclarationSyntax)member; + InterfaceDeclarationRefactoring.ComputeRefactorings(context, interfaceDeclaration); - if (MemberDeclarationListSelection.TryCreate(interfaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) - await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); + if (MemberDeclarationListSelection.TryCreate(interfaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers)) + await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.EnumDeclaration: - { - await EnumDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await EnumDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.EnumMemberDeclaration: - { - await EnumMemberDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumMemberDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await EnumMemberDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumMemberDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.DelegateDeclaration: - { - DelegateDeclarationRefactoring.ComputeRefactorings(context, (DelegateDeclarationSyntax)member); - break; - } + { + DelegateDeclarationRefactoring.ComputeRefactorings(context, (DelegateDeclarationSyntax)member); + break; + } case SyntaxKind.MethodDeclaration: - { - await MethodDeclarationRefactoring.ComputeRefactoringsAsync(context, (MethodDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await MethodDeclarationRefactoring.ComputeRefactoringsAsync(context, (MethodDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.ConstructorDeclaration: - { - await ConstructorDeclarationRefactoring.ComputeRefactoringsAsync(context, (ConstructorDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await ConstructorDeclarationRefactoring.ComputeRefactoringsAsync(context, (ConstructorDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.DestructorDeclaration: - { - DestructorDeclarationRefactoring.ComputeRefactorings(context, (DestructorDeclarationSyntax)member); - break; - } + { + DestructorDeclarationRefactoring.ComputeRefactorings(context, (DestructorDeclarationSyntax)member); + break; + } case SyntaxKind.IndexerDeclaration: - { - await IndexerDeclarationRefactoring.ComputeRefactoringsAsync(context, (IndexerDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await IndexerDeclarationRefactoring.ComputeRefactoringsAsync(context, (IndexerDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.PropertyDeclaration: - { - await PropertyDeclarationRefactoring.ComputeRefactoringsAsync(context, (PropertyDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await PropertyDeclarationRefactoring.ComputeRefactoringsAsync(context, (PropertyDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.OperatorDeclaration: - { - ComputeRefactorings(context, (OperatorDeclarationSyntax)member); - break; - } + { + ComputeRefactorings(context, (OperatorDeclarationSyntax)member); + break; + } case SyntaxKind.ConversionOperatorDeclaration: - { - ComputeRefactorings(context, (ConversionOperatorDeclarationSyntax)member); - break; - } + { + ComputeRefactorings(context, (ConversionOperatorDeclarationSyntax)member); + break; + } case SyntaxKind.FieldDeclaration: - { - await FieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (FieldDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await FieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (FieldDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.EventDeclaration: - { - await EventDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await EventDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventDeclarationSyntax)member).ConfigureAwait(false); + break; + } case SyntaxKind.EventFieldDeclaration: - { - await EventFieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventFieldDeclarationSyntax)member).ConfigureAwait(false); - break; - } + { + await EventFieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventFieldDeclarationSyntax)member).ConfigureAwait(false); + break; + } } if (context.IsRefactoringEnabled(RefactoringDescriptors.MoveUnsafeContextToContainingDeclaration)) @@ -245,66 +245,66 @@ private static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(MemberD switch (member.Kind()) { case SyntaxKind.MethodDeclaration: - { - return FromBody(((MethodDeclarationSyntax)member).Body); - } + { + return FromBody(((MethodDeclarationSyntax)member).Body); + } case SyntaxKind.IndexerDeclaration: - { - return FromAccessorList(((IndexerDeclarationSyntax)member).AccessorList); - } + { + return FromAccessorList(((IndexerDeclarationSyntax)member).AccessorList); + } case SyntaxKind.OperatorDeclaration: - { - return FromBody(((OperatorDeclarationSyntax)member).Body); - } + { + return FromBody(((OperatorDeclarationSyntax)member).Body); + } case SyntaxKind.ConversionOperatorDeclaration: - { - return FromBody(((ConversionOperatorDeclarationSyntax)member).Body); - } + { + return FromBody(((ConversionOperatorDeclarationSyntax)member).Body); + } case SyntaxKind.ConstructorDeclaration: - { - return FromBody(((ConstructorDeclarationSyntax)member).Body); - } + { + return FromBody(((ConstructorDeclarationSyntax)member).Body); + } case SyntaxKind.PropertyDeclaration: - { - return FromAccessorList(((PropertyDeclarationSyntax)member).AccessorList); - } + { + return FromAccessorList(((PropertyDeclarationSyntax)member).AccessorList); + } case SyntaxKind.EventDeclaration: - { - return FromAccessorList(((EventDeclarationSyntax)member).AccessorList); - } + { + return FromAccessorList(((EventDeclarationSyntax)member).AccessorList); + } case SyntaxKind.NamespaceDeclaration: - { - var member1 = ((NamespaceDeclarationSyntax)member); - return (member1.OpenBraceToken, member1.CloseBraceToken); - } + { + var member1 = ((NamespaceDeclarationSyntax)member); + return (member1.OpenBraceToken, member1.CloseBraceToken); + } case SyntaxKind.ClassDeclaration: - { - var member2 = ((ClassDeclarationSyntax)member); - return (member2.OpenBraceToken, member2.CloseBraceToken); - } + { + var member2 = ((ClassDeclarationSyntax)member); + return (member2.OpenBraceToken, member2.CloseBraceToken); + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - var member3 = ((RecordDeclarationSyntax)member); - return (member3.OpenBraceToken, member3.CloseBraceToken); - } + { + var member3 = ((RecordDeclarationSyntax)member); + return (member3.OpenBraceToken, member3.CloseBraceToken); + } case SyntaxKind.StructDeclaration: - { - var member4 = ((StructDeclarationSyntax)member); - return (member4.OpenBraceToken, member4.CloseBraceToken); - } + { + var member4 = ((StructDeclarationSyntax)member); + return (member4.OpenBraceToken, member4.CloseBraceToken); + } case SyntaxKind.InterfaceDeclaration: - { - var member5 = ((InterfaceDeclarationSyntax)member); - return (member5.OpenBraceToken, member5.CloseBraceToken); - } + { + var member5 = ((InterfaceDeclarationSyntax)member); + return (member5.OpenBraceToken, member5.CloseBraceToken); + } case SyntaxKind.EnumDeclaration: - { - var member6 = ((EnumDeclarationSyntax)member); - return (member6.OpenBraceToken, member6.CloseBraceToken); - } + { + var member6 = ((EnumDeclarationSyntax)member); + return (member6.OpenBraceToken, member6.CloseBraceToken); + } } return default; diff --git a/src/Refactorings/CSharp/Refactorings/ParenthesizeExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/ParenthesizeExpressionRefactoring.cs index 671ba87502..cee74d6bab 100644 --- a/src/Refactorings/CSharp/Refactorings/ParenthesizeExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/ParenthesizeExpressionRefactoring.cs @@ -46,48 +46,48 @@ private static bool CanRefactor(SyntaxNode node) case SyntaxKind.AttributeArgument: case SyntaxKind.ThrowExpression: case SyntaxKind.PredefinedType: - { - return false; - } + { + return false; + } case SyntaxKind.QualifiedName: + { + switch (node.Parent?.Kind()) { - switch (node.Parent?.Kind()) + case SyntaxKind.NamespaceDeclaration: + case SyntaxKind.UsingDirective: + case SyntaxKind.QualifiedName: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.TupleElement: + { + return false; + } + default: { - case SyntaxKind.NamespaceDeclaration: - case SyntaxKind.UsingDirective: - case SyntaxKind.QualifiedName: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.TupleElement: - { - return false; - } - default: - { - return true; - } + return true; } } + } case SyntaxKind.TupleType: case SyntaxKind.GenericName: + { + switch (node.Parent.Kind()) { - switch (node.Parent.Kind()) - { - case SyntaxKind.LocalFunctionStatement: - case SyntaxKind.DelegateDeclaration: - case SyntaxKind.FieldDeclaration: - case SyntaxKind.EventFieldDeclaration: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.OperatorDeclaration: - case SyntaxKind.ConversionOperatorDeclaration: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.EventDeclaration: - case SyntaxKind.IndexerDeclaration: - case SyntaxKind.Parameter: - return false; - } - - break; + case SyntaxKind.LocalFunctionStatement: + case SyntaxKind.DelegateDeclaration: + case SyntaxKind.FieldDeclaration: + case SyntaxKind.EventFieldDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.OperatorDeclaration: + case SyntaxKind.ConversionOperatorDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.EventDeclaration: + case SyntaxKind.IndexerDeclaration: + case SyntaxKind.Parameter: + return false; } + + break; + } } SyntaxNode parent = node.Parent; @@ -113,25 +113,25 @@ private static bool CanRefactor(SyntaxNode node) case SyntaxKind.EqualsValueClause: return false; case SyntaxKind.ConditionalAccessExpression: - { - var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; + { + var conditionalAccess = (ConditionalAccessExpressionSyntax)parent; - return node != conditionalAccess.WhenNotNull; - } + return node != conditionalAccess.WhenNotNull; + } case SyntaxKind.ForEachStatement: - { - var forEachStatement = (ForEachStatementSyntax)parent; + { + var forEachStatement = (ForEachStatementSyntax)parent; - return node != forEachStatement.Expression - && node != forEachStatement.Type; - } + return node != forEachStatement.Expression + && node != forEachStatement.Type; + } case SyntaxKind.ForEachVariableStatement: - { - var forEachStatement = (ForEachVariableStatementSyntax)parent; + { + var forEachStatement = (ForEachVariableStatementSyntax)parent; - return node != forEachStatement.Expression - && node != forEachStatement.Variable; - } + return node != forEachStatement.Expression + && node != forEachStatement.Variable; + } case SyntaxKind.WhileStatement: return node != ((WhileStatementSyntax)parent).Condition; case SyntaxKind.DoStatement: @@ -143,19 +143,19 @@ private static bool CanRefactor(SyntaxNode node) case SyntaxKind.SwitchStatement: return node != ((SwitchStatementSyntax)parent).Expression; case SyntaxKind.UsingStatement: - { - var usingStatement = (UsingStatementSyntax)parent; + { + var usingStatement = (UsingStatementSyntax)parent; - return node != usingStatement.Expression - && node != usingStatement.Declaration; - } + return node != usingStatement.Expression + && node != usingStatement.Declaration; + } case SyntaxKind.ConditionalExpression: - { - var conditionalExpression = (ConditionalExpressionSyntax)parent; + { + var conditionalExpression = (ConditionalExpressionSyntax)parent; - return node != conditionalExpression.WhenTrue - && node != conditionalExpression.WhenFalse; - } + return node != conditionalExpression.WhenTrue + && node != conditionalExpression.WhenFalse; + } } return parent is not AssignmentExpressionSyntax; diff --git a/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs index 14cf0b2b4d..cd633df29a 100644 --- a/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PostfixUnaryExpressionRefactoring.cs @@ -20,17 +20,17 @@ public static void ComputeRefactorings(RefactoringContext context, PostfixUnaryE switch (postfixUnaryExpression.Kind()) { case SyntaxKind.PostIncrementExpression: - { - InvertPostIncrement(context, postfixUnaryExpression); - ReplacePostIncrementWithPreIncrement(context, postfixUnaryExpression); - break; - } + { + InvertPostIncrement(context, postfixUnaryExpression); + ReplacePostIncrementWithPreIncrement(context, postfixUnaryExpression); + break; + } case SyntaxKind.PostDecrementExpression: - { - InvertPostDecrement(context, postfixUnaryExpression); - ReplacePostDecrementWithPreDecrement(context, postfixUnaryExpression); - break; - } + { + InvertPostDecrement(context, postfixUnaryExpression); + ReplacePostDecrementWithPreDecrement(context, postfixUnaryExpression); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs b/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs index 8424aa0a0d..9f0306730b 100644 --- a/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/PrefixUnaryExpressionRefactoring.cs @@ -20,17 +20,17 @@ public static void ComputeRefactorings(RefactoringContext context, PrefixUnaryEx switch (prefixUnaryExpression.Kind()) { case SyntaxKind.PreIncrementExpression: - { - InvertPreIncrement(context, prefixUnaryExpression); - ReplacePreIncrementWithPostIncrement(context, prefixUnaryExpression); - break; - } + { + InvertPreIncrement(context, prefixUnaryExpression); + ReplacePreIncrementWithPostIncrement(context, prefixUnaryExpression); + break; + } case SyntaxKind.PreDecrementExpression: - { - InvertPreDecrement(context, prefixUnaryExpression); - ReplacePreDecrementWithPostDecrement(context, prefixUnaryExpression); - break; - } + { + InvertPreDecrement(context, prefixUnaryExpression); + ReplacePreDecrementWithPostDecrement(context, prefixUnaryExpression); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs b/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs index adae427ddc..dddf8a6e18 100644 --- a/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs +++ b/src/Refactorings/CSharp/Refactorings/RefactoringContext.cs @@ -250,35 +250,35 @@ public void ComputeRefactoringsForTokenInsideTrivia() switch (token.Kind()) { case SyntaxKind.XmlTextLiteralToken: + { + if (IsRefactoringEnabled(RefactoringDescriptors.AddTagToDocumentationComment) + && !Span.IsEmpty) { - if (IsRefactoringEnabled(RefactoringDescriptors.AddTagToDocumentationComment) - && !Span.IsEmpty) + TextSpan span = token.Span; + + if (span.Contains(Span)) { - TextSpan span = token.Span; + string text = token.Text; - if (span.Contains(Span)) + if (span.Start == Span.Start + || (!char.IsLetterOrDigit(text[Span.Start - span.Start - 1]) + && char.IsLetterOrDigit(text[Span.Start - span.Start]))) { - string text = token.Text; - - if (span.Start == Span.Start - || (!char.IsLetterOrDigit(text[Span.Start - span.Start - 1]) - && char.IsLetterOrDigit(text[Span.Start - span.Start]))) + if (span.End == Span.End + || (char.IsLetterOrDigit(text[Span.End - span.Start - 1]) + && !char.IsLetterOrDigit(text[Span.End - span.Start]))) { - if (span.End == Span.End - || (char.IsLetterOrDigit(text[Span.End - span.Start - 1]) - && !char.IsLetterOrDigit(text[Span.End - span.Start]))) - { - RegisterRefactoring( - "Add tag 'c'", - ct => Document.WithTextChangeAsync(Span, $"{token.ToString(Span)}", ct), - RefactoringDescriptors.AddTagToDocumentationComment); - } + RegisterRefactoring( + "Add tag 'c'", + ct => Document.WithTextChangeAsync(Span, $"{token.ToString(Span)}", ct), + RefactoringDescriptors.AddTagToDocumentationComment); } } } - - break; } + + break; + } } } @@ -326,45 +326,45 @@ public async Task ComputeRefactoringsForTokenAsync() switch (token.Kind()) { case SyntaxKind.CloseParenToken: - { - await CloseParenTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); - break; - } + { + await CloseParenTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); + break; + } case SyntaxKind.CommaToken: - { - await CommaTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); - break; - } + { + await CommaTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); + break; + } case SyntaxKind.SemicolonToken: - { - SemicolonTokenRefactoring.ComputeRefactorings(this, token); - break; - } + { + SemicolonTokenRefactoring.ComputeRefactorings(this, token); + break; + } case SyntaxKind.PlusToken: - { - await PlusTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); - break; - } + { + await PlusTokenRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); + break; + } case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: - { - if (IsRefactoringEnabled(RefactoringDescriptors.ChangeAccessibility)) - await AccessModifierRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); + { + if (IsRefactoringEnabled(RefactoringDescriptors.ChangeAccessibility)) + await AccessModifierRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); - break; - } + break; + } case SyntaxKind.AsyncKeyword: + { + if (IsRefactoringEnabled(RefactoringDescriptors.RemoveAsyncAwait) + && Span.IsEmptyAndContainedInSpan(token)) { - if (IsRefactoringEnabled(RefactoringDescriptors.RemoveAsyncAwait) - && Span.IsEmptyAndContainedInSpan(token)) - { - await RemoveAsyncAwaitRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); - } - - break; + await RemoveAsyncAwaitRefactoring.ComputeRefactoringsAsync(this, token).ConfigureAwait(false); } + + break; + } } } @@ -447,166 +447,166 @@ public async Task ComputeRefactoringsForNodeAsync() case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: - { - if (flags.IsSet(Flag.Accessor)) - continue; - - AccessorDeclarationRefactoring.ComputeRefactorings(this, (AccessorDeclarationSyntax)node); - flags.Set(Flag.Accessor); + { + if (flags.IsSet(Flag.Accessor)) continue; - } - case SyntaxKind.Argument: - { - if (flags.IsSet(Flag.Argument)) - continue; - ArgumentRefactoring.ComputeRefactorings(this, (ArgumentSyntax)node); - flags.Set(Flag.Argument); + AccessorDeclarationRefactoring.ComputeRefactorings(this, (AccessorDeclarationSyntax)node); + flags.Set(Flag.Accessor); + continue; + } + case SyntaxKind.Argument: + { + if (flags.IsSet(Flag.Argument)) continue; - } - case SyntaxKind.ArgumentList: - { - if (flags.IsSet(Flag.ArgumentList)) - continue; - await ArgumentListRefactoring.ComputeRefactoringsAsync(this, (ArgumentListSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ArgumentList); + ArgumentRefactoring.ComputeRefactorings(this, (ArgumentSyntax)node); + flags.Set(Flag.Argument); + continue; + } + case SyntaxKind.ArgumentList: + { + if (flags.IsSet(Flag.ArgumentList)) continue; - } - case SyntaxKind.AttributeArgumentList: - { - if (flags.IsSet(Flag.AttributeArgumentList)) - continue; - await AttributeArgumentListRefactoring.ComputeRefactoringsAsync(this, (AttributeArgumentListSyntax)node).ConfigureAwait(false); - flags.Set(Flag.AttributeArgumentList); + await ArgumentListRefactoring.ComputeRefactoringsAsync(this, (ArgumentListSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ArgumentList); + continue; + } + case SyntaxKind.AttributeArgumentList: + { + if (flags.IsSet(Flag.AttributeArgumentList)) continue; - } - case SyntaxKind.ArrowExpressionClause: - { - if (flags.IsSet(Flag.ArrowExpressionClause)) - continue; - ArrowExpressionClauseRefactoring.ComputeRefactorings(this, (ArrowExpressionClauseSyntax)node); - flags.Set(Flag.ArrowExpressionClause); + await AttributeArgumentListRefactoring.ComputeRefactoringsAsync(this, (AttributeArgumentListSyntax)node).ConfigureAwait(false); + flags.Set(Flag.AttributeArgumentList); + continue; + } + case SyntaxKind.ArrowExpressionClause: + { + if (flags.IsSet(Flag.ArrowExpressionClause)) continue; - } - case SyntaxKind.Parameter: - { - if (flags.IsSet(Flag.Parameter)) - continue; - await ParameterRefactoring.ComputeRefactoringsAsync(this, (ParameterSyntax)node).ConfigureAwait(false); - flags.Set(Flag.Parameter); + ArrowExpressionClauseRefactoring.ComputeRefactorings(this, (ArrowExpressionClauseSyntax)node); + flags.Set(Flag.ArrowExpressionClause); + continue; + } + case SyntaxKind.Parameter: + { + if (flags.IsSet(Flag.Parameter)) continue; - } - case SyntaxKind.ParameterList: - { - if (flags.IsSet(Flag.ParameterList)) - continue; - await ParameterListRefactoring.ComputeRefactoringsAsync(this, (ParameterListSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ParameterList); + await ParameterRefactoring.ComputeRefactoringsAsync(this, (ParameterSyntax)node).ConfigureAwait(false); + flags.Set(Flag.Parameter); + continue; + } + case SyntaxKind.ParameterList: + { + if (flags.IsSet(Flag.ParameterList)) continue; - } - case SyntaxKind.SwitchSection: - { - if (flags.IsSet(Flag.SwitchSection)) - continue; - await SwitchSectionRefactoring.ComputeRefactoringsAsync(this, (SwitchSectionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.SwitchSection); + await ParameterListRefactoring.ComputeRefactoringsAsync(this, (ParameterListSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ParameterList); + continue; + } + case SyntaxKind.SwitchSection: + { + if (flags.IsSet(Flag.SwitchSection)) continue; - } - case SyntaxKind.VariableDeclaration: - { - if (flags.IsSet(Flag.VariableDeclaration)) - continue; - await VariableDeclarationRefactoring.ComputeRefactoringsAsync(this, (VariableDeclarationSyntax)node).ConfigureAwait(false); - flags.Set(Flag.VariableDeclaration); + await SwitchSectionRefactoring.ComputeRefactoringsAsync(this, (SwitchSectionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.SwitchSection); + continue; + } + case SyntaxKind.VariableDeclaration: + { + if (flags.IsSet(Flag.VariableDeclaration)) continue; - } - case SyntaxKind.VariableDeclarator: - { - if (flags.IsSet(Flag.VariableDeclarator)) - continue; - VariableDeclaratorRefactoring.ComputeRefactorings(this, (VariableDeclaratorSyntax)node); - flags.Set(Flag.VariableDeclarator); + await VariableDeclarationRefactoring.ComputeRefactoringsAsync(this, (VariableDeclarationSyntax)node).ConfigureAwait(false); + flags.Set(Flag.VariableDeclaration); + continue; + } + case SyntaxKind.VariableDeclarator: + { + if (flags.IsSet(Flag.VariableDeclarator)) continue; - } - case SyntaxKind.InterpolatedStringText: - { - if (flags.IsSet(Flag.InterpolatedStringText)) - continue; - await InterpolatedStringTextRefactoring.ComputeRefactoringsAsync(this, (InterpolatedStringTextSyntax)node).ConfigureAwait(false); - flags.Set(Flag.InterpolatedStringText); + VariableDeclaratorRefactoring.ComputeRefactorings(this, (VariableDeclaratorSyntax)node); + flags.Set(Flag.VariableDeclarator); + continue; + } + case SyntaxKind.InterpolatedStringText: + { + if (flags.IsSet(Flag.InterpolatedStringText)) continue; - } - case SyntaxKind.Interpolation: - { - if (flags.IsSet(Flag.Interpolation)) - continue; - InterpolationRefactoring.ComputeRefactorings(this, (InterpolationSyntax)node); - flags.Set(Flag.Interpolation); + await InterpolatedStringTextRefactoring.ComputeRefactoringsAsync(this, (InterpolatedStringTextSyntax)node).ConfigureAwait(false); + flags.Set(Flag.InterpolatedStringText); + continue; + } + case SyntaxKind.Interpolation: + { + if (flags.IsSet(Flag.Interpolation)) continue; - } - case SyntaxKind.ElseClause: - { - if (flags.IsSet(Flag.ElseClause)) - continue; - ElseClauseRefactoring.ComputeRefactorings(this, (ElseClauseSyntax)node); - flags.Set(Flag.ElseClause); + InterpolationRefactoring.ComputeRefactorings(this, (InterpolationSyntax)node); + flags.Set(Flag.Interpolation); + continue; + } + case SyntaxKind.ElseClause: + { + if (flags.IsSet(Flag.ElseClause)) continue; - } - case SyntaxKind.CaseSwitchLabel: - { - if (flags.IsSet(Flag.CaseSwitchLabel)) - continue; - flags.Set(Flag.CaseSwitchLabel); + ElseClauseRefactoring.ComputeRefactorings(this, (ElseClauseSyntax)node); + flags.Set(Flag.ElseClause); + continue; + } + case SyntaxKind.CaseSwitchLabel: + { + if (flags.IsSet(Flag.CaseSwitchLabel)) continue; - } - case SyntaxKind.UsingDirective: - { - if (flags.IsSet(Flag.UsingDirective)) - continue; - UsingDirectiveRefactoring.ComputeRefactoring(this, (UsingDirectiveSyntax)node); - flags.Set(Flag.UsingDirective); + flags.Set(Flag.CaseSwitchLabel); + continue; + } + case SyntaxKind.UsingDirective: + { + if (flags.IsSet(Flag.UsingDirective)) continue; - } - case SyntaxKind.DeclarationPattern: - { - if (flags.IsSet(Flag.DeclarationPattern)) - continue; - await DeclarationPatternRefactoring.ComputeRefactoringAsync(this, (DeclarationPatternSyntax)node).ConfigureAwait(false); - flags.Set(Flag.DeclarationPattern); + UsingDirectiveRefactoring.ComputeRefactoring(this, (UsingDirectiveSyntax)node); + flags.Set(Flag.UsingDirective); + continue; + } + case SyntaxKind.DeclarationPattern: + { + if (flags.IsSet(Flag.DeclarationPattern)) continue; - } - case SyntaxKind.TypeParameterConstraintClause: - { - if (flags.IsSet(Flag.TypeParameterConstraintClause)) - continue; - TypeParameterConstraintClauseRefactoring.ComputeRefactoring(this, (TypeParameterConstraintClauseSyntax)node); - flags.Set(Flag.TypeParameterConstraintClause); + await DeclarationPatternRefactoring.ComputeRefactoringAsync(this, (DeclarationPatternSyntax)node).ConfigureAwait(false); + flags.Set(Flag.DeclarationPattern); + continue; + } + case SyntaxKind.TypeParameterConstraintClause: + { + if (flags.IsSet(Flag.TypeParameterConstraintClause)) continue; - } - case SyntaxKind.Attribute: - { - if (flags.IsSet(Flag.Attribute)) - continue; - await AttributeRefactoring.ComputeRefactoringAsync(this, (AttributeSyntax)node).ConfigureAwait(false); - flags.Set(Flag.Attribute); + TypeParameterConstraintClauseRefactoring.ComputeRefactoring(this, (TypeParameterConstraintClauseSyntax)node); + flags.Set(Flag.TypeParameterConstraintClause); + continue; + } + case SyntaxKind.Attribute: + { + if (flags.IsSet(Flag.Attribute)) continue; - } + + await AttributeRefactoring.ComputeRefactoringAsync(this, (AttributeSyntax)node).ConfigureAwait(false); + flags.Set(Flag.Attribute); + continue; + } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: @@ -618,23 +618,23 @@ public async Task ComputeRefactoringsForNodeAsync() case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: - { - if (flags.IsSet(Flag.AssignmentExpression)) - continue; - - AssignmentExpressionRefactoring.ComputeRefactorings(this, (AssignmentExpressionSyntax)node); - flags.Set(Flag.AssignmentExpression); + { + if (flags.IsSet(Flag.AssignmentExpression)) continue; - } - case SyntaxKind.AnonymousMethodExpression: - { - if (flags.IsSet(Flag.AnonymousMethod)) - continue; - AnonymousMethodExpressionRefactoring.ComputeRefactorings(this, (AnonymousMethodExpressionSyntax)node); - flags.Set(Flag.AnonymousMethod); + AssignmentExpressionRefactoring.ComputeRefactorings(this, (AssignmentExpressionSyntax)node); + flags.Set(Flag.AssignmentExpression); + continue; + } + case SyntaxKind.AnonymousMethodExpression: + { + if (flags.IsSet(Flag.AnonymousMethod)) continue; - } + + AnonymousMethodExpressionRefactoring.ComputeRefactorings(this, (AnonymousMethodExpressionSyntax)node); + flags.Set(Flag.AnonymousMethod); + continue; + } case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: @@ -656,90 +656,90 @@ public async Task ComputeRefactoringsForNodeAsync() case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.CoalesceExpression: - { - if (flags.IsSet(Flag.BinaryExpression)) - continue; - - await BinaryExpressionRefactoring.ComputeRefactoringsAsync(this, (BinaryExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.BinaryExpression); + { + if (flags.IsSet(Flag.BinaryExpression)) continue; - } - case SyntaxKind.ConditionalExpression: - { - if (flags.IsSet(Flag.ConditionalExpression)) - continue; - await ConditionalExpressionRefactoring.ComputeRefactoringsAsync(this, (ConditionalExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ConditionalExpression); + await BinaryExpressionRefactoring.ComputeRefactoringsAsync(this, (BinaryExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.BinaryExpression); + continue; + } + case SyntaxKind.ConditionalExpression: + { + if (flags.IsSet(Flag.ConditionalExpression)) continue; - } - case SyntaxKind.QualifiedName: - { - if (flags.IsSet(Flag.QualifiedName)) - continue; - await QualifiedNameRefactoring.ComputeRefactoringsAsync(this, (QualifiedNameSyntax)node).ConfigureAwait(false); - flags.Set(Flag.QualifiedName); + await ConditionalExpressionRefactoring.ComputeRefactoringsAsync(this, (ConditionalExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ConditionalExpression); + continue; + } + case SyntaxKind.QualifiedName: + { + if (flags.IsSet(Flag.QualifiedName)) continue; - } - case SyntaxKind.GenericName: - { - if (flags.IsSet(Flag.GenericName)) - continue; - flags.Set(Flag.GenericName); + await QualifiedNameRefactoring.ComputeRefactoringsAsync(this, (QualifiedNameSyntax)node).ConfigureAwait(false); + flags.Set(Flag.QualifiedName); + continue; + } + case SyntaxKind.GenericName: + { + if (flags.IsSet(Flag.GenericName)) continue; - } - case SyntaxKind.IdentifierName: - { - if (flags.IsSet(Flag.IdentifierName)) - continue; - await IdentifierNameRefactoring.ComputeRefactoringsAsync(this, (IdentifierNameSyntax)node).ConfigureAwait(false); - flags.Set(Flag.IdentifierName); + flags.Set(Flag.GenericName); + continue; + } + case SyntaxKind.IdentifierName: + { + if (flags.IsSet(Flag.IdentifierName)) continue; - } + + await IdentifierNameRefactoring.ComputeRefactoringsAsync(this, (IdentifierNameSyntax)node).ConfigureAwait(false); + flags.Set(Flag.IdentifierName); + continue; + } case SyntaxKind.ArrayInitializerExpression: case SyntaxKind.CollectionInitializerExpression: case SyntaxKind.ComplexElementInitializerExpression: case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.WithInitializerExpression: - { - if (flags.IsSet(Flag.InitializerExpression)) - continue; - - await InitializerExpressionRefactoring.ComputeRefactoringsAsync(this, (InitializerExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.InitializerExpression); + { + if (flags.IsSet(Flag.InitializerExpression)) continue; - } - case SyntaxKind.InterpolatedStringExpression: - { - if (flags.IsSet(Flag.InterpolatedStringExpression)) - continue; - InterpolatedStringRefactoring.ComputeRefactorings(this, (InterpolatedStringExpressionSyntax)node); - flags.Set(Flag.InterpolatedStringExpression); + await InitializerExpressionRefactoring.ComputeRefactoringsAsync(this, (InitializerExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.InitializerExpression); + continue; + } + case SyntaxKind.InterpolatedStringExpression: + { + if (flags.IsSet(Flag.InterpolatedStringExpression)) continue; - } - case SyntaxKind.InvocationExpression: - { - if (flags.IsSet(Flag.InvocationExpression)) - continue; - await InvocationExpressionRefactoring.ComputeRefactoringsAsync(this, (InvocationExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.InvocationExpression); + InterpolatedStringRefactoring.ComputeRefactorings(this, (InterpolatedStringExpressionSyntax)node); + flags.Set(Flag.InterpolatedStringExpression); + continue; + } + case SyntaxKind.InvocationExpression: + { + if (flags.IsSet(Flag.InvocationExpression)) continue; - } + + await InvocationExpressionRefactoring.ComputeRefactoringsAsync(this, (InvocationExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.InvocationExpression); + continue; + } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: - { - if (flags.IsSet(Flag.LambdaExpression)) - continue; - - await LambdaExpressionRefactoring.ComputeRefactoringsAsync(this, (LambdaExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LambdaExpression); + { + if (flags.IsSet(Flag.LambdaExpression)) continue; - } + + await LambdaExpressionRefactoring.ComputeRefactoringsAsync(this, (LambdaExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LambdaExpression); + continue; + } case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.DefaultLiteralExpression: case SyntaxKind.FalseLiteralExpression: @@ -747,51 +747,51 @@ public async Task ComputeRefactoringsForNodeAsync() case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: - { - if (flags.IsSet(Flag.LiteralExpression)) - continue; - - await LiteralExpressionRefactoring.ComputeRefactoringsAsync(this, (LiteralExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LiteralExpression); + { + if (flags.IsSet(Flag.LiteralExpression)) continue; - } - case SyntaxKind.SimpleMemberAccessExpression: - { - if (flags.IsSet(Flag.SimpleMemberAccessExpression)) - continue; - await SimpleMemberAccessExpressionRefactoring.ComputeRefactoringAsync(this, (MemberAccessExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.SimpleMemberAccessExpression); + await LiteralExpressionRefactoring.ComputeRefactoringsAsync(this, (LiteralExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LiteralExpression); + continue; + } + case SyntaxKind.SimpleMemberAccessExpression: + { + if (flags.IsSet(Flag.SimpleMemberAccessExpression)) continue; - } - case SyntaxKind.ConditionalAccessExpression: - { - if (flags.IsSet(Flag.ConditionalAccessExpression)) - continue; - await ConditionalAccessExpressionRefactoring.ComputeRefactoringAsync(this, (ConditionalAccessExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ConditionalAccessExpression); + await SimpleMemberAccessExpressionRefactoring.ComputeRefactoringAsync(this, (MemberAccessExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.SimpleMemberAccessExpression); + continue; + } + case SyntaxKind.ConditionalAccessExpression: + { + if (flags.IsSet(Flag.ConditionalAccessExpression)) continue; - } - case SyntaxKind.ParenthesizedExpression: - { - if (flags.IsSet(Flag.ParenthesizedExpression)) - continue; - ParenthesizedExpressionRefactoring.ComputeRefactorings(this, (ParenthesizedExpressionSyntax)node); - flags.Set(Flag.ParenthesizedExpression); + await ConditionalAccessExpressionRefactoring.ComputeRefactoringAsync(this, (ConditionalAccessExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ConditionalAccessExpression); + continue; + } + case SyntaxKind.ParenthesizedExpression: + { + if (flags.IsSet(Flag.ParenthesizedExpression)) continue; - } + + ParenthesizedExpressionRefactoring.ComputeRefactorings(this, (ParenthesizedExpressionSyntax)node); + flags.Set(Flag.ParenthesizedExpression); + continue; + } case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: - { - if (flags.IsSet(Flag.PostfixUnaryExpression)) - continue; - - PostfixUnaryExpressionRefactoring.ComputeRefactorings(this, (PostfixUnaryExpressionSyntax)node); - flags.Set(Flag.PostfixUnaryExpression); + { + if (flags.IsSet(Flag.PostfixUnaryExpression)) continue; - } + + PostfixUnaryExpressionRefactoring.ComputeRefactorings(this, (PostfixUnaryExpressionSyntax)node); + flags.Set(Flag.PostfixUnaryExpression); + continue; + } case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.BitwiseNotExpression: @@ -800,212 +800,212 @@ public async Task ComputeRefactoringsForNodeAsync() case SyntaxKind.PreDecrementExpression: case SyntaxKind.AddressOfExpression: case SyntaxKind.PointerIndirectionExpression: - { - if (flags.IsSet(Flag.PrefixUnaryExpression)) - continue; - - PrefixUnaryExpressionRefactoring.ComputeRefactorings(this, (PrefixUnaryExpressionSyntax)node); - flags.Set(Flag.PrefixUnaryExpression); + { + if (flags.IsSet(Flag.PrefixUnaryExpression)) continue; - } - case SyntaxKind.AwaitExpression: - { - if (flags.IsSet(Flag.AwaitExpression)) - continue; - flags.Set(Flag.AwaitExpression); + PrefixUnaryExpressionRefactoring.ComputeRefactorings(this, (PrefixUnaryExpressionSyntax)node); + flags.Set(Flag.PrefixUnaryExpression); + continue; + } + case SyntaxKind.AwaitExpression: + { + if (flags.IsSet(Flag.AwaitExpression)) continue; - } - case SyntaxKind.CastExpression: - { - if (flags.IsSet(Flag.CastExpression)) - continue; - await CastExpressionRefactoring.ComputeRefactoringsAsync(this, (CastExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.CastExpression); + flags.Set(Flag.AwaitExpression); + continue; + } + case SyntaxKind.CastExpression: + { + if (flags.IsSet(Flag.CastExpression)) continue; - } - case SyntaxKind.ThrowExpression: - { - if (flags.IsSet(Flag.ThrowExpression)) - continue; - await ThrowExpressionRefactoring.ComputeRefactoringsAsync(this, (ThrowExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ThrowExpression); + await CastExpressionRefactoring.ComputeRefactoringsAsync(this, (CastExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.CastExpression); + continue; + } + case SyntaxKind.ThrowExpression: + { + if (flags.IsSet(Flag.ThrowExpression)) continue; - } - case SyntaxKind.DeclarationExpression: - { - if (flags.IsSet(Flag.DeclarationExpression)) - continue; - await DeclarationExpressionRefactoring.ComputeRefactoringsAsync(this, (DeclarationExpressionSyntax)node).ConfigureAwait(false); - flags.Set(Flag.DeclarationExpression); + await ThrowExpressionRefactoring.ComputeRefactoringsAsync(this, (ThrowExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ThrowExpression); + continue; + } + case SyntaxKind.DeclarationExpression: + { + if (flags.IsSet(Flag.DeclarationExpression)) continue; - } - case SyntaxKind.IsPatternExpression: - { - if (flags.IsSet(Flag.IsPatternExpression)) - continue; - InvertIsExpressionRefactoring.ComputeRefactoring(this, (IsPatternExpressionSyntax)node); - flags.Set(Flag.IsPatternExpression); + await DeclarationExpressionRefactoring.ComputeRefactoringsAsync(this, (DeclarationExpressionSyntax)node).ConfigureAwait(false); + flags.Set(Flag.DeclarationExpression); + continue; + } + case SyntaxKind.IsPatternExpression: + { + if (flags.IsSet(Flag.IsPatternExpression)) continue; - } - case SyntaxKind.SwitchExpression: - { - if (flags.IsSet(Flag.SwitchExpression)) - continue; - SwitchExpressionRefactoring.ComputeRefactorings(this, (SwitchExpressionSyntax)node); - flags.Set(Flag.SwitchExpression); + InvertIsExpressionRefactoring.ComputeRefactoring(this, (IsPatternExpressionSyntax)node); + flags.Set(Flag.IsPatternExpression); + continue; + } + case SyntaxKind.SwitchExpression: + { + if (flags.IsSet(Flag.SwitchExpression)) continue; - } - case SyntaxKind.DoStatement: - { - if (flags.IsSet(Flag.LoopStatement)) - break; - DoStatementRefactoring.ComputeRefactorings(this, (DoStatementSyntax)node); - flags.Set(Flag.LoopStatement); + SwitchExpressionRefactoring.ComputeRefactorings(this, (SwitchExpressionSyntax)node); + flags.Set(Flag.SwitchExpression); + continue; + } + case SyntaxKind.DoStatement: + { + if (flags.IsSet(Flag.LoopStatement)) break; - } - case SyntaxKind.ExpressionStatement: - { - if (flags.IsSet(Flag.ExpressionStatement)) - break; - await ExpressionStatementRefactoring.ComputeRefactoringsAsync(this, (ExpressionStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ExpressionStatement); + DoStatementRefactoring.ComputeRefactorings(this, (DoStatementSyntax)node); + flags.Set(Flag.LoopStatement); + break; + } + case SyntaxKind.ExpressionStatement: + { + if (flags.IsSet(Flag.ExpressionStatement)) break; - } - case SyntaxKind.ForEachStatement: - { - if (flags.IsSet(Flag.LoopStatement)) - break; - await ForEachStatementRefactoring.ComputeRefactoringsAsync(this, (ForEachStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LoopStatement); + await ExpressionStatementRefactoring.ComputeRefactoringsAsync(this, (ExpressionStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ExpressionStatement); + break; + } + case SyntaxKind.ForEachStatement: + { + if (flags.IsSet(Flag.LoopStatement)) break; - } - case SyntaxKind.ForStatement: - { - if (flags.IsSet(Flag.LoopStatement)) - break; - await ForStatementRefactoring.ComputeRefactoringsAsync(this, (ForStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LoopStatement); + await ForEachStatementRefactoring.ComputeRefactoringsAsync(this, (ForEachStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LoopStatement); + break; + } + case SyntaxKind.ForStatement: + { + if (flags.IsSet(Flag.LoopStatement)) break; - } - case SyntaxKind.IfStatement: - { - if (flags.IsSet(Flag.IfStatement)) - break; - await IfStatementRefactoring.ComputeRefactoringsAsync(this, (IfStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.IfStatement); + await ForStatementRefactoring.ComputeRefactoringsAsync(this, (ForStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LoopStatement); + break; + } + case SyntaxKind.IfStatement: + { + if (flags.IsSet(Flag.IfStatement)) break; - } - case SyntaxKind.LocalDeclarationStatement: - { - if (flags.IsSet(Flag.LocalDeclarationStatement)) - break; - await LocalDeclarationStatementRefactoring.ComputeRefactoringsAsync(this, (LocalDeclarationStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LocalDeclarationStatement); + await IfStatementRefactoring.ComputeRefactoringsAsync(this, (IfStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.IfStatement); + break; + } + case SyntaxKind.LocalDeclarationStatement: + { + if (flags.IsSet(Flag.LocalDeclarationStatement)) break; - } - case SyntaxKind.ReturnStatement: - { - if (flags.IsSet(Flag.ReturnStatement)) - break; - await ReturnStatementRefactoring.ComputeRefactoringsAsync(this, (ReturnStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ReturnStatement); + await LocalDeclarationStatementRefactoring.ComputeRefactoringsAsync(this, (LocalDeclarationStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LocalDeclarationStatement); + break; + } + case SyntaxKind.ReturnStatement: + { + if (flags.IsSet(Flag.ReturnStatement)) break; - } - case SyntaxKind.SwitchStatement: - { - if (flags.IsSet(Flag.SwitchStatement)) - break; - await SwitchStatementRefactoring.ComputeRefactoringsAsync(this, (SwitchStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.SwitchStatement); + await ReturnStatementRefactoring.ComputeRefactoringsAsync(this, (ReturnStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ReturnStatement); + break; + } + case SyntaxKind.SwitchStatement: + { + if (flags.IsSet(Flag.SwitchStatement)) break; - } - case SyntaxKind.UsingStatement: - { - if (flags.IsSet(Flag.UsingStatement)) - break; - UsingStatementRefactoring.ComputeRefactorings(this, (UsingStatementSyntax)node); - flags.Set(Flag.UsingStatement); + await SwitchStatementRefactoring.ComputeRefactoringsAsync(this, (SwitchStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.SwitchStatement); + break; + } + case SyntaxKind.UsingStatement: + { + if (flags.IsSet(Flag.UsingStatement)) break; - } - case SyntaxKind.WhileStatement: - { - if (flags.IsSet(Flag.LoopStatement)) - break; - WhileStatementRefactoring.ComputeRefactorings(this, (WhileStatementSyntax)node); - flags.Set(Flag.LoopStatement); + UsingStatementRefactoring.ComputeRefactorings(this, (UsingStatementSyntax)node); + flags.Set(Flag.UsingStatement); + break; + } + case SyntaxKind.WhileStatement: + { + if (flags.IsSet(Flag.LoopStatement)) break; - } + + WhileStatementRefactoring.ComputeRefactorings(this, (WhileStatementSyntax)node); + flags.Set(Flag.LoopStatement); + break; + } case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: - { - if (flags.IsSet(Flag.YieldStatement)) - break; - - await YieldStatementRefactoring.ComputeRefactoringsAsync(this, (YieldStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.YieldStatement); + { + if (flags.IsSet(Flag.YieldStatement)) break; - } - case SyntaxKind.LockStatement: - { - if (flags.IsSet(Flag.LockStatement)) - break; - LockStatementRefactoring.ComputeRefactorings(this, (LockStatementSyntax)node); - flags.Set(Flag.LockStatement); + await YieldStatementRefactoring.ComputeRefactoringsAsync(this, (YieldStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.YieldStatement); + break; + } + case SyntaxKind.LockStatement: + { + if (flags.IsSet(Flag.LockStatement)) break; - } - case SyntaxKind.Block: - { - if (flags.IsSet(Flag.Block)) - break; - await BlockRefactoring.ComputeRefactoringAsync(this, (BlockSyntax)node).ConfigureAwait(false); - flags.Set(Flag.Block); + LockStatementRefactoring.ComputeRefactorings(this, (LockStatementSyntax)node); + flags.Set(Flag.LockStatement); + break; + } + case SyntaxKind.Block: + { + if (flags.IsSet(Flag.Block)) break; - } - case SyntaxKind.ThrowStatement: - { - if (flags.IsSet(Flag.ThrowStatement)) - break; - await ThrowStatementRefactoring.ComputeRefactoringAsync(this, (ThrowStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.ThrowStatement); + await BlockRefactoring.ComputeRefactoringAsync(this, (BlockSyntax)node).ConfigureAwait(false); + flags.Set(Flag.Block); + break; + } + case SyntaxKind.ThrowStatement: + { + if (flags.IsSet(Flag.ThrowStatement)) break; - } - case SyntaxKind.LocalFunctionStatement: - { - if (flags.IsSet(Flag.LocalFunctionStatement)) - break; - await LocalFunctionStatementRefactoring.ComputeRefactoringsAsync(this, (LocalFunctionStatementSyntax)node).ConfigureAwait(false); - flags.Set(Flag.LocalFunctionStatement); + await ThrowStatementRefactoring.ComputeRefactoringAsync(this, (ThrowStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.ThrowStatement); + break; + } + case SyntaxKind.LocalFunctionStatement: + { + if (flags.IsSet(Flag.LocalFunctionStatement)) break; - } - case SyntaxKind.UnsafeStatement: - { - if (flags.IsSet(Flag.UnsafeStatement)) - break; - UnsafeStatementRefactoring.ComputeRefactorings(this, (UnsafeStatementSyntax)node); - flags.Set(Flag.UnsafeStatement); + await LocalFunctionStatementRefactoring.ComputeRefactoringsAsync(this, (LocalFunctionStatementSyntax)node).ConfigureAwait(false); + flags.Set(Flag.LocalFunctionStatement); + break; + } + case SyntaxKind.UnsafeStatement: + { + if (flags.IsSet(Flag.UnsafeStatement)) break; - } + + UnsafeStatementRefactoring.ComputeRefactorings(this, (UnsafeStatementSyntax)node); + flags.Set(Flag.UnsafeStatement); + break; + } } if (!flags.IsSet(Flag.Statement) diff --git a/src/Refactorings/CSharp/Refactorings/RemoveAllMemberDeclarationsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveAllMemberDeclarationsRefactoring.cs index 83b54ccdcf..49ff5f07db 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveAllMemberDeclarationsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveAllMemberDeclarationsRefactoring.cs @@ -27,29 +27,29 @@ public static bool CanRefactor(MemberDeclarationSyntax member, TextSpan span) switch (member) { case NamespaceDeclarationSyntax declaration: - { - return declaration.Members.Any() - && (declaration.OpenBraceToken.Span.Contains(span) - || declaration.CloseBraceToken.Span.Contains(span)); - } + { + return declaration.Members.Any() + && (declaration.OpenBraceToken.Span.Contains(span) + || declaration.CloseBraceToken.Span.Contains(span)); + } case ClassDeclarationSyntax declaration: - { - return declaration.Members.Any() - && (declaration.OpenBraceToken.Span.Contains(span) - || declaration.CloseBraceToken.Span.Contains(span)); - } + { + return declaration.Members.Any() + && (declaration.OpenBraceToken.Span.Contains(span) + || declaration.CloseBraceToken.Span.Contains(span)); + } case StructDeclarationSyntax declaration: - { - return declaration.Members.Any() - && (declaration.OpenBraceToken.Span.Contains(span) - || declaration.CloseBraceToken.Span.Contains(span)); - } + { + return declaration.Members.Any() + && (declaration.OpenBraceToken.Span.Contains(span) + || declaration.CloseBraceToken.Span.Contains(span)); + } case InterfaceDeclarationSyntax declaration: - { - return declaration.Members.Any() - && (declaration.OpenBraceToken.Span.Contains(span) - || declaration.CloseBraceToken.Span.Contains(span)); - } + { + return declaration.Members.Any() + && (declaration.OpenBraceToken.Span.Contains(span) + || declaration.CloseBraceToken.Span.Contains(span)); + } } return false; diff --git a/src/Refactorings/CSharp/Refactorings/RemoveAllStatementsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveAllStatementsRefactoring.cs index 8d2ebb4504..4d453f15a0 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveAllStatementsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveAllStatementsRefactoring.cs @@ -27,33 +27,33 @@ public static bool CanRefactor(MemberDeclarationSyntax member, TextSpan span) switch (member) { case MethodDeclarationSyntax methodDeclaration: - { - BlockSyntax body = methodDeclaration.Body; + { + BlockSyntax body = methodDeclaration.Body; - return body?.Statements.Any() == true - && BraceContainsSpan(body, span); - } + return body?.Statements.Any() == true + && BraceContainsSpan(body, span); + } case OperatorDeclarationSyntax operatorDeclaration: - { - BlockSyntax body = operatorDeclaration.Body; + { + BlockSyntax body = operatorDeclaration.Body; - return body?.Statements.Any() == true - && BraceContainsSpan(body, span); - } + return body?.Statements.Any() == true + && BraceContainsSpan(body, span); + } case ConversionOperatorDeclarationSyntax conversionOperatorDeclaration: - { - BlockSyntax body = conversionOperatorDeclaration.Body; + { + BlockSyntax body = conversionOperatorDeclaration.Body; - return body?.Statements.Any() == true - && BraceContainsSpan(body, span); - } + return body?.Statements.Any() == true + && BraceContainsSpan(body, span); + } case ConstructorDeclarationSyntax constructorDeclaration: - { - BlockSyntax body = constructorDeclaration.Body; + { + BlockSyntax body = constructorDeclaration.Body; - return body?.Statements.Any() == true - && BraceContainsSpan(body, span); - } + return body?.Statements.Any() == true + && BraceContainsSpan(body, span); + } } return false; diff --git a/src/Refactorings/CSharp/Refactorings/RemoveAsyncAwaitRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveAsyncAwaitRefactoring.cs index 881fd19f3a..03e2ef6cb8 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveAsyncAwaitRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveAsyncAwaitRefactoring.cs @@ -15,65 +15,65 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, Sy switch (token.Parent) { case MethodDeclarationSyntax methodDeclaration: - { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - - using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(methodDeclaration, semanticModel, context.CancellationToken)) - { - if (analysis.Success) - RegisterRefactoring(); - } + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return; - } - case LocalFunctionStatementSyntax localFunction: + using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(methodDeclaration, semanticModel, context.CancellationToken)) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (analysis.Success) + RegisterRefactoring(); + } - using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(localFunction, semanticModel, context.CancellationToken)) - { - if (analysis.Success) - RegisterRefactoring(); - } + return; + } + case LocalFunctionStatementSyntax localFunction: + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return; - } - case ParenthesizedLambdaExpressionSyntax parenthesizedLambda: + using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(localFunction, semanticModel, context.CancellationToken)) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (analysis.Success) + RegisterRefactoring(); + } - using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(parenthesizedLambda, semanticModel, context.CancellationToken)) - { - if (analysis.Success) - RegisterRefactoring(); - } + return; + } + case ParenthesizedLambdaExpressionSyntax parenthesizedLambda: + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return; - } - case SimpleLambdaExpressionSyntax simpleLambda: + using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(parenthesizedLambda, semanticModel, context.CancellationToken)) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (analysis.Success) + RegisterRefactoring(); + } - using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(simpleLambda, semanticModel, context.CancellationToken)) - { - if (analysis.Success) - RegisterRefactoring(); - } + return; + } + case SimpleLambdaExpressionSyntax simpleLambda: + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return; - } - case AnonymousMethodExpressionSyntax anonymousMethod: + using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(simpleLambda, semanticModel, context.CancellationToken)) { - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + if (analysis.Success) + RegisterRefactoring(); + } - using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(anonymousMethod, semanticModel, context.CancellationToken)) - { - if (analysis.Success) - RegisterRefactoring(); - } + return; + } + case AnonymousMethodExpressionSyntax anonymousMethod: + { + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - return; + using (RemoveAsyncAwaitAnalysis analysis = RemoveAsyncAwaitAnalysis.Create(anonymousMethod, semanticModel, context.CancellationToken)) + { + if (analysis.Success) + RegisterRefactoring(); } + + return; + } } void RegisterRefactoring() diff --git a/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs index ee554f9b78..6ed5eda247 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveBracesRefactoring.cs @@ -174,19 +174,19 @@ private static bool IsEmbeddableBlock(BlockSyntax block) { case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.LabeledStatement: - { - return false; - } + { + return false; + } case SyntaxKind.IfStatement: - { - return kind != SyntaxKind.IfStatement - || ((IfStatementSyntax)parent).Else is null - || !((IfStatementSyntax)statement).GetCascadeInfo().EndsWithIf; - } + { + return kind != SyntaxKind.IfStatement + || ((IfStatementSyntax)parent).Else is null + || !((IfStatementSyntax)statement).GetCascadeInfo().EndsWithIf; + } default: - { - return true; - } + { + return true; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs b/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs index af33ac9c7e..0b5dc65c00 100644 --- a/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/RemoveInstantiationOfLocalVariableRefactoring.cs @@ -34,47 +34,47 @@ internal static async Task ComputeRefactoringAsync(RefactoringContext context, L switch (value) { case ObjectCreationExpressionSyntax objectCreation: - { - InitializerExpressionSyntax initializer = objectCreation.Initializer; + { + InitializerExpressionSyntax initializer = objectCreation.Initializer; - if (initializer?.Span.Contains(context.Span) == true) - return; + if (initializer?.Span.Contains(context.Span) == true) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(objectCreation, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(objectCreation, context.CancellationToken); - ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); - break; - } + ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); + break; + } case ArrayCreationExpressionSyntax arrayCreation: - { - InitializerExpressionSyntax initializer = arrayCreation.Initializer; + { + InitializerExpressionSyntax initializer = arrayCreation.Initializer; - if (initializer?.Span.Contains(context.Span) == true) - return; + if (initializer?.Span.Contains(context.Span) == true) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(arrayCreation, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(arrayCreation, context.CancellationToken); - ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); - break; - } + ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); + break; + } case ImplicitArrayCreationExpressionSyntax implicitArrayCreation: - { - InitializerExpressionSyntax initializer = implicitArrayCreation.Initializer; + { + InitializerExpressionSyntax initializer = implicitArrayCreation.Initializer; - if (initializer?.Span.Contains(context.Span) == true) - return; + if (initializer?.Span.Contains(context.Span) == true) + return; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(implicitArrayCreation, context.CancellationToken); + ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(implicitArrayCreation, context.CancellationToken); - ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); - break; - } + ComputeRefactoring(context, title, typeSymbol, localDeclarationStatement, value); + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/SelectedMemberDeclarationsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SelectedMemberDeclarationsRefactoring.cs index 3dfb241dab..82641eacf3 100644 --- a/src/Refactorings/CSharp/Refactorings/SelectedMemberDeclarationsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SelectedMemberDeclarationsRefactoring.cs @@ -100,71 +100,71 @@ bool CanHaveMultipleDeclarations() switch (member.Kind()) { case SyntaxKind.ClassDeclaration: - { - if (((ClassDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) - return true; + { + if (((ClassDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) + return true; - break; - } + break; + } case SyntaxKind.InterfaceDeclaration: - { - if (((InterfaceDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) - return true; + { + if (((InterfaceDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) + return true; - break; - } + break; + } case SyntaxKind.RecordDeclaration: #if ROSLYN_4_0 case SyntaxKind.RecordStructDeclaration: #endif - { - if (((RecordDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) - return true; + { + if (((RecordDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) + return true; - break; - } + break; + } case SyntaxKind.StructDeclaration: - { - if (((StructDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) - return true; + { + if (((StructDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword)) + return true; - break; - } + break; + } case SyntaxKind.MethodDeclaration: - { - if (((MethodDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.PartialKeyword, SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return true; + { + if (((MethodDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.PartialKeyword, SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return true; - break; - } + break; + } case SyntaxKind.PropertyDeclaration: - { - if (((PropertyDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return true; + { + if (((PropertyDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return true; - break; - } + break; + } case SyntaxKind.IndexerDeclaration: - { - if (((IndexerDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return true; + { + if (((IndexerDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return true; - break; - } + break; + } case SyntaxKind.EventDeclaration: - { - if (((EventDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return true; + { + if (((EventDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return true; - break; - } + break; + } case SyntaxKind.EventFieldDeclaration: - { - if (((EventFieldDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) - return true; + { + if (((EventFieldDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword)) + return true; - break; - } + break; + } } } diff --git a/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs b/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs index be809a3af2..02f9f268da 100644 --- a/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/StatementRefactoring.cs @@ -86,90 +86,90 @@ private static StatementSyntax GetStatement( case SyntaxKind.UnsafeStatement: case SyntaxKind.UsingStatement: case SyntaxKind.LockStatement: + { + if (block.OpenBraceToken.Span.Contains(context.Span) + || block.CloseBraceToken.Span.Contains(context.Span)) { - if (block.OpenBraceToken.Span.Contains(context.Span) - || block.CloseBraceToken.Span.Contains(context.Span)) + if (parent is UsingStatementSyntax usingStatement) { - if (parent is UsingStatementSyntax usingStatement) - { - while (usingStatement.IsParentKind(SyntaxKind.UsingStatement)) - usingStatement = (UsingStatementSyntax)usingStatement.Parent; - - return usingStatement; - } + while (usingStatement.IsParentKind(SyntaxKind.UsingStatement)) + usingStatement = (UsingStatementSyntax)usingStatement.Parent; - return (StatementSyntax)parent; + return usingStatement; } - break; + return (StatementSyntax)parent; } + + break; + } case SyntaxKind.TryStatement: - { - var tryStatement = (TryStatementSyntax)parent; + { + var tryStatement = (TryStatementSyntax)parent; - if (tryStatement.Block?.OpenBraceToken.Span.Contains(context.Span) == true) - return (StatementSyntax)parent; + if (tryStatement.Block?.OpenBraceToken.Span.Contains(context.Span) == true) + return (StatementSyntax)parent; - break; - } + break; + } case SyntaxKind.IfStatement: - { - var ifStatement = (IfStatementSyntax)parent; - - if (ifStatement.IsTopmostIf() - && block.OpenBraceToken.Span.Contains(context.Span)) - { - return ifStatement; - } + { + var ifStatement = (IfStatementSyntax)parent; - if (ifStatement.Else is null - && block.CloseBraceToken.Span.Contains(context.Span)) - { - return ifStatement.GetTopmostIf(); - } + if (ifStatement.IsTopmostIf() + && block.OpenBraceToken.Span.Contains(context.Span)) + { + return ifStatement; + } - break; + if (ifStatement.Else is null + && block.CloseBraceToken.Span.Contains(context.Span)) + { + return ifStatement.GetTopmostIf(); } + + break; + } case SyntaxKind.ElseClause: - { - var elseClause = (ElseClauseSyntax)parent; + { + var elseClause = (ElseClauseSyntax)parent; - if (block.CloseBraceToken.Span.Contains(context.Span)) - return elseClause.GetTopmostIf(); + if (block.CloseBraceToken.Span.Contains(context.Span)) + return elseClause.GetTopmostIf(); - break; - } + break; + } case SyntaxKind.CatchClause: + { + var catchClause = (CatchClauseSyntax)parent; + + if (catchClause.IsParentKind(SyntaxKind.TryStatement)) { - var catchClause = (CatchClauseSyntax)parent; + var tryStatement = (TryStatementSyntax)catchClause.Parent; - if (catchClause.IsParentKind(SyntaxKind.TryStatement)) + if (tryStatement.Finally is null + && catchClause.Block?.CloseBraceToken.Span.Contains(context.Span) == true) { - var tryStatement = (TryStatementSyntax)catchClause.Parent; - - if (tryStatement.Finally is null - && catchClause.Block?.CloseBraceToken.Span.Contains(context.Span) == true) - { - return tryStatement; - } + return tryStatement; } - - break; } - case SyntaxKind.FinallyClause: - { - var finallyClause = (FinallyClauseSyntax)parent; - if (finallyClause.IsParentKind(SyntaxKind.TryStatement)) - { - var tryStatement = (TryStatementSyntax)finallyClause.Parent; + break; + } + case SyntaxKind.FinallyClause: + { + var finallyClause = (FinallyClauseSyntax)parent; - if (finallyClause.Block?.CloseBraceToken.Span.Contains(context.Span) == true) - return tryStatement; - } + if (finallyClause.IsParentKind(SyntaxKind.TryStatement)) + { + var tryStatement = (TryStatementSyntax)finallyClause.Parent; - break; + if (finallyClause.Block?.CloseBraceToken.Span.Contains(context.Span) == true) + return tryStatement; } + + break; + } } return null; diff --git a/src/Refactorings/CSharp/Refactorings/SwapBinaryOperandsRefactoring.cs b/src/Refactorings/CSharp/Refactorings/SwapBinaryOperandsRefactoring.cs index 96acc8631b..eaa7246cde 100644 --- a/src/Refactorings/CSharp/Refactorings/SwapBinaryOperandsRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/SwapBinaryOperandsRefactoring.cs @@ -44,24 +44,24 @@ bool CanRefactor() case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: - { - return !info.Left.IsKind(kind); - } + { + return !info.Left.IsKind(kind); + } case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: - { - return !info.Right.IsKind( - SyntaxKind.NullLiteralExpression, - SyntaxKind.TrueLiteralExpression, - SyntaxKind.FalseLiteralExpression); - } + { + return !info.Right.IsKind( + SyntaxKind.NullLiteralExpression, + SyntaxKind.TrueLiteralExpression, + SyntaxKind.FalseLiteralExpression); + } case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: - { - return true; - } + { + return true; + } } return false; diff --git a/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs b/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs index 35990154d4..af0e218e46 100644 --- a/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/UseElementAccessRefactoring.cs @@ -24,56 +24,56 @@ public static async Task ComputeRefactoringsAsync(RefactoringContext context, In switch (invocationInfo.NameText) { case "First": - { - if (invocationInfo.Arguments.Any()) - break; + { + if (invocationInfo.Arguments.Any()) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!UseElementAccessAnalysis.IsFixableFirst(invocationInfo, semanticModel, context.CancellationToken)) - break; + if (!UseElementAccessAnalysis.IsFixableFirst(invocationInfo, semanticModel, context.CancellationToken)) + break; - context.RegisterRefactoring( - "Use [] instead of calling 'First'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfFirstAsync(context.Document, invocation, ct), - RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); + context.RegisterRefactoring( + "Use [] instead of calling 'First'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfFirstAsync(context.Document, invocation, ct), + RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); - break; - } + break; + } case "Last": - { - if (invocationInfo.Arguments.Any()) - break; + { + if (invocationInfo.Arguments.Any()) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!UseElementAccessAnalysis.IsFixableLast(invocationInfo, semanticModel, context.CancellationToken)) - break; + if (!UseElementAccessAnalysis.IsFixableLast(invocationInfo, semanticModel, context.CancellationToken)) + break; - context.RegisterRefactoring( - "Use [] instead of calling 'Last'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(context.Document, invocation, ct), - RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); + context.RegisterRefactoring( + "Use [] instead of calling 'Last'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfLastAsync(context.Document, invocation, ct), + RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); - break; - } + break; + } case "ElementAt": - { - if (invocationInfo.Arguments.SingleOrDefault(shouldThrow: false)?.Expression?.IsMissing != false) - break; + { + if (invocationInfo.Arguments.SingleOrDefault(shouldThrow: false)?.Expression?.IsMissing != false) + break; - SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); + SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); - if (!UseElementAccessAnalysis.IsFixableElementAt(invocationInfo, semanticModel, context.CancellationToken)) - break; + if (!UseElementAccessAnalysis.IsFixableElementAt(invocationInfo, semanticModel, context.CancellationToken)) + break; - context.RegisterRefactoring( - "Use [] instead of calling 'ElementAt'", - ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfElementAtAsync(context.Document, invocation, ct), - RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); + context.RegisterRefactoring( + "Use [] instead of calling 'ElementAt'", + ct => UseElementAccessInsteadOfEnumerableMethodRefactoring.UseElementAccessInsteadOfElementAtAsync(context.Document, invocation, ct), + RefactoringDescriptors.UseElementAccessInsteadOfLinqMethod); - break; - } + break; + } } } } diff --git a/src/Refactorings/CSharp/Refactorings/WrapCallChainRefactoring.cs b/src/Refactorings/CSharp/Refactorings/WrapCallChainRefactoring.cs index c048eb1387..2b47727d6f 100644 --- a/src/Refactorings/CSharp/Refactorings/WrapCallChainRefactoring.cs +++ b/src/Refactorings/CSharp/Refactorings/WrapCallChainRefactoring.cs @@ -61,31 +61,31 @@ private static bool IsFormattable( switch (node.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)node; + { + var memberAccess = (MemberAccessExpressionSyntax)node; - if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) - return levels == 2; + if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) + return levels == 2; - if (semanticModel - .GetSymbol(memberAccess.Expression, cancellationToken)? - .Kind == SymbolKind.Namespace) - { - return levels == 2; - } + if (semanticModel + .GetSymbol(memberAccess.Expression, cancellationToken)? + .Kind == SymbolKind.Namespace) + { + return levels == 2; + } - if (++levels == 2) - return true; + if (++levels == 2) + return true; - break; - } + break; + } case SyntaxKind.MemberBindingExpression: - { - if (++levels == 2) - return true; + { + if (++levels == 2) + return true; - break; - } + break; + } } } diff --git a/src/Tests/CSharp.Tests/SyntaxKindTests.cs b/src/Tests/CSharp.Tests/SyntaxKindTests.cs index 574b84156a..887bb97fa1 100644 --- a/src/Tests/CSharp.Tests/SyntaxKindTests.cs +++ b/src/Tests/CSharp.Tests/SyntaxKindTests.cs @@ -593,14 +593,14 @@ public static void DetectNewSyntaxKinds() case SyntaxKind.AllowsKeyword: case SyntaxKind.RazorContentToken: case SyntaxKind.RefStructConstraint: - { - break; - } + { + break; + } default: - { - (unknownKinds ??= new List()).Add(value); - break; - } + { + (unknownKinds ??= new List()).Add(value); + break; + } } } diff --git a/src/Tests/Testing.Common/Extensions/TestExtensions.cs b/src/Tests/Testing.Common/Extensions/TestExtensions.cs index 2eefe7c53b..2d669c65ff 100644 --- a/src/Tests/Testing.Common/Extensions/TestExtensions.cs +++ b/src/Tests/Testing.Common/Extensions/TestExtensions.cs @@ -83,35 +83,35 @@ LinePosition GetLinePosition(int startIndex, int endIndex) switch (s[i]) { case '\n': + { + if (i == startIndex + && i > 0 + && s[i - 1] == '\r') { - if (i == startIndex - && i > 0 - && s[i - 1] == '\r') - { - throw new InvalidOperationException("Span cannot start of end between '\r' and '\n'."); - } - - if (i > startIndex - && s[i - 1] == '\r') - { - i--; - } - - line++; - break; + throw new InvalidOperationException("Span cannot start of end between '\r' and '\n'."); } + + if (i > startIndex + && s[i - 1] == '\r') + { + i--; + } + + line++; + break; + } case '\r': + { + if (i == endIndex - 1 + && i < length - 1 + && s[i + 1] == '\n') { - if (i == endIndex - 1 - && i < length - 1 - && s[i + 1] == '\n') - { - throw new InvalidOperationException("Span cannot start of end between '\r' and '\n'."); - } - - line++; - break; + throw new InvalidOperationException("Span cannot start of end between '\r' and '\n'."); } + + line++; + break; + } } i--; diff --git a/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs b/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs index d0c4264093..951f99cefc 100644 --- a/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs +++ b/src/Tests/Testing.Common/Testing/Text/TextProcessor.cs @@ -96,80 +96,80 @@ public static (string, ImmutableArray) FindSpansAndRemove(string text) switch (text[i]) { case '\r': + { + if (PeekNextChar() == '\n') { - if (PeekNextChar() == '\n') - { - i++; - } - - line++; - column = 0; i++; - continue; } + + line++; + column = 0; + i++; + continue; + } case '\n': - { - line++; - column = 0; - i++; - continue; - } + { + line++; + column = 0; + i++; + continue; + } case '[': + { + char nextChar = PeekNextChar(); + if (nextChar == '|') { - char nextChar = PeekNextChar(); - if (nextChar == '|') + sb.Append(text, lastPos, i - lastPos); + + var start2 = new LinePositionInfo(sb.Length, line, column); + + if (stack is not null) + { + stack.Push(start2); + } + else if (!startPending) { - sb.Append(text, lastPos, i - lastPos); - - var start2 = new LinePositionInfo(sb.Length, line, column); - - if (stack is not null) - { - stack.Push(start2); - } - else if (!startPending) - { - start = start2; - startPending = true; - } - else - { - stack = new Stack(); - stack.Push(start); - stack.Push(start2); - startPending = false; - } - - i += 2; - lastPos = i; - continue; + start = start2; + startPending = true; } - else if (nextChar == '[' - && PeekChar(2) == '|' - && PeekChar(3) == ']') + else { - i++; - column++; - CloseSpan(); - i += 3; - lastPos = i; - continue; + stack = new Stack(); + stack.Push(start); + stack.Push(start2); + startPending = false; } - break; + i += 2; + lastPos = i; + continue; } - case '|': + else if (nextChar == '[' + && PeekChar(2) == '|' + && PeekChar(3) == ']') { - if (PeekNextChar() == ']') - { - CloseSpan(); - i += 2; - lastPos = i; - continue; - } + i++; + column++; + CloseSpan(); + i += 3; + lastPos = i; + continue; + } - break; + break; + } + case '|': + { + if (PeekNextChar() == ']') + { + CloseSpan(); + i += 2; + lastPos = i; + continue; } + + break; + } } column++; diff --git a/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicLinesWalker.cs b/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicLinesWalker.cs index 60fdaae1ac..342a78380a 100644 --- a/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicLinesWalker.cs +++ b/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicLinesWalker.cs @@ -42,23 +42,23 @@ public override void VisitTrivia(SyntaxTrivia trivia) switch (trivia.Kind()) { case SyntaxKind.CommentTrivia: - { - TextSpan span = trivia.Span; - - TextLine line = Lines.GetLineFromPosition(span.Start); + { + TextSpan span = trivia.Span; - if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) - { - CommentLineCount++; - } + TextLine line = Lines.GetLineFromPosition(span.Start); - break; - } - case SyntaxKind.DocumentationCommentTrivia: + if (line.IsEmptyOrWhiteSpace(TextSpan.FromBounds(line.Start, span.Start))) { - CommentLineCount += Lines.GetLineCount(trivia.Span) - 1; - break; + CommentLineCount++; } + + break; + } + case SyntaxKind.DocumentationCommentTrivia: + { + CommentLineCount += Lines.GetLineCount(trivia.Span) - 1; + break; + } } } diff --git a/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicPhysicalLinesWalker.cs b/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicPhysicalLinesWalker.cs index 93280b720c..f248d57889 100644 --- a/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicPhysicalLinesWalker.cs +++ b/src/VisualBasic.Workspaces/VisualBasic/CodeMetrics/VisualBasicPhysicalLinesWalker.cs @@ -54,17 +54,17 @@ static bool AnalyzeTrailingTrivia(in SyntaxTriviaList trailingTrivia) { case SyntaxKind.EndOfLineTrivia: case SyntaxKind.CommentTrivia: - { - return true; - } + { + return true; + } case SyntaxKind.WhitespaceTrivia: - { - break; - } + { + break; + } default: - { - return false; - } + { + return false; + } } } diff --git a/src/Workspaces.Common/CSharp/CodeActionFactory.cs b/src/Workspaces.Common/CSharp/CodeActionFactory.cs index d5c1cc194e..1d3f32f021 100644 --- a/src/Workspaces.Common/CSharp/CodeActionFactory.cs +++ b/src/Workspaces.Common/CSharp/CodeActionFactory.cs @@ -157,31 +157,31 @@ public static TextChange GetTextChangeForBlankLine(TriviaBlock block) switch (block.Kind) { case TriviaBlockKind.NoNewLine: - { - TriviaBlockReader reader = block.CreateReader(); + { + TriviaBlockReader reader = block.CreateReader(); - if (reader.ReadWhiteSpaceTrivia()) - position = reader.Current.Span.End; + if (reader.ReadWhiteSpaceTrivia()) + position = reader.Current.Span.End; - return new TextChange(new TextSpan(position, 0), endOfLine + endOfLine); - } + return new TextChange(new TextSpan(position, 0), endOfLine + endOfLine); + } case TriviaBlockKind.NewLine: - { - return new TextChange(new TextSpan(position, 0), endOfLine); - } + { + return new TextChange(new TextSpan(position, 0), endOfLine); + } case TriviaBlockKind.BlankLine: - { - TriviaBlockReader reader = block.CreateReader(); + { + TriviaBlockReader reader = block.CreateReader(); - reader.ReadTo(position); - reader.ReadBlankLines(); + reader.ReadTo(position); + reader.ReadBlankLines(); - return new TextChange(TextSpan.FromBounds(position, reader.Current.Span.End), ""); - } + return new TextChange(TextSpan.FromBounds(position, reader.Current.Span.End), ""); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } @@ -200,34 +200,34 @@ public static TextChange GetTextChangeForNewLine( switch (block.Kind) { case TriviaBlockKind.NoNewLine: - { - int end = (reader.ReadWhiteSpaceTrivia()) ? reader.Current.Span.End : position; + { + int end = (reader.ReadWhiteSpaceTrivia()) ? reader.Current.Span.End : position; - string endOfLine = SyntaxTriviaAnalysis.DetermineEndOfLine(node).ToString(); + string endOfLine = SyntaxTriviaAnalysis.DetermineEndOfLine(node).ToString(); - indentation ??= (increaseIndentation) - ? GetIncreasedIndentation(node, configOptions, cancellationToken) - : SyntaxTriviaAnalysis.DetermineIndentation(node, cancellationToken).ToString(); + indentation ??= (increaseIndentation) + ? GetIncreasedIndentation(node, configOptions, cancellationToken) + : SyntaxTriviaAnalysis.DetermineIndentation(node, cancellationToken).ToString(); - return new TextChange(TextSpan.FromBounds(position, end), endOfLine + indentation); - } + return new TextChange(TextSpan.FromBounds(position, end), endOfLine + indentation); + } case TriviaBlockKind.NewLine: - { - reader.ReadWhiteSpace(); + { + reader.ReadWhiteSpace(); - return new TextChange(TextSpan.FromBounds(position, reader.Current.Span.End), newLineReplacement); - } + return new TextChange(TextSpan.FromBounds(position, reader.Current.Span.End), newLineReplacement); + } case TriviaBlockKind.BlankLine: - { - reader.ReadTo(position); - reader.ReadWhiteSpace(); + { + reader.ReadTo(position); + reader.ReadWhiteSpace(); - return new TextChange(TextSpan.FromBounds(node.Span.End, reader.Current.Span.End), newLineReplacement); - } + return new TextChange(TextSpan.FromBounds(node.Span.End, reader.Current.Span.End), newLineReplacement); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs b/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs index 5334cdf155..a54eb33521 100644 --- a/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs +++ b/src/Workspaces.Common/CSharp/CodeFixes/ModifiersCodeFixRegistrator.cs @@ -67,29 +67,29 @@ private static TNode AddModifier( switch (modifierKind) { case SyntaxKind.AbstractKeyword: - { - node = node.RemoveModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword); - break; - } + { + node = node.RemoveModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword); + break; + } case SyntaxKind.VirtualKeyword: - { - node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.OverrideKeyword); - break; - } + { + node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.OverrideKeyword); + break; + } case SyntaxKind.OverrideKeyword: - { - node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword); - break; - } + { + node = node.RemoveModifiers(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword); + break; + } case SyntaxKind.StaticKeyword: - { - if (node.IsKind(SyntaxKind.ConstructorDeclaration)) - node = SyntaxAccessibility.WithoutExplicitAccessibility(node); + { + if (node.IsKind(SyntaxKind.ConstructorDeclaration)) + node = SyntaxAccessibility.WithoutExplicitAccessibility(node); - node = node.RemoveModifier(SyntaxKind.SealedKeyword); + node = node.RemoveModifier(SyntaxKind.SealedKeyword); - break; - } + break; + } } return node.InsertModifier(modifierKind, comparer); diff --git a/src/Workspaces.Common/CSharp/DocumentRefactorings.cs b/src/Workspaces.Common/CSharp/DocumentRefactorings.cs index a8c5aff360..f363c9e98d 100644 --- a/src/Workspaces.Common/CSharp/DocumentRefactorings.cs +++ b/src/Workspaces.Common/CSharp/DocumentRefactorings.cs @@ -36,22 +36,22 @@ public static async Task ChangeTypeAsync( switch (parent.Kind()) { case SyntaxKind.SimpleAssignmentExpression: - { - var assignmentExpression = (AssignmentExpressionSyntax)parent; - Debug.Assert(object.ReferenceEquals(assignmentExpression.Left, declarationExpression)); - break; - } + { + var assignmentExpression = (AssignmentExpressionSyntax)parent; + Debug.Assert(object.ReferenceEquals(assignmentExpression.Left, declarationExpression)); + break; + } case SyntaxKind.ForEachVariableStatement: - { - var forEachStatement = (ForEachVariableStatementSyntax)parent; - Debug.Assert(object.ReferenceEquals(forEachStatement.Variable, declarationExpression)); - break; - } + { + var forEachStatement = (ForEachVariableStatementSyntax)parent; + Debug.Assert(object.ReferenceEquals(forEachStatement.Variable, declarationExpression)); + break; + } default: - { - SyntaxDebug.Fail(parent); - break; - } + { + SyntaxDebug.Fail(parent); + break; + } } #endif TupleExpressionSyntax tupleExpression = CreateTupleExpression(typeSymbol, designation, GetSymbolDisplayFormat(semanticModel, type.SpanStart)) @@ -360,50 +360,50 @@ public static Task RemoveParenthesesAsync( switch (parent.Kind()) { case SyntaxKind.ReturnStatement: - { - var returnStatement = (ReturnStatementSyntax)parent; - - SyntaxToken returnKeyword = returnStatement.ReturnKeyword; + { + var returnStatement = (ReturnStatementSyntax)parent; - if (!returnKeyword.TrailingTrivia.Any()) - { - ReturnStatementSyntax newNode = returnStatement.Update(returnKeyword.WithTrailingTrivia(Space), newExpression, returnStatement.SemicolonToken); + SyntaxToken returnKeyword = returnStatement.ReturnKeyword; - return document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken); - } + if (!returnKeyword.TrailingTrivia.Any()) + { + ReturnStatementSyntax newNode = returnStatement.Update(returnKeyword.WithTrailingTrivia(Space), newExpression, returnStatement.SemicolonToken); - break; + return document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken); } - case SyntaxKind.YieldReturnStatement: - { - var yieldReturn = (YieldStatementSyntax)parent; - SyntaxToken returnKeyword = yieldReturn.ReturnOrBreakKeyword; + break; + } + case SyntaxKind.YieldReturnStatement: + { + var yieldReturn = (YieldStatementSyntax)parent; - if (!returnKeyword.TrailingTrivia.Any()) - { - YieldStatementSyntax newNode = yieldReturn.Update(yieldReturn.YieldKeyword, returnKeyword.WithTrailingTrivia(Space), newExpression, yieldReturn.SemicolonToken); + SyntaxToken returnKeyword = yieldReturn.ReturnOrBreakKeyword; - return document.ReplaceNodeAsync(yieldReturn, newNode, cancellationToken); - } + if (!returnKeyword.TrailingTrivia.Any()) + { + YieldStatementSyntax newNode = yieldReturn.Update(yieldReturn.YieldKeyword, returnKeyword.WithTrailingTrivia(Space), newExpression, yieldReturn.SemicolonToken); - break; + return document.ReplaceNodeAsync(yieldReturn, newNode, cancellationToken); } - case SyntaxKind.AwaitExpression: - { - var awaitExpression = (AwaitExpressionSyntax)parent; - SyntaxToken awaitKeyword = awaitExpression.AwaitKeyword; + break; + } + case SyntaxKind.AwaitExpression: + { + var awaitExpression = (AwaitExpressionSyntax)parent; - if (!awaitKeyword.TrailingTrivia.Any()) - { - AwaitExpressionSyntax newNode = awaitExpression.Update(awaitKeyword.WithTrailingTrivia(Space), newExpression); + SyntaxToken awaitKeyword = awaitExpression.AwaitKeyword; - return document.ReplaceNodeAsync(awaitExpression, newNode, cancellationToken); - } + if (!awaitKeyword.TrailingTrivia.Any()) + { + AwaitExpressionSyntax newNode = awaitExpression.Update(awaitKeyword.WithTrailingTrivia(Space), newExpression); - break; + return document.ReplaceNodeAsync(awaitExpression, newNode, cancellationToken); } + + break; + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs index fdd43e6579..6deeb25f2c 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/AddExceptionToDocumentationComment/AddExceptionElementToDocumentationCommentRefactoring.cs @@ -31,32 +31,32 @@ private static IEnumerable GetOtherUndocumentedExceptions( switch (node.Kind()) { case SyntaxKind.ThrowStatement: + { + if (predicate(node)) { - if (predicate(node)) - { - var throwStatement = (ThrowStatementSyntax)node; + var throwStatement = (ThrowStatementSyntax)node; - ThrowInfo info = GetUndocumentedExceptionInfo(node, throwStatement.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - - if (info is not null) - yield return info; - } + ThrowInfo info = GetUndocumentedExceptionInfo(node, throwStatement.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - break; + if (info is not null) + yield return info; } + + break; + } case SyntaxKind.ThrowExpression: + { + if (predicate(node)) { - if (predicate(node)) - { - var throwExpression = (ThrowExpressionSyntax)node; - ThrowInfo info = GetUndocumentedExceptionInfo(node, throwExpression.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - - if (info is not null) - yield return info; - } + var throwExpression = (ThrowExpressionSyntax)node; + ThrowInfo info = GetUndocumentedExceptionInfo(node, throwExpression.Expression, declaration, declarationSymbol, exceptionSymbol, semanticModel, cancellationToken); - break; + if (info is not null) + yield return info; } + + break; + } } } } @@ -109,32 +109,32 @@ private static bool CanAddExceptionToComment( { case XmlTag.Include: case XmlTag.Exclude: - { - if (isFirst) - containsIncludeOrExclude = true; + { + if (isFirst) + containsIncludeOrExclude = true; - break; - } + break; + } case XmlTag.InheritDoc: - { - return false; - } + { + return false; + } case XmlTag.Exception: + { + if (!containsException) { - if (!containsException) + if (info.IsEmptyElement) { - if (info.IsEmptyElement) - { - containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); - } - else - { - containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); - } + containsException = ContainsException((XmlEmptyElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); + } + else + { + containsException = ContainsException((XmlElementSyntax)info.Element, exceptionSymbol, semanticModel, cancellationToken); } - - break; } + + break; + } } if (isFirst) diff --git a/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs index a9b3eedbfa..81c2b5e3f1 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/AddParameterToInterfaceMemberRefactoring.cs @@ -22,21 +22,21 @@ public static CodeAction ComputeRefactoringForExplicitImplementation( switch (memberDeclaration) { case MethodDeclarationSyntax methodDeclaration: - { - return ComputeRefactoringForExplicitImplementation( - context, - methodDeclaration, - methodDeclaration.ExplicitInterfaceSpecifier, - methodDeclaration.ParameterList?.Parameters ?? default); - } + { + return ComputeRefactoringForExplicitImplementation( + context, + methodDeclaration, + methodDeclaration.ExplicitInterfaceSpecifier, + methodDeclaration.ParameterList?.Parameters ?? default); + } case IndexerDeclarationSyntax indexerDeclaration: - { - return ComputeRefactoringForExplicitImplementation( - context, - indexerDeclaration, - indexerDeclaration.ExplicitInterfaceSpecifier, - indexerDeclaration.ParameterList?.Parameters ?? default); - } + { + return ComputeRefactoringForExplicitImplementation( + context, + indexerDeclaration, + indexerDeclaration.ExplicitInterfaceSpecifier, + indexerDeclaration.ParameterList?.Parameters ?? default); + } } return default; @@ -209,18 +209,18 @@ private static ISymbol FindInterfaceMember( switch (memberSymbol.Kind) { case SymbolKind.Method: - { - return FindInterfaceMethod((IMethodSymbol)memberSymbol, interfaceSymbol); - } + { + return FindInterfaceMethod((IMethodSymbol)memberSymbol, interfaceSymbol); + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)memberSymbol; + { + var propertySymbol = (IPropertySymbol)memberSymbol; - if (propertySymbol.IsIndexer) - return FindInterfaceIndexer(propertySymbol, interfaceSymbol); + if (propertySymbol.IsIndexer) + return FindInterfaceIndexer(propertySymbol, interfaceSymbol); - break; - } + break; + } } return null; diff --git a/src/Workspaces.Common/CSharp/Refactorings/CallExtensionMethodAsInstanceMethodRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/CallExtensionMethodAsInstanceMethodRefactoring.cs index 61e49036d0..a42db9298e 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/CallExtensionMethodAsInstanceMethodRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/CallExtensionMethodAsInstanceMethodRefactoring.cs @@ -43,25 +43,25 @@ MemberAccessExpressionSyntax CreateNewMemberAccessExpression() { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: - { - ExpressionSyntax newExpression = argument.Expression - .WithLeadingTrivia(expression.GetLeadingTrivia()) - .Parenthesize(); + { + ExpressionSyntax newExpression = argument.Expression + .WithLeadingTrivia(expression.GetLeadingTrivia()) + .Parenthesize(); - return SimpleMemberAccessExpression( - newExpression, - (SimpleNameSyntax)expression.WithoutLeadingTrivia()); - } + return SimpleMemberAccessExpression( + newExpression, + (SimpleNameSyntax)expression.WithoutLeadingTrivia()); + } case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)expression; + { + var memberAccess = (MemberAccessExpressionSyntax)expression; - ExpressionSyntax newExpression = argument.Expression - .WithTriviaFrom(memberAccess.Expression) - .Parenthesize(); + ExpressionSyntax newExpression = argument.Expression + .WithTriviaFrom(memberAccess.Expression) + .Parenthesize(); - return memberAccess.WithExpression(newExpression); - } + return memberAccess.WithExpression(newExpression); + } } throw new InvalidOperationException(); diff --git a/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs index ba970a9056..d9cc9a78bf 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ChangeAccessibilityRefactoring.cs @@ -176,22 +176,22 @@ private static IEnumerable GetMemberDeclarations( switch (syntaxReference.GetSyntax(cancellationToken)) { case MemberDeclarationSyntax memberDeclaration: - { - yield return memberDeclaration; - break; - } + { + yield return memberDeclaration; + break; + } case VariableDeclaratorSyntax variableDeclarator: - { - if (variableDeclarator.Parent.Parent is MemberDeclarationSyntax memberDeclaration2) - yield return memberDeclaration2; + { + if (variableDeclarator.Parent.Parent is MemberDeclarationSyntax memberDeclaration2) + yield return memberDeclaration2; - break; - } + break; + } default: - { - Debug.Fail(syntaxReference.GetSyntax(cancellationToken).Kind().ToString()); - break; - } + { + Debug.Fail(syntaxReference.GetSyntax(cancellationToken).Kind().ToString()); + break; + } } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs index 17d634203c..1f96f8c38f 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertBlockBodyToExpressionBodyRefactoring.cs @@ -196,104 +196,104 @@ private static SyntaxNode Refactor(SyntaxNode node, AnalyzerConfigOptions config switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - var methodDeclaration = (MethodDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(methodDeclaration.Body); - - return methodDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, methodDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(methodDeclaration.Body, analysis)) - .WithBody(null); - } + { + var methodDeclaration = (MethodDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(methodDeclaration.Body); + + return methodDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, methodDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(methodDeclaration.Body, analysis)) + .WithBody(null); + } case SyntaxKind.ConstructorDeclaration: - { - var constructorDeclaration = (ConstructorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(constructorDeclaration.Body); - - return constructorDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, constructorDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(constructorDeclaration.Body, analysis)) - .WithBody(null); - } + { + var constructorDeclaration = (ConstructorDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(constructorDeclaration.Body); + + return constructorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, constructorDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(constructorDeclaration.Body, analysis)) + .WithBody(null); + } case SyntaxKind.DestructorDeclaration: - { - var destructorDeclaration = (DestructorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(destructorDeclaration.Body); - - return destructorDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, destructorDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(destructorDeclaration.Body, analysis)) - .WithBody(null); - } + { + var destructorDeclaration = (DestructorDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(destructorDeclaration.Body); + + return destructorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, destructorDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(destructorDeclaration.Body, analysis)) + .WithBody(null); + } case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(localFunction.Body); - - return localFunction - .WithExpressionBody(CreateExpressionBody(analysis, localFunction, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(localFunction.Body, analysis)) - .WithBody(null); - } + { + var localFunction = (LocalFunctionStatementSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(localFunction.Body); + + return localFunction + .WithExpressionBody(CreateExpressionBody(analysis, localFunction, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(localFunction.Body, analysis)) + .WithBody(null); + } case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(operatorDeclaration.Body); - - return operatorDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, operatorDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(operatorDeclaration.Body, analysis)) - .WithBody(null); - } + { + var operatorDeclaration = (OperatorDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(operatorDeclaration.Body); + + return operatorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, operatorDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(operatorDeclaration.Body, analysis)) + .WithBody(null); + } case SyntaxKind.ConversionOperatorDeclaration: - { - var operatorDeclaration = (ConversionOperatorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(operatorDeclaration.Body); - - return operatorDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, operatorDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(operatorDeclaration.Body, analysis)) - .WithBody(null); - } + { + var operatorDeclaration = (ConversionOperatorDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(operatorDeclaration.Body); + + return operatorDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, operatorDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(operatorDeclaration.Body, analysis)) + .WithBody(null); + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(propertyDeclaration.AccessorList); - - return propertyDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, propertyDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) - .WithAccessorList(null); - } + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(propertyDeclaration.AccessorList); + + return propertyDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, propertyDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) + .WithAccessorList(null); + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(indexerDeclaration.AccessorList); - - return indexerDeclaration - .WithExpressionBody(CreateExpressionBody(analysis, indexerDeclaration, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) - .WithAccessorList(null); - } + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(indexerDeclaration.AccessorList); + + return indexerDeclaration + .WithExpressionBody(CreateExpressionBody(analysis, indexerDeclaration, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) + .WithAccessorList(null); + } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; - BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(accessor); - - return accessor - .WithExpressionBody(CreateExpressionBody(analysis, accessor, configOptions)) - .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) - .WithBody(null); - } + { + var accessor = (AccessorDeclarationSyntax)node; + BlockExpressionAnalysis analysis = BlockExpressionAnalysis.Create(accessor); + + return accessor + .WithExpressionBody(CreateExpressionBody(analysis, accessor, configOptions)) + .WithSemicolonToken(CreateSemicolonToken(analysis.Block, analysis)) + .WithBody(null); + } default: - { - SyntaxDebug.Fail(node); - return node; - } + { + SyntaxDebug.Fail(node); + return node; + } } } @@ -311,24 +311,24 @@ private static ArrowExpressionClauseSyntax CreateExpressionBody( switch (keyword.Kind()) { case SyntaxKind.ThrowKeyword: - { - expression = ThrowExpression(keyword, expression); - break; - } + { + expression = ThrowExpression(keyword, expression); + break; + } case SyntaxKind.ReturnKeyword: - { - SyntaxTriviaList leading = keyword.LeadingTrivia; + { + SyntaxTriviaList leading = keyword.LeadingTrivia; - if (!leading.IsEmptyOrWhitespace()) - arrowToken = arrowToken.WithLeadingTrivia(leading); + if (!leading.IsEmptyOrWhitespace()) + arrowToken = arrowToken.WithLeadingTrivia(leading); - SyntaxTriviaList trailing = keyword.TrailingTrivia; + SyntaxTriviaList trailing = keyword.TrailingTrivia; - if (!trailing.IsEmptyOrWhitespace()) - arrowToken = arrowToken.WithTrailingTrivia(trailing); + if (!trailing.IsEmptyOrWhitespace()) + arrowToken = arrowToken.WithTrailingTrivia(trailing); - break; - } + break; + } } expression = SyntaxTriviaAnalysis.SetIndentation(expression, declaration, configOptions); diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertConditionalExpressionToIfElseRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertConditionalExpressionToIfElseRefactoring.cs index 4879fb8bba..4a0f4c79df 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertConditionalExpressionToIfElseRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertConditionalExpressionToIfElseRefactoring.cs @@ -134,25 +134,25 @@ private static StatementSyntax CreateNewStatement(StatementSyntax statement, Exp switch (statement.Kind()) { case SyntaxKind.ReturnStatement: - { - return ((ReturnStatementSyntax)statement).WithExpression(expression); - } + { + return ((ReturnStatementSyntax)statement).WithExpression(expression); + } case SyntaxKind.YieldReturnStatement: - { - return ((YieldStatementSyntax)statement).WithExpression(expression); - } + { + return ((YieldStatementSyntax)statement).WithExpression(expression); + } case SyntaxKind.ExpressionStatement: - { - var expressionStatement = (ExpressionStatementSyntax)statement; + { + var expressionStatement = (ExpressionStatementSyntax)statement; - var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; + var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; - return expressionStatement.WithExpression(assignment.WithRight(expression)); - } + return expressionStatement.WithExpression(assignment.WithRight(expression)); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs index 11b9b93590..53269e8091 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertExpressionBodyToBlockBodyRefactoring.cs @@ -86,103 +86,103 @@ public static SyntaxNode Refactor( switch (node.Kind()) { case SyntaxKind.MethodDeclaration: - { - var method = (MethodDeclarationSyntax)node; + { + var method = (MethodDeclarationSyntax)node; - return method - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(method, expression, method.SemicolonToken, method.ReturnType, configOptions, semanticModel, cancellationToken)); - } + return method + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(method, expression, method.SemicolonToken, method.ReturnType, configOptions, semanticModel, cancellationToken)); + } case SyntaxKind.ConstructorDeclaration: - { - var constructor = (ConstructorDeclarationSyntax)node; + { + var constructor = (ConstructorDeclarationSyntax)node; - return constructor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(constructor, expression, constructor.SemicolonToken, configOptions)); - } + return constructor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(constructor, expression, constructor.SemicolonToken, configOptions)); + } case SyntaxKind.DestructorDeclaration: - { - var destructor = (DestructorDeclarationSyntax)node; + { + var destructor = (DestructorDeclarationSyntax)node; - return destructor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(destructor, expression, destructor.SemicolonToken, configOptions)); - } + return destructor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(destructor, expression, destructor.SemicolonToken, configOptions)); + } case SyntaxKind.OperatorDeclaration: - { - var operatorDeclaration = (OperatorDeclarationSyntax)node; + { + var operatorDeclaration = (OperatorDeclarationSyntax)node; - return operatorDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(operatorDeclaration, expression, operatorDeclaration.SemicolonToken, configOptions)); - } + return operatorDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(operatorDeclaration, expression, operatorDeclaration.SemicolonToken, configOptions)); + } case SyntaxKind.ConversionOperatorDeclaration: - { - var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; + { + var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; - return conversionOperatorDeclaration - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(conversionOperatorDeclaration, expression, conversionOperatorDeclaration.SemicolonToken, configOptions)); - } + return conversionOperatorDeclaration + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(conversionOperatorDeclaration, expression, conversionOperatorDeclaration.SemicolonToken, configOptions)); + } case SyntaxKind.PropertyDeclaration: - { - var propertyDeclaration = (PropertyDeclarationSyntax)node; + { + var propertyDeclaration = (PropertyDeclarationSyntax)node; - return propertyDeclaration - .WithAccessorList(CreateAccessorList(propertyDeclaration, expression, propertyDeclaration.SemicolonToken, configOptions)) - .WithExpressionBody(null) - .WithSemicolonToken(default); - } + return propertyDeclaration + .WithAccessorList(CreateAccessorList(propertyDeclaration, expression, propertyDeclaration.SemicolonToken, configOptions)) + .WithExpressionBody(null) + .WithSemicolonToken(default); + } case SyntaxKind.IndexerDeclaration: - { - var indexerDeclaration = (IndexerDeclarationSyntax)node; + { + var indexerDeclaration = (IndexerDeclarationSyntax)node; - return indexerDeclaration - .WithAccessorList(CreateAccessorList(indexerDeclaration, expression, indexerDeclaration.SemicolonToken, configOptions)) - .WithExpressionBody(null) - .WithSemicolonToken(default); - } + return indexerDeclaration + .WithAccessorList(CreateAccessorList(indexerDeclaration, expression, indexerDeclaration.SemicolonToken, configOptions)) + .WithExpressionBody(null) + .WithSemicolonToken(default); + } case SyntaxKind.GetAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; + { + var accessor = (AccessorDeclarationSyntax)node; - return accessor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(accessor, expression, accessor.SemicolonToken, configOptions)); - } + return accessor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(accessor, expression, accessor.SemicolonToken, configOptions)); + } case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: - { - var accessor = (AccessorDeclarationSyntax)node; + { + var accessor = (AccessorDeclarationSyntax)node; - return accessor - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlockWithExpressionStatement(accessor, expression, accessor.SemicolonToken, configOptions)); - } + return accessor + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlockWithExpressionStatement(accessor, expression, accessor.SemicolonToken, configOptions)); + } case SyntaxKind.LocalFunctionStatement: - { - var localFunction = (LocalFunctionStatementSyntax)node; + { + var localFunction = (LocalFunctionStatementSyntax)node; - return localFunction - .WithExpressionBody(null) - .WithSemicolonToken(default) - .WithBody(CreateBlock(localFunction, expression, localFunction.SemicolonToken, localFunction.ReturnType, configOptions, semanticModel, cancellationToken)); - } + return localFunction + .WithExpressionBody(null) + .WithSemicolonToken(default) + .WithBody(CreateBlock(localFunction, expression, localFunction.SemicolonToken, localFunction.ReturnType, configOptions, semanticModel, cancellationToken)); + } default: - { - SyntaxDebug.Fail(node); - return node; - } + { + SyntaxDebug.Fail(node); + return node; + } } } @@ -226,23 +226,23 @@ static bool ShouldCreateExpressionStatement( switch (expression.Kind()) { case SyntaxKind.ThrowExpression: + { + return true; + } + case SyntaxKind.AwaitExpression: + { + ITypeSymbol originalDefinition = semanticModel + .GetTypeSymbol(returnType, cancellationToken) + .OriginalDefinition; + + if (!originalDefinition.HasMetadataName(MetadataNames.System_Threading_Tasks_ValueTask_T) + && !originalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) { return true; } - case SyntaxKind.AwaitExpression: - { - ITypeSymbol originalDefinition = semanticModel - .GetTypeSymbol(returnType, cancellationToken) - .OriginalDefinition; - if (!originalDefinition.HasMetadataName(MetadataNames.System_Threading_Tasks_ValueTask_T) - && !originalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Threading_Tasks_Task_T)) - { - return true; - } - - break; - } + break; + } } return false; diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertHasFlagCallToBitwiseOperationRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertHasFlagCallToBitwiseOperationRefactoring.cs index 75d5fc3670..51740678d3 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertHasFlagCallToBitwiseOperationRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertHasFlagCallToBitwiseOperationRefactoring.cs @@ -51,31 +51,31 @@ public static Task RefactorAsync( switch (parent.Kind()) { case SyntaxKind.LogicalNotExpression: - { - binaryExpressionKind = (isComposite) ? SyntaxKind.NotEqualsExpression : SyntaxKind.EqualsExpression; - nodeToReplace = parent; - break; - } + { + binaryExpressionKind = (isComposite) ? SyntaxKind.NotEqualsExpression : SyntaxKind.EqualsExpression; + nodeToReplace = parent; + break; + } case SyntaxKind.EqualsExpression: + { + switch (((BinaryExpressionSyntax)parent).Right?.Kind()) { - switch (((BinaryExpressionSyntax)parent).Right?.Kind()) + case SyntaxKind.TrueLiteralExpression: { - case SyntaxKind.TrueLiteralExpression: - { - binaryExpressionKind = (isComposite) ? SyntaxKind.EqualsExpression : SyntaxKind.NotEqualsExpression; - nodeToReplace = parent; - break; - } - case SyntaxKind.FalseLiteralExpression: - { - binaryExpressionKind = (isComposite) ? SyntaxKind.NotEqualsExpression : SyntaxKind.EqualsExpression; - nodeToReplace = parent; - break; - } + binaryExpressionKind = (isComposite) ? SyntaxKind.EqualsExpression : SyntaxKind.NotEqualsExpression; + nodeToReplace = parent; + break; + } + case SyntaxKind.FalseLiteralExpression: + { + binaryExpressionKind = (isComposite) ? SyntaxKind.NotEqualsExpression : SyntaxKind.EqualsExpression; + nodeToReplace = parent; + break; } - - break; } + + break; + } } } diff --git a/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs b/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs index bcc98d10bb..80fe1a8b81 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/ConvertInterpolatedStringToStringBuilderMethodRefactoring.cs @@ -25,87 +25,87 @@ public static (SyntaxKind contentKind, string methodName, ImmutableArray RefactorAsync(Document document, IfAnalysis ifAnaly switch (ifAnalysis.Kind) { case IfAnalysisKind.IfElseToAssignmentWithCoalesceExpression: - { - return IfElseToAssignmentWithCoalesceExpressionAsync(document, (IfElseToAssignmentWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToAssignmentWithCoalesceExpressionAsync(document, (IfElseToAssignmentWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToAssignmentWithConditionalExpression: - { - return IfElseToAssignmentWithConditionalExpressionAsync(document, (IfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToAssignmentWithConditionalExpressionAsync(document, (IfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.AssignmentAndIfToAssignmentWithConditionalExpression: - { - var analysis = (AssignmentAndIfToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; + { + var analysis = (AssignmentAndIfToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); - ExpressionStatementSyntax newStatement = analysis.Statement.ReplaceNode(analysis.Right, conditionalExpression); + ExpressionStatementSyntax newStatement = analysis.Statement.ReplaceNode(analysis.Right, conditionalExpression); - return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); - } + return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); + } case IfAnalysisKind.LocalDeclarationAndIfElseAssignmentWithConditionalExpression: - { - var analysis = (LocalDeclarationAndIfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; + { + var analysis = (LocalDeclarationAndIfElseToAssignmentWithConditionalExpressionAnalysis)ifAnalysis; - ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); + ConditionalExpressionSyntax conditionalExpression = CreateConditionalExpression(analysis.IfStatement.Condition, analysis.WhenTrue, analysis.WhenFalse); - VariableDeclaratorSyntax declarator = analysis.Statement.Declaration.Variables[0]; + VariableDeclaratorSyntax declarator = analysis.Statement.Declaration.Variables[0]; - EqualsValueClauseSyntax initializer = declarator.Initializer; + EqualsValueClauseSyntax initializer = declarator.Initializer; - EqualsValueClauseSyntax newInitializer = (initializer is not null) - ? initializer.WithValue(conditionalExpression) - : EqualsValueClause(conditionalExpression); + EqualsValueClauseSyntax newInitializer = (initializer is not null) + ? initializer.WithValue(conditionalExpression) + : EqualsValueClause(conditionalExpression); - LocalDeclarationStatementSyntax newStatement = analysis.Statement.ReplaceNode(declarator, declarator.WithInitializer(newInitializer)); + LocalDeclarationStatementSyntax newStatement = analysis.Statement.ReplaceNode(declarator, declarator.WithInitializer(newInitializer)); - return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); - } + return ToAssignmentWithConditionalExpressionAsync(document, analysis, newStatement, cancellationToken); + } case IfAnalysisKind.IfElseToAssignmentWithExpression: - { - return IfElseToAssignmentWithExpressionAsync(document, (IfElseToAssignmentWithExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToAssignmentWithExpressionAsync(document, (IfElseToAssignmentWithExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToAssignmentWithCondition: - { - return IfElseToAssignmentWithConditionAsync(document, (IfElseToAssignmentWithConditionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToAssignmentWithConditionAsync(document, (IfElseToAssignmentWithConditionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToReturnWithCoalesceExpression: case IfAnalysisKind.IfElseToYieldReturnWithCoalesceExpression: case IfAnalysisKind.IfReturnToReturnWithCoalesceExpression: - { - return IfToReturnWithCoalesceExpressionAsync(document, (IfToReturnWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfToReturnWithCoalesceExpressionAsync(document, (IfToReturnWithCoalesceExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToReturnWithConditionalExpression: - { - return IfElseToReturnWithConditionalExpressionAsync(document, (IfElseToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToReturnWithConditionalExpressionAsync(document, (IfElseToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToReturnWithBooleanExpression: - { - return IfElseToReturnWithBooleanExpressionAsync(document, (IfElseToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToReturnWithBooleanExpressionAsync(document, (IfElseToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToReturnWithExpression: case IfAnalysisKind.IfElseToYieldReturnWithExpression: case IfAnalysisKind.IfReturnToReturnWithExpression: - { - return IfToReturnWithExpressionAsync(document, (IfToReturnWithExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfToReturnWithExpressionAsync(document, (IfToReturnWithExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToYieldReturnWithConditionalExpression: - { - return IfElseToYieldReturnWithConditionalExpressionAsync(document, (IfElseToYieldReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToYieldReturnWithConditionalExpressionAsync(document, (IfElseToYieldReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfElseToYieldReturnWithBooleanExpression: - { - return IfElseToYieldReturnWithBooleanExpressionAsync(document, (IfElseToYieldReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfElseToYieldReturnWithBooleanExpressionAsync(document, (IfElseToYieldReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfReturnToReturnWithConditionalExpression: - { - return IfReturnToReturnWithConditionalExpressionAsync(document, (IfReturnToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfReturnToReturnWithConditionalExpressionAsync(document, (IfReturnToReturnWithConditionalExpressionAnalysis)ifAnalysis, cancellationToken); + } case IfAnalysisKind.IfReturnToReturnWithBooleanExpression: - { - return IfReturnToReturnWithBooleanExpressionAsync(document, (IfReturnToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); - } + { + return IfReturnToReturnWithBooleanExpressionAsync(document, (IfReturnToReturnWithBooleanExpressionAnalysis)ifAnalysis, cancellationToken); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } @@ -478,41 +478,41 @@ private static ExpressionSyntax GetBooleanExpression( switch (expression1.Kind()) { case SyntaxKind.TrueLiteralExpression: + { + switch (expression2.Kind()) { - switch (expression2.Kind()) - { - case SyntaxKind.TrueLiteralExpression: - return expression2; - case SyntaxKind.FalseLiteralExpression: - return condition; - default: - return LogicalOrExpression(condition, expression2); - } + case SyntaxKind.TrueLiteralExpression: + return expression2; + case SyntaxKind.FalseLiteralExpression: + return condition; + default: + return LogicalOrExpression(condition, expression2); } + } case SyntaxKind.FalseLiteralExpression: + { + switch (expression2.Kind()) { - switch (expression2.Kind()) - { - case SyntaxKind.TrueLiteralExpression: - return SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken); - case SyntaxKind.FalseLiteralExpression: - return expression2; - default: - return LogicalAndExpression(SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken), expression2); - } + case SyntaxKind.TrueLiteralExpression: + return SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken); + case SyntaxKind.FalseLiteralExpression: + return expression2; + default: + return LogicalAndExpression(SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken), expression2); } + } default: + { + switch (expression2.Kind()) { - switch (expression2.Kind()) - { - case SyntaxKind.TrueLiteralExpression: - return LogicalOrExpression(SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken), expression1); - case SyntaxKind.FalseLiteralExpression: - return LogicalAndExpression(condition, expression1); - default: - throw new InvalidOperationException(); - } + case SyntaxKind.TrueLiteralExpression: + return LogicalOrExpression(SyntaxLogicalInverter.GetInstance(document).LogicallyInvert(condition, semanticModel, cancellationToken), expression1); + case SyntaxKind.FalseLiteralExpression: + return LogicalAndExpression(condition, expression1); + default: + throw new InvalidOperationException(); } + } } static BinaryExpressionSyntax LogicalAndExpression(ExpressionSyntax left, ExpressionSyntax right) diff --git a/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs b/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs index f69e2177c7..c376434362 100644 --- a/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs +++ b/src/Workspaces.Common/CSharp/Refactorings/RemoveAsyncAwait.cs @@ -32,51 +32,51 @@ SyntaxNode GetNewNode() switch (node) { case MethodDeclarationSyntax methodDeclaration: + { + return remover + .VisitMethodDeclaration(methodDeclaration) + .RemoveModifier(SyntaxKind.AsyncKeyword); + } + case LocalFunctionStatementSyntax localFunction: + { + BlockSyntax body = localFunction.Body; + + if (body is not null) { - return remover - .VisitMethodDeclaration(methodDeclaration) - .RemoveModifier(SyntaxKind.AsyncKeyword); + localFunction = localFunction.WithBody((BlockSyntax)remover.VisitBlock(body)); } - case LocalFunctionStatementSyntax localFunction: + else { - BlockSyntax body = localFunction.Body; - - if (body is not null) - { - localFunction = localFunction.WithBody((BlockSyntax)remover.VisitBlock(body)); - } - else - { - ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; + ArrowExpressionClauseSyntax expressionBody = localFunction.ExpressionBody; - if (expressionBody is not null) - localFunction = localFunction.WithExpressionBody((ArrowExpressionClauseSyntax)remover.VisitArrowExpressionClause(expressionBody)); - } - - return localFunction.RemoveModifier(SyntaxKind.AsyncKeyword); + if (expressionBody is not null) + localFunction = localFunction.WithExpressionBody((ArrowExpressionClauseSyntax)remover.VisitArrowExpressionClause(expressionBody)); } + + return localFunction.RemoveModifier(SyntaxKind.AsyncKeyword); + } case SimpleLambdaExpressionSyntax lambda: - { - return lambda - .WithBody((CSharpSyntaxNode)remover.Visit(lambda.Body)) - .WithAsyncKeyword(GetMissingAsyncKeyword(lambda.AsyncKeyword)); - } + { + return lambda + .WithBody((CSharpSyntaxNode)remover.Visit(lambda.Body)) + .WithAsyncKeyword(GetMissingAsyncKeyword(lambda.AsyncKeyword)); + } case ParenthesizedLambdaExpressionSyntax lambda: - { - return lambda - .WithBody((CSharpSyntaxNode)remover.Visit(lambda.Body)) - .WithAsyncKeyword(GetMissingAsyncKeyword(lambda.AsyncKeyword)); - } + { + return lambda + .WithBody((CSharpSyntaxNode)remover.Visit(lambda.Body)) + .WithAsyncKeyword(GetMissingAsyncKeyword(lambda.AsyncKeyword)); + } case AnonymousMethodExpressionSyntax anonymousMethod: - { - return anonymousMethod - .WithBody((CSharpSyntaxNode)remover.Visit(anonymousMethod.Body)) - .WithAsyncKeyword(GetMissingAsyncKeyword(anonymousMethod.AsyncKeyword)); - } + { + return anonymousMethod + .WithBody((CSharpSyntaxNode)remover.Visit(anonymousMethod.Body)) + .WithAsyncKeyword(GetMissingAsyncKeyword(anonymousMethod.AsyncKeyword)); + } default: - { - throw new InvalidOperationException(); - } + { + throw new InvalidOperationException(); + } } } } diff --git a/src/Workspaces.Common/CSharp/SyntaxFormatter.cs b/src/Workspaces.Common/CSharp/SyntaxFormatter.cs index a91f9ca734..9439794f3d 100644 --- a/src/Workspaces.Common/CSharp/SyntaxFormatter.cs +++ b/src/Workspaces.Common/CSharp/SyntaxFormatter.cs @@ -102,89 +102,89 @@ public static Task ToSingleLineAsync( switch (parent.Kind()) { case SyntaxKind.ObjectCreationExpression: - { - var expression = (ObjectCreationExpressionSyntax)parent; - - expression = expression.WithInitializer(newInitializer); + { + var expression = (ObjectCreationExpressionSyntax)parent; - ArgumentListSyntax argumentList = expression.ArgumentList; + expression = expression.WithInitializer(newInitializer); - if (argumentList is not null) - { - newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); - } - else - { - newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space)); - } + ArgumentListSyntax argumentList = expression.ArgumentList; - break; + if (argumentList is not null) + { + newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); } - case SyntaxKind.ImplicitObjectCreationExpression: + else { - var expression = (ImplicitObjectCreationExpressionSyntax)parent; + newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space)); + } - expression = expression.WithInitializer(newInitializer); + break; + } + case SyntaxKind.ImplicitObjectCreationExpression: + { + var expression = (ImplicitObjectCreationExpressionSyntax)parent; - ArgumentListSyntax argumentList = expression.ArgumentList; + expression = expression.WithInitializer(newInitializer); - if (argumentList is not null) - { - newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); - } - else - { - newParent = expression.WithNewKeyword(expression.NewKeyword.WithTrailingTrivia(Space)); - } + ArgumentListSyntax argumentList = expression.ArgumentList; - break; + if (argumentList is not null) + { + newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); } - case SyntaxKind.ArrayCreationExpression: + else { - var expression = (ArrayCreationExpressionSyntax)parent; + newParent = expression.WithNewKeyword(expression.NewKeyword.WithTrailingTrivia(Space)); + } - newParent = expression - .WithInitializer(newInitializer) - .WithType(expression.Type.WithTrailingTrivia(Space)); + break; + } + case SyntaxKind.ArrayCreationExpression: + { + var expression = (ArrayCreationExpressionSyntax)parent; - break; - } + newParent = expression + .WithInitializer(newInitializer) + .WithType(expression.Type.WithTrailingTrivia(Space)); + + break; + } case SyntaxKind.ImplicitArrayCreationExpression: - { - var expression = (ImplicitArrayCreationExpressionSyntax)parent; + { + var expression = (ImplicitArrayCreationExpressionSyntax)parent; - newParent = expression - .WithInitializer(newInitializer) - .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space)); + newParent = expression + .WithInitializer(newInitializer) + .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space)); - break; - } + break; + } case SyntaxKind.EqualsValueClause: - { - var equalsValueClause = (EqualsValueClauseSyntax)parent; + { + var equalsValueClause = (EqualsValueClauseSyntax)parent; - newParent = equalsValueClause - .WithValue(newInitializer) - .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space)); + newParent = equalsValueClause + .WithValue(newInitializer) + .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space)); - break; - } + break; + } case SyntaxKind.SimpleAssignmentExpression: - { - var simpleAssignment = (AssignmentExpressionSyntax)parent; + { + var simpleAssignment = (AssignmentExpressionSyntax)parent; - newParent = simpleAssignment - .WithRight(newInitializer) - .WithOperatorToken(simpleAssignment.OperatorToken.WithoutTrailingTrivia()); + newParent = simpleAssignment + .WithRight(newInitializer) + .WithOperatorToken(simpleAssignment.OperatorToken.WithoutTrailingTrivia()); - break; - } + break; + } default: - { - SyntaxDebug.Fail(parent); + { + SyntaxDebug.Fail(parent); - return document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken); - } + return document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken); + } } return document.ReplaceNodeAsync(parent, newParent, cancellationToken); @@ -413,29 +413,29 @@ public static Task WrapCallChainAsync( switch (node.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: - { - var memberAccess = (MemberAccessExpressionSyntax)node; - - if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) - break; + { + var memberAccess = (MemberAccessExpressionSyntax)node; - if (semanticModel - .GetSymbol(memberAccess.Expression, cancellationToken)? - .Kind == SymbolKind.Namespace) - { - break; - } + if (memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) + break; - AddTextChange(memberAccess.OperatorToken); + if (semanticModel + .GetSymbol(memberAccess.Expression, cancellationToken)? + .Kind == SymbolKind.Namespace) + { break; } + + AddTextChange(memberAccess.OperatorToken); + break; + } case SyntaxKind.MemberBindingExpression: - { - var memberBinding = (MemberBindingExpressionSyntax)node; + { + var memberBinding = (MemberBindingExpressionSyntax)node; - AddTextChange(memberBinding.OperatorToken); - break; - } + AddTextChange(memberBinding.OperatorToken); + break; + } } } diff --git a/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs index 9600b3aad8..e352235e0d 100644 --- a/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/MemberSymbolDefinitionComparer.cs @@ -60,50 +60,50 @@ public int Compare(ISymbol x, ISymbol y) { case MemberDeclarationKind.Constructor: case MemberDeclarationKind.Method: - { - return CompareMethods((IMethodSymbol)x, (IMethodSymbol)y); - } + { + return CompareMethods((IMethodSymbol)x, (IMethodSymbol)y); + } case MemberDeclarationKind.Indexer: case MemberDeclarationKind.Property: - { - return CompareProperties((IPropertySymbol)x, (IPropertySymbol)y); - } + { + return CompareProperties((IPropertySymbol)x, (IPropertySymbol)y); + } case MemberDeclarationKind.ExplicitlyImplementedEvent: - { - var e1 = (IEventSymbol)x; - var e2 = (IEventSymbol)y; + { + var e1 = (IEventSymbol)x; + var e2 = (IEventSymbol)y; - diff = CompareExplicitImplementations(e1.ExplicitInterfaceImplementations, e2.ExplicitInterfaceImplementations); + diff = CompareExplicitImplementations(e1.ExplicitInterfaceImplementations, e2.ExplicitInterfaceImplementations); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - break; - } + break; + } case MemberDeclarationKind.ExplicitlyImplementedMethod: - { - var m1 = (IMethodSymbol)x; - var m2 = (IMethodSymbol)y; + { + var m1 = (IMethodSymbol)x; + var m2 = (IMethodSymbol)y; - diff = CompareExplicitImplementations(m1.ExplicitInterfaceImplementations, m2.ExplicitInterfaceImplementations); + diff = CompareExplicitImplementations(m1.ExplicitInterfaceImplementations, m2.ExplicitInterfaceImplementations); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - return CompareMethods(m1, m2); - } + return CompareMethods(m1, m2); + } case MemberDeclarationKind.ExplicitlyImplementedProperty: - { - var p1 = (IPropertySymbol)x; - var p2 = (IPropertySymbol)y; + { + var p1 = (IPropertySymbol)x; + var p2 = (IPropertySymbol)y; - diff = CompareExplicitImplementations(p1.ExplicitInterfaceImplementations, p2.ExplicitInterfaceImplementations); + diff = CompareExplicitImplementations(p1.ExplicitInterfaceImplementations, p2.ExplicitInterfaceImplementations); - if (diff != 0) - return diff; + if (diff != 0) + return diff; - return CompareProperties(p1, p2); - } + return CompareProperties(p1, p2); + } } diff = SymbolDefinitionComparer.CompareName(x, y); diff --git a/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs b/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs index 94e583fd92..b6a87e7db2 100644 --- a/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs +++ b/src/Workspaces.Core/Comparers/SymbolDefinitionComparer.cs @@ -45,62 +45,62 @@ public int Compare(ISymbol x, ISymbol y) switch (x.Kind) { case SymbolKind.Namespace: + { + var namespaceSymbol = (INamespaceSymbol)x; + + switch (y.Kind) { - var namespaceSymbol = (INamespaceSymbol)x; - - switch (y.Kind) - { - case SymbolKind.Namespace: - return NamespaceComparer.Compare(namespaceSymbol, (INamespaceSymbol)y); - case SymbolKind.NamedType: - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - case SymbolKind.Property: - return -CompareSymbolAndNamespaceSymbol(y, namespaceSymbol); - } - - break; + case SymbolKind.Namespace: + return NamespaceComparer.Compare(namespaceSymbol, (INamespaceSymbol)y); + case SymbolKind.NamedType: + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: + case SymbolKind.Property: + return -CompareSymbolAndNamespaceSymbol(y, namespaceSymbol); } + + break; + } case SymbolKind.NamedType: + { + var typeSymbol = (INamedTypeSymbol)x; + + switch (y.Kind) { - var typeSymbol = (INamedTypeSymbol)x; - - switch (y.Kind) - { - case SymbolKind.Namespace: - return CompareSymbolAndNamespaceSymbol(typeSymbol, (INamespaceSymbol)y); - case SymbolKind.NamedType: - return CompareNamedTypeSymbol(typeSymbol, (INamedTypeSymbol)y); - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - case SymbolKind.Property: - return -CompareSymbolAndNamedTypeSymbol(y, typeSymbol); - } - - break; + case SymbolKind.Namespace: + return CompareSymbolAndNamespaceSymbol(typeSymbol, (INamespaceSymbol)y); + case SymbolKind.NamedType: + return CompareNamedTypeSymbol(typeSymbol, (INamedTypeSymbol)y); + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: + case SymbolKind.Property: + return -CompareSymbolAndNamedTypeSymbol(y, typeSymbol); } + + break; + } case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: + { + switch (y.Kind) { - switch (y.Kind) - { - case SymbolKind.Namespace: - return CompareSymbolAndNamespaceSymbol(x, (INamespaceSymbol)y); - case SymbolKind.NamedType: - return CompareSymbolAndNamedTypeSymbol(x, (INamedTypeSymbol)y); - case SymbolKind.Event: - case SymbolKind.Field: - case SymbolKind.Method: - case SymbolKind.Property: - return CompareMemberSymbol(x, y); - } - - break; + case SymbolKind.Namespace: + return CompareSymbolAndNamespaceSymbol(x, (INamespaceSymbol)y); + case SymbolKind.NamedType: + return CompareSymbolAndNamedTypeSymbol(x, (INamedTypeSymbol)y); + case SymbolKind.Event: + case SymbolKind.Field: + case SymbolKind.Method: + case SymbolKind.Property: + return CompareMemberSymbol(x, y); } + + break; + } } throw new InvalidOperationException(); diff --git a/src/Workspaces.Core/ConsoleUtility.cs b/src/Workspaces.Core/ConsoleUtility.cs index 59d01456f0..c52aef9d3e 100644 --- a/src/Workspaces.Core/ConsoleUtility.cs +++ b/src/Workspaces.Core/ConsoleUtility.cs @@ -75,191 +75,191 @@ public static string ReadUserInput(string defaultValue, string prompt, int posit switch (keyInfo.Key) { case ConsoleKey.LeftArrow: - { - int index = GetIndex(); + { + int index = GetIndex(); - if (index == 0) - break; + if (index == 0) + break; - if (keyInfo.Modifiers == ConsoleModifiers.Control) + if (keyInfo.Modifiers == ConsoleModifiers.Control) + { + int i = index - 1; + while (i > 0) { - int i = index - 1; - while (i > 0) + if (char.IsLetterOrDigit(buffer[i]) + && !char.IsLetterOrDigit(buffer[i - 1])) { - if (char.IsLetterOrDigit(buffer[i]) - && !char.IsLetterOrDigit(buffer[i - 1])) - { - break; - } - - i--; + break; } - MoveCursorLeft(index - i); - break; - } - - if (Console.CursorLeft == 0) - { - Console.SetCursorPosition(Console.WindowWidth - 1, Console.CursorTop - 1); - } - else - { - Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); + i--; } + MoveCursorLeft(index - i); break; } - case ConsoleKey.RightArrow: + + if (Console.CursorLeft == 0) + { + Console.SetCursorPosition(Console.WindowWidth - 1, Console.CursorTop - 1); + } + else { - int index = GetIndex(); + Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); + } - if (index == buffer.Count) - break; + break; + } + case ConsoleKey.RightArrow: + { + int index = GetIndex(); - if (keyInfo.Modifiers == ConsoleModifiers.Control) + if (index == buffer.Count) + break; + + if (keyInfo.Modifiers == ConsoleModifiers.Control) + { + int i = index + 1; + while (i < buffer.Count - 1) { - int i = index + 1; - while (i < buffer.Count - 1) + if (char.IsLetterOrDigit(buffer[i]) + && !char.IsLetterOrDigit(buffer[i + 1])) { - if (char.IsLetterOrDigit(buffer[i]) - && !char.IsLetterOrDigit(buffer[i + 1])) - { - break; - } - - i++; + break; } - MoveCursorRight(i + 1 - index); - break; - } - - if (Console.CursorLeft == Console.WindowWidth - 1) - { - Console.SetCursorPosition(0, Console.CursorTop + 1); - } - else - { - Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); + i++; } + MoveCursorRight(i + 1 - index); break; } - case ConsoleKey.Home: + + if (Console.CursorLeft == Console.WindowWidth - 1) { - Console.SetCursorPosition(initLeft, initTop); - break; + Console.SetCursorPosition(0, Console.CursorTop + 1); } - case ConsoleKey.End: + else { - MoveCursorRight(buffer.Count - GetIndex()); - break; + Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop); } + + break; + } + case ConsoleKey.Home: + { + Console.SetCursorPosition(initLeft, initTop); + break; + } + case ConsoleKey.End: + { + MoveCursorRight(buffer.Count - GetIndex()); + break; + } case ConsoleKey.Backspace: - { - if (buffer.Count == 0) - break; + { + if (buffer.Count == 0) + break; - int index = GetIndex(); + int index = GetIndex(); - if (index == 0) - break; + if (index == 0) + break; - buffer.RemoveAt(index - 1); + buffer.RemoveAt(index - 1); - int left = Console.CursorLeft - 1; - int top = Console.CursorTop; + int left = Console.CursorLeft - 1; + int top = Console.CursorTop; - if (Console.CursorLeft == 0) - { - left = Console.WindowWidth - 1; - top--; - } + if (Console.CursorLeft == 0) + { + left = Console.WindowWidth - 1; + top--; + } - Console.SetCursorPosition(left, top); + Console.SetCursorPosition(left, top); - char[] text = buffer.Skip(index - 1).Append(' ').ToArray(); - Console.Write(text); + char[] text = buffer.Skip(index - 1).Append(' ').ToArray(); + Console.Write(text); - Console.SetCursorPosition(left, top); - break; - } + Console.SetCursorPosition(left, top); + break; + } case ConsoleKey.Delete: - { - if (buffer.Count == 0) - break; + { + if (buffer.Count == 0) + break; - int index = GetIndex(); + int index = GetIndex(); - if (buffer.Count == index) - break; + if (buffer.Count == index) + break; - buffer.RemoveAt(index); + buffer.RemoveAt(index); - int left = Console.CursorLeft; - int top = Console.CursorTop; + int left = Console.CursorLeft; + int top = Console.CursorTop; - char[] text = buffer.Skip(index).Append(' ').ToArray(); - Console.Write(text); + char[] text = buffer.Skip(index).Append(' ').ToArray(); + Console.Write(text); - Console.SetCursorPosition(left, top); + Console.SetCursorPosition(left, top); - break; - } + break; + } case ConsoleKey.Escape: - { - Reset(useDefaultValue: buffer.Count == 0); - break; - } + { + Reset(useDefaultValue: buffer.Count == 0); + break; + } case ConsoleKey.PageDown: - { - if (keyInfo.Modifiers != ConsoleModifiers.Control) - Reset(); + { + if (keyInfo.Modifiers != ConsoleModifiers.Control) + Reset(); - break; - } + break; + } case ConsoleKey.UpArrow: - { - Reset(); - break; - } + { + Reset(); + break; + } default: - { - char ch = keyInfo.KeyChar; - - // ctrl+c - if (keyInfo.Modifiers == ConsoleModifiers.Control - && ch == 3) - { - Console.WriteLine(); - throw new OperationCanceledException(); - } + { + char ch = keyInfo.KeyChar; - if (ch < 32) - break; + // ctrl+c + if (keyInfo.Modifiers == ConsoleModifiers.Control + && ch == 3) + { + Console.WriteLine(); + throw new OperationCanceledException(); + } - int index = GetIndex(); + if (ch < 32) + break; - buffer.Insert(index, ch); + int index = GetIndex(); - int left = Console.CursorLeft; - int top = Console.CursorTop; + buffer.Insert(index, ch); - char[] text = buffer.Skip(index).ToArray(); - Console.Write(text); + int left = Console.CursorLeft; + int top = Console.CursorTop; - if (left == Console.WindowWidth - 1) - { - Console.SetCursorPosition(0, top + 1); - } - else - { - Console.SetCursorPosition(left + 1, top); - } + char[] text = buffer.Skip(index).ToArray(); + Console.Write(text); - break; + if (left == Console.WindowWidth - 1) + { + Console.SetCursorPosition(0, top + 1); + } + else + { + Console.SetCursorPosition(left + 1, top); } + + break; + } } keyInfo = Console.ReadKey(true); diff --git a/src/Workspaces.Core/DiagnosticFormatter.cs b/src/Workspaces.Core/DiagnosticFormatter.cs index bffa806edc..6caf8f64a4 100644 --- a/src/Workspaces.Core/DiagnosticFormatter.cs +++ b/src/Workspaces.Core/DiagnosticFormatter.cs @@ -53,31 +53,31 @@ private static void FormatLocation( case LocationKind.SourceFile: case LocationKind.XmlFile: case LocationKind.ExternalFile: + { + FileLinePositionSpan span = location.GetMappedLineSpan(); + + if (span.IsValid) { - FileLinePositionSpan span = location.GetMappedLineSpan(); + sb.Append(PathUtilities.TrimStart(span.Path, baseDirectoryPath)); - if (span.IsValid) + if (omitSpan) { - sb.Append(PathUtilities.TrimStart(span.Path, baseDirectoryPath)); - - if (omitSpan) - { - sb.Append(": "); - } - else - { - LinePosition linePosition = span.StartLinePosition; - - sb.Append('('); - sb.Append(linePosition.Line + 1); - sb.Append(','); - sb.Append(linePosition.Character + 1); - sb.Append("): "); - } + sb.Append(": "); } + else + { + LinePosition linePosition = span.StartLinePosition; - break; + sb.Append('('); + sb.Append(linePosition.Line + 1); + sb.Append(','); + sb.Append(linePosition.Character + 1); + sb.Append("): "); + } } + + break; + } } } @@ -125,65 +125,65 @@ static string GetSymbolTitle(ISymbol symbol) switch (symbol.Kind) { case SymbolKind.Event: - { - return "event"; - } + { + return "event"; + } case SymbolKind.Field: - { - return (symbol.ContainingType.TypeKind == TypeKind.Enum) ? "enum field" : "field"; - } + { + return (symbol.ContainingType.TypeKind == TypeKind.Enum) ? "enum field" : "field"; + } case SymbolKind.Local: - { - return "local"; - } + { + return "local"; + } case SymbolKind.Method: + { + var methodSymbol = (IMethodSymbol)symbol; + + switch (methodSymbol.MethodKind) { - var methodSymbol = (IMethodSymbol)symbol; - - switch (methodSymbol.MethodKind) - { - case MethodKind.Ordinary: - return "method"; - case MethodKind.LocalFunction: - return "local function"; - } - - Debug.Fail(methodSymbol.MethodKind.ToString()); - break; + case MethodKind.Ordinary: + return "method"; + case MethodKind.LocalFunction: + return "local function"; } + + Debug.Fail(methodSymbol.MethodKind.ToString()); + break; + } case SymbolKind.NamedType: + { + var typeSymbol = (INamedTypeSymbol)symbol; + + switch (typeSymbol.TypeKind) { - var typeSymbol = (INamedTypeSymbol)symbol; - - switch (typeSymbol.TypeKind) - { - case TypeKind.Class: - return "class"; - case TypeKind.Delegate: - return "delegate"; - case TypeKind.Enum: - return "enum"; - case TypeKind.Interface: - return "interface"; - case TypeKind.Struct: - return "struct"; - } - - Debug.Fail(typeSymbol.TypeKind.ToString()); - break; + case TypeKind.Class: + return "class"; + case TypeKind.Delegate: + return "delegate"; + case TypeKind.Enum: + return "enum"; + case TypeKind.Interface: + return "interface"; + case TypeKind.Struct: + return "struct"; } + + Debug.Fail(typeSymbol.TypeKind.ToString()); + break; + } case SymbolKind.Parameter: - { - return "parameter"; - } + { + return "parameter"; + } case SymbolKind.Property: - { - return (((IPropertySymbol)symbol).IsIndexer) ? "indexer" : "property"; - } + { + return (((IPropertySymbol)symbol).IsIndexer) ? "indexer" : "property"; + } case SymbolKind.TypeParameter: - { - return "type parameter"; - } + { + return "type parameter"; + } } Debug.Fail(symbol.Kind.ToString()); diff --git a/src/Workspaces.Core/Extensions/Extensions.cs b/src/Workspaces.Core/Extensions/Extensions.cs index 7cc8c3bb90..e592468fd7 100644 --- a/src/Workspaces.Core/Extensions/Extensions.cs +++ b/src/Workspaces.Core/Extensions/Extensions.cs @@ -69,62 +69,62 @@ public static MemberDeclarationKind GetMemberDeclarationKind(this ISymbol symbol switch (symbol.Kind) { case SymbolKind.Event: - { - return (((IEventSymbol)symbol).ExplicitInterfaceImplementations.Any()) - ? MemberDeclarationKind.ExplicitlyImplementedEvent - : MemberDeclarationKind.Event; - } + { + return (((IEventSymbol)symbol).ExplicitInterfaceImplementations.Any()) + ? MemberDeclarationKind.ExplicitlyImplementedEvent + : MemberDeclarationKind.Event; + } case SymbolKind.Field: - { - var fieldSymbol = (IFieldSymbol)symbol; + { + var fieldSymbol = (IFieldSymbol)symbol; - return (fieldSymbol.IsConst) - ? MemberDeclarationKind.Const - : MemberDeclarationKind.Field; - } + return (fieldSymbol.IsConst) + ? MemberDeclarationKind.Const + : MemberDeclarationKind.Field; + } case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; - - switch (methodSymbol.MethodKind) - { - case MethodKind.Ordinary: - return MemberDeclarationKind.Method; - case MethodKind.ExplicitInterfaceImplementation: - return MemberDeclarationKind.ExplicitlyImplementedMethod; - case MethodKind.Constructor: - return MemberDeclarationKind.Constructor; - case MethodKind.Destructor: - return MemberDeclarationKind.Destructor; - case MethodKind.StaticConstructor: - return MemberDeclarationKind.StaticConstructor; - case MethodKind.Conversion: - return MemberDeclarationKind.ConversionOperator; - case MethodKind.UserDefinedOperator: - return MemberDeclarationKind.Operator; - } + { + var methodSymbol = (IMethodSymbol)symbol; - break; + switch (methodSymbol.MethodKind) + { + case MethodKind.Ordinary: + return MemberDeclarationKind.Method; + case MethodKind.ExplicitInterfaceImplementation: + return MemberDeclarationKind.ExplicitlyImplementedMethod; + case MethodKind.Constructor: + return MemberDeclarationKind.Constructor; + case MethodKind.Destructor: + return MemberDeclarationKind.Destructor; + case MethodKind.StaticConstructor: + return MemberDeclarationKind.StaticConstructor; + case MethodKind.Conversion: + return MemberDeclarationKind.ConversionOperator; + case MethodKind.UserDefinedOperator: + return MemberDeclarationKind.Operator; } + + break; + } case SymbolKind.Property: - { - var propertySymbol = (IPropertySymbol)symbol; + { + var propertySymbol = (IPropertySymbol)symbol; - bool explicitlyImplemented = propertySymbol.ExplicitInterfaceImplementations.Any(); + bool explicitlyImplemented = propertySymbol.ExplicitInterfaceImplementations.Any(); - if (propertySymbol.IsIndexer) - { - return (explicitlyImplemented) - ? MemberDeclarationKind.ExplicitlyImplementedIndexer - : MemberDeclarationKind.Indexer; - } - else - { - return (explicitlyImplemented) - ? MemberDeclarationKind.ExplicitlyImplementedProperty - : MemberDeclarationKind.Property; - } + if (propertySymbol.IsIndexer) + { + return (explicitlyImplemented) + ? MemberDeclarationKind.ExplicitlyImplementedIndexer + : MemberDeclarationKind.Indexer; + } + else + { + return (explicitlyImplemented) + ? MemberDeclarationKind.ExplicitlyImplementedProperty + : MemberDeclarationKind.Property; } + } } Debug.Fail(symbol.ToDisplayString(SymbolDisplayFormats.Test)); @@ -137,48 +137,48 @@ public static SymbolGroup GetSymbolGroup(this ISymbol symbol) switch (symbol.Kind) { case SymbolKind.NamedType: - { - var namedType = (INamedTypeSymbol)symbol; - - switch (namedType.TypeKind) - { - case TypeKind.Class: - return SymbolGroup.Class; - case TypeKind.Module: - return SymbolGroup.Module; - case TypeKind.Delegate: - return SymbolGroup.Delegate; - case TypeKind.Enum: - return SymbolGroup.Enum; - case TypeKind.Interface: - return SymbolGroup.Interface; - case TypeKind.Struct: - return SymbolGroup.Struct; - } + { + var namedType = (INamedTypeSymbol)symbol; - Debug.Fail(namedType.TypeKind.ToString()); - return SymbolGroup.None; - } - case SymbolKind.Event: + switch (namedType.TypeKind) { - return SymbolGroup.Event; + case TypeKind.Class: + return SymbolGroup.Class; + case TypeKind.Module: + return SymbolGroup.Module; + case TypeKind.Delegate: + return SymbolGroup.Delegate; + case TypeKind.Enum: + return SymbolGroup.Enum; + case TypeKind.Interface: + return SymbolGroup.Interface; + case TypeKind.Struct: + return SymbolGroup.Struct; } + + Debug.Fail(namedType.TypeKind.ToString()); + return SymbolGroup.None; + } + case SymbolKind.Event: + { + return SymbolGroup.Event; + } case SymbolKind.Field: - { - return (((IFieldSymbol)symbol).IsConst) - ? SymbolGroup.Const - : SymbolGroup.Field; - } + { + return (((IFieldSymbol)symbol).IsConst) + ? SymbolGroup.Const + : SymbolGroup.Field; + } case SymbolKind.Method: - { - return SymbolGroup.Method; - } + { + return SymbolGroup.Method; + } case SymbolKind.Property: - { - return (((IPropertySymbol)symbol).IsIndexer) - ? SymbolGroup.Indexer - : SymbolGroup.Property; - } + { + return (((IPropertySymbol)symbol).IsIndexer) + ? SymbolGroup.Indexer + : SymbolGroup.Property; + } } Debug.Fail(symbol.Kind.ToString()); diff --git a/src/Workspaces.Core/FindSymbols/IgnoredNameSymbolFilterRule.cs b/src/Workspaces.Core/FindSymbols/IgnoredNameSymbolFilterRule.cs index 1837c9d3d0..23478f7858 100644 --- a/src/Workspaces.Core/FindSymbols/IgnoredNameSymbolFilterRule.cs +++ b/src/Workspaces.Core/FindSymbols/IgnoredNameSymbolFilterRule.cs @@ -35,12 +35,12 @@ public override bool IsMatch(ISymbol value) { case SymbolKind.Namespace: case SymbolKind.NamedType: - { - if (Names.Contains(value)) - return false; + { + if (Names.Contains(value)) + return false; - break; - } + break; + } } return true; diff --git a/src/Workspaces.Core/FindSymbols/SymbolFilterOptions.cs b/src/Workspaces.Core/FindSymbols/SymbolFilterOptions.cs index bcde940153..6fe6ce7b52 100644 --- a/src/Workspaces.Core/FindSymbols/SymbolFilterOptions.cs +++ b/src/Workspaces.Core/FindSymbols/SymbolFilterOptions.cs @@ -195,32 +195,32 @@ public virtual SymbolFilterReason GetReason(IMethodSymbol symbol) switch (symbol.MethodKind) { case MethodKind.Constructor: - { - TypeKind typeKind = symbol.ContainingType.TypeKind; - - Debug.Assert(typeKind.Is(TypeKind.Class, TypeKind.Struct, TypeKind.Enum), symbol.ToDisplayString(SymbolDisplayFormats.Test)); + { + TypeKind typeKind = symbol.ContainingType.TypeKind; - if (typeKind == TypeKind.Class - && !symbol.Parameters.Any()) - { - canBeImplicitlyDeclared = true; - } + Debug.Assert(typeKind.Is(TypeKind.Class, TypeKind.Struct, TypeKind.Enum), symbol.ToDisplayString(SymbolDisplayFormats.Test)); - break; + if (typeKind == TypeKind.Class + && !symbol.Parameters.Any()) + { + canBeImplicitlyDeclared = true; } + + break; + } case MethodKind.Conversion: case MethodKind.UserDefinedOperator: case MethodKind.Ordinary: case MethodKind.StaticConstructor: case MethodKind.Destructor: case MethodKind.ExplicitInterfaceImplementation: - { - break; - } + { + break; + } default: - { - return SymbolFilterReason.Other; - } + { + return SymbolFilterReason.Other; + } } if (!canBeImplicitlyDeclared && symbol.IsImplicitlyDeclared) diff --git a/src/Workspaces.Core/Rename/SymbolProvider.cs b/src/Workspaces.Core/Rename/SymbolProvider.cs index 49158acf37..a3fa1e8430 100644 --- a/src/Workspaces.Core/Rename/SymbolProvider.cs +++ b/src/Workspaces.Core/Rename/SymbolProvider.cs @@ -119,33 +119,33 @@ private void AnalyzeSymbol(SymbolAnalysisContext context) case SymbolKind.Field: case SymbolKind.NamedType: case SymbolKind.Property: - { - AddSymbol(symbol); - break; - } + { + AddSymbol(symbol); + break; + } case SymbolKind.Method: - { - var methodSymbol = (IMethodSymbol)symbol; + { + var methodSymbol = (IMethodSymbol)symbol; - switch (methodSymbol.MethodKind) + switch (methodSymbol.MethodKind) + { + case MethodKind.Ordinary: + case MethodKind.Constructor: + case MethodKind.UserDefinedOperator: + case MethodKind.Conversion: { - case MethodKind.Ordinary: - case MethodKind.Constructor: - case MethodKind.UserDefinedOperator: - case MethodKind.Conversion: - { - AddSymbol(methodSymbol); - break; - } + AddSymbol(methodSymbol); + break; } - - break; } + + break; + } default: - { - Debug.Fail(symbol.Kind.ToString()); - break; - } + { + Debug.Fail(symbol.Kind.ToString()); + break; + } } } diff --git a/src/Workspaces.Core/Rename/SymbolRenameState.cs b/src/Workspaces.Core/Rename/SymbolRenameState.cs index c79932f84c..c5fbc0e561 100644 --- a/src/Workspaces.Core/Rename/SymbolRenameState.cs +++ b/src/Workspaces.Core/Rename/SymbolRenameState.cs @@ -839,56 +839,56 @@ private void Report( switch (symbol.Kind) { case SymbolKind.Local: - { - return null; - } + { + return null; + } case SymbolKind.Method: + { + var methodSymbol = (IMethodSymbol)symbol; + + if (methodSymbol.MethodKind == MethodKind.LocalFunction) { - var methodSymbol = (IMethodSymbol)symbol; + id = symbol.Name; + ISymbol cs = symbol.ContainingSymbol; - if (methodSymbol.MethodKind == MethodKind.LocalFunction) + while (cs is IMethodSymbol { MethodKind: MethodKind.LocalFunction }) { - id = symbol.Name; - ISymbol cs = symbol.ContainingSymbol; - - while (cs is IMethodSymbol { MethodKind: MethodKind.LocalFunction }) - { - id = cs.Name + "." + id; - cs = cs.ContainingSymbol; - } - - return id; + id = cs.Name + "." + id; + cs = cs.ContainingSymbol; } - break; + return id; } + + break; + } case SymbolKind.Parameter: case SymbolKind.TypeParameter: + { + ISymbol cs = symbol.ContainingSymbol; + + if (cs is IMethodSymbol methodSymbol) { - ISymbol cs = symbol.ContainingSymbol; + if (methodSymbol.MethodKind == MethodKind.AnonymousFunction) + return null; - if (cs is IMethodSymbol methodSymbol) + if (methodSymbol.MethodKind == MethodKind.LocalFunction) { - if (methodSymbol.MethodKind == MethodKind.AnonymousFunction) - return null; + id = cs.Name + " " + symbol.Name; + cs = cs.ContainingSymbol; - if (methodSymbol.MethodKind == MethodKind.LocalFunction) + while (cs is IMethodSymbol { MethodKind: MethodKind.LocalFunction }) { - id = cs.Name + " " + symbol.Name; + id = cs.Name + "." + id; cs = cs.ContainingSymbol; - - while (cs is IMethodSymbol { MethodKind: MethodKind.LocalFunction }) - { - id = cs.Name + "." + id; - cs = cs.ContainingSymbol; - } - - return id; } - } - return symbol.ContainingSymbol.GetDocumentationCommentId() + " " + (symbol.GetDocumentationCommentId() ?? symbol.Name); + return id; + } } + + return symbol.ContainingSymbol.GetDocumentationCommentId() + " " + (symbol.GetDocumentationCommentId() ?? symbol.Name); + } } return symbol.GetDocumentationCommentId();